11import { useFrame , useThree } from "@react-three/fiber"
22import type { DHParameter , MotionGroupState } from "@wandelbots/nova-js/v2"
3- import React , { useEffect , useRef } from "react"
3+ import React , { useEffect , useRef , useCallback } from "react"
44import type { Group , Object3D } from "three"
55import { useAutorun } from "../utils/hooks"
66import { ValueInterpolator } from "../utils/interpolation"
@@ -64,11 +64,6 @@ export default function RobotAnimator({
6464 invalidate ( )
6565 }
6666
67- function updateJoints ( newJointValues : number [ ] ) {
68- jointValues . current = newJointValues
69- interpolatorRef . current ?. setTarget ( newJointValues )
70- }
71-
7267 function setRotation ( ) {
7368 const updatedJointValues = interpolatorRef . current ?. getCurrentValues ( ) || [ ]
7469
@@ -86,12 +81,32 @@ export default function RobotAnimator({
8681 }
8782 }
8883
89- useAutorun ( ( ) => {
84+ const updateJoints = useCallback ( ( ) => {
9085 const newJointValues = rapidlyChangingMotionState . joint_position . filter (
9186 ( item ) => item !== undefined ,
9287 )
9388
94- requestAnimationFrame ( ( ) => updateJoints ( newJointValues ) )
89+ requestAnimationFrame ( ( ) => {
90+ jointValues . current = newJointValues
91+ interpolatorRef . current ?. setTarget ( newJointValues )
92+ } )
93+ } , [ rapidlyChangingMotionState ] )
94+
95+ /**
96+ * Fire an update joints call on every motion state change.
97+ * requestAnimationFrame used to avoid blocking main thread
98+ */
99+ useEffect ( ( ) => {
100+ updateJoints ( )
101+ } , [ rapidlyChangingMotionState , updateJoints ] )
102+
103+ /**
104+ * As some consumer applications (eg. storybook) deliver
105+ * mobx observable for rapidlyChangingMotionState, we need to
106+ * register the watcher to get the newest value updates
107+ */
108+ useAutorun ( ( ) => {
109+ updateJoints ( )
95110 } )
96111
97112 return < group ref = { setGroupRef } > { children } </ group >
0 commit comments