Refactor vehicle simulation components for improved path handling and state management

- Updated PointsCreator component to enhance event data selection and keyboard handling.
- Refactored VehicleAnimator to streamline animation logic and reset handling.
- Simplified VehicleInstance logic for better clarity and maintainability.
- Modified vehicle data structure to include rotation information for pick-up and unload points.
- Adjusted TypeScript types to reflect new vehicle point schema with nested position and rotation properties.
This commit is contained in:
Jerald-Golden-B 2025-04-29 10:33:30 +05:30
parent ccc7a1d954
commit ea53af62c4
6 changed files with 538 additions and 563 deletions

View File

@ -4,196 +4,182 @@ import RenameInput from "../../../../../ui/inputs/RenameInput";
import LabledDropdown from "../../../../../ui/inputs/LabledDropdown";
import Trigger from "../trigger/Trigger";
import {
useSelectedEventData,
useSelectedProduct,
useSelectedEventData,
useSelectedProduct,
} from "../../../../../../store/simulation/useSimulationStore";
import { useProductStore } from "../../../../../../store/simulation/useProductStore";
import TravelAction from "../actions/TravelAction";
import ActionsList from "../components/ActionsList";
function VehicleMechanics() {
const [activeOption, setActiveOption] = useState<"default" | "travel">(
"default"
);
const [selectedPointData, setSelectedPointData] = useState<
VehiclePointSchema | undefined
>();
const { selectedEventData } = useSelectedEventData();
const { getPointByUuid, updateEvent, updateAction } = useProductStore();
const { selectedProduct } = useSelectedProduct();
const [activeOption, setActiveOption] = useState<"default" | "travel">(
"default"
);
const [selectedPointData, setSelectedPointData] = useState<VehiclePointSchema | undefined>();
const { selectedEventData } = useSelectedEventData();
const { getPointByUuid, updateEvent, updateAction } = useProductStore();
const { selectedProduct } = useSelectedProduct();
useEffect(() => {
if (selectedEventData) {
const point = getPointByUuid(
selectedProduct.productId,
selectedEventData.data.modelUuid,
selectedEventData.selectedPoint
) as VehiclePointSchema | undefined;
useEffect(() => {
if (selectedEventData) {
const point = getPointByUuid(
selectedProduct.productId,
selectedEventData.data.modelUuid,
selectedEventData.selectedPoint
) as VehiclePointSchema | undefined;
if (point) {
setSelectedPointData(point);
setActiveOption(point.action.actionType as "travel");
}
}
}, [selectedProduct, selectedEventData, getPointByUuid]);
if (point) {
setSelectedPointData(point);
setActiveOption(point.action.actionType as "travel");
}
}
}, [selectedProduct, selectedEventData, getPointByUuid]);
const handleSpeedChange = (value: string) => {
if (!selectedEventData) return;
updateEvent(selectedProduct.productId, selectedEventData.data.modelUuid, {
speed: parseFloat(value),
});
};
const handleSpeedChange = (value: string) => {
if (!selectedEventData) return;
updateEvent(selectedProduct.productId, selectedEventData.data.modelUuid, {
speed: parseFloat(value),
});
};
const handleActionTypeChange = (option: string) => {
if (!selectedEventData || !selectedPointData) return;
const validOption = option as "travel";
setActiveOption(validOption);
const handleActionTypeChange = (option: string) => {
if (!selectedEventData || !selectedPointData) return;
const validOption = option as "travel";
setActiveOption(validOption);
updateAction(selectedPointData.action.actionUuid, {
actionType: validOption,
});
};
updateAction(selectedPointData.action.actionUuid, {
actionType: validOption,
});
};
const handleRenameAction = (newName: string) => {
if (!selectedPointData) return;
updateAction(selectedPointData.action.actionUuid, { actionName: newName });
};
const handleRenameAction = (newName: string) => {
if (!selectedPointData) return;
updateAction(selectedPointData.action.actionUuid, { actionName: newName });
};
const handleLoadCapacityChange = (value: string) => {
if (!selectedPointData) return;
updateAction(selectedPointData.action.actionUuid, {
loadCapacity: parseFloat(value),
});
};
const handleLoadCapacityChange = (value: string) => {
if (!selectedPointData) return;
updateAction(selectedPointData.action.actionUuid, {
loadCapacity: parseFloat(value),
});
};
const handleUnloadDurationChange = (value: string) => {
if (!selectedPointData) return;
updateAction(selectedPointData.action.actionUuid, {
unLoadDuration: parseFloat(value),
});
};
const handleUnloadDurationChange = (value: string) => {
if (!selectedPointData) return;
updateAction(selectedPointData.action.actionUuid, {
unLoadDuration: parseFloat(value),
});
};
const handlePickPointChange = (value: string) => {
if (!selectedPointData) return;
const [x, y, z] = value.split(",").map(Number);
updateAction(selectedPointData.action.actionUuid, {
pickUpPoint: { x, y, z },
});
};
const handlePickPointChange = (value: string) => {
if (!selectedPointData) return;
};
const handleUnloadPointChange = (value: string) => {
if (!selectedPointData) return;
const [x, y, z] = value.split(",").map(Number);
updateAction(selectedPointData.action.actionUuid, {
unLoadPoint: { x, y, z },
});
};
const handleUnloadPointChange = (value: string) => {
if (!selectedPointData) return;
};
// Get current values from store
const currentSpeed =
selectedEventData?.data.type === "vehicle"
? selectedEventData.data.speed.toString()
: "0.5";
// Get current values from store
const currentSpeed =
selectedEventData?.data.type === "vehicle"
? selectedEventData.data.speed.toString()
: "0.5";
const currentActionName = selectedPointData
? selectedPointData.action.actionName
: "Action Name";
const currentActionName = selectedPointData
? selectedPointData.action.actionName
: "Action Name";
const currentLoadCapacity = selectedPointData
? selectedPointData.action.loadCapacity.toString()
: "1";
const currentLoadCapacity = selectedPointData
? selectedPointData.action.loadCapacity.toString()
: "1";
const currentUnloadDuration = selectedPointData
? selectedPointData.action.unLoadDuration.toString()
: "1";
const currentUnloadDuration = selectedPointData
? selectedPointData.action.unLoadDuration.toString()
: "1";
const currentPickPoint = selectedPointData?.action.pickUpPoint
? `${selectedPointData.action.pickUpPoint.x},${selectedPointData.action.pickUpPoint.y},${selectedPointData.action.pickUpPoint.z}`
: "";
const currentPickPoint = selectedPointData?.action.pickUpPoint;
const currentUnloadPoint = selectedPointData?.action.unLoadPoint
? `${selectedPointData.action.unLoadPoint.x},${selectedPointData.action.unLoadPoint.y},${selectedPointData.action.unLoadPoint.z}`
: "";
const currentUnloadPoint = selectedPointData?.action.unLoadPoint;
const availableActions = {
defaultOption: "travel",
options: ["travel"],
};
const availableActions = {
defaultOption: "travel",
options: ["travel"],
};
return (
<>
{selectedEventData && (
return (
<>
<div className="global-props">
<div className="property-list-container">
<div className="property-item">
<InputWithDropDown
label="Speed"
value={currentSpeed}
min={0}
step={0.1}
defaultValue={"0.5"}
max={10}
activeOption="m/s"
onClick={() => {}}
onChange={handleSpeedChange}
/>
</div>
</div>
</div>
<ActionsList
setSelectedPointData={setSelectedPointData}
selectedPointData={selectedPointData}
/>
<div className="selected-actions-details">
<div className="selected-actions-header">
<RenameInput
value={currentActionName}
onRename={handleRenameAction}
/>
</div>
<div className="selected-actions-list">
<LabledDropdown
defaultOption="travel"
options={availableActions.options}
onSelect={handleActionTypeChange}
/>
{selectedEventData && (
<>
<div className="global-props">
<div className="property-list-container">
<div className="property-item">
<InputWithDropDown
label="Speed"
value={currentSpeed}
min={0}
step={0.1}
defaultValue={"0.5"}
max={10}
activeOption="m/s"
onClick={() => { }}
onChange={handleSpeedChange}
/>
</div>
</div>
</div>
<ActionsList
setSelectedPointData={setSelectedPointData}
selectedPointData={selectedPointData}
/>
<div className="selected-actions-details">
<div className="selected-actions-header">
<RenameInput
value={currentActionName}
onRename={handleRenameAction}
/>
</div>
<div className="selected-actions-list">
<LabledDropdown
defaultOption="travel"
options={availableActions.options}
onSelect={handleActionTypeChange}
/>
{activeOption === "travel" && (
<TravelAction
loadCapacity={{
value: currentLoadCapacity,
min: 1,
max: 100,
defaultValue: "1",
onChange: handleLoadCapacityChange,
}}
unloadDuration={{
value: currentUnloadDuration,
min: 1,
max: 60,
defaultValue: "1",
onChange: handleUnloadDurationChange,
}}
// pickPoint={{
// value: currentPickPoint,
// onChange: handlePickPointChange,
// }}
// unloadPoint={{
// value: currentUnloadPoint,
// onChange: handleUnloadPointChange,
// }}
/>
)}
</div>
</div>
<div className="tirgger">
<Trigger />
</div>
{activeOption === "travel" && (
<TravelAction
loadCapacity={{
value: currentLoadCapacity,
min: 1,
max: 100,
defaultValue: "1",
onChange: handleLoadCapacityChange,
}}
unloadDuration={{
value: currentUnloadDuration,
min: 1,
max: 60,
defaultValue: "1",
onChange: handleUnloadDurationChange,
}}
// pickPoint={{
// value: currentPickPoint,
// onChange: handlePickPointChange,
// }}
// unloadPoint={{
// value: currentUnloadPoint,
// onChange: handleUnloadPointChange,
// }}
/>
)}
</div>
</div>
<div className="tirgger">
<Trigger />
</div>
</>
)}
</>
)}
</>
);
);
}
export default VehicleMechanics;

View File

@ -15,36 +15,36 @@ function PointsCreator() {
const { selectedEventSphere, setSelectedEventSphere, clearSelectedEventSphere } = useSelectedEventSphere();
const { setSelectedEventData, clearSelectedEventData } = useSelectedEventData();
useEffect(() => {
if (selectedEventSphere) {
const eventData = getEventByModelUuid(
selectedEventSphere.userData.modelUuid
);
if (eventData) {
setSelectedEventData(eventData, selectedEventSphere.userData.pointUuid);
} else {
clearSelectedEventData();
}
} else {
clearSelectedEventData();
}
}, [selectedEventSphere]);
useEffect(() => {
if (selectedEventSphere) {
const eventData = getEventByModelUuid(
selectedEventSphere.userData.modelUuid
);
if (eventData) {
setSelectedEventData(eventData, selectedEventSphere.userData.pointUuid);
} else {
clearSelectedEventData();
}
} else {
clearSelectedEventData();
}
}, [selectedEventSphere]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const keyCombination = detectModifierKeys(e);
if (!selectedEventSphere) return;
if (keyCombination === "G") {
setTransformMode((prev) => (prev === "translate" ? null : "translate"));
}
if (keyCombination === "R") {
setTransformMode((prev) => (prev === "rotate" ? null : "rotate"));
}
};
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const keyCombination = detectModifierKeys(e);
if (!selectedEventSphere) return;
if (keyCombination === "G") {
setTransformMode((prev) => (prev === "translate" ? null : "translate"));
}
if (keyCombination === "R") {
setTransformMode((prev) => (prev === "rotate" ? null : "rotate"));
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [selectedEventSphere]);
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [selectedEventSphere]);
const updatePointToState = (selectedEventSphere: THREE.Mesh) => {
let point = JSON.parse(JSON.stringify(getPointByUuid(selectedEventSphere.userData.modelUuid, selectedEventSphere.userData.pointUuid)));

View File

@ -7,269 +7,267 @@ import { useAnimationPlaySpeed, usePauseButtonStore, useResetButtonStore } from
import { useVehicleStore } from '../../../../../store/simulation/useVehicleStore';
interface VehicleAnimatorProps {
path: [number, number, number][];
handleCallBack: () => void;
reset: () => void;
currentPhase: string;
agvUuid: number;
agvDetail: any;
path: [number, number, number][];
handleCallBack: () => void;
reset: () => void;
currentPhase: string;
agvUuid: number;
agvDetail: any;
}
function VehicleAnimator({ path, handleCallBack, currentPhase, agvUuid, agvDetail, reset }: VehicleAnimatorProps) {
const { decrementVehicleLoad, vehicles } = useVehicleStore();
const { isPaused } = usePauseButtonStore();
const { speed } = useAnimationPlaySpeed();
const { isReset } = useResetButtonStore();
const [restRotation, setRestingRotation] = useState<boolean>(true);
const [progress, setProgress] = useState<number>(0);
const [currentPath, setCurrentPath] = useState<[number, number, number][]>([]);
const { scene } = useThree();
const progressRef = useRef<number>(0);
const movingForward = useRef<boolean>(true);
const completedRef = useRef<boolean>(false);
let startTime: number;
let pausedTime: number;
let fixedInterval: number;
const { decrementVehicleLoad, vehicles } = useVehicleStore();
const { isPaused } = usePauseButtonStore();
const { speed } = useAnimationPlaySpeed();
const { isReset } = useResetButtonStore();
const [restRotation, setRestingRotation] = useState<boolean>(true);
const [progress, setProgress] = useState<number>(0);
const [currentPath, setCurrentPath] = useState<[number, number, number][]>([]);
const { scene } = useThree();
const progressRef = useRef<number>(0);
const movingForward = useRef<boolean>(true);
const completedRef = useRef<boolean>(false);
let startTime: number;
let pausedTime: number;
let fixedInterval: number;
useEffect(() => {
if (currentPhase === 'stationed-pickup' && path.length > 0) {
setCurrentPath(path);
} else if (currentPhase === 'pickup-drop' && path.length > 0) {
setCurrentPath(path);
} else if (currentPhase === 'drop-pickup' && path.length > 0) {
setCurrentPath(path);
}
}, [currentPhase, path]);
useEffect(() => {
setProgress(0);
completedRef.current = false;
}, [currentPath]);
// useEffect(() => {
// console.log('isReset: ', isReset);
// if (isReset) {
// reset();
// setCurrentPath([]);
// setProgress(0);
// completedRef.current = false;
// decrementVehicleLoad(agvDetail.modelUuid, 0)
// }
// }, [isReset])
// useFrame((_, delta) => {
// const object = scene.getObjectByProperty('uuid', agvUuid);
// if (!object || currentPath.length < 2) return;
// if (isPaused) return;
// let totalDistance = 0;
// const distances = [];
// for (let i = 0; i < currentPath.length - 1; i++) {
// const start = new THREE.Vector3(...currentPath[i]);
// const end = new THREE.Vector3(...currentPath[i + 1]);
// const segmentDistance = start.distanceTo(end);
// distances.push(segmentDistance);
// totalDistance += segmentDistance;
// }
// let coveredDistance = progressRef.current;
// let accumulatedDistance = 0;
// let index = 0;
// while (
// index < distances.length &&
// coveredDistance > accumulatedDistance + distances[index]
// ) {
// accumulatedDistance += distances[index];
// index++;
// }
// if (index < distances.length) {
// const start = new THREE.Vector3(...currentPath[index]);
// const end = new THREE.Vector3(...currentPath[index + 1]);
// const segmentDistance = distances[index];
// const currentDirection = new THREE.Vector3().subVectors(end, start).normalize();
// const targetAngle = Math.atan2(currentDirection.x, currentDirection.z);
// const rotationSpeed = 2.0;
// const currentAngle = object.rotation.y;
// let angleDifference = targetAngle - currentAngle;
// if (angleDifference > Math.PI) angleDifference -= 2 * Math.PI;
// if (angleDifference < -Math.PI) angleDifference += 2 * Math.PI;
// const maxRotationStep = rotationSpeed * delta;
// object.rotation.y += Math.sign(angleDifference) * Math.min(Math.abs(angleDifference), maxRotationStep);
// const isAligned = Math.abs(angleDifference) < 0.01;
// if (isAligned) {
// progressRef.current += delta * (speed * agvDetail.speed);
// coveredDistance = progressRef.current;
// const t = (coveredDistance - accumulatedDistance) / segmentDistance;
// const position = start.clone().lerp(end, t);
// object.position.copy(position);
// }
// }
// if (progressRef.current >= totalDistance) {
// if (restRotation) {
// const targetQuaternion = new THREE.Quaternion().setFromEuler(new THREE.Euler(0, 0, 0));
// object.quaternion.slerp(targetQuaternion, delta * 2);
// const angleDiff = object.quaternion.angleTo(targetQuaternion);
// if (angleDiff < 0.01) {
// let objectRotation = agvDetail.point.rotation
// object.rotation.set(objectRotation[0], objectRotation[1], objectRotation[2]);
// setRestingRotation(false);
// }
// return;
// }
// }
// if (progressRef.current >= totalDistance) {
// setRestingRotation(true);
// progressRef.current = 0;
// movingForward.current = !movingForward.current;
// setCurrentPath([]);
// handleCallBack();
// if (currentPhase === 'pickup-drop') {
// requestAnimationFrame(firstFrame);
// }
// }
// });
useEffect(() => {
console.log('isReset: ', isReset);
if (isReset) {
reset();
setCurrentPath([]);
setProgress(0);
progressRef.current = 0;
completedRef.current = false;
movingForward.current = true;
setRestingRotation(false);
decrementVehicleLoad(agvDetail.modelUuid, 0);
console.log('agvDetail: ', vehicles);
}
}, [isReset]);
useFrame((_, delta) => {
// If reset is active, don't run anything in frame
if (isReset) return;
const object = scene.getObjectByProperty('uuid', agvUuid);
if (!object || currentPath.length < 2) return;
if (isPaused) return;
let totalDistance = 0;
const distances = [];
for (let i = 0; i < currentPath.length - 1; i++) {
const start = new THREE.Vector3(...currentPath[i]);
const end = new THREE.Vector3(...currentPath[i + 1]);
const segmentDistance = start.distanceTo(end);
distances.push(segmentDistance);
totalDistance += segmentDistance;
}
let coveredDistance = progressRef.current;
let accumulatedDistance = 0;
let index = 0;
while (index < distances.length && coveredDistance > accumulatedDistance + distances[index]) {
accumulatedDistance += distances[index];
index++;
}
if (index < distances.length) {
const start = new THREE.Vector3(...currentPath[index]);
const end = new THREE.Vector3(...currentPath[index + 1]);
const segmentDistance = distances[index];
const currentDirection = new THREE.Vector3().subVectors(end, start).normalize();
const targetAngle = Math.atan2(currentDirection.x, currentDirection.z);
const currentAngle = object.rotation.y;
let angleDifference = targetAngle - currentAngle;
if (angleDifference > Math.PI) angleDifference -= 2 * Math.PI;
if (angleDifference < -Math.PI) angleDifference += 2 * Math.PI;
const rotationSpeed = 2.0;
const maxRotationStep = rotationSpeed * delta;
const rotationStep = Math.sign(angleDifference) * Math.min(Math.abs(angleDifference), maxRotationStep);
object.rotation.y += rotationStep;
const isAligned = Math.abs(angleDifference) < 0.01;
if (isAligned) {
progressRef.current += delta * (speed * agvDetail.speed);
coveredDistance = progressRef.current;
const t = (coveredDistance - accumulatedDistance) / segmentDistance;
const position = start.clone().lerp(end, t);
object.position.copy(position);
}
}
if (progressRef.current >= totalDistance) {
if (restRotation) {
const targetQuaternion = new THREE.Quaternion().setFromEuler(new THREE.Euler(0, 0, 0));
object.quaternion.slerp(targetQuaternion, delta * 2);
const angleDiff = object.quaternion.angleTo(targetQuaternion);
if (angleDiff < 0.01) {
const objectRotation = agvDetail.point.rotation;
object.rotation.set(objectRotation[0], objectRotation[1], objectRotation[2]);
setRestingRotation(false);
useEffect(() => {
if (currentPhase === 'stationed-pickup' && path.length > 0) {
setCurrentPath(path);
} else if (currentPhase === 'pickup-drop' && path.length > 0) {
setCurrentPath(path);
} else if (currentPhase === 'drop-pickup' && path.length > 0) {
setCurrentPath(path);
}
} else {
setRestingRotation(true);
progressRef.current = 0;
movingForward.current = !movingForward.current;
setCurrentPath([]);
handleCallBack();
if (currentPhase === 'pickup-drop') {
requestAnimationFrame(firstFrame);
}, [currentPhase, path]);
useEffect(() => {
setProgress(0);
completedRef.current = false;
}, [currentPath]);
// useEffect(() => {
// console.log('isReset: ', isReset);
// if (isReset) {
// reset();
// setCurrentPath([]);
// setProgress(0);
// completedRef.current = false;
// decrementVehicleLoad(agvDetail.modelUuid, 0)
// }
// }, [isReset])
// useFrame((_, delta) => {
// const object = scene.getObjectByProperty('uuid', agvUuid);
// if (!object || currentPath.length < 2) return;
// if (isPaused) return;
// let totalDistance = 0;
// const distances = [];
// for (let i = 0; i < currentPath.length - 1; i++) {
// const start = new THREE.Vector3(...currentPath[i]);
// const end = new THREE.Vector3(...currentPath[i + 1]);
// const segmentDistance = start.distanceTo(end);
// distances.push(segmentDistance);
// totalDistance += segmentDistance;
// }
// let coveredDistance = progressRef.current;
// let accumulatedDistance = 0;
// let index = 0;
// while (
// index < distances.length &&
// coveredDistance > accumulatedDistance + distances[index]
// ) {
// accumulatedDistance += distances[index];
// index++;
// }
// if (index < distances.length) {
// const start = new THREE.Vector3(...currentPath[index]);
// const end = new THREE.Vector3(...currentPath[index + 1]);
// const segmentDistance = distances[index];
// const currentDirection = new THREE.Vector3().subVectors(end, start).normalize();
// const targetAngle = Math.atan2(currentDirection.x, currentDirection.z);
// const rotationSpeed = 2.0;
// const currentAngle = object.rotation.y;
// let angleDifference = targetAngle - currentAngle;
// if (angleDifference > Math.PI) angleDifference -= 2 * Math.PI;
// if (angleDifference < -Math.PI) angleDifference += 2 * Math.PI;
// const maxRotationStep = rotationSpeed * delta;
// object.rotation.y += Math.sign(angleDifference) * Math.min(Math.abs(angleDifference), maxRotationStep);
// const isAligned = Math.abs(angleDifference) < 0.01;
// if (isAligned) {
// progressRef.current += delta * (speed * agvDetail.speed);
// coveredDistance = progressRef.current;
// const t = (coveredDistance - accumulatedDistance) / segmentDistance;
// const position = start.clone().lerp(end, t);
// object.position.copy(position);
// }
// }
// if (progressRef.current >= totalDistance) {
// if (restRotation) {
// const targetQuaternion = new THREE.Quaternion().setFromEuler(new THREE.Euler(0, 0, 0));
// object.quaternion.slerp(targetQuaternion, delta * 2);
// const angleDiff = object.quaternion.angleTo(targetQuaternion);
// if (angleDiff < 0.01) {
// let objectRotation = agvDetail.point.rotation
// object.rotation.set(objectRotation[0], objectRotation[1], objectRotation[2]);
// setRestingRotation(false);
// }
// return;
// }
// }
// if (progressRef.current >= totalDistance) {
// setRestingRotation(true);
// progressRef.current = 0;
// movingForward.current = !movingForward.current;
// setCurrentPath([]);
// handleCallBack();
// if (currentPhase === 'pickup-drop') {
// requestAnimationFrame(firstFrame);
// }
// }
// });
useEffect(() => {
if (isReset) {
reset();
setCurrentPath([]);
setProgress(0);
progressRef.current = 0;
completedRef.current = false;
movingForward.current = true;
setRestingRotation(false);
decrementVehicleLoad(agvDetail.modelUuid, 0);
}
}
}, [isReset]);
useFrame((_, delta) => {
// If reset is active, don't run anything in frame
if (isReset) return;
const object = scene.getObjectByProperty('uuid', agvUuid);
if (!object || currentPath.length < 2) return;
if (isPaused) return;
let totalDistance = 0;
const distances = [];
for (let i = 0; i < currentPath.length - 1; i++) {
const start = new THREE.Vector3(...currentPath[i]);
const end = new THREE.Vector3(...currentPath[i + 1]);
const segmentDistance = start.distanceTo(end);
distances.push(segmentDistance);
totalDistance += segmentDistance;
}
let coveredDistance = progressRef.current;
let accumulatedDistance = 0;
let index = 0;
while (index < distances.length && coveredDistance > accumulatedDistance + distances[index]) {
accumulatedDistance += distances[index];
index++;
}
if (index < distances.length) {
const start = new THREE.Vector3(...currentPath[index]);
const end = new THREE.Vector3(...currentPath[index + 1]);
const segmentDistance = distances[index];
const currentDirection = new THREE.Vector3().subVectors(end, start).normalize();
const targetAngle = Math.atan2(currentDirection.x, currentDirection.z);
const currentAngle = object.rotation.y;
let angleDifference = targetAngle - currentAngle;
if (angleDifference > Math.PI) angleDifference -= 2 * Math.PI;
if (angleDifference < -Math.PI) angleDifference += 2 * Math.PI;
const rotationSpeed = 2.0;
const maxRotationStep = rotationSpeed * delta;
const rotationStep = Math.sign(angleDifference) * Math.min(Math.abs(angleDifference), maxRotationStep);
object.rotation.y += rotationStep;
const isAligned = Math.abs(angleDifference) < 0.01;
if (isAligned) {
progressRef.current += delta * (speed * agvDetail.speed);
coveredDistance = progressRef.current;
const t = (coveredDistance - accumulatedDistance) / segmentDistance;
const position = start.clone().lerp(end, t);
object.position.copy(position);
}
}
if (progressRef.current >= totalDistance) {
if (restRotation) {
const targetQuaternion = new THREE.Quaternion().setFromEuler(new THREE.Euler(0, 0, 0));
object.quaternion.slerp(targetQuaternion, delta * 2);
const angleDiff = object.quaternion.angleTo(targetQuaternion);
if (angleDiff < 0.01) {
const objectRotation = agvDetail.point.rotation;
object.rotation.set(objectRotation[0], objectRotation[1], objectRotation[2]);
setRestingRotation(false);
}
} else {
setRestingRotation(true);
progressRef.current = 0;
movingForward.current = !movingForward.current;
setCurrentPath([]);
handleCallBack();
if (currentPhase === 'pickup-drop') {
requestAnimationFrame(firstFrame);
}
}
}
});
function firstFrame() {
const unLoadDuration = agvDetail.point.action.unLoadDuration;
const droppedMaterial = agvDetail.currentLoad;
fixedInterval = (unLoadDuration / droppedMaterial) * 1000;
startTime = performance.now();
step(droppedMaterial);
}
});
function firstFrame() {
const unLoadDuration = agvDetail.point.action.unLoadDuration;
const droppedMaterial = agvDetail.currentLoad;
fixedInterval = (unLoadDuration / droppedMaterial) * 1000;
startTime = performance.now();
step(droppedMaterial);
}
function step(droppedMaterial: number) {
const elapsedTime = (performance.now() - startTime) * speed;
if (elapsedTime >= fixedInterval) {
let droppedMat = droppedMaterial - 1;
decrementVehicleLoad(agvDetail.modelUuid, 1);
if (droppedMat === 0) return;
startTime = performance.now();
requestAnimationFrame(() => step(droppedMat));
} else {
requestAnimationFrame(() => step(droppedMaterial));
function step(droppedMaterial: number) {
const elapsedTime = (performance.now() - startTime) * speed;
if (elapsedTime >= fixedInterval) {
let droppedMat = droppedMaterial - 1;
decrementVehicleLoad(agvDetail.modelUuid, 1);
if (droppedMat === 0) return;
startTime = performance.now();
requestAnimationFrame(() => step(droppedMat));
} else {
requestAnimationFrame(() => step(droppedMaterial));
}
}
}
return (
<>
{currentPath.length > 0 && (
return (
<>
<Line points={currentPath} color="blue" lineWidth={3} />
{currentPath.map((point, index) => (
<mesh key={index} position={point}>
<sphereGeometry args={[0.1, 16, 16]} />
<meshStandardMaterial color="red" />
</mesh>
))}
{currentPath.length > 0 && (
<>
<Line points={currentPath} color="blue" lineWidth={3} />
{currentPath.map((point, index) => (
<mesh key={index} position={point}>
<sphereGeometry args={[0.1, 16, 16]} />
<meshStandardMaterial color="red" />
</mesh>
))}
</>
)}
</>
)}
</>
);
);
}
export default VehicleAnimator;

View File

@ -7,126 +7,116 @@ import { usePlayButtonStore, useResetButtonStore } from '../../../../../store/us
import { useVehicleStore } from '../../../../../store/simulation/useVehicleStore';
function VehicleInstance({ agvDetail }: any) {
const { navMesh } = useNavMesh();
const { isPlaying, setIsPlaying } = usePlayButtonStore();
const { isReset } = useResetButtonStore();
const { vehicles, setVehicleActive, setVehicleState, incrementVehicleLoad } = useVehicleStore();
const [currentPhase, setCurrentPhase] = useState<string>('stationed');
const [path, setPath] = useState<[number, number, number][]>([]);
const { navMesh } = useNavMesh();
const { isPlaying, setIsPlaying } = usePlayButtonStore();
const { isReset } = useResetButtonStore();
const { vehicles, setVehicleActive, setVehicleState, incrementVehicleLoad } = useVehicleStore();
const [currentPhase, setCurrentPhase] = useState<string>('stationed');
const [path, setPath] = useState<[number, number, number][]>([]);
const computePath = useCallback(
(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 [];
}
},
[navMesh]
);
const computePath = useCallback(
(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 [];
}
},
[navMesh]
);
function vehicleStatus(modelid: string, status: string) {
// console.log(`AGV ${modelid}: ${status}`);
}
function reset() {
console.log("runs");
setVehicleActive(agvDetail.modelUuid, false);
setVehicleState(agvDetail.modelUuid, 'idle');
setPath([]);
setCurrentPhase('stationed')
}
function vehicleStatus(modelid: string, status: string) {
// console.log(`AGV ${modelid}: ${status}`);
}
function reset() {
setVehicleActive(agvDetail.modelUuid, false);
setVehicleState(agvDetail.modelUuid, 'idle');
setPath([]);
setCurrentPhase('stationed')
}
useEffect(() => {
if (isPlaying) {
if (!agvDetail.isActive && agvDetail.state === 'idle' && currentPhase === 'stationed') {
const toPickupPath = computePath(
new THREE.Vector3(agvDetail.position[0], agvDetail.position[1], agvDetail.position[2]),
agvDetail.point.action.pickUpPoint
);
setPath(toPickupPath);
setVehicleActive(agvDetail.modelUuid, true);
setVehicleState(agvDetail.modelUuid, 'running');
setCurrentPhase('stationed-pickup');
vehicleStatus(agvDetail.modelUuid, 'Started from station, heading to pickup');
return;
} else if (
!agvDetail.isActive &&
agvDetail.state === 'idle' &&
currentPhase === 'picking'
) {
useEffect(() => {
if (isPlaying) {
if (!agvDetail.isActive && agvDetail.state === 'idle' && currentPhase === 'stationed') {
const toPickupPath = computePath(
new THREE.Vector3(agvDetail.position[0], agvDetail.position[1], agvDetail.position[2]),
agvDetail.point.action.pickUpPoint
);
setPath(toPickupPath);
setVehicleActive(agvDetail.modelUuid, true);
setVehicleState(agvDetail.modelUuid, 'running');
setCurrentPhase('stationed-pickup');
vehicleStatus(agvDetail.modelUuid, 'Started from station, heading to pickup');
return;
} else if (!agvDetail.isActive && agvDetail.state === 'idle' && currentPhase === 'picking') {
setTimeout(() => {
incrementVehicleLoad(agvDetail.modelUuid, 2);
}, 5000);
setTimeout(() => {
incrementVehicleLoad(agvDetail.modelUuid, 2);
}, 5000);
if (agvDetail.currentLoad === agvDetail.point.action.loadCapacity) {
const toDrop = computePath(
agvDetail.point.action.pickUpPoint,
agvDetail.point.action.unLoadPoint
);
setPath(toDrop);
setVehicleActive(agvDetail.modelUuid, true);
setVehicleState(agvDetail.modelUuid, 'running');
setCurrentPhase('pickup-drop');
vehicleStatus(agvDetail.modelUuid, 'Started from pickup point, heading to drop point');
if (agvDetail.currentLoad === agvDetail.point.action.loadCapacity) {
const toDrop = computePath(
agvDetail.point.action.pickUpPoint,
agvDetail.point.action.unLoadPoint
);
setPath(toDrop);
setVehicleActive(agvDetail.modelUuid, true);
setVehicleState(agvDetail.modelUuid, 'running');
setCurrentPhase('pickup-drop');
vehicleStatus(agvDetail.modelUuid, 'Started from pickup point, heading to drop point');
}
} else if (!agvDetail.isActive && agvDetail.state === 'idle' && currentPhase === 'dropping' && agvDetail.currentLoad === 0) {
const dropToPickup = computePath(
agvDetail.point.action.unLoadPoint,
agvDetail.point.action.pickUpPoint
);
setPath(dropToPickup);
setVehicleActive(agvDetail.modelUuid, true);
setVehicleState(agvDetail.modelUuid, 'running');
setCurrentPhase('drop-pickup');
vehicleStatus(agvDetail.modelUuid, 'Started from dropping point, heading to pickup point');
}
}
} else if (
!agvDetail.isActive &&
agvDetail.state === 'idle' &&
currentPhase === 'dropping' &&
agvDetail.currentLoad === 0
) {
const dropToPickup = computePath(
agvDetail.point.action.unLoadPoint,
agvDetail.point.action.pickUpPoint
);
setPath(dropToPickup);
setVehicleActive(agvDetail.modelUuid, true);
setVehicleState(agvDetail.modelUuid, 'running');
setCurrentPhase('drop-pickup');
vehicleStatus(agvDetail.modelUuid, 'Started from dropping point, heading to pickup point');
}
}
}, [vehicles, currentPhase, path, isPlaying, isReset]);
}, [vehicles, currentPhase, path, isPlaying, isReset]);
function handleCallBack() {
if (currentPhase === 'stationed-pickup') {
setVehicleActive(agvDetail.modelUuid, false);
setVehicleState(agvDetail.modelUuid, 'idle');
setCurrentPhase('picking');
vehicleStatus(agvDetail.modelUuid, 'Reached pickup point, waiting for material');
setPath([]);
} else if (currentPhase === 'pickup-drop') {
setVehicleActive(agvDetail.modelUuid, false);
setVehicleState(agvDetail.modelUuid, 'idle');
setCurrentPhase('dropping');
vehicleStatus(agvDetail.modelUuid, 'Reached drop point');
setPath([]);
} else if (currentPhase === 'drop-pickup') {
setVehicleActive(agvDetail.modelUuid, false);
setVehicleState(agvDetail.modelUuid, 'idle');
setCurrentPhase('picking');
setPath([]);
vehicleStatus(agvDetail.modelUuid, 'Reached pickup point again, cycle complete');
function handleCallBack() {
if (currentPhase === 'stationed-pickup') {
setVehicleActive(agvDetail.modelUuid, false);
setVehicleState(agvDetail.modelUuid, 'idle');
setCurrentPhase('picking');
vehicleStatus(agvDetail.modelUuid, 'Reached pickup point, waiting for material');
setPath([]);
} else if (currentPhase === 'pickup-drop') {
setVehicleActive(agvDetail.modelUuid, false);
setVehicleState(agvDetail.modelUuid, 'idle');
setCurrentPhase('dropping');
vehicleStatus(agvDetail.modelUuid, 'Reached drop point');
setPath([]);
} else if (currentPhase === 'drop-pickup') {
setVehicleActive(agvDetail.modelUuid, false);
setVehicleState(agvDetail.modelUuid, 'idle');
setCurrentPhase('picking');
setPath([]);
vehicleStatus(agvDetail.modelUuid, 'Reached pickup point again, cycle complete');
}
}
}
return (
<>
<VehicleAnimator
path={path}
handleCallBack={handleCallBack}
currentPhase={currentPhase}
agvUuid={agvDetail?.modelUuid}
agvDetail={agvDetail}
reset={reset}
/>
</>
);
return (
<>
<VehicleAnimator
path={path}
handleCallBack={handleCallBack}
currentPhase={currentPhase}
agvUuid={agvDetail?.modelUuid}
agvDetail={agvDetail}
reset={reset}
/>
</>
);
}
export default VehicleInstance;

View File

@ -28,8 +28,8 @@ function Vehicles() {
actionType: "travel",
unLoadDuration: 10,
loadCapacity: 2,
pickUpPoint: { x: 98.71483985219794, y: 0, z: 28.66321267938962 },
unLoadPoint: { x: 105.71483985219794, y: 0, z: 28.66321267938962 },
pickUpPoint: { position: { x: 98.71483985219794, y: 0, z: 28.66321267938962 }, rotation: { x: 0, y: 0, z: 0 } },
unLoadPoint: { position: { x: 105.71483985219794, y: 0, z: 28.66321267938962 }, rotation: { x: 0, y: 0, z: 0 } },
triggers: [
{
triggerUuid: "trig-001",
@ -71,8 +71,8 @@ function Vehicles() {
actionType: "travel",
unLoadDuration: 10,
loadCapacity: 2,
pickUpPoint: { x: 90, y: 0, z: 28 },
unLoadPoint: { x: 20, y: 0, z: 10 },
pickUpPoint: { position: { x: 90, y: 0, z: 28 }, rotation: { x: 0, y: 0, z: 0 } },
unLoadPoint: { position: { x: 20, y: 0, z: 10 }, rotation: { x: 0, y: 0, z: 0 } },
triggers: [
{
triggerUuid: "trig-001",
@ -95,7 +95,8 @@ function Vehicles() {
]
}
}
}, {
},
{
modelUuid: "e729a4f1-11d2-4778-8d6a-468f1b4f6b79",
modelName: "forklift",
position: [98.85729337188162, 0, 38.36616546567653],
@ -113,8 +114,8 @@ function Vehicles() {
actionType: "travel",
unLoadDuration: 15,
loadCapacity: 5,
pickUpPoint: { x: 98.71483985219794, y: 0, z: 28.66321267938962 },
unLoadPoint: { x: 20, y: 0, z: 10 },
pickUpPoint: { position: { x: 98.71483985219794, y: 0, z: 28.66321267938962 }, rotation: { x: 0, y: 0, z: 0 } },
unLoadPoint: { position: { x: 20, y: 0, z: 10 }, rotation: { x: 0, y: 0, z: 0 } },
triggers: [
{
triggerUuid: "trig-001",

View File

@ -44,8 +44,8 @@ interface VehiclePointSchema {
actionType: "travel";
unLoadDuration: number;
loadCapacity: number;
pickUpPoint: { x: number; y: number, z: number } | null;
unLoadPoint: { x: number; y: number, z: number } | null;
pickUpPoint: { position: { x: number; y: number, z: number }, rotation: { x: number; y: number, z: number } } | null;
unLoadPoint: { position: { x: number; y: number, z: number }, rotation: { x: number; y: number, z: number } } | null;
triggers: TriggerSchema[];
};
}
@ -134,7 +134,7 @@ interface ConveyorStatus extends ConveyorEventSchema {
isActive: boolean;
idleTime: number;
activeTime: number;
}
interface MachineStatus extends MachineEventSchema {