"updated Animation"

This commit is contained in:
SreeNath14
2025-04-10 10:21:24 +05:30
parent 1eec500955
commit e48195db98
15 changed files with 1609 additions and 1169 deletions

View File

@@ -1,68 +1,107 @@
import { useEffect, useState } from "react";
import { Line } from "@react-three/drei";
import { useNavMesh, useSimulationStates } from "../../../store/store";
import {
useNavMesh,
usePlayAgv,
useSimulationStates,
} from "../../../store/store";
import PathNavigator from "./pathNavigator";
import { usePlayButtonStore } from "../../../store/usePlayButtonStore";
type PathPoints = {
modelUuid: string;
modelSpeed: number;
bufferTime: number;
points: { x: number; y: number; z: number }[];
hitCount: number;
modelUuid: string;
modelSpeed: number;
bufferTime: number;
points: { x: number; y: number; z: number }[];
hitCount: number;
};
interface ProcessContainerProps {
processes: any[];
agvRef: any;
}
const Agv = () => {
const [pathPoints, setPathPoints] = useState<PathPoints[]>([]);
const { simulationStates } = useSimulationStates();
const { navMesh } = useNavMesh();
const { isPlaying } = usePlayButtonStore();
const Agv: React.FC<ProcessContainerProps> = ({ processes, agvRef }) => {
const [pathPoints, setPathPoints] = useState<PathPoints[]>([]);
const { simulationStates } = useSimulationStates();
const { navMesh } = useNavMesh();
const { isPlaying } = usePlayButtonStore();
const { PlayAgv, setPlayAgv } = usePlayAgv();
useEffect(() => {
if (simulationStates.length > 0) {
useEffect(() => {
console.log("agvRef: ", agvRef);
}, [agvRef]);
const agvModels = simulationStates.filter((val) => val.modelName === "agv" && val.type === "Vehicle");
useEffect(() => {
if (simulationStates.length > 0) {
const agvModels = simulationStates.filter(
(val) => val.modelName === "agv" && val.type === "Vehicle"
);
const newPathPoints = agvModels.filter((model: any) => model.points && model.points.actions && typeof model.points.actions.start === "object" && typeof model.points.actions.end === "object" && "x" in model.points.actions.start && "y" in model.points.actions.start && "x" in model.points.actions.end && "y" in model.points.actions.end)
.map((model: any) => ({
modelUuid: model.modeluuid,
modelSpeed: model.points.speed,
bufferTime: model.points.actions.buffer,
hitCount: model.points.actions.hitCount,
points: [
{ x: model.position[0], y: model.position[1], z: model.position[2] },
{ x: model.points.actions.start.x, y: 0, z: model.points.actions.start.y },
{ x: model.points.actions.end.x, y: 0, z: model.points.actions.end.y },
],
}));
const newPathPoints = agvModels
.filter(
(model: any) =>
model.points &&
model.points.actions &&
typeof model.points.actions.start === "object" &&
typeof model.points.actions.end === "object" &&
"x" in model.points.actions.start &&
"y" in model.points.actions.start &&
"x" in model.points.actions.end &&
"y" in model.points.actions.end
)
.map((model: any) => ({
modelUuid: model.modeluuid,
modelSpeed: model.points.speed,
bufferTime: model.points.actions.buffer,
hitCount: model.points.actions.hitCount,
points: [
{
x: model.position[0],
y: model.position[1],
z: model.position[2],
},
{
x: model.points.actions.start.x,
y: 0,
z: model.points.actions.start.y,
},
{
x: model.points.actions.end.x,
y: 0,
z: model.points.actions.end.y,
},
],
}));
setPathPoints(newPathPoints);
}
}, [simulationStates]);
setPathPoints(newPathPoints);
}
}, [simulationStates]);
return (
<>
{pathPoints.map((pair, i) => (
<group key={i} visible={!isPlaying}>
<PathNavigator
navMesh={navMesh}
pathPoints={pair.points}
id={pair.modelUuid}
speed={pair.modelSpeed}
bufferTime={pair.bufferTime}
hitCount={pair.hitCount}
/>
return (
<>
{pathPoints.map((pair, i) => (
<group key={i} visible={!isPlaying}>
<PathNavigator
navMesh={navMesh}
pathPoints={pair.points}
id={pair.modelUuid}
speed={pair.modelSpeed}
bufferTime={pair.bufferTime}
hitCount={pair.hitCount}
processes={processes}
agvRef={agvRef}
/>
{pair.points.slice(1).map((point, idx) => (
<mesh position={[point.x, point.y, point.z]} key={idx}>
<sphereGeometry args={[0.3, 15, 15]} />
<meshStandardMaterial color="red" />
</mesh>
))}
</group>
))}
</>
);
{pair.points.slice(1).map((point, idx) => (
<mesh position={[point.x, point.y, point.z]} key={idx}>
<sphereGeometry args={[0.3, 15, 15]} />
<meshStandardMaterial color="red" />
</mesh>
))}
</group>
))}
</>
);
};
export default Agv;

View File

@@ -4,206 +4,368 @@ import { useFrame, useThree } from "@react-three/fiber";
import { NavMeshQuery } from "@recast-navigation/core";
import { Line } from "@react-three/drei";
import { usePlayButtonStore } from "../../../store/usePlayButtonStore";
import { usePlayAgv } from "../../../store/store";
interface PathNavigatorProps {
navMesh: any;
pathPoints: any;
id: string;
speed: number;
bufferTime: number;
hitCount: number;
navMesh: any;
pathPoints: any;
id: string;
speed: number;
bufferTime: number;
hitCount: number;
processes: any[];
agvRef: any;
}
interface AGVData {
processId: string;
vehicleId: string;
hitCount: number;
totalHits: number;
}
type Phase = "initial" | "toDrop" | "toPickup";
export default function PathNavigator({
navMesh,
pathPoints,
id,
speed,
bufferTime,
hitCount
navMesh,
pathPoints,
id,
speed,
bufferTime,
hitCount,
processes,
agvRef,
}: PathNavigatorProps) {
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 [currentPhase, setCurrentPhase] = useState<Phase>("initial");
// console.log('agvRef: ', agvRef);
const distancesRef = useRef<number[]>([]);
const totalDistanceRef = useRef(0);
const progressRef = useRef(0);
const isWaiting = useRef(false);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const [path, setPath] = useState<[number, number, number][]>([]);
const { scene } = useThree();
const { isPlaying } = usePlayButtonStore();
// 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
);
useEffect(() => {
const object = scene.getObjectByProperty("uuid", id);
if (object) {
setInitialPosition(object.position.clone());
setInitialRotation(object.rotation.clone());
}
}, [scene, id]);
const distancesRef = useRef<number[]>([]);
const totalDistanceRef = useRef(0);
const progressRef = useRef(0);
const isWaiting = useRef(false);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const hasStarted = useRef(false);
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 [];
}
};
const { scene } = useThree();
const { isPlaying } = usePlayButtonStore();
const { PlayAgv, setPlayAgv } = usePlayAgv();
const resetState = () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
useEffect(() => {
const object = scene.getObjectByProperty("uuid", id);
if (object) {
setInitialPosition(object.position.clone());
setInitialRotation(object.rotation.clone());
}
}, [scene, id]);
setPath([]);
setCurrentPhase('initial');
setPickupDropPath([]);
setDropPickupPath([]);
distancesRef.current = [];
totalDistanceRef.current = 0;
progressRef.current = 0;
isWaiting.current = false;
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 [];
}
};
if (initialPosition && initialRotation) {
const object = scene.getObjectByProperty("uuid", id);
if (object) {
object.position.copy(initialPosition);
object.rotation.copy(initialRotation);
}
}
};
const resetState = () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
useEffect(() => {
if (!isPlaying) {
resetState();
}
setPath([]);
setCurrentPhase("initial");
setPickupDropPath([]);
setDropPickupPath([]);
distancesRef.current = [];
totalDistanceRef.current = 0;
progressRef.current = 0;
isWaiting.current = false;
if (!navMesh || pathPoints.length < 2) return;
if (initialPosition && initialRotation) {
const object = scene.getObjectByProperty("uuid", id);
if (object) {
object.position.copy(initialPosition);
object.rotation.copy(initialRotation);
}
}
};
const [pickup, drop] = pathPoints.slice(-2);
const object = scene.getObjectByProperty("uuid", id);
if (!object) return;
useEffect(() => {
if (!isPlaying) {
resetState();
}
const currentPosition = { x: object.position.x, y: object.position.y, z: object.position.z };
if (!navMesh || pathPoints.length < 2) return;
const toPickupPath = computePath(currentPosition, pickup);
const pickupToDropPath = computePath(pickup, drop);
const dropToPickupPath = computePath(drop, pickup);
const [pickup, drop] = pathPoints.slice(-2);
const object = scene.getObjectByProperty("uuid", id);
if (toPickupPath.length && pickupToDropPath.length && dropToPickupPath.length) {
setPickupDropPath(pickupToDropPath);
setDropPickupPath(dropToPickupPath);
setToPickupPath(toPickupPath);
setPath(toPickupPath);
setCurrentPhase('initial');
}
}, [navMesh, pathPoints, hitCount, isPlaying]);
if (!object) return;
useEffect(() => {
if (path.length < 2) return;
const currentPosition = {
x: object.position.x,
y: object.position.y,
z: object.position.z,
};
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;
});
const toPickupPath = computePath(currentPosition, pickup);
const pickupToDropPath = computePath(pickup, drop);
const dropToPickupPath = computePath(drop, pickup);
distancesRef.current = segmentDistances;
totalDistanceRef.current = total;
progressRef.current = 0;
isWaiting.current = false;
}, [path]);
if (
toPickupPath.length &&
pickupToDropPath.length &&
dropToPickupPath.length
) {
setPickupDropPath(pickupToDropPath);
setDropPickupPath(dropToPickupPath);
setToPickupPath(toPickupPath);
setPath(toPickupPath);
setCurrentPhase("initial");
}
}, [navMesh, pathPoints, hitCount, isPlaying, PlayAgv]);
useFrame((_, delta) => {
if (!isPlaying || path.length < 2 || !scene || !id) return;
useEffect(() => {
if (path.length < 2) return;
const object = scene.getObjectByProperty("uuid", id);
if (!object) return;
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;
});
const speedFactor = speed;
progressRef.current += delta * speedFactor;
distancesRef.current = segmentDistances;
totalDistanceRef.current = total;
progressRef.current = 0;
isWaiting.current = false;
}, [path]);
let covered = progressRef.current;
let accumulated = 0;
let index = 0;
// Add these refs outside the useFrame if not already present:
const startPointReached = useRef(false);
while (
index < distancesRef.current.length &&
covered > accumulated + distancesRef.current[index]
) {
accumulated += distancesRef.current[index];
index++;
}
useFrame((_, delta) => {});
if (index >= distancesRef.current.length) {
progressRef.current = totalDistanceRef.current;
useFrame((_, delta) => {
const currentAgv = (agvRef.current || []).find(
(agv: AGVData) => agv.vehicleId === id
);
console.log("currentAgv: ", currentAgv?.isplaying);
if (!isWaiting.current) {
isWaiting.current = true;
if (!scene || !id || !isPlaying) return;
timeoutRef.current = setTimeout(() => {
if (currentPhase === 'initial') {
setPath(pickupDropPath);
setCurrentPhase('loop');
} else {
setPath(prevPath =>
prevPath === pickupDropPath ? dropPickupPath : pickupDropPath
);
}
const object = scene.getObjectByProperty("uuid", id);
if (!object) return;
progressRef.current = 0;
isWaiting.current = false;
}, bufferTime * 1000);
}
return;
}
if (isPlaying && !hasStarted.current) {
hasStarted.current = false;
startPointReached.current = false;
progressRef.current = 0;
isWaiting.current = false;
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
}
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);
const isAgvReady = () => {
if (!agvRef.current || agvRef.current.length === 0) return false;
if (!currentAgv) return false;
return hitCount === currentAgv.expectedHitCount;
};
object.position.copy(position);
// Step 1: Snap to start point on first play
if (isPlaying && !hasStarted.current && toPickupPath.length > 0) {
const startPoint = new THREE.Vector3(...toPickupPath[0]);
object.position.copy(startPoint);
const direction = new THREE.Vector3().subVectors(end, start).normalize();
const targetRotationY = Math.atan2(direction.x, direction.z);
if (toPickupPath.length > 1) {
const nextPoint = new THREE.Vector3(...toPickupPath[1]);
const direction = nextPoint.clone().sub(startPoint).normalize();
object.rotation.y = 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;
});
hasStarted.current = true;
startPointReached.current = true;
progressRef.current = 0;
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
return;
}
return (
<group name="path-navigator-lines" visible={!isPlaying} >
{toPickupPath.length > 0 && (
<Line points={toPickupPath} color="blue" lineWidth={3} dashed dashSize={0.75} dashScale={2} />
)}
// Step 2: Wait at start point for AGV readiness (only if expected hit count is not met)
if (
isPlaying &&
startPointReached.current &&
path.length === 0 &&
currentAgv?.isplaying
) {
if (!isAgvReady()) {
return; // Prevent transitioning to the next phase if AGV is not ready
}
{pickupDropPath.length > 0 && (
<Line points={pickupDropPath} color="red" lineWidth={3} />
)}
setPath([...toPickupPath]); // Start path transition once the AGV is ready
setCurrentPhase("toDrop");
progressRef.current = 0;
startPointReached.current = false;
{dropPickupPath.length > 0 && (
<Line points={dropPickupPath} color="red" lineWidth={3} />
)}
</group>
);
}
return;
}
if (path.length < 2) return;
progressRef.current += delta * speed;
let covered = progressRef.current;
let accumulated = 0;
let index = 0;
if (distancesRef.current.length !== path.length - 1) {
distancesRef.current = [];
totalDistanceRef.current = 0;
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 distance = start.distanceTo(end);
distancesRef.current.push(distance);
totalDistanceRef.current += distance;
}
}
while (
index < distancesRef.current.length &&
covered > accumulated + distancesRef.current[index]
) {
accumulated += distancesRef.current[index];
index++;
}
// AGV has completed its path
if (index >= distancesRef.current.length) {
progressRef.current = totalDistanceRef.current;
timeoutRef.current = setTimeout(() => {
if (!isAgvReady()) {
isWaiting.current = false;
return;
}
let nextPath = [];
let nextPhase = currentPhase;
if (currentPhase === "toDrop") {
nextPath = dropPickupPath;
nextPhase = "toPickup";
} else if (currentPhase === "toPickup") {
nextPath = pickupDropPath;
nextPhase = "toDrop";
} else {
nextPath = pickupDropPath;
nextPhase = "toDrop";
}
setPath([...nextPath]);
setCurrentPhase(nextPhase);
progressRef.current = 0;
isWaiting.current = false;
distancesRef.current = [];
// Decrease the expected count if AGV is ready and has completed its path
if (currentAgv) {
currentAgv.expectedCount = Math.max(0, currentAgv.expectedCount - 1); // Decrease but ensure it's not negative
console.log(
"Decreased expected count to: ",
currentAgv.expectedCount
);
}
if (agvRef.current) {
agvRef.current = agvRef.current.map((agv: AGVData) =>
agv.vehicleId === id ? { ...agv, hitCount: null } : agv
);
}
// 🔁 Reset and wait again after reaching start
if (currentPhase === "toPickup" && currentAgv) {
currentAgv.isplaying = false;
setPath([]);
startPointReached.current = true;
progressRef.current = 0;
}
}, bufferTime * 1000);
return;
}
// Step 4: Interpolate position and rotation
const start = new THREE.Vector3(...path[index]);
const end = new THREE.Vector3(...path[index + 1]);
const dist = distancesRef.current[index];
if (!dist || dist === 0) return;
const t = THREE.MathUtils.clamp((covered - accumulated) / dist, 0, 1);
object.position.copy(start.clone().lerp(end, t));
const direction = new THREE.Vector3().subVectors(end, start).normalize();
object.rotation.y = Math.atan2(direction.x, direction.z);
});
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>
);
}

View File

@@ -150,6 +150,7 @@ async function handleModelLoad(
const organization = email ? email.split("@")[1].split(".")[0] : "";
getAssetEventType(selectedItem.id, organization).then(async (res) => {
console.log('res: ', res);
if (res.type === "Conveyor") {
const pointUUIDs = res.points.map(() => THREE.MathUtils.generateUUID());
@@ -224,6 +225,7 @@ async function handleModelLoad(
eventData as Types.ConveyorEventsSchema
]);
console.log('data: ', data);
socket.emit("v2:model-asset:add", data);
} else if (res.type === "Vehicle") {
@@ -324,6 +326,7 @@ async function handleModelLoad(
return updatedItems;
});
console.log('data: ', data);
socket.emit("v2:model-asset:add", data);
}