Refactor AGV and PathNavigator components; add NavMeshCreator for improved navigation handling and added backend event storage for connections

This commit is contained in:
2025-04-05 12:25:29 +05:30
parent e92345d820
commit 34aea0ecf1
9 changed files with 305 additions and 202 deletions

View File

@@ -3,179 +3,207 @@ import * as THREE from "three";
import { useFrame, useThree } from "@react-three/fiber";
import { NavMeshQuery } from "@recast-navigation/core";
import { Line } from "@react-three/drei";
import { useActiveTool } from "../../../store/store";
import { usePlayButtonStore } from "../../../store/usePlayButtonStore";
interface PathNavigatorProps {
navMesh: any;
selectedPoints: any;
id: string;
speed: number;
bufferTime: number;
hitCount: number;
navMesh: any;
pathPoints: any;
id: string;
speed: number;
bufferTime: number;
hitCount: number;
}
export default function PathNavigator({
navMesh,
selectedPoints,
id,
speed,
bufferTime,
hitCount,
navMesh,
pathPoints,
id,
speed,
bufferTime,
hitCount
}: PathNavigatorProps) {
const [path, setPath] = useState<[number, number, number][]>([]);
const progressRef = useRef(0);
const distancesRef = useRef<number[]>([]);
const totalDistanceRef = useRef(0);
const currentSegmentIndex = useRef(0);
const [stop, setStop] = useState<boolean>(true);
const { scene } = useThree();
const { isPlaying, setIsPlaying } = usePlayButtonStore();
const [startPoint, setStartPoint] = useState(new THREE.Vector3());
const isWaiting = useRef<boolean>(false); // Flag to track waiting state
const delayTime = bufferTime;
const [path, setPath] = useState<[number, number, number][]>([]);
const [currentPhase, setCurrentPhase] = useState<'initial' | 'loop'>('initial');
const [toPickupPath, setToPickupPath] = useState<[number, number, number][]>([]);
const [pickupDropPath, setPickupDropPath] = useState<[number, number, number][]>([]);
const [dropPickupPath, setDropPickupPath] = useState<[number, number, number][]>([]);
const [initialPosition, setInitialPosition] = useState<THREE.Vector3 | null>(null);
const [initialRotation, setInitialRotation] = useState<THREE.Euler | null>(null);
const movingForward = useRef<boolean>(true); // Tracks whether the object is moving forward
// Compute distances and total distance when the path changes
useEffect(() => {
if (!scene || !id || path.length < 2) return;
const distancesRef = useRef<number[]>([]);
const totalDistanceRef = useRef(0);
const progressRef = useRef(0);
const isWaiting = useRef(false);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
let totalDistance = 0;
const distances: number[] = [];
for (let i = 0; i < path.length - 1; i++) {
const start = new THREE.Vector3(...path[i]);
const end = new THREE.Vector3(...path[i + 1]);
const segmentDistance = start.distanceTo(end);
distances.push(segmentDistance);
totalDistance += segmentDistance;
}
distancesRef.current = distances;
totalDistanceRef.current = totalDistance;
progressRef.current = 0;
}, [path]);
const { scene } = useThree();
const { isPlaying } = usePlayButtonStore();
// Compute the path using NavMeshQuery
useEffect(() => {
if (!navMesh || selectedPoints.length === 0) return;
useEffect(() => {
const object = scene.getObjectByProperty("uuid", id);
if (object) {
setInitialPosition(object.position.clone());
setInitialRotation(object.rotation.clone());
}
}, [scene, id]);
const allPoints = selectedPoints.flat();
const computedPath: [number, number, number][] = [];
const computePath = (start: any, end: any) => {
try {
const navMeshQuery = new NavMeshQuery(navMesh);
const { path: segmentPath } = navMeshQuery.computePath(start, end);
return segmentPath?.map(({ x, y, z }) => [x, y + 0.1, z] as [number, number, number]) || [];
} catch {
return [];
}
};
for (let i = 0; i < allPoints.length - 1; i++) {
const start = allPoints[i];
setStartPoint(
new THREE.Vector3(allPoints[0].x, allPoints[0].y, allPoints[0].z)
);
const resetState = () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
const end = allPoints[i + 1];
setPath([]);
setCurrentPhase('initial');
setPickupDropPath([]);
setDropPickupPath([]);
distancesRef.current = [];
totalDistanceRef.current = 0;
progressRef.current = 0;
isWaiting.current = false;
try {
const navMeshQuery = new NavMeshQuery(navMesh);
const { path: segmentPath } = navMeshQuery.computePath(start, end);
if (initialPosition && initialRotation) {
const object = scene.getObjectByProperty("uuid", id);
if (object) {
object.position.copy(initialPosition);
object.rotation.copy(initialRotation);
}
}
};
if (!segmentPath || segmentPath.length === 0) {
continue;
}
useEffect(() => {
if (!isPlaying) {
resetState();
}
computedPath.push(
...segmentPath.map(({ x, y, z }): [number, number, number] => [
x,
y + 0.1,
z,
])
);
} catch (error) {}
}
if (!navMesh || pathPoints.length < 2) return;
if (computedPath.length > 0) {
setPath(computedPath);
currentSegmentIndex.current = 0;
}
}, [selectedPoints, navMesh]);
useFrame((_, delta) => {
if (!scene || !id || path.length < 2) return;
const [pickup, drop] = pathPoints.slice(-2);
const object = scene.getObjectByProperty("uuid", id);
if (!object) return;
// Find the object in the scene by its UUID
const findObject = scene.getObjectByProperty("uuid", id);
if (!findObject) return;
const currentPosition = { x: object.position.x, y: object.position.y, z: object.position.z };
if (isPlaying) {
const fast = speed;
progressRef.current += delta * fast;
const toPickupPath = computePath(currentPosition, pickup);
const pickupToDropPath = computePath(pickup, drop);
const dropToPickupPath = computePath(drop, pickup);
let coveredDistance = progressRef.current;
let accumulatedDistance = 0;
let index = 0;
if (toPickupPath.length && pickupToDropPath.length && dropToPickupPath.length) {
setPickupDropPath(pickupToDropPath);
setDropPickupPath(dropToPickupPath);
setToPickupPath(toPickupPath);
setPath(toPickupPath);
setCurrentPhase('initial');
}
}, [navMesh, pathPoints, hitCount, isPlaying]);
// Determine the current segment of the path
while (
index < distancesRef.current.length &&
coveredDistance > accumulatedDistance + distancesRef.current[index]
) {
accumulatedDistance += distancesRef.current[index];
index++;
}
useEffect(() => {
if (path.length < 2) return;
if (index >= distancesRef.current.length) {
progressRef.current = totalDistanceRef.current;
let total = 0;
const segmentDistances = path.slice(0, -1).map((point, i) => {
const dist = new THREE.Vector3(...point).distanceTo(new THREE.Vector3(...path[i + 1]));
total += dist;
return dist;
});
if (!isWaiting.current) {
isWaiting.current = true; // Set waiting flag
distancesRef.current = segmentDistances;
totalDistanceRef.current = total;
progressRef.current = 0;
isWaiting.current = false;
}, [path]);
if (movingForward.current) {
// Moving forward: reached the end, wait for `delay`
// console.log(
// "Reached end position. Waiting for delay:",
// delayTime,
// "seconds"
// );
setTimeout(() => {
// After delay, reverse direction
movingForward.current = false;
progressRef.current = 0; // Reset progress
path.reverse(); // Reverse the path
distancesRef.current.reverse();
isWaiting.current = false; // Reset waiting flag
}, delayTime * 1000); // Wait for `delay` seconds
}
}
return;
}
useFrame((_, delta) => {
if (!isPlaying || path.length < 2 || !scene || !id) return;
// Interpolate position within the current segment
const start = new THREE.Vector3(...path[index]);
const end = new THREE.Vector3(...path[index + 1]);
const segmentDistance = distancesRef.current[index];
const object = scene.getObjectByProperty("uuid", id);
if (!object) return;
const t = Math.min(
(coveredDistance - accumulatedDistance) / segmentDistance,
1
); // Clamp t to avoid overshooting
const position = start.clone().lerp(end, t);
findObject.position.copy(position);
const speedFactor = speed;
progressRef.current += delta * speedFactor;
// Rotate the object to face the direction of movement
const direction = new THREE.Vector3().subVectors(end, start).normalize();
const targetYRotation = Math.atan2(direction.x, direction.z);
findObject.rotation.y += (targetYRotation - findObject.rotation.y) * 0.1;
} else {
findObject.position.copy(startPoint);
}
});
let covered = progressRef.current;
let accumulated = 0;
let index = 0;
return (
<>
{path.length > 0 && (
<>
<Line points={path} color="blue" lineWidth={3} />
{selectedPoints.map((val: any, i: any) => (
<mesh position={[val[0], val[1] + 1, val[2]]} key={i}>
<sphereGeometry args={[50, 5, 5]} />
<meshBasicMaterial color={"red"} />
</mesh>
))}
</>
)}
</>
);
}
while (
index < distancesRef.current.length &&
covered > accumulated + distancesRef.current[index]
) {
accumulated += distancesRef.current[index];
index++;
}
if (index >= distancesRef.current.length) {
progressRef.current = totalDistanceRef.current;
if (!isWaiting.current) {
isWaiting.current = true;
timeoutRef.current = setTimeout(() => {
if (currentPhase === 'initial') {
setPath(pickupDropPath);
setCurrentPhase('loop');
} else {
setPath(prevPath =>
prevPath === pickupDropPath ? dropPickupPath : pickupDropPath
);
}
progressRef.current = 0;
isWaiting.current = false;
}, bufferTime * 1000);
}
return;
}
const start = new THREE.Vector3(...path[index]);
const end = new THREE.Vector3(...path[index + 1]);
const dist = distancesRef.current[index];
const t = THREE.MathUtils.clamp((covered - accumulated) / dist, 0, 1);
const position = start.clone().lerp(end, t);
object.position.copy(position);
const direction = new THREE.Vector3().subVectors(end, start).normalize();
const targetRotationY = Math.atan2(direction.x, direction.z);
let angleDifference = targetRotationY - object.rotation.y;
angleDifference = ((angleDifference + Math.PI) % (Math.PI * 2)) - Math.PI;
object.rotation.y += angleDifference * 0.1;
});
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
return (
<group name="path-navigator-lines" visible={!isPlaying} >
{toPickupPath.length > 0 && (
<Line points={toPickupPath} color="blue" lineWidth={3} dashed dashSize={0.75} dashScale={2} />
)}
{pickupDropPath.length > 0 && (
<Line points={pickupDropPath} color="red" lineWidth={3} />
)}
{dropPickupPath.length > 0 && (
<Line points={dropPickupPath} color="red" lineWidth={3} />
)}
</group>
);
}