Skip to content

packages/core/src/features/physics/lib/2d/canvas/components.ts

Read as Markdown

This is the source snapshot used to build these API details. View this revision on GitHub.

Back to reference

1 import { resolveTexturePaint } from '@pibbl/core/internal';
2 import type { FillStyle, StrokeStyle } from '@pibbl/core';
3 import {
4   useEventTarget,
5   definePrimitive,
6   type RenderingContext2D,
7 } from '@pibbl/core';
8 import type {
9   Capsule2DProps,
10   Capsule2DStyle,
11   Chain2DProps,
12   Chain2DStyle,
13   PhysicsShape2DProps,
14   PhysicsShape2DStyle,
15   Segment2DProps,
16   Segment2DStyle,
17 } from '../types.js';
18 import type { PibblPhysicsShape2D, PibblPhysicsVector2 } from '../../../2d-geometry.js';
19 import { boundsOfShape2D, capsuleShape2D, chainShape2D, segmentShape2D } from '../shapes.js';
20 import { requireShapeRecord2D, type ConvexLeaf2D } from '../shape-records.js';
21 import { installCustomShapeResolver2D } from './inference.js';
22 const layoutPropertyKeys = [
23     'width', 'height', 'minWidth', 'maxWidth', 'minHeight', 'maxHeight', 'padding', 'overflow',
24     'left', 'top', 'alignSelf', 'justifySelf', 'flexBasis', 'flexGrow', 'flexShrink',
25     'gridColumnStart', 'gridColumnSpan', 'gridRowStart', 'gridRowSpan',
26   ] as const;
27 
28 type LayoutProperty = typeof layoutPropertyKeys[number];
29 type ResolvedPhysicsShapeStyle2D = Omit<Readonly<PhysicsShape2DStyle>, LayoutProperty>;
30 type ResolvedCapsuleStyle2D = Omit<Readonly<Capsule2DStyle>, 'start' | 'end' | LayoutProperty> & {
31   readonly start: PibblPhysicsVector2;
32   readonly end: PibblPhysicsVector2;
33 };
34 type ResolvedSegmentStyle2D = Omit<Readonly<Segment2DStyle>, 'start' | 'end' | LayoutProperty> & {
35   readonly start: PibblPhysicsVector2;
36   readonly end: PibblPhysicsVector2;
37 };
38 type ResolvedChainStyle2D = Omit<Readonly<Chain2DStyle>, 'points' | LayoutProperty> & {
39   readonly points: readonly PibblPhysicsVector2[];
40 };
41 
42 function renderPhysicsShape2D(
43   props: PhysicsShape2DProps,
44   style: ResolvedPhysicsShapeStyle2D,
45   context: RenderingContext2D,
46 ): void {
47   renderShape(props, style, style.shape, context);
48 }
49 
50 function renderCapsule2D(
51   props: Capsule2DProps,
52   style: Readonly<ResolvedCapsuleStyle2D>,
53   context: RenderingContext2D,
54 ): void {
55   renderShape(props, style, capsuleShape2D(style), context);
56 }
57 
58 function renderSegment2D(
59   props: Segment2DProps,
60   style: Readonly<ResolvedSegmentStyle2D>,
61   context: RenderingContext2D,
62 ): void {
63   renderShape(props, style, segmentShape2D(style), context);
64 }
65 
66 function renderChain2D(
67   props: Chain2DProps,
68   style: Readonly<ResolvedChainStyle2D>,
69   context: RenderingContext2D,
70 ): void {
71   renderShape(props, style, chainShape2D(style), context);
72 }
73 
74 /**
75  * Draws an immutable physics shape as a Canvas primitive with optional body or collider
76  * attachment.
77  *
78  * @param props - Authored component inputs, supplied through JSX or createElement. See the linked
79  * props and style types.
80  * @throws When called directly; Pibbl mounts this component through JSX or createElement.
81  *
82  * @see {@link PhysicsShape2DProps}
83  * @see {@link PhysicsShape2DStyle}
84  */
85 export const PhysicsShape2D = definePrimitive<
86   PhysicsShape2DProps,
87   PhysicsShape2DStyle,
88   PhysicsShape2DStyle,
89   ResolvedPhysicsShapeStyle2D
90 >(renderPhysicsShape2D, { resolveStyle: resolvePhysicsShapeStyle });
91 
92 /**
93  * Draws a capsule between two endpoints with optional physics attachment.
94  *
95  * @param props - Authored component inputs, supplied through JSX or createElement. See the linked
96  * props and style types.
97  * @throws When called directly; Pibbl mounts this component through JSX or createElement.
98  *
99  * @see {@link Capsule2DProps}
100  * @see {@link Capsule2DStyle}
101  */
102 export const Capsule2D = definePrimitive<
103   Capsule2DProps,
104   Capsule2DStyle,
105   Capsule2DStyle,
106   ResolvedCapsuleStyle2D
107 >(renderCapsule2D, { resolveStyle: style => ({
108   ...stripLayout(style),
109   start: copyPoint(style.start, 'Capsule2D.start'),
110   end: copyPoint(style.end, 'Capsule2D.end'),
111   radius: positive(style.radius, 'Capsule2D.radius'),
112 }) });
113 
114 /**
115  * Draws a line segment with optional physics attachment.
116  *
117  * @param props - Authored component inputs, supplied through JSX or createElement. See the linked
118  * props and style types.
119  * @throws When called directly; Pibbl mounts this component through JSX or createElement.
120  *
121  * @see {@link Segment2DProps}
122  * @see {@link Segment2DStyle}
123  */
124 export const Segment2D = definePrimitive<
125   Segment2DProps,
126   Segment2DStyle,
127   Segment2DStyle,
128   ResolvedSegmentStyle2D
129 >(renderSegment2D, { resolveStyle: style => ({
130   ...stripLayout(style),
131   start: copyPoint(style.start, 'Segment2D.start'),
132   end: copyPoint(style.end, 'Segment2D.end'),
133 }) });
134 
135 /**
136  * Draws an open or closed point chain with optional physics attachment.
137  *
138  * @param props - Authored component inputs, supplied through JSX or createElement. See the linked
139  * props and style types.
140  * @throws When called directly; Pibbl mounts this component through JSX or createElement.
141  *
142  * @see {@link Chain2DProps}
143  * @see {@link Chain2DStyle}
144  */
145 export const Chain2D = definePrimitive<
146   Chain2DProps,
147   Chain2DStyle,
148   Chain2DStyle,
149   ResolvedChainStyle2D
150 >(renderChain2D, { resolveStyle: style => ({
151   ...stripLayout(style),
152   points: Object.freeze(style.points.map((point, index) => copyPoint(point, `Chain2D.points[${index}]`))),
153   closed: style.closed ?? false,
154   radius: nonnegative(style.radius ?? 0, 'Chain2D.radius'),
155 }) });
156 
157 installCustomShapeResolver2D(PhysicsShape2D, style => requireShape(style.shape, 'PhysicsShape2D.shape'));
158 installCustomShapeResolver2D(Capsule2D, style => capsuleShape2D({
159   start: copyPoint(style.start, 'Capsule2D.start'),
160   end: copyPoint(style.end, 'Capsule2D.end'),
161   radius: positive(style.radius, 'Capsule2D.radius'),
162 }));
163 installCustomShapeResolver2D(Segment2D, style => segmentShape2D({
164   start: copyPoint(style.start, 'Segment2D.start'),
165   end: copyPoint(style.end, 'Segment2D.end'),
166 }));
167 installCustomShapeResolver2D(Chain2D, style => chainShape2D({
168   points: copyPoints(style.points, 'Chain2D.points'),
169   closed: style.closed === true,
170   radius: nonnegative(style.radius ?? 0, 'Chain2D.radius'),
171 }));
172 
173 function resolvePhysicsShapeStyle(style: Readonly<PhysicsShape2DStyle>): ResolvedPhysicsShapeStyle2D {
174   requireShape(style.shape, 'PhysicsShape2D.shape');
175   return stripLayout(style) as ResolvedPhysicsShapeStyle2D;
176 }
177 
178 function renderShape(
179   props: PhysicsShape2DProps,
180   style: Readonly<{
181     readonly fill?: FillStyle;
182     readonly stroke?: StrokeStyle;
183     readonly strokeWidth?: number;
184     readonly opacity?: number;
185     readonly cursor?: string;
186     readonly lineInteractionWidth?: number;
187   }>,
188   shape: PibblPhysicsShape2D,
189   context: RenderingContext2D,
190 ): void {
191   const record = requireShapeRecord2D(shape);
192   const path = pathForShape(shape);
193   const opacity = style.opacity ?? 1;
194   if (!Number.isFinite(opacity) || opacity < 0 || opacity > 1) {
195     throw new RangeError('Physics shape opacity must be finite from zero through one.');
196   }
197   const bounds = boundsOfShape2D(shape);
198   const paintBounds = {x: bounds.min[0], y: bounds.min[1], width: bounds.max[0]-bounds.min[0], height: bounds.max[1]-bounds.min[1]};
199   context.globalAlpha *= opacity;
200   if (style.fill !== undefined) {
201     context.fillStyle = resolveTexturePaint(style.fill, context, paintBounds);
202     context.fill(path);
203   }
204   const strokeWidth = nonnegative(style.strokeWidth ?? 0, 'Physics shape strokeWidth');
205   if (style.stroke !== undefined && strokeWidth > 0) {
206     context.strokeStyle = resolveTexturePaint(style.stroke, context, paintBounds);
207     context.lineWidth = strokeWidth;
208     context.stroke(path);
209   }
210   const interactivePath = props.pointerEvents === 'none' ? new Path2D() : path;
211   useEventTarget(props, {
212     path: interactivePath,
213     fill: style.fill !== undefined && record.area > 0,
214     lineInteractionWidth: style.lineInteractionWidth ?? strokeWidth,
215     cursor: style.cursor,
216     keyboardFocusable: props.keyboardFocusable,
217     keyboardNavigationBounds: props.keyboardNavigationBounds ?? {
218       x: bounds.min[0], y: bounds.min[1],
219       width: bounds.max[0] - bounds.min[0], height: bounds.max[1] - bounds.min[1],
220     },
221   });
222 }
223 
224 function pathForShape(shape: PibblPhysicsShape2D): Path2D {
225   const record = requireShapeRecord2D(shape);
226   const local = new Path2D();
227   for (const leaf of record.leaves) appendLeaf(local, leaf);
228   if (record.localPose.x === 0 && record.localPose.y === 0 && record.localPose.rotationRadians === 0) return local;
229   const result = new Path2D();
230   result.addPath(local, new DOMMatrix()
231     .translate(record.localPose.x, record.localPose.y)
232     .rotate(record.localPose.rotationRadians * 180 / Math.PI));
233   return result;
234 }
235 
236 function appendLeaf(path: Path2D, leaf: ConvexLeaf2D): void {
237   switch (leaf.kind) {
238     case 'circle':
239       path.moveTo(leaf.center[0]! + leaf.radius, leaf.center[1]!);
240       path.arc(leaf.center[0]!, leaf.center[1]!, leaf.radius, 0, Math.PI * 2);
241       path.closePath();
242       return;
243     case 'ellipse':
244       path.moveTo(leaf.center[0]! + leaf.radiusX, leaf.center[1]!);
245       path.ellipse(leaf.center[0]!, leaf.center[1]!, leaf.radiusX, leaf.radiusY, leaf.rotationRadians, 0, Math.PI * 2);
246       path.closePath();
247       return;
248     case 'box':
249       path.rect(leaf.center[0]! - leaf.halfWidth, leaf.center[1]! - leaf.halfHeight, leaf.halfWidth * 2, leaf.halfHeight * 2);
250       return;
251     case 'rounded-box':
252       path.roundRect(
253         leaf.center[0]! - leaf.halfWidth,
254         leaf.center[1]! - leaf.halfHeight,
255         leaf.halfWidth * 2,
256         leaf.halfHeight * 2,
257         Array.from(leaf.radii),
258       );
259       return;
260     case 'capsule':
261       appendCapsule(path, leaf.start, leaf.end, leaf.radius);
262       return;
263     case 'segment':
264       path.moveTo(leaf.start[0]!, leaf.start[1]!);
265       path.lineTo(leaf.end[0]!, leaf.end[1]!);
266       return;
267     case 'polygon':
268       path.moveTo(leaf.vertices[0]!, leaf.vertices[1]!);
269       for (let index = 2; index < leaf.vertices.length; index += 2) path.lineTo(leaf.vertices[index]!, leaf.vertices[index + 1]!);
270       path.closePath();
271   }
272 }
273 
274 function appendCapsule(path: Path2D, start: Float64Array, end: Float64Array, radius: number): void {
275   const dx = end[0]! - start[0]!, dy = end[1]! - start[1]!, length = Math.hypot(dx, dy);
276   if (length === 0) {
277     path.moveTo(start[0]! + radius, start[1]!);
278     path.arc(start[0]!, start[1]!, radius, 0, Math.PI * 2);
279     path.closePath();
280     return;
281   }
282   const normal = Math.atan2(dy, dx) - Math.PI / 2;
283   path.moveTo(start[0]! + Math.cos(normal) * radius, start[1]! + Math.sin(normal) * radius);
284   path.lineTo(end[0]! + Math.cos(normal) * radius, end[1]! + Math.sin(normal) * radius);
285   path.arc(end[0]!, end[1]!, radius, normal, normal + Math.PI);
286   path.lineTo(start[0]! - Math.cos(normal) * radius, start[1]! - Math.sin(normal) * radius);
287   path.arc(start[0]!, start[1]!, radius, normal + Math.PI, normal + Math.PI * 2);
288   path.closePath();
289 }
290 
291 function stripLayout<T extends Readonly<Record<PropertyKey, unknown>>>(style: T): T {
292   const result = { ...style } as Record<PropertyKey, unknown>;
293   for (let keyIndex = 0; keyIndex < layoutPropertyKeys.length; keyIndex++) {
294     const key = layoutPropertyKeys[keyIndex];
295     delete result[key];
296   }
297   return result as T;
298 }
299 
300 function copyPoints(value: unknown, path: string): readonly PibblPhysicsVector2[] {
301   if (!Array.isArray(value)) throw new TypeError(`${path} must be an array.`);
302   return Object.freeze(value.map((point, index) => copyPoint(point, `${path}[${index}]`)));
303 }
304 
305 function copyPoint(value: unknown, path: string): PibblPhysicsVector2 {
306   if (!Array.isArray(value) || value.length !== 2 || value.some(entry => typeof entry !== 'number' || !Number.isFinite(entry))) {
307     throw new TypeError(`${path} must be a finite two-dimensional point.`);
308   }
309   return Object.freeze([value[0] as number, value[1] as number] as const);
310 }
311 
312 function positive(value: unknown, path: string): number {
313   if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) throw new RangeError(`${path} must be finite and greater than zero.`);
314   return value;
315 }
316 
317 function nonnegative(value: unknown, path: string): number {
318   if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) throw new RangeError(`${path} must be finite and nonnegative.`);
319   return value;
320 }
321 
322 function requireShape(value: unknown, path: string): PibblPhysicsShape2D {
323   try {
324     requireShapeRecord2D(value as PibblPhysicsShape2D);
325     return value as PibblPhysicsShape2D;
326   } catch {
327     throw new TypeError(`${path} must be a Pibbl physics 2D shape.`);
328   }
329 }
330 

Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.