@motionscript/geography 0.1.0-alpha.8 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,268 +1,268 @@
1
- import {
2
- Flow,
3
- Graphics2D,
4
- Paint,
5
- Shapes,
6
- Types,
7
- component2d,
8
- type EntryOptions,
9
- type FillResolved,
10
- type NodeOf,
11
- // Named so this component's emitted type reaches the shape surface it spreads through the sdk, not core.
12
- type Alignment as _Alignment,
13
- type Fill as _Fill,
14
- type FlowMode as _FlowMode,
15
- type FlowResolved as _FlowResolved,
16
- type GapSize as _GapSize,
17
- type Node2D as _Node2D,
18
- type Node2DProps as _Node2DProps,
19
- type Shadow as _Shadow,
20
- type Stroke as _Stroke,
21
- type Vector2 as _Vector2,
22
- type PathBounds,
23
- type ShadowResolved,
24
- type ShapeProps,
25
- type Size2D,
26
- type StrokeResolved,
27
- type Type,
28
- } from "@motionscript/sdk"
29
- import { snapValue } from "@motionscript/sdk/component"
30
-
31
- import { geoGeometry, type GeoBorders, type GeoContour, type GeoGeometry, type GeoProjectionKind } from "./geometry"
32
- import { geoDataVersion, geoLoader } from "./loader"
33
- import { geoRegistry } from "./registry"
34
- import { geoFilesFor, normalizeIso, selectGeoFeatures, type GeoFrame, type GeoLevel } from "./selection"
35
-
36
- export interface GeoBorderProps extends ShapeProps {
37
- /** ISO 3166-1 alpha-2 (`"FR"`) or ISO 3166-2 (`"US-CA"`) codes. */
38
- iso: string | readonly string[]
39
- level: GeoLevel
40
- /** 0–1: 1 is full resolution, lower is a more stylised outline. */
41
- detail: number
42
- projection: GeoProjectionKind
43
- frame: GeoFrame
44
- borders: GeoBorders
45
- }
46
-
47
- interface Chunk {
48
- data: string
49
- /** Where this chunk's contours sit along the whole drawing, as fractions of its length. */
50
- from: number
51
- to: number
52
- }
53
-
54
- interface Drawn {
55
- geometry: GeoGeometry
56
- width: number
57
- height: number
58
- fills: Chunk[]
59
- lines: Chunk[]
60
- }
61
-
62
- // A renderer's cost for one path grows faster than its contour count, and a shape
63
- // drawn as several paths under one paint is unioned every frame — so a region
64
- // is cut into paths of bounded size, each painted on its own.
65
- const CONTOURS_PER_PATH = 256
66
- const POINTS_PER_PATH = 40_000
67
-
68
- const coordinate = (value: number) => String(Math.round(value * 100) / 100)
69
-
70
- function chunk(contours: readonly GeoContour[], total: number, scale: number): Chunk[] {
71
- const chunks: Chunk[] = []
72
- let parts: string[] = []
73
- let count = 0
74
- let points = 0
75
- let from = 0
76
- let length = 0
77
- const flush = () => {
78
- if (count === 0) return
79
- const to = total > 0 ? Math.min(1, length / total) : 1
80
- chunks.push({ data: parts.join(""), from, to })
81
- from = to
82
- parts = []
83
- count = 0
84
- points = 0
85
- }
86
- for (const contour of contours) {
87
- const p = contour.points
88
- // Path data is y-down; the unit geometry is y-up.
89
- for (let i = 0; i < p.length; i += 2) {
90
- parts.push(i === 0 ? "M" : "L", coordinate(p[i] * scale), " ", coordinate(-p[i + 1] * scale))
91
- }
92
- if (contour.closed) parts.push("Z")
93
- count++
94
- points += p.length / 2
95
- length += contour.length
96
- if (count >= CONTOURS_PER_PATH || points >= POINTS_PER_PATH) flush()
97
- }
98
- flush()
99
- return chunks
100
- }
101
-
102
- /** One of `values`, switched at the end of a `to`, with its choices listed as its `options`. */
103
- function choice<const V extends readonly string[]>(values: V, initial: V[number]): Type<V[number]> {
104
- return Types.custom<V[number], V[number], EntryOptions & { readonly options: V }>(initial, { lerp: snapValue, options: values })
105
- }
106
-
107
- /** A node's own drawing state, kept by its fields' view (one object per node, the same every frame). */
108
- interface Kept {
109
- drawn: Drawn | null
110
- readonly warned: Set<string>
111
- }
112
-
113
- const kept = new WeakMap<object, Kept>()
114
-
115
- function keptBy(state: object): Kept {
116
- let entry = kept.get(state)
117
- if (!entry) kept.set(state, (entry = { drawn: null, warned: new Set() }))
118
- return entry
119
- }
120
-
121
- interface Selected {
122
- readonly iso: readonly string[]
123
- readonly level: GeoLevel
124
- readonly frame: GeoFrame
125
- readonly projection: GeoProjectionKind
126
- readonly borders: GeoBorders
127
- readonly detail: number
128
- }
129
-
130
- /** The selection's outlines cut into paths at `size`, or `null` while there is nothing to draw. */
131
- function drawnOf(state: Selected, size: Size2D): Drawn | null {
132
- const own = keptBy(state)
133
- const codes = state.iso
134
- const { level, frame } = state
135
- const selection = selectGeoFeatures(codes, level, frame)
136
- for (const code of selection.unknown) {
137
- if (own.warned.has(code)) continue
138
- own.warned.add(code)
139
- console.warn(`[GeoBorder] no region with code ${code}`)
140
- }
141
- if (selection.features.length === 0) return null
142
-
143
- const geometry = geoGeometry({
144
- selectionKey: `${geoRegistry.generation}:${geoDataVersion()}:${level}:${frame}:${codes.join(",")}`,
145
- features: selection.features,
146
- frame,
147
- projection: state.projection,
148
- borders: state.borders,
149
- detail: state.detail,
150
- })
151
- if (!geometry) return null
152
-
153
- const { width, height } = size
154
- const cached = own.drawn
155
- if (cached && cached.geometry === geometry && cached.width === width && cached.height === height) return cached
156
- const scale = Math.min(width / geometry.width, height / geometry.height)
157
- const drawn: Drawn = {
158
- geometry,
159
- width,
160
- height,
161
- fills: chunk(geometry.fills, geometry.fillLength, scale),
162
- lines: chunk(geometry.lines, geometry.lineLength, scale),
163
- }
164
- own.drawn = drawn
165
- return drawn
166
- }
167
-
168
- /** Adds `chunk` to `g`, trimmed by `start`/`end` along the whole drawing; `false` when none of it is drawn. */
169
- function pathOp(g: Graphics2D, chunk: Chunk, size: Size2D, start: number, end: number): boolean {
170
- const { width, height } = size
171
- const centerBounds: PathBounds = [-width / 2, -height / 2, width / 2, height / 2]
172
- if (start <= 0 && end >= 1) {
173
- g.path({ data: chunk.data, centerBounds })
174
- return true
175
- }
176
- const span = chunk.to - chunk.from
177
- if (span <= 0) return false
178
- const localStart = Math.max(0, (start - chunk.from) / span)
179
- const localEnd = Math.min(1, (end - chunk.from) / span)
180
- if (localEnd <= localStart) return false
181
- g.path({ data: chunk.data, centerBounds, start: localStart, end: localEnd })
182
- return true
183
- }
184
-
185
- /**
186
- * Country and subdivision outlines by ISO 3166 code, fitted into the node's box.
187
- *
188
- * <GeoBorder iso={["FR", "DE"]} detail={0.4} stroke={{ weight: 2, fill: "white" }} />
189
- *
190
- * Geometry comes from whatever `geoRegistry` has been given — a URL, a loader,
191
- * or shapes defined by hand — and loads as a declared asset, so a frame never
192
- * draws half a country. Fill and stroke are separate geometry: the fill is each
193
- * region's polygons, the stroke is every border once, which is why a border two
194
- * selected regions share is not drawn twice and why `stroke.align` does not
195
- * apply.
196
- */
197
- export const GeoBorder = component2d({
198
- key: "geoBorder",
199
- state: {
200
- ...Paint.state,
201
- ...Flow.state,
202
- iso: Types.custom<string | readonly string[], string[]>(["FR"], { resolve: normalizeIso, lerp: snapValue }),
203
- level: choice(["country", "state"], "country"),
204
- detail: Types.number(0.5, { min: 0, max: 1, step: 0.01 }),
205
- projection: choice(["conic", "mercator", "equirectangular", "orthographic"], "conic"),
206
- frame: choice(["mainland", "all"], "mainland"),
207
- borders: choice(["all", "outline"], "all"),
208
- },
209
- commands: { ...Paint.commands },
210
- // The data gates the draw, not layout: the box never waits on it.
211
- load: (loader, state) => {
212
- for (const file of geoFilesFor(state.iso, state.level)) loader.task(`geo:${file}`, geoLoader(file))
213
- },
214
- measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),
215
- layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),
216
- render: (ctx, state) => {
217
- const size = ctx.size
218
- const { start, end } = state
219
- const fill = state.fill as FillResolved[]
220
- const shadow = state.shadow as ShadowResolved[]
221
- const drawn = () => drawnOf(state, size)
222
-
223
- ctx.inFront(() => {
224
- const shape = drawn()
225
- if (!shape || shape.fills.length === 0) return
226
- const g = new Graphics2D()
227
- for (const part of shape.fills) {
228
- if (!pathOp(g, part, size, start, end)) continue
229
- if (shadow.length > 0) g.shadow(shadow)
230
- g.fill(fill)
231
- }
232
- ctx.draw(g)
233
- })
234
-
235
- // The box, not the outline, confines the children and is what picking
236
- // tests: a path clip has no winding test, and a country's bounding box is
237
- // what the selection shows.
238
- Paint.draw(ctx, state, null, { clipShape: Shapes.box(size) })
239
-
240
- ctx.inFront(() => {
241
- const overlay = state.overlay as FillResolved[]
242
- if (overlay.length > 0) {
243
- const shape = drawn()
244
- if (shape) {
245
- const g = new Graphics2D()
246
- for (const part of shape.fills) if (pathOp(g, part, size, start, end)) g.fill(overlay)
247
- ctx.draw(g)
248
- }
249
- }
250
-
251
- const stroke = state.stroke as StrokeResolved[]
252
- if (stroke.length === 0) return
253
- const shape = drawn()
254
- if (!shape || shape.lines.length === 0) return
255
- const centred = stroke.map((layer) => (layer.align === 0 ? layer : { ...layer, align: 0 }))
256
- const castsShadow = shadow.length > 0 && !fill.some((layer) => (layer.opacity ?? 1) > 0)
257
- const g = new Graphics2D()
258
- for (const part of shape.lines) {
259
- if (!pathOp(g, part, size, start, end)) continue
260
- if (castsShadow) g.shadow(shadow)
261
- g.stroke(centred)
262
- }
263
- ctx.draw(g)
264
- })
265
- },
266
- })
267
-
268
- export type GeoBorder = NodeOf<typeof GeoBorder>
1
+ import {
2
+ Flow,
3
+ Graphics2D,
4
+ Paint,
5
+ Shapes,
6
+ Types,
7
+ component2d,
8
+ type EntryOptions,
9
+ type FillResolved,
10
+ type NodeOf,
11
+ // Named so this component's emitted type reaches the shape surface it spreads through the sdk, not core.
12
+ type Alignment as _Alignment,
13
+ type Fill as _Fill,
14
+ type FlowMode as _FlowMode,
15
+ type FlowResolved as _FlowResolved,
16
+ type GapSize as _GapSize,
17
+ type Node2D as _Node2D,
18
+ type Node2DProps as _Node2DProps,
19
+ type Shadow as _Shadow,
20
+ type Stroke as _Stroke,
21
+ type Vector2 as _Vector2,
22
+ type PathBounds,
23
+ type ShadowResolved,
24
+ type ShapeProps,
25
+ type Size2D,
26
+ type StrokeResolved,
27
+ type Type,
28
+ } from "@motionscript/sdk"
29
+ import { snapValue } from "@motionscript/sdk/component"
30
+
31
+ import { geoGeometry, type GeoBorders, type GeoContour, type GeoGeometry, type GeoProjectionKind } from "./geometry"
32
+ import { geoDataVersion, geoLoader } from "./loader"
33
+ import { geoRegistry } from "./registry"
34
+ import { geoFilesFor, normalizeIso, selectGeoFeatures, type GeoFrame, type GeoLevel } from "./selection"
35
+
36
+ export interface GeoBorderProps extends ShapeProps {
37
+ /** ISO 3166-1 alpha-2 (`"FR"`) or ISO 3166-2 (`"US-CA"`) codes. */
38
+ iso: string | readonly string[]
39
+ level: GeoLevel
40
+ /** 0–1: 1 is full resolution, lower is a more stylised outline. */
41
+ detail: number
42
+ projection: GeoProjectionKind
43
+ frame: GeoFrame
44
+ borders: GeoBorders
45
+ }
46
+
47
+ interface Chunk {
48
+ data: string
49
+ /** Where this chunk's contours sit along the whole drawing, as fractions of its length. */
50
+ from: number
51
+ to: number
52
+ }
53
+
54
+ interface Drawn {
55
+ geometry: GeoGeometry
56
+ width: number
57
+ height: number
58
+ fills: Chunk[]
59
+ lines: Chunk[]
60
+ }
61
+
62
+ // A renderer's cost for one path grows faster than its contour count, and a shape
63
+ // drawn as several paths under one paint is unioned every frame — so a region
64
+ // is cut into paths of bounded size, each painted on its own.
65
+ const CONTOURS_PER_PATH = 256
66
+ const POINTS_PER_PATH = 40_000
67
+
68
+ const coordinate = (value: number) => String(Math.round(value * 100) / 100)
69
+
70
+ function chunk(contours: readonly GeoContour[], total: number, scale: number): Chunk[] {
71
+ const chunks: Chunk[] = []
72
+ let parts: string[] = []
73
+ let count = 0
74
+ let points = 0
75
+ let from = 0
76
+ let length = 0
77
+ const flush = () => {
78
+ if (count === 0) return
79
+ const to = total > 0 ? Math.min(1, length / total) : 1
80
+ chunks.push({ data: parts.join(""), from, to })
81
+ from = to
82
+ parts = []
83
+ count = 0
84
+ points = 0
85
+ }
86
+ for (const contour of contours) {
87
+ const p = contour.points
88
+ // Path data is y-down; the unit geometry is y-up.
89
+ for (let i = 0; i < p.length; i += 2) {
90
+ parts.push(i === 0 ? "M" : "L", coordinate(p[i] * scale), " ", coordinate(-p[i + 1] * scale))
91
+ }
92
+ if (contour.closed) parts.push("Z")
93
+ count++
94
+ points += p.length / 2
95
+ length += contour.length
96
+ if (count >= CONTOURS_PER_PATH || points >= POINTS_PER_PATH) flush()
97
+ }
98
+ flush()
99
+ return chunks
100
+ }
101
+
102
+ /** One of `values`, switched at the end of a `to`, with its choices listed as its `options`. */
103
+ function choice<const V extends readonly string[]>(values: V, initial: V[number]): Type<V[number]> {
104
+ return Types.custom<V[number], V[number], EntryOptions & { readonly options: V }>(initial, { lerp: snapValue, options: values })
105
+ }
106
+
107
+ /** A node's own drawing state, kept by its fields' view (one object per node, the same every frame). */
108
+ interface Kept {
109
+ drawn: Drawn | null
110
+ readonly warned: Set<string>
111
+ }
112
+
113
+ const kept = new WeakMap<object, Kept>()
114
+
115
+ function keptBy(state: object): Kept {
116
+ let entry = kept.get(state)
117
+ if (!entry) kept.set(state, (entry = { drawn: null, warned: new Set() }))
118
+ return entry
119
+ }
120
+
121
+ interface Selected {
122
+ readonly iso: readonly string[]
123
+ readonly level: GeoLevel
124
+ readonly frame: GeoFrame
125
+ readonly projection: GeoProjectionKind
126
+ readonly borders: GeoBorders
127
+ readonly detail: number
128
+ }
129
+
130
+ /** The selection's outlines cut into paths at `size`, or `null` while there is nothing to draw. */
131
+ function drawnOf(state: Selected, size: Size2D): Drawn | null {
132
+ const own = keptBy(state)
133
+ const codes = state.iso
134
+ const { level, frame } = state
135
+ const selection = selectGeoFeatures(codes, level, frame)
136
+ for (const code of selection.unknown) {
137
+ if (own.warned.has(code)) continue
138
+ own.warned.add(code)
139
+ console.warn(`[GeoBorder] no region with code ${code}`)
140
+ }
141
+ if (selection.features.length === 0) return null
142
+
143
+ const geometry = geoGeometry({
144
+ selectionKey: `${geoRegistry.generation}:${geoDataVersion()}:${level}:${frame}:${codes.join(",")}`,
145
+ features: selection.features,
146
+ frame,
147
+ projection: state.projection,
148
+ borders: state.borders,
149
+ detail: state.detail,
150
+ })
151
+ if (!geometry) return null
152
+
153
+ const { width, height } = size
154
+ const cached = own.drawn
155
+ if (cached && cached.geometry === geometry && cached.width === width && cached.height === height) return cached
156
+ const scale = Math.min(width / geometry.width, height / geometry.height)
157
+ const drawn: Drawn = {
158
+ geometry,
159
+ width,
160
+ height,
161
+ fills: chunk(geometry.fills, geometry.fillLength, scale),
162
+ lines: chunk(geometry.lines, geometry.lineLength, scale),
163
+ }
164
+ own.drawn = drawn
165
+ return drawn
166
+ }
167
+
168
+ /** Adds `chunk` to `g`, trimmed by `start`/`end` along the whole drawing; `false` when none of it is drawn. */
169
+ function pathOp(g: Graphics2D, chunk: Chunk, size: Size2D, start: number, end: number): boolean {
170
+ const { width, height } = size
171
+ const centerBounds: PathBounds = [-width / 2, -height / 2, width / 2, height / 2]
172
+ if (start <= 0 && end >= 1) {
173
+ g.path({ data: chunk.data, centerBounds })
174
+ return true
175
+ }
176
+ const span = chunk.to - chunk.from
177
+ if (span <= 0) return false
178
+ const localStart = Math.max(0, (start - chunk.from) / span)
179
+ const localEnd = Math.min(1, (end - chunk.from) / span)
180
+ if (localEnd <= localStart) return false
181
+ g.path({ data: chunk.data, centerBounds, start: localStart, end: localEnd })
182
+ return true
183
+ }
184
+
185
+ /**
186
+ * Country and subdivision outlines by ISO 3166 code, fitted into the node's box.
187
+ *
188
+ * <GeoBorder iso={["FR", "DE"]} detail={0.4} stroke={{ weight: 2, fill: "white" }} />
189
+ *
190
+ * Geometry comes from whatever `geoRegistry` has been given — a URL, a loader,
191
+ * or shapes defined by hand — and loads as a declared asset, so a frame never
192
+ * draws half a country. Fill and stroke are separate geometry: the fill is each
193
+ * region's polygons, the stroke is every border once, which is why a border two
194
+ * selected regions share is not drawn twice and why `stroke.align` does not
195
+ * apply.
196
+ */
197
+ export const GeoBorder = component2d({
198
+ key: "geoBorder",
199
+ state: {
200
+ ...Paint.state,
201
+ ...Flow.state,
202
+ iso: Types.custom<string | readonly string[], string[]>(["FR"], { resolve: normalizeIso, lerp: snapValue }),
203
+ level: choice(["country", "state"], "country"),
204
+ detail: Types.number(0.5, { min: 0, max: 1, step: 0.01 }),
205
+ projection: choice(["conic", "mercator", "equirectangular", "orthographic"], "conic"),
206
+ frame: choice(["mainland", "all"], "mainland"),
207
+ borders: choice(["all", "outline"], "all"),
208
+ },
209
+ commands: { ...Paint.commands },
210
+ // The data gates the draw, not layout: the box never waits on it.
211
+ load: (loader, state) => {
212
+ for (const file of geoFilesFor(state.iso, state.level)) loader.task(`geo:${file}`, geoLoader(file))
213
+ },
214
+ measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),
215
+ layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),
216
+ render: (ctx, state) => {
217
+ const size = ctx.size
218
+ const { start, end } = state
219
+ const fill = state.fill as FillResolved[]
220
+ const shadow = state.shadow as ShadowResolved[]
221
+ const drawn = () => drawnOf(state, size)
222
+
223
+ ctx.inFront(() => {
224
+ const shape = drawn()
225
+ if (!shape || shape.fills.length === 0) return
226
+ const g = new Graphics2D()
227
+ for (const part of shape.fills) {
228
+ if (!pathOp(g, part, size, start, end)) continue
229
+ if (shadow.length > 0) g.shadow(shadow)
230
+ g.fill(fill)
231
+ }
232
+ ctx.draw(g)
233
+ })
234
+
235
+ // The box, not the outline, confines the children and is what picking
236
+ // tests: a path clip has no winding test, and a country's bounding box is
237
+ // what the selection shows.
238
+ Paint.draw(ctx, state, null, { clipShape: Shapes.box(size) })
239
+
240
+ ctx.inFront(() => {
241
+ const overlay = state.overlay as FillResolved[]
242
+ if (overlay.length > 0) {
243
+ const shape = drawn()
244
+ if (shape) {
245
+ const g = new Graphics2D()
246
+ for (const part of shape.fills) if (pathOp(g, part, size, start, end)) g.fill(overlay)
247
+ ctx.draw(g)
248
+ }
249
+ }
250
+
251
+ const stroke = state.stroke as StrokeResolved[]
252
+ if (stroke.length === 0) return
253
+ const shape = drawn()
254
+ if (!shape || shape.lines.length === 0) return
255
+ const centred = stroke.map((layer) => (layer.align === 0 ? layer : { ...layer, align: 0 }))
256
+ const castsShadow = shadow.length > 0 && !fill.some((layer) => (layer.opacity ?? 1) > 0)
257
+ const g = new Graphics2D()
258
+ for (const part of shape.lines) {
259
+ if (!pathOp(g, part, size, start, end)) continue
260
+ if (castsShadow) g.shadow(shadow)
261
+ g.stroke(centred)
262
+ }
263
+ ctx.draw(g)
264
+ })
265
+ },
266
+ })
267
+
268
+ export type GeoBorder = NodeOf<typeof GeoBorder>