|
| 1 | +import { Injector, Signal, computed, effect, inject, runInInjectionContext, untracked } from '@angular/core'; |
| 2 | +import { SpringOptns } from '@pmndrs/cannon-worker-api'; |
| 3 | +import { NgtAnyRecord, NgtInjectedRef, assertInjectionContext, injectNgtRef, is, makeId } from 'angular-three'; |
| 4 | +import { NGTC_PHYSICS_API } from 'angular-three-cannon'; |
| 5 | + |
| 6 | +export interface NgtcSpringApi { |
| 7 | + setDamping: (value: number) => void; |
| 8 | + setRestLength: (value: number) => void; |
| 9 | + setStiffness: (value: number) => void; |
| 10 | + remove: () => void; |
| 11 | +} |
| 12 | + |
| 13 | +export interface NgtcSpringReturn< |
| 14 | + TObjectA extends THREE.Object3D = THREE.Object3D, |
| 15 | + TObjectB extends THREE.Object3D = THREE.Object3D |
| 16 | +> { |
| 17 | + bodyA: NgtInjectedRef<TObjectA>; |
| 18 | + bodyB: NgtInjectedRef<TObjectB>; |
| 19 | + api: Signal<NgtcSpringApi>; |
| 20 | +} |
| 21 | + |
| 22 | +export function injectSpring<A extends THREE.Object3D, B extends THREE.Object3D>( |
| 23 | + bodyA: NgtInjectedRef<A> | A, |
| 24 | + bodyB: NgtInjectedRef<B> | B, |
| 25 | + { |
| 26 | + injector, |
| 27 | + opts = () => ({}), |
| 28 | + deps = () => ({}), |
| 29 | + }: { injector?: Injector; deps?: () => NgtAnyRecord; opts?: () => SpringOptns } = {} |
| 30 | +): NgtcSpringReturn<A, B> { |
| 31 | + injector = assertInjectionContext(injectSpring, injector); |
| 32 | + return runInInjectionContext(injector, () => { |
| 33 | + const physicsApi = inject(NGTC_PHYSICS_API); |
| 34 | + const { worker } = physicsApi(); |
| 35 | + |
| 36 | + const uuid = makeId(); |
| 37 | + |
| 38 | + const bodyARef = is.ref(bodyA) ? bodyA : injectNgtRef(bodyA); |
| 39 | + const bodyBRef = is.ref(bodyB) ? bodyB : injectNgtRef(bodyB); |
| 40 | + |
| 41 | + effect((onCleanup) => { |
| 42 | + deps(); |
| 43 | + if (bodyARef.nativeElement && bodyBRef.nativeElement) { |
| 44 | + worker.addSpring({ |
| 45 | + props: [bodyARef.nativeElement.uuid, bodyBRef.nativeElement.uuid, untracked(opts)], |
| 46 | + uuid, |
| 47 | + }); |
| 48 | + onCleanup(() => worker.removeSpring({ uuid })); |
| 49 | + } |
| 50 | + }); |
| 51 | + |
| 52 | + const api = computed(() => { |
| 53 | + deps(); |
| 54 | + return { |
| 55 | + setDamping: (value: number) => worker.setSpringDamping({ props: value, uuid }), |
| 56 | + setRestLength: (value: number) => worker.setSpringRestLength({ props: value, uuid }), |
| 57 | + setStiffness: (value: number) => worker.setSpringStiffness({ props: value, uuid }), |
| 58 | + remove: () => worker.removeSpring({ uuid }), |
| 59 | + }; |
| 60 | + }); |
| 61 | + |
| 62 | + return { bodyA: bodyARef, bodyB: bodyBRef, api }; |
| 63 | + }); |
| 64 | +} |
0 commit comments