@wardic/three 0.0.0-stage → 1.3.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 (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +84 -2
  3. package/THIRD_PARTY_NOTICES.md +145 -0
  4. package/dist/TestStage.d.ts +45 -0
  5. package/dist/TestStage.d.ts.map +1 -0
  6. package/dist/TestStage.js +140 -0
  7. package/dist/TestStage.js.map +1 -0
  8. package/dist/ThreeColours.d.ts +53 -0
  9. package/dist/ThreeColours.d.ts.map +1 -0
  10. package/dist/ThreeColours.js +246 -0
  11. package/dist/ThreeColours.js.map +1 -0
  12. package/dist/ThreeDrag.d.ts +82 -0
  13. package/dist/ThreeDrag.d.ts.map +1 -0
  14. package/dist/ThreeDrag.js +243 -0
  15. package/dist/ThreeDrag.js.map +1 -0
  16. package/dist/ThreeInput.d.ts +69 -0
  17. package/dist/ThreeInput.d.ts.map +1 -0
  18. package/dist/ThreeInput.js +592 -0
  19. package/dist/ThreeInput.js.map +1 -0
  20. package/dist/ThreeInstances.d.ts +47 -0
  21. package/dist/ThreeInstances.d.ts.map +1 -0
  22. package/dist/ThreeInstances.js +392 -0
  23. package/dist/ThreeInstances.js.map +1 -0
  24. package/dist/ThreeRenderer.d.ts +45 -0
  25. package/dist/ThreeRenderer.d.ts.map +1 -0
  26. package/dist/ThreeRenderer.js +121 -0
  27. package/dist/ThreeRenderer.js.map +1 -0
  28. package/dist/ThreeValues.d.ts +15 -0
  29. package/dist/ThreeValues.d.ts.map +1 -0
  30. package/dist/ThreeValues.js +61 -0
  31. package/dist/ThreeValues.js.map +1 -0
  32. package/dist/WardicThree.d.ts +207 -0
  33. package/dist/WardicThree.d.ts.map +1 -0
  34. package/dist/WardicThree.js +162 -0
  35. package/dist/WardicThree.js.map +1 -0
  36. package/dist/index.d.ts +26 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +27 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/internal/dev.d.ts +10 -0
  41. package/dist/internal/dev.d.ts.map +1 -0
  42. package/dist/internal/dev.js +11 -0
  43. package/dist/internal/dev.js.map +1 -0
  44. package/dist/internal/dev.production.d.ts +8 -0
  45. package/dist/internal/dev.production.d.ts.map +1 -0
  46. package/dist/internal/dev.production.js +8 -0
  47. package/dist/internal/dev.production.js.map +1 -0
  48. package/dist/internal/lookup.d.ts +29 -0
  49. package/dist/internal/lookup.d.ts.map +1 -0
  50. package/dist/internal/lookup.js +245 -0
  51. package/dist/internal/lookup.js.map +1 -0
  52. package/dist/internal/shared-material.d.ts +8 -0
  53. package/dist/internal/shared-material.d.ts.map +1 -0
  54. package/dist/internal/shared-material.js +95 -0
  55. package/dist/internal/shared-material.js.map +1 -0
  56. package/dist/solid/feature.d.ts +42 -0
  57. package/dist/solid/feature.d.ts.map +1 -0
  58. package/dist/solid/feature.js +2 -0
  59. package/dist/solid/feature.js.map +1 -0
  60. package/dist/solid/scene-batch.d.ts +10 -0
  61. package/dist/solid/scene-batch.d.ts.map +1 -0
  62. package/dist/solid/scene-batch.js +436 -0
  63. package/dist/solid/scene-batch.js.map +1 -0
  64. package/dist/solid/scene-object.d.ts +27 -0
  65. package/dist/solid/scene-object.d.ts.map +1 -0
  66. package/dist/solid/scene-object.js +111 -0
  67. package/dist/solid/scene-object.js.map +1 -0
  68. package/dist/solid/stage-batches.d.ts +10 -0
  69. package/dist/solid/stage-batches.d.ts.map +1 -0
  70. package/dist/solid/stage-batches.js +6 -0
  71. package/dist/solid/stage-batches.js.map +1 -0
  72. package/dist/solid/stage-drag.d.ts +4 -0
  73. package/dist/solid/stage-drag.d.ts.map +1 -0
  74. package/dist/solid/stage-drag.js +19 -0
  75. package/dist/solid/stage-drag.js.map +1 -0
  76. package/dist/solid/stage.d.ts +107 -0
  77. package/dist/solid/stage.d.ts.map +1 -0
  78. package/dist/solid/stage.js +320 -0
  79. package/dist/solid/stage.js.map +1 -0
  80. package/dist/solid/test-stage.d.ts +29 -0
  81. package/dist/solid/test-stage.d.ts.map +1 -0
  82. package/dist/solid/test-stage.js +16 -0
  83. package/dist/solid/test-stage.js.map +1 -0
  84. package/dist/solid.d.ts +55 -0
  85. package/dist/solid.d.ts.map +1 -0
  86. package/dist/solid.js +9 -0
  87. package/dist/solid.js.map +1 -0
  88. package/package.json +99 -4
  89. package/src/TestStage.ts +177 -0
  90. package/src/ThreeColours.ts +259 -0
  91. package/src/ThreeDrag.ts +341 -0
  92. package/src/ThreeInput.ts +744 -0
  93. package/src/ThreeInstances.ts +481 -0
  94. package/src/ThreeRenderer.ts +159 -0
  95. package/src/ThreeValues.ts +69 -0
  96. package/src/WardicThree.ts +364 -0
  97. package/src/index.ts +26 -0
  98. package/src/internal/dev.production.ts +7 -0
  99. package/src/internal/dev.ts +10 -0
  100. package/src/internal/lookup.ts +247 -0
  101. package/src/internal/shared-material.ts +101 -0
  102. package/src/solid/feature.ts +38 -0
  103. package/src/solid/scene-batch.ts +490 -0
  104. package/src/solid/scene-object.ts +145 -0
  105. package/src/solid/stage-batches.ts +13 -0
  106. package/src/solid/stage-drag.ts +26 -0
  107. package/src/solid/stage.ts +409 -0
  108. package/src/solid/test-stage.ts +40 -0
  109. package/src/solid.ts +111 -0
@@ -0,0 +1,409 @@
1
+ /**
2
+ * `createStage` (ADR-0073 decisions 11–13): a Stage that runs a three.js scene for its owner. It's the
3
+ * `Stage` the hooks under a `<WardicStage>` find (`ward(mesh, config)`, `createFrameEffect`, the sensors),
4
+ * and the ref that mounts and sizes the renderer's canvas:
5
+ *
6
+ * ```tsx
7
+ * const stage = createStage({ renderer: () => new WebGLRenderer({ antialias: true }), scene, camera })
8
+ * <WardicStage value={stage}>
9
+ * <div class="viewport" ref={stage} />
10
+ * <Crate />
11
+ * </WardicStage>
12
+ * ```
13
+ *
14
+ * - **Its Host loop:** `renderer.setAnimationLoop`, the scene's raycast, then Wardic's frame, then the
15
+ * render. With `frameloop: "demand"`, it renders only when something moves, or after `invalidate()`.
16
+ * - **Given as a ref,** an element mounts `renderer.domElement` and keeps it sized: `setSize`, and a
17
+ * perspective camera's `aspect`. `resize: false` leaves the size to the app.
18
+ * - **`renderer`** is an instance, in client-only code, or a factory the browser calls once the page has
19
+ * settled. `{ wardic: made }` adopts a runtime made outside Solid, whose maker pumps its frames.
20
+ * - **On a server** it does nothing: its ref renders nothing, and the hooks under it animate nothing.
21
+ * - **It ends with its owner:** the loop, the input and the runtime stop; the renderer, scene and camera
22
+ * stay the app's.
23
+ *
24
+ * @module
25
+ */
26
+ // #885's PR 1 (ADR-0073, *Amendment (#885)*, Q2–Q4).
27
+ import { isServer } from "@solidjs/web"
28
+ import * as InputFeed from "@wardic/core/InputFeed"
29
+ import type * as InputSource from "@wardic/core/InputSource"
30
+ import { type Stage, type StageDrag, type StageGraph, type StageWard, stageWard, type StageWardEnvironment } from "@wardic/solid"
31
+ import * as Arr from "effect/Array"
32
+ import * as Bool from "effect/Boolean"
33
+ import { constUndefined, constVoid } from "effect/Function"
34
+ import * as Option from "effect/Option"
35
+ import * as Predicate from "effect/Predicate"
36
+ import * as Atom from "effect/reactivity/Atom"
37
+ import * as UndefinedOr from "effect/UndefinedOr"
38
+ import { onCleanup, onSettled, untrack } from "solid-js"
39
+ import type { Camera, Object3D } from "three"
40
+ import * as ThreeColours from "../ThreeColours.ts"
41
+ import type { StageFeature, StageView } from "./feature.ts"
42
+ import * as ThreeInput from "../ThreeInput.ts"
43
+ import * as ThreeValues from "../ThreeValues.ts"
44
+ import * as WardicThree from "../WardicThree.ts"
45
+
46
+ /** What a Stage needs of a renderer: three's `WebGLRenderer` and `WebGPURenderer` both have it. */
47
+ export interface RendererLike {
48
+ readonly domElement: HTMLCanvasElement
49
+ readonly setSize: (width: number, height: number, updateStyle?: boolean) => void
50
+ readonly setAnimationLoop: (callback: ((time: number) => void) | null) => unknown
51
+ readonly render: (scene: Object3D, camera: Camera) => unknown
52
+ }
53
+
54
+ /** A Stage's options: the scene it draws, its camera, its renderer, and the runtime's own options. */
55
+ export interface StageOptions extends Omit<WardicThree.Options, "canvas" | "camera" | "scene" | "now"> {
56
+ /** The scene it draws and a pointer hits. */
57
+ readonly scene: Object3D
58
+ /** The camera it draws with, or a function giving the one active now. */
59
+ readonly camera: Camera | (() => Camera)
60
+ /** The renderer, or a function making it, which the browser calls once the page has settled. */
61
+ readonly renderer: RendererLike | (() => RendererLike)
62
+ /** `"always"` renders every frame; `"demand"`, only when something moves, or after `invalidate()`. */
63
+ readonly frameloop?: "always" | "demand" | undefined
64
+ /** `false` leaves the canvas's size to the app. */
65
+ readonly resize?: boolean | undefined
66
+ /** What it does beyond a ward's motion, each its code only where it's given: `stageDrag`, `stageBatches`. */
67
+ readonly features?: ReadonlyArray<StageFeature> | undefined
68
+ }
69
+
70
+ /** A Stage over a runtime made outside Solid: its maker pumps its frames and draws. */
71
+ export interface AdoptOptions {
72
+ readonly wardic: WardicThree.WardicThree
73
+ /** Its features: `stageBatches`; `stageDrag` drags nothing with no view of its own. */
74
+ readonly features?: ReadonlyArray<StageFeature> | undefined
75
+ }
76
+
77
+ /** A three.js Stage: the `Stage` the hooks find, the ref that mounts its canvas, and its own calls. */
78
+ export interface ThreeStage extends Stage {
79
+ /** Mount the renderer's canvas in `element`, kept sized: give the Stage to an element's `ref`. */
80
+ (element: HTMLElement): void
81
+ /** Draw a frame under `frameloop: "demand"`: the scene changed in a way Wardic didn't. */
82
+ readonly invalidate: () => void
83
+ /** The runtime, for code outside Solid: `stage.wardic.batch(…)`, `stage.wardic.hover(…)`. */
84
+ readonly wardic: WardicThree.WardicThree | undefined
85
+ }
86
+
87
+ /** Whether `value` is one of a scene's Subjects: an `Object3D` or a `Material`, by three's flags. */
88
+ export const isThreeSubject = (value: unknown): boolean =>
89
+ Predicate.isObject(value) && ((value as { readonly isObject3D?: unknown }).isObject3D === true || (value as { readonly isMaterial?: unknown }).isMaterial === true)
90
+
91
+ /**
92
+ * An `InputSource` the Stage's hooks can watch before its canvas is made (a renderer made once the page
93
+ * has settled): each feed connects to the scene's input as it's attached. Internal; exported for its test.
94
+ */
95
+ export const lateInput = (): { readonly source: InputSource.InputSource["Service"]; readonly attach: (source: InputSource.InputSource["Service"]) => void } => {
96
+ let real: InputSource.InputSource["Service"] | undefined
97
+ const waiting = new Set<(given: InputSource.InputSource["Service"]) => void>()
98
+ const later =
99
+ <A>(feedOf: (source: InputSource.InputSource["Service"]) => InputFeed.InputFeed<A>): InputFeed.InputFeed<A> =>
100
+ (emit, end) => {
101
+ if (Predicate.isNotUndefined(real)) return feedOf(real)(emit, end)
102
+ let cancel: () => void = constVoid
103
+ const connect = (given: InputSource.InputSource["Service"]): void => {
104
+ cancel = feedOf(given)(emit, end)
105
+ }
106
+ waiting.add(connect)
107
+ return () => {
108
+ waiting.delete(connect)
109
+ cancel()
110
+ }
111
+ }
112
+ const source: InputSource.InputSource["Service"] = {
113
+ pointer: (target) => later((given) => given.pointer(target)),
114
+ keyboard: () => InputFeed.empty,
115
+ focus: () => InputFeed.empty,
116
+ adoptPointer: () => Option.none(),
117
+ pointerAmong: (memberOf) => later((given) => UndefinedOr.match(given.pointerAmong, { onUndefined: () => InputFeed.empty, onDefined: (among) => among(memberOf) })),
118
+ }
119
+ const attach = (given: InputSource.InputSource["Service"]): void => {
120
+ real = given
121
+ const connecting = Arr.fromIterable(waiting)
122
+ waiting.clear()
123
+ Arr.forEach(connecting, (connect) => connect(given))
124
+ }
125
+ return { source, attach }
126
+ }
127
+
128
+ /**
129
+ * `subject`, a Subject or an accessor of one, as the Subject now: an accessor read untracked, since the
130
+ * colour split only looks up which keys are a colour on it, often in the component's body, and the ward
131
+ * follows the Subject itself.
132
+ */
133
+ const subjectNowOf = (subject: unknown): (() => unknown) => {
134
+ if (Predicate.isFunction(subject)) return () => untrack(subject as () => unknown)
135
+ return () => subject
136
+ }
137
+
138
+ /** A Subject's parent in three's graph: an object's, none for a material or at the root. */
139
+ const graphParentOf = (subject: object): object | undefined => {
140
+ const parent = (subject as { readonly parent?: Object3D | null }).parent
141
+ if (Predicate.isNullish(parent)) return undefined
142
+ return parent
143
+ }
144
+
145
+ /** The object directly below `ancestor` on `descendant`'s path up: none when `ancestor` isn't above it. */
146
+ const branchOf = (descendant: Object3D, ancestor: object): Object3D | undefined => {
147
+ const parent = descendant.parent
148
+ if (Predicate.isNull(parent)) return undefined
149
+ if (parent === ancestor) return descendant
150
+ return branchOf(parent, ancestor)
151
+ }
152
+
153
+ /**
154
+ * three.js's graph, as a Stage ward reads it (#885's PR 3; ADR-0073 decision 17): an object's parent,
155
+ * its `added` and `removed` events, its branch's index among an ancestor's `children`, and its descendants.
156
+ */
157
+ export const THREE_GRAPH: StageGraph = {
158
+ parentOf: graphParentOf,
159
+ onMoved: (subject, moved) => {
160
+ if (Bool.not(isThreeSubject(subject)) || Predicate.isUndefined((subject as Partial<Object3D>).isObject3D)) return constVoid
161
+ const object = subject as Object3D
162
+ object.addEventListener("added", moved)
163
+ object.addEventListener("removed", moved)
164
+ return () => {
165
+ object.removeEventListener("added", moved)
166
+ object.removeEventListener("removed", moved)
167
+ }
168
+ },
169
+ orderOf: (descendant, ancestor) =>
170
+ UndefinedOr.match(branchOf(descendant as Object3D, ancestor), {
171
+ onUndefined: () => Number.MAX_SAFE_INTEGER,
172
+ onDefined: (branch) => (ancestor as Object3D).children.indexOf(branch),
173
+ }),
174
+ below: (subject, visit) => {
175
+ if (Predicate.isUndefined((subject as Partial<Object3D>).isObject3D)) return
176
+ ;(subject as Object3D).traverse((descendant) => {
177
+ if (descendant !== subject) visit(descendant)
178
+ })
179
+ },
180
+ }
181
+
182
+ /** Where a three.js Stage keeps what `createSceneObject` needs of it: not the `Stage` interface's. */
183
+ export const SCENE: unique symbol = Symbol.for("@wardic/three/solid/scene")
184
+
185
+ /**
186
+ * What `createSceneObject` needs of a Stage (#885): what its wards run on, its scene, and its exits in
187
+ * flight. `createSceneObject` makes its own ward on it, so a Stage app that never calls it carries none.
188
+ */
189
+ export interface SceneOf {
190
+ /** What its wards run on. */
191
+ readonly environment: StageWardEnvironment
192
+ /** A config's colours split into their channels on `subject`, as the Stage's ward splits them. */
193
+ readonly split: <C>(subject: unknown, config: C) => C
194
+ /** The scene a Scene object with no parent joins: none on a Stage adopting a runtime. */
195
+ readonly scene: Object3D | undefined
196
+ /** Each exit in flight, by what lands it now: the Stage lands them as it ends. */
197
+ readonly exits: Set<() => void>
198
+ }
199
+
200
+ /** A three.js Stage, with what `createSceneObject` needs of it. */
201
+ export type SceneStage = Stage & { readonly [SCENE]: SceneOf }
202
+
203
+ /** Every exit still in flight landed: its Subject taken out, as the Stage ends (*Amendment (#885)* Q5). */
204
+ export const landExits = (stage: { readonly [SCENE]: SceneOf }): void =>
205
+ Arr.forEach(Arr.fromIterable(stage[SCENE].exits), (land) => land())
206
+
207
+ /** The first of `features` that gives `pick`'s. */
208
+ const firstOf = <A,>(features: ReadonlyArray<StageFeature>, pick: (feature: StageFeature) => A | undefined): A | undefined =>
209
+ Option.getOrUndefined(Option.flatMap(Arr.findFirst(features, (feature) => Predicate.isNotUndefined(pick(feature))), (feature) => Option.fromUndefinedOr(pick(feature))))
210
+
211
+ /**
212
+ * The Stage over `runtime`: its Subjects three's, its ward the Stage ward on the runtime, each colour of
213
+ * its config split into its channels in linear light as three's `animate` splits a call's, its input
214
+ * `input`. `scene` is what a Scene object with no parent joins. Its drag and its Batches are its
215
+ * `features`' (#885's PR 5): `stageDrag` drags on `view`'s camera and canvas.
216
+ */
217
+ export const stageOver = (
218
+ runtime: WardicThree.WardicThree,
219
+ input: InputSource.InputSource["Service"],
220
+ scene: Object3D | undefined,
221
+ view: StageView | undefined,
222
+ features: ReadonlyArray<StageFeature> = [],
223
+ ): SceneStage => {
224
+ const parts = { runtime, view, scene }
225
+ const drag = UndefinedOr.match(firstOf(features, (feature) => feature.drag), { onUndefined: (): StageDrag | undefined => undefined, onDefined: (make) => make(parts) })
226
+ const environment: StageWardEnvironment = { ...runtime.stageEnvironment, input, graph: THREE_GRAPH, drag }
227
+ const ward = stageWard(environment)
228
+ const split = <C,>(subject: unknown, config: C): C => ThreeColours.splitConfig(subjectNowOf(subject), config as Readonly<Record<string, unknown>>) as C
229
+ return {
230
+ isSubject: isThreeSubject,
231
+ ward: (subject, config, options) => ward(subject, split(subject, config), options),
232
+ animate: runtime.animate as unknown as Stage["animate"],
233
+ frameEffects: runtime.stageEnvironment.frameEffects,
234
+ input,
235
+ drag,
236
+ batch: UndefinedOr.map(firstOf(features, (feature) => feature.batch), (make) => make(parts, environment)),
237
+ [SCENE]: {
238
+ environment,
239
+ split,
240
+ scene,
241
+ exits: new Set(),
242
+ },
243
+ }
244
+ }
245
+
246
+ /** No input: a runtime made with no canvas, on a server. */
247
+ const NO_INPUT: InputSource.InputSource["Service"] = {
248
+ pointer: () => InputFeed.empty,
249
+ keyboard: () => InputFeed.empty,
250
+ focus: () => InputFeed.empty,
251
+ adoptPointer: () => Option.none(),
252
+ }
253
+
254
+ /** A ward that does nothing, reading nothing. */
255
+ const INERT_WARD: StageWard = {
256
+ held: undefined,
257
+ settled: constUndefined,
258
+ tapped: constUndefined,
259
+ next: () => new Promise(() => {}),
260
+ each: () => ({ [Symbol.asyncIterator]: () => ({ next: () => new Promise(() => {}) }) }),
261
+ when: () => constUndefined as never,
262
+ read: (() => constUndefined) as unknown as StageWard["read"],
263
+ atom: () => Atom.make<unknown>(undefined),
264
+ }
265
+
266
+ /**
267
+ * A ward on `given` that does nothing: a server's, and a server's Scene object's. Its `read` gives its
268
+ * Subject's own value, as a ward's does before it moves a key (#939): what a scene's object holds as it's made.
269
+ */
270
+ export const inertWardOn = (given: unknown): StageWard => ({
271
+ ...INERT_WARD,
272
+ read: ((key: string) => () =>
273
+ Option.getOrUndefined(
274
+ Option.flatMap(Option.liftPredicate(subjectNow(given), Predicate.isObject), (subject) =>
275
+ Option.flatten(Option.liftThrowable(() => ThreeValues.startLinksOf(subject).ownValue(key))()),
276
+ ),
277
+ )) as unknown as StageWard["read"],
278
+ })
279
+
280
+ /** The Subject `given` is now: itself, or what its accessor gives. */
281
+ const subjectNow = (given: unknown): unknown => Bool.match(Predicate.isFunction(given), { onTrue: () => (given as () => unknown)(), onFalse: () => given })
282
+
283
+ /** A Stage on a server: its ref renders nothing, its hooks animate nothing, and it runs no loop. */
284
+ // ADR-0073 decision 13: the host `<div>` renders empty, so hydration matches.
285
+ export const inertStage = (): ThreeStage =>
286
+ Object.assign((_element: HTMLElement) => undefined, {
287
+ isSubject: isThreeSubject,
288
+ ward: inertWardOn,
289
+ animate: (): never => {
290
+ throw new Error("A Stage animates nothing on a server: call animate in the browser, in an event or once the page has settled.")
291
+ },
292
+ frameEffects: { add: () => constVoid, request: constVoid },
293
+ input: NO_INPUT,
294
+ invalidate: constVoid,
295
+ wardic: undefined,
296
+ }) as ThreeStage
297
+
298
+ /** `options.renderer`'s renderer, made: a factory is called, an instance is itself. */
299
+ const rendererOf = (renderer: StageOptions["renderer"]): RendererLike => {
300
+ if (Predicate.isFunction(renderer)) return (renderer as () => RendererLike)()
301
+ return renderer
302
+ }
303
+
304
+ /** The camera now: one given, or the one a function gives. */
305
+ const cameraOf = (camera: StageOptions["camera"]): Camera => {
306
+ if (Predicate.isFunction(camera)) return (camera as () => Camera)()
307
+ return camera
308
+ }
309
+
310
+ /** A Stage over `made`, a runtime made outside Solid: its maker pumps its frames and draws; it adopts no loop. */
311
+ const adopted = (made: WardicThree.WardicThree, features: ReadonlyArray<StageFeature> | undefined): ThreeStage =>
312
+ Object.assign((_element: HTMLElement) => undefined, stageOver(made, UndefinedOr.match(made.input, { onUndefined: () => NO_INPUT, onDefined: (given) => given }), undefined, undefined, features), {
313
+ invalidate: constVoid,
314
+ wardic: made,
315
+ }) as ThreeStage
316
+
317
+ /**
318
+ * A Stage that runs `options.scene` for its owner: its Host loop, its pointer input, and its canvas's size.
319
+ * Make it in a component's body; it ends with its owner. Given `{ wardic }`, it adopts that runtime.
320
+ *
321
+ * @example
322
+ * const stage = createStage({ renderer: () => new WebGLRenderer({ antialias: true }), scene, camera })
323
+ * <WardicStage value={stage}>
324
+ * <div class="viewport" ref={stage} />
325
+ * </WardicStage>
326
+ */
327
+ export const createStage = (options: StageOptions | AdoptOptions): ThreeStage => {
328
+ if (isServer) return inertStage()
329
+ if ("wardic" in options) return adopted(options.wardic, options.features)
330
+ const { scene, camera, frameloop = "always", resize = true, renderer: given, features, ...rest } = options
331
+ const runtime = WardicThree.make({ ...rest, scene, camera })
332
+ const late = lateInput()
333
+ let renderer: RendererLike | undefined
334
+ let input: ThreeInput.SceneInput | undefined
335
+ let host: HTMLElement | undefined
336
+ let observer: ResizeObserver | undefined
337
+ // The first frame draws, as does each one after `invalidate()`.
338
+ let invalidated = true
339
+
340
+ /** The canvas in `element`, kept sized to it: the renderer's size, and a perspective camera's aspect. */
341
+ const mount = (element: HTMLElement, made: RendererLike): void => {
342
+ if (made.domElement.parentElement !== element) element.append(made.domElement)
343
+ if (Bool.not(resize)) return
344
+ UndefinedOr.map(observer, (last) => last.disconnect())
345
+ const sized = new ResizeObserver(() => {
346
+ const width = Math.max(1, element.clientWidth)
347
+ const height = Math.max(1, element.clientHeight)
348
+ made.setSize(width, height)
349
+ const now = cameraOf(camera) as Camera & { readonly isPerspectiveCamera?: boolean; aspect?: number; readonly updateProjectionMatrix?: () => void }
350
+ if (now.isPerspectiveCamera === true) {
351
+ now.aspect = width / height
352
+ UndefinedOr.map(now.updateProjectionMatrix, (update) => update.call(now))
353
+ }
354
+ invalidated = true
355
+ })
356
+ sized.observe(element)
357
+ observer = sized
358
+ }
359
+
360
+ /** The renderer made: its input attached, its canvas mounted, and its loop started. */
361
+ const start = (made: RendererLike): void => {
362
+ renderer = made
363
+ const madeInput = ThreeInput.make({ canvas: made.domElement, camera, scene, hitTest: rest.hitTest, window: rest.window })
364
+ input = madeInput
365
+ late.attach(madeInput.source)
366
+ UndefinedOr.map(host, (element) => mount(element, made))
367
+ made.setAnimationLoop((time) => {
368
+ // A frame asked for before it runs draws: a Frame effect's apply can move the scene with nothing
369
+ // animating, and its request is spent by the frame that runs it (#885's PR 6, CS9).
370
+ const asked = runtime.wantsFrame()
371
+ // The raycast first, against what was last drawn; then Wardic's writes; then the render.
372
+ madeInput.frame()
373
+ runtime.frame(time)
374
+ if (frameloop === "demand" && Bool.not(Bool.some([invalidated, asked, runtime.wantsFrame(), madeInput.wantsFrame()]))) return
375
+ invalidated = false
376
+ made.render(scene, cameraOf(camera))
377
+ })
378
+ }
379
+
380
+ // A factory waits for the page to settle, so a server never calls it and hydration makes no canvas.
381
+ Bool.match(Predicate.isFunction(given), {
382
+ onTrue: () => onSettled(() => start(rendererOf(given))),
383
+ onFalse: () => start(given as RendererLike),
384
+ })
385
+
386
+ const over = stageOver(runtime, late.source, scene, { camera, canvas: () => UndefinedOr.map(renderer, (made) => made.domElement) }, features)
387
+ onCleanup(() => {
388
+ // Exits still in flight land first: their Subjects leave the scene, which stays the app's.
389
+ landExits(over)
390
+ UndefinedOr.map(renderer, (made) => {
391
+ made.setAnimationLoop(null)
392
+ made.domElement.remove()
393
+ })
394
+ UndefinedOr.map(observer, (sized) => sized.disconnect())
395
+ UndefinedOr.map(input, (madeInput) => madeInput.dispose())
396
+ runtime.dispose()
397
+ })
398
+
399
+ const ref = (element: HTMLElement): void => {
400
+ host = element
401
+ UndefinedOr.map(renderer, (made) => mount(element, made))
402
+ }
403
+ return Object.assign(ref, over, {
404
+ invalidate: () => {
405
+ invalidated = true
406
+ },
407
+ wardic: runtime,
408
+ }) as ThreeStage
409
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `TestStage` as a Stage (ADR-0073 decision 26): `@wardic/three/TestStage`'s scene on frames the test
3
+ * pumps, with no renderer, that is also the `Stage` its hooks find. A test mounts its tree under it and
4
+ * drives the scene through it:
5
+ *
6
+ * ```tsx
7
+ * const stage = TestStage.make({ scene, camera, size: { width: 800, height: 600 } })
8
+ * render(() => <WardicStage value={stage}><Crate mesh={crate} /></WardicStage>)
9
+ * stage.pointer.over(crate)
10
+ * stage.frame()
11
+ * expect(crate.scale.x).toBeCloseTo(1.08)
12
+ * ```
13
+ *
14
+ * @module
15
+ */
16
+ // #885's PR 1 (ADR-0073, *Amendment (#885)*, Q10): the Solid entry's, so `@wardic/three/TestStage` stays free of Solid.
17
+ import type { Stage } from "@wardic/solid"
18
+ import * as UndefinedOr from "effect/UndefinedOr"
19
+ import * as Plain from "../TestStage.ts"
20
+ import type { CanvasRect } from "../ThreeDrag.ts"
21
+ import type { StageFeature } from "./feature.ts"
22
+ import { landExits, SCENE, type SceneOf, stageOver } from "./stage.ts"
23
+
24
+ export type { Options, TestPointer } from "../TestStage.ts"
25
+
26
+ /** A test's scene that's also a Stage: `@wardic/three/TestStage`'s, with the `Stage` the hooks under it find. */
27
+ export type TestStage = Plain.TestStage & Stage & { readonly [SCENE]: SceneOf }
28
+
29
+ /** A test's scene, on a stand-in canvas of `options.size`, that's also a Stage. */
30
+ export const make = (options: Plain.Options & { readonly features?: ReadonlyArray<StageFeature> | undefined }): TestStage => {
31
+ const plain = Plain.make(options)
32
+ // A TestStage is made with its stand-in canvas, so it always has its input.
33
+ const over = stageOver(plain as never, UndefinedOr.getOrThrow(plain.input), options.scene, { camera: options.camera, canvas: () => plain.canvas as unknown as CanvasRect }, options.features)
34
+ // Its end lands the exits still in flight, as `createStage`'s does.
35
+ const dispose = (): void => {
36
+ landExits(over)
37
+ plain.dispose()
38
+ }
39
+ return { ...plain, ...over, dispose } as TestStage
40
+ }
package/src/solid.ts ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * `@wardic/three/solid` (ADR-0073 decision 20): a three.js scene for Solid 2's hooks. `createStage` makes
3
+ * the Stage that runs a scene for its owner; under `<WardicStage value={stage}>`, `ward`, `createBatch`,
4
+ * `createFrameEffect` and the sensors run in that scene, and `createSceneObject` adds an object to it,
5
+ * with an exit as it leaves. Its hooks are a scene's alone, with none of the page's code (#927):
6
+ * `@wardic/solid`'s own take a mesh too, for a page that has both. Importing it types three's objects as
7
+ * a Stage's Subjects, so `ward(mesh, config)` and `ward(material, config)` typecheck.
8
+ *
9
+ * @example
10
+ * import { createStage, ward, WardicStage } from "@wardic/three/solid"
11
+ *
12
+ * const stage = createStage({ renderer: () => new WebGLRenderer({ antialias: true }), scene, camera })
13
+ * <WardicStage value={stage}>
14
+ * <div class="viewport" ref={stage} />
15
+ * <Crate />
16
+ * </WardicStage>
17
+ *
18
+ * @module
19
+ */
20
+ // #885 (ADR-0073, *Amendment (#885)*): step 4 of #564, Solid 2 only.
21
+ import type {
22
+ AmbientLight,
23
+ BufferGeometry,
24
+ DirectionalLight,
25
+ HemisphereLight,
26
+ Line,
27
+ LineDashedMaterial,
28
+ Material,
29
+ Mesh,
30
+ MeshLambertMaterial,
31
+ MeshMatcapMaterial,
32
+ MeshPhongMaterial,
33
+ MeshPhysicalMaterial,
34
+ MeshToonMaterial,
35
+ Object3D,
36
+ OrthographicCamera,
37
+ PerspectiveCamera,
38
+ Plane,
39
+ PointLight,
40
+ Points,
41
+ PointsMaterial,
42
+ RectAreaLight,
43
+ SpotLight,
44
+ Sprite,
45
+ } from "three"
46
+ import type { ColourKey, SceneKey } from "./WardicThree.ts"
47
+
48
+ /**
49
+ * The Subjects whose keys a scene's ward takes: a mesh of each of three's materials (the physical one's
50
+ * keys hold the standard's), points, a dashed line, a sprite, the cameras and the lights. A union of
51
+ * meshes, not a mesh of a union of materials, whose keys would be the materials' common ones alone.
52
+ */
53
+ type SceneSubject =
54
+ | Mesh<BufferGeometry, MeshPhysicalMaterial>
55
+ | Mesh<BufferGeometry, MeshPhongMaterial>
56
+ | Mesh<BufferGeometry, MeshLambertMaterial>
57
+ | Mesh<BufferGeometry, MeshToonMaterial>
58
+ | Mesh<BufferGeometry, MeshMatcapMaterial>
59
+ | Points<BufferGeometry, PointsMaterial>
60
+ | Line<BufferGeometry, LineDashedMaterial>
61
+ | Sprite
62
+ | PerspectiveCamera
63
+ | OrthographicCamera
64
+ | AmbientLight
65
+ | DirectionalLight
66
+ | HemisphereLight
67
+ | PointLight
68
+ | SpotLight
69
+ | RectAreaLight
70
+
71
+ /** Every key three's `animate` takes on them, numbers and colours: what a ward's config on a Stage's Subject can name. */
72
+ type SceneValueKey = SceneKey<SceneSubject> | ColourKey<SceneSubject>
73
+
74
+ /** What a three Subject's keys read as (#939): its own numbers, its vectors' axes and its material's, each a number. A colour animates by its channels, which read as numbers. */
75
+ type SceneReads<S> = { readonly [K in SceneKey<S>]: number }
76
+
77
+ // A scene's hooks alone (#927): `@wardic/solid`'s Stage halves under the hooks' own names, so a scene with
78
+ // no page wards carries none of the page's ward, Batch or gesture Features (57.6 KB gzipped for `ward`).
79
+ export {
80
+ createBatchOnStage as createBatch,
81
+ createDragOnStage as createDrag,
82
+ createFrameEffect,
83
+ createHoverOnStage as createHover,
84
+ createPressOnStage as createPress,
85
+ wardOnStage as ward,
86
+ WardicStage,
87
+ } from "@wardic/solid"
88
+ export type { StageFeature, StageParts, StageView } from "./solid/feature.ts"
89
+ export { createSceneObject, type SceneObject, type SceneObjectConfig } from "./solid/scene-object.ts"
90
+ export { stageBatches } from "./solid/stage-batches.ts"
91
+ export { stageDrag } from "./solid/stage-drag.ts"
92
+ export { type AdoptOptions, createStage, isThreeSubject, type RendererLike, type StageOptions, type ThreeStage } from "./solid/stage.ts"
93
+ export * as TestStage from "./solid/test-stage.ts"
94
+
95
+ // A Stage's Subjects, for `ward`'s types: three's objects and materials (Q2), and their values (#934); and its
96
+ // drag's plane (#885's PR 4).
97
+ declare module "@wardic/solid" {
98
+ interface StageSubjects {
99
+ readonly three: Object3D | Material
100
+ }
101
+ // Their values beyond an element's (#934): a material's `roughness`, a light's `intensity`, a camera's `fov`.
102
+ interface StageValues extends Record<SceneValueKey, unknown> {}
103
+ // What each of a Subject's keys reads as (#939), so a ward's `read` gives a mesh's `y` or a light's `intensity` as a number.
104
+ interface StageReads<S> {
105
+ readonly three: SceneReads<S>
106
+ }
107
+ interface StageDragConfig {
108
+ /** A fixed plane, in world space, to drag on: the ground's, `new Plane(new Vector3(0, 1, 0), 0)`. */
109
+ readonly dragPlane?: Plane | undefined
110
+ }
111
+ }