solved few bugs in agv

This commit is contained in:
2025-04-04 09:46:18 +05:30
parent 1dc04d19bb
commit 37f912a6f1
4 changed files with 130 additions and 58 deletions

View File

@@ -3,30 +3,38 @@ 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 { useTh } from "leva/dist/declarations/src/styles";
import { useActiveTool } from "../../../store/store";
import { usePlayButtonStore } from "../../../store/usePlayButtonStore";
// Define interface for props
interface PathNavigatorProps {
navMesh: any;
selectedPoints: any;
id: string;
speed: number;
bufferTime: number;
}
export default function PathNavigator({
navMesh,
selectedPoints,
id,
speed,
bufferTime,
}: 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 { activeTool } = useActiveTool();
const { isPlaying, setIsPlaying } = usePlayButtonStore();
const [startPoint, setStartPoint] = useState(new THREE.Vector3());
const meshRef = useRef<THREE.Mesh | null>(null);
const isWaiting = useRef<boolean>(false); // Flag to track waiting state
const delayTime = bufferTime;
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;
@@ -39,19 +47,17 @@ export default function PathNavigator({
distances.push(segmentDistance);
totalDistance += segmentDistance;
}
distancesRef.current = distances;
totalDistanceRef.current = totalDistance;
progressRef.current = 0; // Reset progress when the path changes
progressRef.current = 0;
}, [path]);
useEffect(() => {
if (!navMesh || selectedPoints.length === 0) return;
// Flatten the selectedPoints array into a single list of points
const allPoints = selectedPoints.flat();
// Compute paths between consecutive points
const computedPath: [number, number, number][] = [];
for (let i = 0; i < allPoints.length - 1; i++) {
const start = allPoints[i];
setStartPoint(
@@ -64,36 +70,35 @@ export default function PathNavigator({
const navMeshQuery = new NavMeshQuery(navMesh);
const { path: segmentPath } = navMeshQuery.computePath(start, end);
if (segmentPath && segmentPath.length > 0) {
computedPath.push(
...segmentPath.map(({ x, y, z }): [number, number, number] => [
x,
y + 0.1,
z,
])
);
if (!segmentPath || segmentPath.length === 0) {
continue;
}
computedPath.push(
...segmentPath.map(({ x, y, z }): [number, number, number] => [
x,
y + 0.1,
z,
])
);
} catch (error) {}
}
// Set the full computed path
if (computedPath.length > 0) {
setPath(computedPath);
currentSegmentIndex.current = 0; // Reset to the first segment
currentSegmentIndex.current = 0;
}
}, [selectedPoints, navMesh, path]);
}, [selectedPoints, navMesh]);
useFrame((_, delta) => {
if (!scene || !id || path.length < 2) return;
// Find the object in the scene
// Find the object in the scene by its UUID
const findObject = scene.getObjectByProperty("uuid", id);
if (activeTool === "play") {
if (!findObject) return;
if (!findObject) return;
const speed = 5;
progressRef.current += delta * speed;
if (isPlaying) {
const fast = speed;
progressRef.current += delta * fast;
let coveredDistance = progressRef.current;
let accumulatedDistance = 0;
@@ -108,9 +113,24 @@ export default function PathNavigator({
index++;
}
// If the object has reached the end of the path, stop moving
if (index >= distancesRef.current.length) {
progressRef.current = totalDistanceRef.current;
if (!isWaiting.current) {
isWaiting.current = true; // Set waiting flag
setTimeout(() => {
progressRef.current = 0; // Reset progress
movingForward.current = !movingForward.current; // Toggle direction
// Reverse the path and distances arrays
path.reverse();
distancesRef.current.reverse();
// Reset the waiting flag
isWaiting.current = false;
}, delayTime * 1000); // Convert seconds to milliseconds
}
return;
}
@@ -119,31 +139,35 @@ export default function PathNavigator({
const end = new THREE.Vector3(...path[index + 1]);
const segmentDistance = distancesRef.current[index];
const t = (coveredDistance - accumulatedDistance) / segmentDistance;
const t = Math.min(
(coveredDistance - accumulatedDistance) / segmentDistance,
1
); // Clamp t to avoid overshooting
const position = start.clone().lerp(end, t);
findObject.position.copy(position);
// Rotate the object to face the direction of movement
const direction = new THREE.Vector3().subVectors(end, start).normalize();
const targetQuaternion = new THREE.Quaternion().setFromUnitVectors(
new THREE.Vector3(0, 0, 1), // Assuming forward direction is (0, 0, 1)
direction
);
findObject.quaternion.slerp(targetQuaternion, 0.1); // Smoothly interpolate rotation
} else if (activeTool === "cursor") {
findObject?.position.copy(startPoint);
const targetYRotation = Math.atan2(direction.x, direction.z);
findObject.rotation.y += (targetYRotation - findObject.rotation.y) * 0.1;
} else {
findObject.position.copy(startPoint);
}
});
return (
<>
{path.length > 0 && <Line points={path} color="blue" lineWidth={3} />}
{/* {path.length > 0 && (
<mesh ref={meshRef} position={path.length > 0 ? path[0] : [0, 0.1, 0]}>
<boxGeometry args={[1, 1, 1]} />
<meshNormalMaterial />
</mesh>
)} */}
{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>
))}
</>
)}
</>
);
}