packages/core/src/features/physics/2d-testing.ts
This is the source snapshot used to build these API details. View this revision on GitHub.
1 /**
2 * Deterministic test support for public 2D physics compositions.
3 *
4 * The harness drives Pibbl's existing realm scheduler. `advanceFrames()` advances
5 * host frames; a physics world may run zero, one, or several fixed ticks in a
6 * host frame according to its public fixed-step configuration.
7 */
8 import type { PibblController, PibblNode } from "@pibbl/core";
9 import { pibblSync } from "../../sync.js";
10 import {
11 PibblInternalManualSchedulerDriver,
12 pibblInternalInstallTestSchedulerDriver,
13 pibblInternalSnapshotRealmScheduler,
14 } from "@pibbl/core/internal";
15
16 /**
17 * Caller-owned canvas, root factory, and observation callback for deterministic physics testing.
18 *
19 * @see {@link PibblNode}
20 * @see {@link createPhysicsTestHarness2D}
21 */
22 export interface PibblPhysicsTestHarness2DOptions<Observation> {
23 /** The caller owns this canvas; disposing the harness never removes it. */
24 readonly canvas: HTMLCanvasElement;
25 /**
26 * Creates a new public Pibbl root for the initial mount and each reset.
27 * @returns The Pibbl root tree mounted by the test harness. See {@link PibblNode}.
28 */
29 readonly root: () => PibblNode;
30 /**
31 * Reads application state after a frame or action.
32 * @returns The semantic state to expose through the harness's observe method.
33 */
34 readonly observe: () => Observation;
35 }
36
37 /**
38 * A disposable test mount with explicit host-frame advancement and public-state observations.
39 *
40 * @see {@link createPhysicsTestHarness2D}
41 */
42 export interface PibblPhysicsTestHarness2D<Observation> {
43 /** Number of host callbacks currently requested by Pibbl (zero or one). */
44 readonly pendingFrames: number;
45 /**
46 * Delivers one already-requested host frame at the current host time.
47 * @returns Whether a pending frame was flushed.
48 */
49 flush(): boolean;
50 /**
51 * Advances up to `count` requested host frames by `milliseconds` each.
52 * This advances the host clock, not a guaranteed count of physics fixed ticks.
53 * @param count - Number of frames to advance.
54 * @param milliseconds - Duration of each frame in milliseconds.
55 * @returns The number of frames advanced.
56 */
57 advanceFrames(count: number, milliseconds?: number): number;
58 /**
59 * Runs an application action and delivers one resulting frame at the current time.
60 * @param callback - Action to run within the harness's deterministic scheduling context.
61 * @returns The action's return value.
62 */
63 act<Result>(callback: () => Result): Result;
64 /**
65 * Reads the caller-provided public observation without scheduling work.
66 * @returns The current observation from the configured observer.
67 */
68 observe(): Observation;
69 /** Disposes the mounted root and mounts a new one without moving host time backward. */
70 reset(): void;
71 /** Disposes the root and restores the previous realm scheduler driver. */
72 dispose(): void;
73 }
74
75 const DEFAULT_FRAME_MILLISECONDS = 1000 / 60;
76
77 /**
78 * Creates an isolated manual-clock test mount for one Pibbl 2D physics composition.
79 *
80 * It refuses a realm with an existing root because a Pibbl realm deliberately has
81 * one scheduler. Use ordinary browser tests when a test needs multiple roots.
82 *
83 * @param options - Caller-owned canvas, root factory, and semantic state observer. See
84 * {@link PibblPhysicsTestHarness2DOptions} .
85 * @returns A harness owning the test mount and scheduler lifetime; dispose it after use. See
86 * {@link PibblPhysicsTestHarness2D} .
87 *
88 * @see {@link PibblPhysicsTestHarness2DOptions}
89 * @see {@link PibblPhysicsTestHarness2D}
90 */
91 export function createPhysicsTestHarness2D<Observation>(
92 options: PibblPhysicsTestHarness2DOptions<Observation>,
93 ): PibblPhysicsTestHarness2D<Observation> {
94 const before = pibblInternalSnapshotRealmScheduler();
95 if (before.registeredRoots !== 0) {
96 throw new Error(
97 "createPhysicsTestHarness2D() requires an isolated Pibbl realm; dispose existing Pibbl roots before creating the harness.",
98 );
99 }
100 if (before.phase !== "idle" || before.pendingHostFrames !== 0) {
101 throw new Error(
102 "createPhysicsTestHarness2D() cannot replace the Pibbl clock while realm work is active.",
103 );
104 }
105
106 const driver = new PibblInternalManualSchedulerDriver();
107 let restoreDriver: (() => void) | undefined;
108 let controller: PibblController | undefined;
109 let disposed = false;
110 let hostTime = 0;
111
112 try {
113 restoreDriver = pibblInternalInstallTestSchedulerDriver(driver);
114 controller = mountRoot(options);
115 } catch (error) {
116 try {
117 controller?.dispose();
118 } finally {
119 controller = undefined;
120 restoreSchedulerDriver();
121 }
122 throw error;
123 }
124
125 const requireLive = (): void => {
126 if (disposed) {
127 throw new Error("This Pibbl physics 2D test harness has been disposed.");
128 }
129 };
130 const flush = (): boolean => {
131 requireLive();
132 if (driver.pendingHostFrames === 0) return false;
133 driver.flush(hostTime);
134 return true;
135 };
136
137 return Object.freeze({
138 get pendingFrames(): number {
139 return driver.pendingHostFrames;
140 },
141 flush,
142 advanceFrames(
143 count: number,
144 milliseconds = DEFAULT_FRAME_MILLISECONDS,
145 ): number {
146 requireLive();
147 requireFrameCount(count);
148 requireMilliseconds(milliseconds);
149 let advanced = 0;
150 for (let index = 0; index < count; index++) {
151 if (driver.pendingHostFrames === 0) break;
152 const nextHostTime = hostTime + milliseconds;
153 if (!Number.isFinite(nextHostTime)) {
154 throw new RangeError(
155 "advanceFrames() cannot advance the host clock beyond a finite time.",
156 );
157 }
158 hostTime = nextHostTime;
159 driver.flush(hostTime);
160 advanced++;
161 }
162 return advanced;
163 },
164 act<Result>(callback: () => Result): Result {
165 requireLive();
166 const result = callback();
167 flush();
168 return result;
169 },
170 observe(): Observation {
171 requireLive();
172 return options.observe();
173 },
174 reset(): void {
175 requireLive();
176 const previousController = controller;
177 controller = undefined;
178 try {
179 previousController?.dispose();
180 controller = mountRoot(options);
181 } catch (error) {
182 disposed = true;
183 try {
184 restoreSchedulerDriver();
185 } catch (restoreError) {
186 throw new AggregateError(
187 [error, restoreError],
188 "Pibbl physics 2D test harness reset failed and could not restore the scheduler driver.",
189 { cause: restoreError },
190 );
191 }
192 throw error;
193 }
194 },
195 dispose(): void {
196 if (disposed) return;
197 disposed = true;
198 const currentController = controller;
199 controller = undefined;
200 try {
201 currentController?.dispose();
202 } finally {
203 restoreSchedulerDriver();
204 }
205 },
206 });
207
208 function restoreSchedulerDriver(): void {
209 const restore = restoreDriver;
210 restoreDriver = undefined;
211 restore?.();
212 }
213 }
214
215 function mountRoot<Observation>(
216 options: PibblPhysicsTestHarness2DOptions<Observation>,
217 ): PibblController {
218 return pibblSync(options.canvas, options.root());
219 }
220
221 function requireFrameCount(count: number): void {
222 if (!Number.isSafeInteger(count) || count < 0) {
223 throw new RangeError(
224 "advanceFrames(count) requires a non-negative safe integer.",
225 );
226 }
227 }
228
229 function requireMilliseconds(milliseconds: number): void {
230 if (!Number.isFinite(milliseconds) || milliseconds < 0) {
231 throw new RangeError(
232 "advanceFrames(milliseconds) requires a finite non-negative number.",
233 );
234 }
235 }
236
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.