Skip to content

Commit be14df8

Browse files
committed
refactor(cannon): adjust injectBody
1 parent 908ef39 commit be14df8

File tree

6 files changed

+64
-22
lines changed

6 files changed

+64
-22
lines changed

Diff for: apps/sandbox/src/app/app.component.ts

+15-2
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
1-
import { Component, Type, ViewChild, ViewContainerRef, effect, signal } from '@angular/core';
1+
import { NgIf } from '@angular/common';
2+
import { Component, Type, ViewChild, ViewContainerRef, computed, effect, signal } from '@angular/core';
23
import { extend } from 'angular-three';
34
import { NgtsLoader } from 'angular-three-soba/loaders';
45
import * as THREE from 'three';
56
import { AviatorCanvas } from './aviator/canvas.component';
67
import { BotCanvas } from './bot/canvas.component';
78
import { CannonCanvas } from './cannon/canvas.component';
89
import { SkyDivingCanvas } from './skydiving/canvas.component';
10+
import { gravity, isDebugging } from './states';
911
import { VaporwareCanvas } from './vaporware/canvas.component';
1012

1113
extend(THREE);
@@ -23,12 +25,20 @@ type AvailableCanvas = (typeof availableCanvases)[number];
2325

2426
@Component({
2527
standalone: true,
26-
imports: [NgtsLoader],
28+
imports: [NgtsLoader, NgIf],
2729
selector: 'sandbox-root',
2830
template: `
2931
<ng-container #anchor />
3032
<ngts-loader />
3133
<button class="cycle" (click)="cycleCanvas()">Current canvas: {{ canvas() }}</button>
34+
<ng-container *ngIf="showDebugging()">
35+
<button class="cycle" style="left: 12rem" (click)="isDebugging.toggle()">
36+
Is debugging? {{ isDebugging.isDebugging() }}
37+
</button>
38+
<button class="cycle" style="left: 22rem" (click)="gravity.change()">
39+
{{ gravity.btnText() }}
40+
</button>
41+
</ng-container>
3242
`,
3343
host: {
3444
'[style.--background]': 'background',
@@ -37,6 +47,9 @@ type AvailableCanvas = (typeof availableCanvases)[number];
3747
})
3848
export class AppComponent {
3949
canvas = signal<AvailableCanvas>('cannon');
50+
isDebugging = isDebugging;
51+
gravity = gravity;
52+
showDebugging = computed(() => this.canvas() === 'cannon');
4053

4154
@ViewChild('anchor', { static: true, read: ViewContainerRef }) vcr!: ViewContainerRef;
4255

Diff for: apps/sandbox/src/app/cannon/scene.component.ts

+5-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { NgtArgs } from 'angular-three';
55
import { NgtcPhysics } from 'angular-three-cannon';
66
import { NgtcDebug } from 'angular-three-cannon/debug';
77
import { injectBox, injectPlane } from 'angular-three-cannon/services';
8+
import { gravity, isDebugging } from '../states';
89

910
@Component({
1011
selector: 'app-plane',
@@ -55,8 +56,8 @@ export class Box {
5556
[penumbra]="1"
5657
[castShadow]="true"
5758
/>
58-
<ngtc-physics [gravity]="[0, 0, -25]" [iterations]="10">
59-
<ngtc-debug color="white" [disabled]="true">
59+
<ngtc-physics [gravity]="[0, 0, gravity.gravity()]" [iterations]="10">
60+
<ngtc-debug color="white" [disabled]="!isDebugging.isDebugging()">
6061
<app-plane [position]="[0, 0, -10]" />
6162
<app-plane *ngIf="showPlane()" />
6263
<app-box [position]="[1, 0, 1]" />
@@ -75,6 +76,8 @@ export class Box {
7576
export class CannonScene {
7677
Math = Math;
7778
showPlane = signal(true);
79+
isDebugging = isDebugging;
80+
gravity = gravity;
7881

7982
ngOnInit() {
8083
setTimeout(() => {

Diff for: apps/sandbox/src/app/states.ts

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { computed, signal } from '@angular/core';
2+
3+
export const isDebugging = (() => {
4+
const state = signal(false);
5+
6+
return {
7+
toggle: () => {
8+
state.update((prev) => !prev);
9+
},
10+
isDebugging: state.asReadonly(),
11+
};
12+
})();
13+
14+
export const gravity = (() => {
15+
const state = signal(-20);
16+
17+
return {
18+
change: () => {
19+
state.update((prev) => (prev === -20 ? -10 : -20));
20+
},
21+
gravity: state.asReadonly(),
22+
btnText: computed(() => `Change gravity to ${state() === -20 ? '-10' : '-20'}`),
23+
};
24+
})();

Diff for: libs/cannon/services/src/lib/body.ts

+18-15
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ const quaternionToRotation = (callback: (v: Triplet) => void) => {
9999

100100
let incrementingId = 0;
101101

102-
export function subscribe<T extends SubscriptionName>(
102+
export function createSubscribe<T extends SubscriptionName>(
103103
ref: ElementRef<THREE.Object3D>,
104104
worker: CannonWorkerAPI,
105105
subscriptions: Subscriptions,
@@ -236,14 +236,17 @@ function injectBody<TBodyProps extends BodyProps, TObject extends THREE.Object3D
236236
): NgtcBodyReturn<TObject> {
237237
injector = assertInjector(injectBody, injector);
238238
return runInInjectionContext(injector, () => {
239-
const bodyRef = ref || injectNgtRef<TObject>();
240-
241-
const physicsApi = injectNgtcPhysicsApi();
242-
const debugApi = injectNgtcDebugApi({ optional: true });
243-
244-
const { add: debugAdd, remove: debugRemove } = debugApi || {};
245-
const { refs, subscriptions, scaleOverrides, events, bodies } = physicsApi.get();
246-
const worker = physicsApi.select('worker');
239+
const [bodyRef, physicsApi, debugApi] = [
240+
ref || injectNgtRef<TObject>(),
241+
injectNgtcPhysicsApi(),
242+
injectNgtcDebugApi({ optional: true }),
243+
];
244+
245+
const [
246+
{ add: addToDebug, remove: removeFromDebug },
247+
{ refs, subscriptions, scaleOverrides, events, bodies },
248+
worker,
249+
] = [debugApi || {}, physicsApi.get(), physicsApi.select('worker')];
247250

248251
effect((onCleanup) => {
249252
// register deps
@@ -277,15 +280,15 @@ function injectBody<TBodyProps extends BodyProps, TObject extends THREE.Object3D
277280
object.setMatrixAt(i, temp.matrix);
278281
object.instanceMatrix.needsUpdate = true;
279282
refs[id] = object;
280-
debugAdd?.(id, props, type);
283+
addToDebug?.(id, props, type);
281284
setupCollision(events, props, id);
282285
return { ...props, args: argsFn(props.args) };
283286
})
284287
: uuid.map((id, i) => {
285288
const props = getPropsFn(i);
286289
prepare(object, props);
287290
refs[id] = object;
288-
debugAdd?.(id, props, type);
291+
addToDebug?.(id, props, type);
289292
setupCollision(events, props, id);
290293
return { ...props, args: argsFn(props.args) };
291294
});
@@ -302,7 +305,7 @@ function injectBody<TBodyProps extends BodyProps, TObject extends THREE.Object3D
302305
onCleanup(() => {
303306
uuid.forEach((id) => {
304307
delete refs[id];
305-
debugRemove?.(id);
308+
removeFromDebug?.(id);
306309
delete events[id];
307310
});
308311
currentWorker.removeBodies({ uuid });
@@ -322,7 +325,7 @@ function injectBody<TBodyProps extends BodyProps, TObject extends THREE.Object3D
322325
uuid,
323326
} as never);
324327
},
325-
subscribe: subscribe(bodyRef, worker(), subscriptions, type, index),
328+
subscribe: createSubscribe(bodyRef, worker(), subscriptions, type, index),
326329
};
327330
};
328331

@@ -337,7 +340,7 @@ function injectBody<TBodyProps extends BodyProps, TObject extends THREE.Object3D
337340
const uuid = getUUID(bodyRef, index);
338341
uuid && bodies[uuid] != null && worker().setQuaternion({ props: [x, y, z, w], uuid });
339342
},
340-
subscribe: subscribe(bodyRef, worker(), subscriptions, type, index),
343+
subscribe: createSubscribe(bodyRef, worker(), subscriptions, type, index),
341344
};
342345
};
343346

@@ -378,7 +381,7 @@ function injectBody<TBodyProps extends BodyProps, TObject extends THREE.Object3D
378381
const uuid = getUUID(bodyRef, index);
379382
uuid && bodies[uuid] != null && worker()[op]({ props: [x, y, z], uuid });
380383
},
381-
subscribe: subscribe(bodyRef, worker(), subscriptions, type, index),
384+
subscribe: createSubscribe(bodyRef, worker(), subscriptions, type, index),
382385
};
383386
};
384387

Diff for: libs/cannon/services/src/lib/raycast-vehicle.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { injectNgtRef, type NgtAnyRecord, type NgtInjectedRef } from 'angular-th
44
import { injectNgtcPhysicsApi } from 'angular-three-cannon';
55
import { assertInjector } from 'ngxtension/assert-injector';
66
import * as THREE from 'three';
7-
import { getUUID, subscribe } from './body';
7+
import { createSubscribe, getUUID } from './body';
88

99
function isString(v: unknown): v is string {
1010
return typeof v === 'string';
@@ -101,7 +101,7 @@ export function injectRaycastVehicle<TObject extends THREE.Object3D = THREE.Obje
101101
});
102102
},
103103
sliding: {
104-
subscribe: subscribe(instanceRef, worker(), subscriptions, 'sliding', undefined, 'vehicles'),
104+
subscribe: createSubscribe(instanceRef, worker(), subscriptions, 'sliding', undefined, 'vehicles'),
105105
},
106106

107107
remove: () => {

Diff for: nx.json

-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
{
2-
"$schema": "./node_modules/nx/schemas/nx-schema.json",
32
"tasksRunnerOptions": {
43
"default": {
54
"runner": "nx/tasks-runners/default",

0 commit comments

Comments
 (0)