From 82a7cd0001b0efd91e7dcc91b73a1f58f0a1f720 Mon Sep 17 00:00:00 2001 From: Poovizhi99 Date: Tue, 15 Apr 2025 09:11:01 +0530 Subject: [PATCH 01/12] updated paths --- .../modules/simulation/path/pathConnector.tsx | 2562 ++++++++++------- 1 file changed, 1445 insertions(+), 1117 deletions(-) diff --git a/app/src/modules/simulation/path/pathConnector.tsx b/app/src/modules/simulation/path/pathConnector.tsx index c561cbb..f6ee51f 100644 --- a/app/src/modules/simulation/path/pathConnector.tsx +++ b/app/src/modules/simulation/path/pathConnector.tsx @@ -1,1170 +1,1498 @@ -import { useFrame, useThree } from '@react-three/fiber'; -import React, { useEffect, useRef, useState } from 'react'; -import * as THREE from 'three'; -import * as Types from '../../../types/world/worldTypes'; -import { QuadraticBezierLine } from '@react-three/drei'; -import { useDeleteTool, useIsConnecting, useRenderDistance, useSimulationStates, useSocketStore } from '../../../store/store'; -import useModuleStore from '../../../store/useModuleStore'; -import { usePlayButtonStore } from '../../../store/usePlayButtonStore'; -import { setEventApi } from '../../../services/factoryBuilder/assest/floorAsset/setEventsApt'; +import { useFrame, useThree } from "@react-three/fiber"; +import React, { useEffect, useRef, useState } from "react"; +import * as THREE from "three"; +import * as Types from "../../../types/world/worldTypes"; +import { QuadraticBezierLine } from "@react-three/drei"; +import { + useDeleteTool, + useIsConnecting, + useRenderDistance, + useSimulationStates, + useSocketStore, +} from "../../../store/store"; +import useModuleStore from "../../../store/useModuleStore"; +import { usePlayButtonStore } from "../../../store/usePlayButtonStore"; +import { setEventApi } from "../../../services/factoryBuilder/assest/floorAsset/setEventsApt"; -function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObject }) { - const { activeModule } = useModuleStore(); - const { gl, raycaster, scene, pointer, camera } = useThree(); - const { deleteTool } = useDeleteTool(); - const { renderDistance } = useRenderDistance(); - const { setIsConnecting } = useIsConnecting(); - const { simulationStates, setSimulationStates } = useSimulationStates(); - const { isPlaying } = usePlayButtonStore(); - const { socket } = useSocketStore(); - const groupRefs = useRef<{ [key: string]: any }>({}); +function PathConnector({ + pathsGroupRef, +}: { + pathsGroupRef: React.MutableRefObject; +}) { + const { activeModule } = useModuleStore(); + const { gl, raycaster, scene, pointer, camera } = useThree(); + const { deleteTool } = useDeleteTool(); + const { renderDistance } = useRenderDistance(); + const { setIsConnecting } = useIsConnecting(); + const { simulationStates, setSimulationStates } = useSimulationStates(); + const { isPlaying } = usePlayButtonStore(); + const { socket } = useSocketStore(); + const groupRefs = useRef<{ [key: string]: any }>({}); - const [firstSelected, setFirstSelected] = useState<{ modelUUID: string; sphereUUID: string; position: THREE.Vector3; isCorner: boolean; } | null>(null); - const [currentLine, setCurrentLine] = useState<{ start: THREE.Vector3, end: THREE.Vector3, mid: THREE.Vector3 } | null>(null); - const [helperlineColor, setHelperLineColor] = useState('red'); - const [hoveredLineKey, setHoveredLineKey] = useState(null); + const [firstSelected, setFirstSelected] = useState<{ + modelUUID: string; + sphereUUID: string; + position: THREE.Vector3; + isCorner: boolean; + } | null>(null); + const [currentLine, setCurrentLine] = useState<{ + start: THREE.Vector3; + end: THREE.Vector3; + mid: THREE.Vector3; + } | null>(null); + const [helperlineColor, setHelperLineColor] = useState("red"); + const [hoveredLineKey, setHoveredLineKey] = useState(null); - const updatePathConnections = (fromModelUUID: string, fromPointUUID: string, toModelUUID: string, toPointUUID: string) => { - const updatedPaths = simulationStates.map(path => { - if (path.type === 'Conveyor') { - // Handle outgoing connections from Conveyor - if (path.modeluuid === fromModelUUID) { - return { - ...path, - points: path.points.map(point => { - if (point.uuid === fromPointUUID) { - const newTarget = { - modelUUID: toModelUUID, - pointUUID: toPointUUID - }; - const existingTargets = point.connections.targets || []; + const updatePathConnections = ( + fromModelUUID: string, + fromPointUUID: string, + toModelUUID: string, + toPointUUID: string + ) => { + const updatedPaths = simulationStates.map((path) => { + if (path.type === "Conveyor") { + // Handle outgoing connections from Conveyor + if (path.modeluuid === fromModelUUID) { + return { + ...path, + points: path.points.map((point) => { + if (point.uuid === fromPointUUID) { + const newTarget = { + modelUUID: toModelUUID, + pointUUID: toPointUUID, + }; + const existingTargets = point.connections.targets || []; - if (!existingTargets.some(target => - target.modelUUID === newTarget.modelUUID && - target.pointUUID === newTarget.pointUUID - )) { - return { - ...point, - connections: { - ...point.connections, - targets: [...existingTargets, newTarget] - } - }; - } - } - return point; - }) - }; + if ( + !existingTargets.some( + (target) => + target.modelUUID === newTarget.modelUUID && + target.pointUUID === newTarget.pointUUID + ) + ) { + return { + ...point, + connections: { + ...point.connections, + targets: [...existingTargets, newTarget], + }, + }; } - // Handle incoming connections to Conveyor - else if (path.modeluuid === toModelUUID) { - return { - ...path, - points: path.points.map(point => { - if (point.uuid === toPointUUID) { - const reverseTarget = { - modelUUID: fromModelUUID, - pointUUID: fromPointUUID - }; - const existingTargets = point.connections.targets || []; + } + return point; + }), + }; + } + // Handle incoming connections to Conveyor + else if (path.modeluuid === toModelUUID) { + return { + ...path, + points: path.points.map((point) => { + if (point.uuid === toPointUUID) { + const reverseTarget = { + modelUUID: fromModelUUID, + pointUUID: fromPointUUID, + }; + const existingTargets = point.connections.targets || []; - if (!existingTargets.some(target => - target.modelUUID === reverseTarget.modelUUID && - target.pointUUID === reverseTarget.pointUUID - )) { - return { - ...point, - connections: { - ...point.connections, - targets: [...existingTargets, reverseTarget] - } - }; - } - } - return point; - }) - }; + if ( + !existingTargets.some( + (target) => + target.modelUUID === reverseTarget.modelUUID && + target.pointUUID === reverseTarget.pointUUID + ) + ) { + return { + ...point, + connections: { + ...point.connections, + targets: [...existingTargets, reverseTarget], + }, + }; } - } - else if (path.type === 'Vehicle') { - // Handle outgoing connections from Vehicle - if (path.modeluuid === fromModelUUID && path.points.uuid === fromPointUUID) { - const newTarget = { - modelUUID: toModelUUID, - pointUUID: toPointUUID - }; - const existingTargets = path.points.connections.targets || []; - - // Check if target is a Conveyor - const toPath = simulationStates.find(p => p.modeluuid === toModelUUID); - if (toPath?.type !== 'Conveyor') { - console.log("Vehicle can only connect to Conveyors"); - return path; - } - - // Check if already has a connection - if (existingTargets.length >= 1) { - console.log("Vehicle can have only one connection"); - return path; - } - - if (!existingTargets.some(target => - target.modelUUID === newTarget.modelUUID && - target.pointUUID === newTarget.pointUUID - )) { - return { - ...path, - points: { - ...path.points, - connections: { - ...path.points.connections, - targets: [...existingTargets, newTarget] - } - } - }; - } - } - // Handle incoming connections to Vehicle - else if (path.modeluuid === toModelUUID && path.points.uuid === toPointUUID) { - const reverseTarget = { - modelUUID: fromModelUUID, - pointUUID: fromPointUUID - }; - const existingTargets = path.points.connections.targets || []; - - // Check if source is a Conveyor - const fromPath = simulationStates.find(p => p.modeluuid === fromModelUUID); - if (fromPath?.type !== 'Conveyor') { - console.log("Vehicle can only connect to Conveyors"); - return path; - } - - // Check if already has a connection - if (existingTargets.length >= 1) { - console.log("Vehicle can have only one connection"); - return path; - } - - if (!existingTargets.some(target => - target.modelUUID === reverseTarget.modelUUID && - target.pointUUID === reverseTarget.pointUUID - )) { - return { - ...path, - points: { - ...path.points, - connections: { - ...path.points.connections, - targets: [...existingTargets, reverseTarget] - } - } - }; - } - } - return path; - } - else if (path.type === 'StaticMachine') { - // Handle outgoing connections from StaticMachine - if (path.modeluuid === fromModelUUID && path.points.uuid === fromPointUUID) { - const newTarget = { - modelUUID: toModelUUID, - pointUUID: toPointUUID - }; - - // Ensure target is an ArmBot - const toPath = simulationStates.find(p => p.modeluuid === toModelUUID); - if (toPath?.type !== 'ArmBot') { - console.log("StaticMachine can only connect to ArmBot"); - return path; - } - - const existingTargets = path.points.connections.targets || []; - - // Allow only one connection - if (existingTargets.length >= 1) { - console.log("StaticMachine can only have one connection"); - return path; - } - - if (!existingTargets.some(target => - target.modelUUID === newTarget.modelUUID && - target.pointUUID === newTarget.pointUUID - )) { - return { - ...path, - points: { - ...path.points, - connections: { - ...path.points.connections, - targets: [...existingTargets, newTarget] - } - } - }; - } - } - - // Handle incoming connections to StaticMachine - else if (path.modeluuid === toModelUUID && path.points.uuid === toPointUUID) { - const reverseTarget = { - modelUUID: fromModelUUID, - pointUUID: fromPointUUID - }; - - const fromPath = simulationStates.find(p => p.modeluuid === fromModelUUID); - if (fromPath?.type !== 'ArmBot') { - console.log("StaticMachine can only be connected from ArmBot"); - return path; - } - - const existingTargets = path.points.connections.targets || []; - - if (existingTargets.length >= 1) { - console.log("StaticMachine can only have one connection"); - return path; - } - - if (!existingTargets.some(target => - target.modelUUID === reverseTarget.modelUUID && - target.pointUUID === reverseTarget.pointUUID - )) { - return { - ...path, - points: { - ...path.points, - connections: { - ...path.points.connections, - targets: [...existingTargets, reverseTarget] - } - } - }; - } - } - return path; - } - else if (path.type === 'ArmBot') { - // Handle outgoing connections from ArmBot - if (path.modeluuid === fromModelUUID && path.points.uuid === fromPointUUID) { - const newTarget = { - modelUUID: toModelUUID, - pointUUID: toPointUUID - }; - - const toPath = simulationStates.find(p => p.modeluuid === toModelUUID); - if (!toPath) return path; - - const existingTargets = path.points.connections.targets || []; - - // Check if connecting to a StaticMachine and already connected to one - const alreadyConnectedToStatic = existingTargets.some(target => { - const targetPath = simulationStates.find(p => p.modeluuid === target.modelUUID); - return targetPath?.type === 'StaticMachine'; - }); - - if (toPath.type === 'StaticMachine') { - if (alreadyConnectedToStatic) { - console.log("ArmBot can only connect to one StaticMachine"); - return path; - } - } - - if (!existingTargets.some(target => - target.modelUUID === newTarget.modelUUID && - target.pointUUID === newTarget.pointUUID - )) { - return { - ...path, - points: { - ...path.points, - connections: { - ...path.points.connections, - targets: [...existingTargets, newTarget] - } - } - }; - } - } - - // Handle incoming connections to ArmBot - else if (path.modeluuid === toModelUUID && path.points.uuid === toPointUUID) { - const reverseTarget = { - modelUUID: fromModelUUID, - pointUUID: fromPointUUID - }; - - const fromPath = simulationStates.find(p => p.modeluuid === fromModelUUID); - if (!fromPath) return path; - - const existingTargets = path.points.connections.targets || []; - - const alreadyConnectedFromStatic = existingTargets.some(target => { - const targetPath = simulationStates.find(p => p.modeluuid === target.modelUUID); - return targetPath?.type === 'StaticMachine'; - }); - - if (fromPath.type === 'StaticMachine') { - if (alreadyConnectedFromStatic) { - console.log("ArmBot can only be connected from one StaticMachine"); - return path; - } - } - - if (!existingTargets.some(target => - target.modelUUID === reverseTarget.modelUUID && - target.pointUUID === reverseTarget.pointUUID - )) { - return { - ...path, - points: { - ...path.points, - connections: { - ...path.points.connections, - targets: [...existingTargets, reverseTarget] - } - } - }; - } - } - return path; - } + } + return point; + }), + }; + } + } else if (path.type === "Vehicle") { + // Handle outgoing connections from Vehicle + if ( + path.modeluuid === fromModelUUID && + path.points.uuid === fromPointUUID + ) { + const newTarget = { + modelUUID: toModelUUID, + pointUUID: toPointUUID, + }; + const existingTargets = path.points.connections.targets || []; + // Check if target is a Conveyor + const toPath = simulationStates.find( + (p) => p.modeluuid === toModelUUID + ); + if (toPath?.type !== "Conveyor") { + console.log("Vehicle can only connect to Conveyors"); return path; - }); + } - setSimulationStates(updatedPaths); + // Check if already has a connection + if (existingTargets.length >= 1) { + console.log("Vehicle can have only one connection"); + return path; + } - const updatedPathDetails = updatedPaths.filter(path => - path.modeluuid === fromModelUUID || path.modeluuid === toModelUUID - ); + if ( + !existingTargets.some( + (target) => + target.modelUUID === newTarget.modelUUID && + target.pointUUID === newTarget.pointUUID + ) + ) { + return { + ...path, + points: { + ...path.points, + connections: { + ...path.points.connections, + targets: [...existingTargets, newTarget], + }, + }, + }; + } + } + // Handle incoming connections to Vehicle + else if ( + path.modeluuid === toModelUUID && + path.points.uuid === toPointUUID + ) { + const reverseTarget = { + modelUUID: fromModelUUID, + pointUUID: fromPointUUID, + }; + const existingTargets = path.points.connections.targets || []; - updateBackend(updatedPathDetails); + // Check if source is a Conveyor + const fromPath = simulationStates.find( + (p) => p.modeluuid === fromModelUUID + ); + if (fromPath?.type !== "Conveyor") { + console.log("Vehicle can only connect to Conveyors"); + return path; + } + + // Check if already has a connection + if (existingTargets.length >= 1) { + console.log("Vehicle can have only one connection"); + return path; + } + + if ( + !existingTargets.some( + (target) => + target.modelUUID === reverseTarget.modelUUID && + target.pointUUID === reverseTarget.pointUUID + ) + ) { + return { + ...path, + points: { + ...path.points, + connections: { + ...path.points.connections, + targets: [...existingTargets, reverseTarget], + }, + }, + }; + } + } + return path; + } else if (path.type === "StaticMachine") { + // Handle outgoing connections from StaticMachine + if ( + path.modeluuid === fromModelUUID && + path.points.uuid === fromPointUUID + ) { + const newTarget = { + modelUUID: toModelUUID, + pointUUID: toPointUUID, + }; + + // Ensure target is an ArmBot + const toPath = simulationStates.find( + (p) => p.modeluuid === toModelUUID + ); + if (toPath?.type !== "ArmBot") { + console.log("StaticMachine can only connect to ArmBot"); + return path; + } + + const existingTargets = path.points.connections.targets || []; + + // Allow only one connection + if (existingTargets.length >= 1) { + console.log("StaticMachine can only have one connection"); + return path; + } + + if ( + !existingTargets.some( + (target) => + target.modelUUID === newTarget.modelUUID && + target.pointUUID === newTarget.pointUUID + ) + ) { + return { + ...path, + points: { + ...path.points, + connections: { + ...path.points.connections, + targets: [...existingTargets, newTarget], + }, + }, + }; + } + } + + // Handle incoming connections to StaticMachine + else if ( + path.modeluuid === toModelUUID && + path.points.uuid === toPointUUID + ) { + const reverseTarget = { + modelUUID: fromModelUUID, + pointUUID: fromPointUUID, + }; + + const fromPath = simulationStates.find( + (p) => p.modeluuid === fromModelUUID + ); + if (fromPath?.type !== "ArmBot") { + console.log("StaticMachine can only be connected from ArmBot"); + return path; + } + + const existingTargets = path.points.connections.targets || []; + + if (existingTargets.length >= 1) { + console.log("StaticMachine can only have one connection"); + return path; + } + + if ( + !existingTargets.some( + (target) => + target.modelUUID === reverseTarget.modelUUID && + target.pointUUID === reverseTarget.pointUUID + ) + ) { + return { + ...path, + points: { + ...path.points, + connections: { + ...path.points.connections, + targets: [...existingTargets, reverseTarget], + }, + }, + }; + } + } + return path; + } else if (path.type === "ArmBot") { + // Handle outgoing connections from ArmBot + if ( + path.modeluuid === fromModelUUID && + path.points.uuid === fromPointUUID + ) { + const newTarget = { + modelUUID: toModelUUID, + pointUUID: toPointUUID, + }; + + const toPath = simulationStates.find( + (p) => p.modeluuid === toModelUUID + ); + if (!toPath) return path; + + const existingTargets = path.points.connections.targets || []; + + // Check if connecting to a StaticMachine and already connected to one + const alreadyConnectedToStatic = existingTargets.some((target) => { + const targetPath = simulationStates.find( + (p) => p.modeluuid === target.modelUUID + ); + return targetPath?.type === "StaticMachine"; + }); + + if (toPath.type === "StaticMachine") { + if (alreadyConnectedToStatic) { + console.log("ArmBot can only connect to one StaticMachine"); + return path; + } + } + + if ( + !existingTargets.some( + (target) => + target.modelUUID === newTarget.modelUUID && + target.pointUUID === newTarget.pointUUID + ) + ) { + return { + ...path, + points: { + ...path.points, + connections: { + ...path.points.connections, + targets: [...existingTargets, newTarget], + }, + }, + }; + } + } + + // Handle incoming connections to ArmBot + else if ( + path.modeluuid === toModelUUID && + path.points.uuid === toPointUUID + ) { + const reverseTarget = { + modelUUID: fromModelUUID, + pointUUID: fromPointUUID, + }; + + const fromPath = simulationStates.find( + (p) => p.modeluuid === fromModelUUID + ); + if (!fromPath) return path; + + const existingTargets = path.points.connections.targets || []; + + const alreadyConnectedFromStatic = existingTargets.some((target) => { + const targetPath = simulationStates.find( + (p) => p.modeluuid === target.modelUUID + ); + return targetPath?.type === "StaticMachine"; + }); + + if (fromPath.type === "StaticMachine") { + if (alreadyConnectedFromStatic) { + console.log( + "ArmBot can only be connected from one StaticMachine" + ); + return path; + } + } + + if ( + !existingTargets.some( + (target) => + target.modelUUID === reverseTarget.modelUUID && + target.pointUUID === reverseTarget.pointUUID + ) + ) { + return { + ...path, + points: { + ...path.points, + connections: { + ...path.points.connections, + targets: [...existingTargets, reverseTarget], + }, + }, + }; + } + } + return path; + } + + return path; + }); + + setSimulationStates(updatedPaths); + + const updatedPathDetails = updatedPaths.filter( + (path) => + path.modeluuid === fromModelUUID || path.modeluuid === toModelUUID + ); + + updateBackend(updatedPathDetails); + }; + + const updateBackend = async ( + updatedPaths: ( + | Types.ConveyorEventsSchema + | Types.VehicleEventsSchema + | Types.StaticMachineEventsSchema + | Types.ArmBotEventsSchema + )[] + ) => { + if (updatedPaths.length === 0) return; + const email = localStorage.getItem("email"); + const organization = email ? email.split("@")[1].split(".")[0] : ""; + + updatedPaths.forEach(async (updatedPath) => { + if (updatedPath.type === "Conveyor") { + // await setEventApi( + // organization, + // updatedPath.modeluuid, + // { type: "Conveyor", points: updatedPath.points, speed: updatedPath.speed } + // ); + + const data = { + organization: organization, + modeluuid: updatedPath.modeluuid, + eventData: { + type: "Conveyor", + points: updatedPath.points, + speed: updatedPath.speed, + }, + }; + + socket.emit("v2:model-asset:updateEventData", data); + } else if (updatedPath.type === "Vehicle") { + // await setEventApi( + // organization, + // updatedPath.modeluuid, + // { type: "Vehicle", points: updatedPath.points } + // ); + + const data = { + organization: organization, + modeluuid: updatedPath.modeluuid, + eventData: { type: "Vehicle", points: updatedPath.points }, + }; + + socket.emit("v2:model-asset:updateEventData", data); + } else if (updatedPath.type === "StaticMachine") { + // await setEventApi( + // organization, + // updatedPath.modeluuid, + // { type: "StaticMachine", points: updatedPath.points } + // ); + + const data = { + organization: organization, + modeluuid: updatedPath.modeluuid, + eventData: { type: "StaticMachine", points: updatedPath.points }, + }; + + socket.emit("v2:model-asset:updateEventData", data); + } else if (updatedPath.type === "ArmBot") { + // await setEventApi( + // organization, + // updatedPath.modeluuid, + // { type: "ArmBot", points: updatedPath.points } + // ); + + const data = { + organization: organization, + modeluuid: updatedPath.modeluuid, + eventData: { type: "ArmBot", points: updatedPath.points }, + }; + + socket.emit("v2:model-asset:updateEventData", data); + } + }); + }; + + const handleAddConnection = ( + fromModelUUID: string, + fromUUID: string, + toModelUUID: string, + toUUID: string + ) => { + updatePathConnections(fromModelUUID, fromUUID, toModelUUID, toUUID); + setFirstSelected(null); + setCurrentLine(null); + setIsConnecting(false); + }; + + useEffect(() => { + const canvasElement = gl.domElement; + let drag = false; + let MouseDown = false; + + const onMouseDown = () => { + MouseDown = true; + drag = false; }; - const updateBackend = async (updatedPaths: (Types.ConveyorEventsSchema | Types.VehicleEventsSchema | Types.StaticMachineEventsSchema | Types.ArmBotEventsSchema)[]) => { - if (updatedPaths.length === 0) return; - const email = localStorage.getItem("email"); - const organization = email ? email.split("@")[1].split(".")[0] : ""; + const onMouseUp = () => { + MouseDown = false; + }; - updatedPaths.forEach(async (updatedPath) => { - if (updatedPath.type === 'Conveyor') { + const onMouseMove = () => { + if (MouseDown) { + drag = true; + } + }; - // await setEventApi( - // organization, - // updatedPath.modeluuid, - // { type: "Conveyor", points: updatedPath.points, speed: updatedPath.speed } - // ); + const onContextMenu = (evt: MouseEvent) => { + evt.preventDefault(); + if (drag || evt.button === 0) return; - const data = { - organization: organization, - modeluuid: updatedPath.modeluuid, - eventData: { type: "Conveyor", points: updatedPath.points, speed: updatedPath.speed } - } + raycaster.setFromCamera(pointer, camera); + const intersects = raycaster.intersectObjects( + pathsGroupRef.current.children, + true + ); - socket.emit('v2:model-asset:updateEventData', data); + if (intersects.length > 0) { + const intersected = intersects[0].object; - } else if (updatedPath.type === 'Vehicle') { + if (intersected.name.includes("events-sphere")) { + const modelUUID = intersected.userData.path.modeluuid; + const sphereUUID = intersected.uuid; + const worldPosition = new THREE.Vector3(); + intersected.getWorldPosition(worldPosition); - // await setEventApi( - // organization, - // updatedPath.modeluuid, - // { type: "Vehicle", points: updatedPath.points } - // ); + let isStartOrEnd = false; - const data = { - organization: organization, - modeluuid: updatedPath.modeluuid, - eventData: { type: "Vehicle", points: updatedPath.points } - } + if ( + intersected.userData.path.points && + intersected.userData.path.points.length > 1 + ) { + isStartOrEnd = + intersected.userData.path.points.length > 0 && + (sphereUUID === intersected.userData.path.points[0].uuid || + sphereUUID === + intersected.userData.path.points[ + intersected.userData.path.points.length - 1 + ].uuid); + } else if (intersected.userData.path.points) { + isStartOrEnd = sphereUUID === intersected.userData.path.points.uuid; + } - socket.emit('v2:model-asset:updateEventData', data); - - } else if (updatedPath.type === 'StaticMachine') { - - // await setEventApi( - // organization, - // updatedPath.modeluuid, - // { type: "StaticMachine", points: updatedPath.points } - // ); - - const data = { - organization: organization, - modeluuid: updatedPath.modeluuid, - eventData: { type: "StaticMachine", points: updatedPath.points } - } - - socket.emit('v2:model-asset:updateEventData', data); - - } else if (updatedPath.type === 'ArmBot') { - - // await setEventApi( - // organization, - // updatedPath.modeluuid, - // { type: "ArmBot", points: updatedPath.points } - // ); - - const data = { - organization: organization, - modeluuid: updatedPath.modeluuid, - eventData: { type: "ArmBot", points: updatedPath.points } - } - - socket.emit('v2:model-asset:updateEventData', data); + if (modelUUID) { + const firstPath = simulationStates.find( + (p) => p.modeluuid === firstSelected?.modelUUID + ); + const secondPath = simulationStates.find( + (p) => p.modeluuid === modelUUID + ); + // Prevent vehicle-to-vehicle connections + if ( + firstPath && + secondPath && + firstPath.type === "Vehicle" && + secondPath.type === "Vehicle" + ) { + console.log("Cannot connect two vehicle paths together"); + return; } - }) - } + // Prevent conveyor middle point to conveyor connections + if ( + firstPath && + secondPath && + firstPath.type === "Conveyor" && + secondPath.type === "Conveyor" && + (!firstSelected?.isCorner || !isStartOrEnd) + ) { + console.log( + "Conveyor connections must be between start/end points" + ); + return; + } - const handleAddConnection = (fromModelUUID: string, fromUUID: string, toModelUUID: string, toUUID: string) => { - updatePathConnections(fromModelUUID, fromUUID, toModelUUID, toUUID); + // Check if this specific connection already exists + const isDuplicateConnection = firstSelected + ? simulationStates.some((path) => { + if (path.modeluuid === firstSelected.modelUUID) { + if (path.type === "Conveyor") { + const point = path.points.find( + (p) => p.uuid === firstSelected.sphereUUID + ); + return point?.connections.targets.some( + (t) => + t.modelUUID === modelUUID && + t.pointUUID === sphereUUID + ); + } else if (path.type === "Vehicle") { + return path.points.connections.targets.some( + (t) => + t.modelUUID === modelUUID && + t.pointUUID === sphereUUID + ); + } + } + return false; + }) + : false; + + if (isDuplicateConnection) { + console.log("These points are already connected. Ignoring."); + return; + } + + // For Vehicles, check if they're already connected to anything + if (intersected.userData.path.type === "Vehicle") { + const vehicleConnections = + intersected.userData.path.points.connections.targets.length; + if (vehicleConnections >= 1) { + console.log("Vehicle can only have one connection"); + return; + } + } + + // For non-Vehicle paths, check if already connected + if (intersected.userData.path.type !== "Vehicle") { + const isAlreadyConnected = simulationStates.some((path) => { + if (path.type === "Conveyor") { + return path.points.some( + (point) => + point.uuid === sphereUUID && + point.connections.targets.length > 0 + ); + } + return false; + }); + + if (isAlreadyConnected) { + console.log("Conveyor point is already connected. Ignoring."); + return; + } + } + + if (firstSelected) { + // Check if trying to connect Vehicle to non-Conveyor + if ( + (firstPath?.type === "Vehicle" && + secondPath?.type !== "Conveyor") || + (secondPath?.type === "Vehicle" && + firstPath?.type !== "Conveyor") + ) { + console.log("Vehicle can only connect to Conveyors"); + return; + } + + // Prevent same-path connections + if (firstSelected.modelUUID === modelUUID) { + console.log("Cannot connect spheres on the same path."); + return; + } + + // Check if StaticMachine is involved in the connection + if ( + (firstPath?.type === "StaticMachine" && + secondPath?.type !== "ArmBot") || + (secondPath?.type === "StaticMachine" && + firstPath?.type !== "ArmBot") + ) { + console.log("StaticMachine can only connect to ArmBot"); + return; + } + + // Check if StaticMachine already has a connection + if (firstPath?.type === "StaticMachine") { + const staticConnections = + firstPath.points.connections.targets.length; + if (staticConnections >= 1) { + console.log("StaticMachine can only have one connection"); + return; + } + } + if (secondPath?.type === "StaticMachine") { + const staticConnections = + secondPath.points.connections.targets.length; + if (staticConnections >= 1) { + console.log("StaticMachine can only have one connection"); + return; + } + } + + // Check if ArmBot is involved + if ( + (firstPath?.type === "ArmBot" && + secondPath?.type === "StaticMachine") || + (secondPath?.type === "ArmBot" && + firstPath?.type === "StaticMachine") + ) { + const armBotPath = + firstPath?.type === "ArmBot" ? firstPath : secondPath; + const staticPath = + firstPath?.type === "StaticMachine" ? firstPath : secondPath; + + const armBotConnections = + armBotPath.points.connections.targets || []; + const alreadyConnectedToStatic = armBotConnections.some( + (target) => { + const targetPath = simulationStates.find( + (p) => p.modeluuid === target.modelUUID + ); + return targetPath?.type === "StaticMachine"; + } + ); + + if (alreadyConnectedToStatic) { + console.log("ArmBot can only connect to one StaticMachine"); + return; + } + + const staticConnections = + staticPath.points.connections.targets.length; + if (staticConnections >= 1) { + console.log("StaticMachine can only have one connection"); + return; + } + } + + // Prevent ArmBot ↔ ArmBot + if ( + firstPath?.type === "ArmBot" && + secondPath?.type === "ArmBot" + ) { + console.log("Cannot connect two ArmBots together"); + return; + } + + // If one is ArmBot, ensure the other is StaticMachine or Conveyor + if ( + firstPath?.type === "ArmBot" || + secondPath?.type === "ArmBot" + ) { + const otherType = + firstPath?.type === "ArmBot" + ? secondPath?.type + : firstPath?.type; + if (otherType !== "StaticMachine" && otherType !== "Conveyor") { + console.log( + "ArmBot can only connect to Conveyors or one StaticMachine" + ); + return; + } + } + + // At least one must be start/end point + if (!firstSelected.isCorner && !isStartOrEnd) { + console.log( + "At least one of the selected spheres must be a start or end point." + ); + return; + } + + // All checks passed - make the connection + handleAddConnection( + firstSelected.modelUUID, + firstSelected.sphereUUID, + modelUUID, + sphereUUID + ); + } else { + // First selection - just store it + setFirstSelected({ + modelUUID, + sphereUUID, + position: worldPosition, + isCorner: isStartOrEnd, + }); + setIsConnecting(true); + } + } + } + } else { + // Clicked outside - cancel connection setFirstSelected(null); setCurrentLine(null); setIsConnecting(false); + } }; - useEffect(() => { - const canvasElement = gl.domElement; - let drag = false; - let MouseDown = false; + if (activeModule === "simulation" && !deleteTool) { + canvasElement.addEventListener("mousedown", onMouseDown); + canvasElement.addEventListener("mouseup", onMouseUp); + canvasElement.addEventListener("mousemove", onMouseMove); + canvasElement.addEventListener("contextmenu", onContextMenu); + } else { + setFirstSelected(null); + setCurrentLine(null); + setIsConnecting(false); + } - const onMouseDown = () => { - MouseDown = true; - drag = false; - }; + return () => { + canvasElement.removeEventListener("mousedown", onMouseDown); + canvasElement.removeEventListener("mouseup", onMouseUp); + canvasElement.removeEventListener("mousemove", onMouseMove); + canvasElement.removeEventListener("contextmenu", onContextMenu); + }; + }, [camera, scene, raycaster, firstSelected, simulationStates, deleteTool]); - const onMouseUp = () => { - MouseDown = false; - }; - - const onMouseMove = () => { - if (MouseDown) { - drag = true; - } - }; - - const onContextMenu = (evt: MouseEvent) => { - evt.preventDefault(); - if (drag || evt.button === 0) return; - - raycaster.setFromCamera(pointer, camera); - const intersects = raycaster.intersectObjects(pathsGroupRef.current.children, true); - - if (intersects.length > 0) { - const intersected = intersects[0].object; - - if (intersected.name.includes("events-sphere")) { - const modelUUID = intersected.userData.path.modeluuid; - const sphereUUID = intersected.uuid; - const worldPosition = new THREE.Vector3(); - intersected.getWorldPosition(worldPosition); - - let isStartOrEnd = false; - - if (intersected.userData.path.points && intersected.userData.path.points.length > 1) { - isStartOrEnd = intersected.userData.path.points.length > 0 && ( - sphereUUID === intersected.userData.path.points[0].uuid || - sphereUUID === intersected.userData.path.points[intersected.userData.path.points.length - 1].uuid - ); - } else if (intersected.userData.path.points) { - isStartOrEnd = sphereUUID === intersected.userData.path.points.uuid; - } - - if (modelUUID) { - const firstPath = simulationStates.find(p => p.modeluuid === firstSelected?.modelUUID); - const secondPath = simulationStates.find(p => p.modeluuid === modelUUID); - - // Prevent vehicle-to-vehicle connections - if (firstPath && secondPath && firstPath.type === 'Vehicle' && secondPath.type === 'Vehicle') { - console.log("Cannot connect two vehicle paths together"); - return; - } - - // Prevent conveyor middle point to conveyor connections - if (firstPath && secondPath && - firstPath.type === 'Conveyor' && - secondPath.type === 'Conveyor' && - (!firstSelected?.isCorner || !isStartOrEnd)) { - console.log("Conveyor connections must be between start/end points"); - return; - } - - // Check if this specific connection already exists - const isDuplicateConnection = firstSelected - ? simulationStates.some(path => { - if (path.modeluuid === firstSelected.modelUUID) { - if (path.type === 'Conveyor') { - const point = path.points.find(p => p.uuid === firstSelected.sphereUUID); - return point?.connections.targets.some(t => - t.modelUUID === modelUUID && t.pointUUID === sphereUUID - ); - } else if (path.type === 'Vehicle') { - return path.points.connections.targets.some(t => - t.modelUUID === modelUUID && t.pointUUID === sphereUUID - ); - } - } - return false; - }) - : false; - - if (isDuplicateConnection) { - console.log("These points are already connected. Ignoring."); - return; - } - - // For Vehicles, check if they're already connected to anything - if (intersected.userData.path.type === 'Vehicle') { - const vehicleConnections = intersected.userData.path.points.connections.targets.length; - if (vehicleConnections >= 1) { - console.log("Vehicle can only have one connection"); - return; - } - } - - // For non-Vehicle paths, check if already connected - if (intersected.userData.path.type !== 'Vehicle') { - const isAlreadyConnected = simulationStates.some(path => { - if (path.type === 'Conveyor') { - return path.points.some(point => - point.uuid === sphereUUID && - point.connections.targets.length > 0 - ); - } - return false; - }); - - if (isAlreadyConnected) { - console.log("Conveyor point is already connected. Ignoring."); - return; - } - } - - if (firstSelected) { - // Check if trying to connect Vehicle to non-Conveyor - if ((firstPath?.type === 'Vehicle' && secondPath?.type !== 'Conveyor') || - (secondPath?.type === 'Vehicle' && firstPath?.type !== 'Conveyor')) { - console.log("Vehicle can only connect to Conveyors"); - return; - } - - // Prevent same-path connections - if (firstSelected.modelUUID === modelUUID) { - console.log("Cannot connect spheres on the same path."); - return; - } - - // Check if StaticMachine is involved in the connection - if ((firstPath?.type === 'StaticMachine' && secondPath?.type !== 'ArmBot') || - (secondPath?.type === 'StaticMachine' && firstPath?.type !== 'ArmBot')) { - console.log("StaticMachine can only connect to ArmBot"); - return; - } - - // Check if StaticMachine already has a connection - if (firstPath?.type === 'StaticMachine') { - const staticConnections = firstPath.points.connections.targets.length; - if (staticConnections >= 1) { - console.log("StaticMachine can only have one connection"); - return; - } - } - if (secondPath?.type === 'StaticMachine') { - const staticConnections = secondPath.points.connections.targets.length; - if (staticConnections >= 1) { - console.log("StaticMachine can only have one connection"); - return; - } - } - - // Check if ArmBot is involved - if ((firstPath?.type === 'ArmBot' && secondPath?.type === 'StaticMachine') || - (secondPath?.type === 'ArmBot' && firstPath?.type === 'StaticMachine')) { - - const armBotPath = firstPath?.type === 'ArmBot' ? firstPath : secondPath; - const staticPath = firstPath?.type === 'StaticMachine' ? firstPath : secondPath; - - const armBotConnections = armBotPath.points.connections.targets || []; - const alreadyConnectedToStatic = armBotConnections.some(target => { - const targetPath = simulationStates.find(p => p.modeluuid === target.modelUUID); - return targetPath?.type === 'StaticMachine'; - }); - - if (alreadyConnectedToStatic) { - console.log("ArmBot can only connect to one StaticMachine"); - return; - } - - const staticConnections = staticPath.points.connections.targets.length; - if (staticConnections >= 1) { - console.log("StaticMachine can only have one connection"); - return; - } - } - - // Prevent ArmBot ↔ ArmBot - if (firstPath?.type === 'ArmBot' && secondPath?.type === 'ArmBot') { - console.log("Cannot connect two ArmBots together"); - return; - } - - // If one is ArmBot, ensure the other is StaticMachine or Conveyor - if (firstPath?.type === 'ArmBot' || secondPath?.type === 'ArmBot') { - const otherType = firstPath?.type === 'ArmBot' ? secondPath?.type : firstPath?.type; - if (otherType !== 'StaticMachine' && otherType !== 'Conveyor') { - console.log("ArmBot can only connect to Conveyors or one StaticMachine"); - return; - } - } - - // At least one must be start/end point - if (!firstSelected.isCorner && !isStartOrEnd) { - console.log("At least one of the selected spheres must be a start or end point."); - return; - } - - // All checks passed - make the connection - handleAddConnection(firstSelected.modelUUID, firstSelected.sphereUUID, modelUUID, sphereUUID); - } else { - // First selection - just store it - setFirstSelected({ modelUUID, sphereUUID, position: worldPosition, isCorner: isStartOrEnd }); - setIsConnecting(true); - } - } - } - } else { - // Clicked outside - cancel connection - setFirstSelected(null); - setCurrentLine(null); - setIsConnecting(false); - } - }; - - if (activeModule === 'simulation' && !deleteTool) { - canvasElement.addEventListener("mousedown", onMouseDown); - canvasElement.addEventListener("mouseup", onMouseUp); - canvasElement.addEventListener("mousemove", onMouseMove); - canvasElement.addEventListener("contextmenu", onContextMenu); - } else { - setFirstSelected(null); - setCurrentLine(null); - setIsConnecting(false); - } - - return () => { - canvasElement.removeEventListener("mousedown", onMouseDown); - canvasElement.removeEventListener("mouseup", onMouseUp); - canvasElement.removeEventListener("mousemove", onMouseMove); - canvasElement.removeEventListener("contextmenu", onContextMenu); - }; - }, [camera, scene, raycaster, firstSelected, simulationStates, deleteTool]); - - useFrame(() => { - Object.values(groupRefs.current).forEach((group) => { - if (group) { - const distance = new THREE.Vector3(...group.position.toArray()).distanceTo(camera.position); - group.visible = ((distance <= renderDistance) && !isPlaying); - } - }); + useFrame(() => { + Object.values(groupRefs.current).forEach((group) => { + if (group) { + const distance = new THREE.Vector3( + ...group.position.toArray() + ).distanceTo(camera.position); + group.visible = distance <= renderDistance && !isPlaying; + } }); + }); - useFrame(() => { - if (firstSelected) { - raycaster.setFromCamera(pointer, camera); - const intersects = raycaster.intersectObjects(scene.children, true).filter((intersect) => - !intersect.object.name.includes("Roof") && - !intersect.object.name.includes("agv-collider") && - !intersect.object.name.includes("MeasurementReference") && - !intersect.object.userData.isPathObject && - !(intersect.object.type === "GridHelper") - ); - - let point: THREE.Vector3 | null = null; - let snappedSphere: { sphereUUID: string, position: THREE.Vector3, modelUUID: string, isCorner: boolean } | null = null; - let isInvalidConnection = false; - - if (intersects.length > 0) { - point = intersects[0].point; - if (point.y < 0.05) { - point = new THREE.Vector3(point.x, 0.05, point.z); - } - } - - const sphereIntersects = raycaster.intersectObjects(pathsGroupRef.current.children, true).filter((obj) => obj.object.name.includes("events-sphere")); - - if (sphereIntersects.length > 0) { - const sphere = sphereIntersects[0].object; - const sphereUUID = sphere.uuid; - const spherePosition = new THREE.Vector3(); - sphere.getWorldPosition(spherePosition); - const pathData = sphere.userData.path; - const modelUUID = pathData.modeluuid; - - const firstPath = simulationStates.find(p => p.modeluuid === firstSelected.modelUUID); - const secondPath = simulationStates.find(p => p.modeluuid === modelUUID); - const isVehicleToVehicle = firstPath?.type === 'Vehicle' && secondPath?.type === 'Vehicle'; - - // Inside the useFrame hook, where we check for snapped spheres: - const isConnectable = ( - pathData.type === 'Vehicle' || - pathData.type === 'ArmBot' || - (pathData.points.length > 0 && ( - sphereUUID === pathData.points[0].uuid || - sphereUUID === pathData.points[pathData.points.length - 1].uuid || - (pathData.type === 'Conveyor' && firstPath?.type === 'ArmBot') // Allow ArmBot to connect to middle points - )) - ) && - !isVehicleToVehicle && - !( - firstPath?.type === 'Conveyor' && - pathData.type === 'Conveyor' && - !firstSelected.isCorner - ); - - // Check for duplicate connection (regardless of path type) - const isDuplicateConnection = simulationStates.some(path => { - if (path.modeluuid === firstSelected.modelUUID) { - if (path.type === 'Conveyor') { - const point = path.points.find(p => p.uuid === firstSelected.sphereUUID); - return point?.connections.targets.some(t => - t.modelUUID === modelUUID && t.pointUUID === sphereUUID - ); - } else if (path.type === 'Vehicle') { - return path.points.connections.targets.some(t => - t.modelUUID === modelUUID && t.pointUUID === sphereUUID - ); - } - } - return false; - }); - - // For non-Vehicle paths, check if already connected - const isNonVehicleAlreadyConnected = pathData.type !== 'Vehicle' && - simulationStates.some(path => { - if (path.type === 'Conveyor') { - return path.points.some(point => - point.uuid === sphereUUID && - point.connections.targets.length > 0 - ); - } - return false; - }); - - // Check vehicle connection rules - const isVehicleAtMaxConnections = pathData.type === 'Vehicle' && - pathData.points.connections.targets.length >= 1; - const isVehicleConnectingToNonConveyor = - (firstPath?.type === 'Vehicle' && secondPath?.type !== 'Conveyor') || - (secondPath?.type === 'Vehicle' && firstPath?.type !== 'Conveyor'); - - // Check if StaticMachine is connecting to non-ArmBot - const isStaticMachineToNonArmBot = - (firstPath?.type === 'StaticMachine' && secondPath?.type !== 'ArmBot') || - (secondPath?.type === 'StaticMachine' && firstPath?.type !== 'ArmBot'); - - // Check if StaticMachine already has a connection - const isStaticMachineAtMaxConnections = - (firstPath?.type === 'StaticMachine' && firstPath.points.connections.targets.length >= 1) || - (secondPath?.type === 'StaticMachine' && secondPath.points.connections.targets.length >= 1); - - // Check if ArmBot is connecting to StaticMachine - const isArmBotToStaticMachine = - (firstPath?.type === 'ArmBot' && secondPath?.type === 'StaticMachine') || - (secondPath?.type === 'ArmBot' && firstPath?.type === 'StaticMachine'); - - // Prevent multiple StaticMachine connections to ArmBot - let isArmBotAlreadyConnectedToStatic = false; - if (isArmBotToStaticMachine) { - const armBotPath = firstPath?.type === 'ArmBot' ? firstPath : secondPath; - isArmBotAlreadyConnectedToStatic = armBotPath.points.connections.targets.some(target => { - const targetPath = simulationStates.find(p => p.modeluuid === target.modelUUID); - return targetPath?.type === 'StaticMachine'; - }); - } - - // Prevent ArmBot to ArmBot - const isArmBotToArmBot = firstPath?.type === 'ArmBot' && secondPath?.type === 'ArmBot'; - - // If ArmBot is involved, other must be Conveyor or StaticMachine - const isArmBotToInvalidType = (firstPath?.type === 'ArmBot' || secondPath?.type === 'ArmBot') && - !(firstPath?.type === 'Conveyor' || firstPath?.type === 'StaticMachine' || - secondPath?.type === 'Conveyor' || secondPath?.type === 'StaticMachine'); - - if ( - !isDuplicateConnection && - !isVehicleToVehicle && - !isNonVehicleAlreadyConnected && - !isVehicleAtMaxConnections && - !isVehicleConnectingToNonConveyor && - !isStaticMachineToNonArmBot && - !isStaticMachineAtMaxConnections && - !isArmBotToArmBot && - !isArmBotToInvalidType && - !isArmBotAlreadyConnectedToStatic && - firstSelected.sphereUUID !== sphereUUID && - firstSelected.modelUUID !== modelUUID && - (firstSelected.isCorner || isConnectable) && - !(firstPath?.type === 'Conveyor' && - pathData.type === 'Conveyor' && - !(firstSelected.isCorner && isConnectable)) - ) { - snappedSphere = { - sphereUUID, - position: spherePosition, - modelUUID, - isCorner: isConnectable - }; - } else { - isInvalidConnection = true; - } - - } - - if (snappedSphere) { - point = snappedSphere.position; - } - - if (point) { - const distance = firstSelected.position.distanceTo(point); - const heightFactor = Math.max(0.5, distance * 0.2); - const midPoint = new THREE.Vector3( - (firstSelected.position.x + point.x) / 2, - Math.max(firstSelected.position.y, point.y) + heightFactor, - (firstSelected.position.z + point.z) / 2 - ); - - setCurrentLine({ - start: firstSelected.position, - end: point, - mid: midPoint, - }); - - if (sphereIntersects.length > 0) { - setHelperLineColor(isInvalidConnection ? 'red' : '#6cf542'); - } else { - setHelperLineColor('yellow'); - } - } else { - setCurrentLine(null); - setIsConnecting(false); - } - } else { - setCurrentLine(null); - setIsConnecting(false); - } - }); - - const removeConnections = (connection1: { model: string; point: string }, connection2: { model: string; point: string }) => { - const updatedStates = simulationStates.map(state => { - // Handle Conveyor (which has multiple points) - if (state.type === 'Conveyor') { - const updatedConveyor: Types.ConveyorEventsSchema = { - ...state, - points: state.points.map(point => { - // Check if this point is either connection1 or connection2 - if ((state.modeluuid === connection1.model && point.uuid === connection1.point) || - (state.modeluuid === connection2.model && point.uuid === connection2.point)) { - - return { - ...point, - connections: { - ...point.connections, - targets: point.connections.targets.filter(target => { - // Remove the target that matches the other connection - return !( - (target.modelUUID === connection1.model && target.pointUUID === connection1.point) || - (target.modelUUID === connection2.model && target.pointUUID === connection2.point) - ); - }) - } - }; - } - return point; - }) - }; - return updatedConveyor; - } - // Handle Vehicle - else if (state.type === 'Vehicle') { - if ((state.modeluuid === connection1.model && state.points.uuid === connection1.point) || - (state.modeluuid === connection2.model && state.points.uuid === connection2.point)) { - - const updatedVehicle: Types.VehicleEventsSchema = { - ...state, - points: { - ...state.points, - connections: { - ...state.points.connections, - targets: state.points.connections.targets.filter(target => { - return !( - (target.modelUUID === connection1.model && target.pointUUID === connection1.point) || - (target.modelUUID === connection2.model && target.pointUUID === connection2.point) - ); - }) - }, - // Ensure all required Vehicle point properties are included - speed: state.points.speed, - actions: state.points.actions - } - }; - return updatedVehicle; - } - } - // Handle StaticMachine - else if (state.type === 'StaticMachine') { - if ((state.modeluuid === connection1.model && state.points.uuid === connection1.point) || - (state.modeluuid === connection2.model && state.points.uuid === connection2.point)) { - - const updatedStaticMachine: Types.StaticMachineEventsSchema = { - ...state, - points: { - ...state.points, - connections: { - ...state.points.connections, - targets: state.points.connections.targets.filter(target => { - return !( - (target.modelUUID === connection1.model && target.pointUUID === connection1.point) || - (target.modelUUID === connection2.model && target.pointUUID === connection2.point) - ); - }) - }, - // Ensure all required StaticMachine point properties are included - actions: state.points.actions, - triggers: state.points.triggers - } - }; - return updatedStaticMachine; - } - } - // Handle ArmBot - else if (state.type === 'ArmBot') { - if ((state.modeluuid === connection1.model && state.points.uuid === connection1.point) || - (state.modeluuid === connection2.model && state.points.uuid === connection2.point)) { - - const updatedArmBot: Types.ArmBotEventsSchema = { - ...state, - points: { - ...state.points, - connections: { - ...state.points.connections, - targets: state.points.connections.targets.filter(target => { - return !( - (target.modelUUID === connection1.model && target.pointUUID === connection1.point) || - (target.modelUUID === connection2.model && target.pointUUID === connection2.point) - ); - }) - }, - actions: { - ...state.points.actions, - processes: state.points.actions.processes?.filter(process => { - return !( - process.startPoint === connection1.point || - process.endPoint === connection1.point || - process.startPoint === connection2.point || - process.endPoint === connection2.point - ); - }) || [] - }, - triggers: state.points.triggers - } - }; - return updatedArmBot; - } - } - return state; - }); - - const updatedPaths = updatedStates.filter(state => - state.modeluuid === connection1.model || state.modeluuid === connection2.model + useFrame(() => { + if (firstSelected) { + raycaster.setFromCamera(pointer, camera); + const intersects = raycaster + .intersectObjects(scene.children, true) + .filter( + (intersect) => + !intersect.object.name.includes("Roof") && + !intersect.object.name.includes("agv-collider") && + !intersect.object.name.includes("MeasurementReference") && + !intersect.object.userData.isPathObject && + !(intersect.object.type === "GridHelper") ); - updateBackend(updatedPaths); + let point: THREE.Vector3 | null = null; + let snappedSphere: { + sphereUUID: string; + position: THREE.Vector3; + modelUUID: string; + isCorner: boolean; + } | null = null; + let isInvalidConnection = false; - setSimulationStates(updatedStates); - }; + if (intersects.length > 0) { + point = intersects[0].point; + if (point.y < 0.05) { + point = new THREE.Vector3(point.x, 0.05, point.z); + } + } + const sphereIntersects = raycaster + .intersectObjects(pathsGroupRef.current.children, true) + .filter((obj) => obj.object.name.includes("events-sphere")); - return ( - - {simulationStates.flatMap(path => { - if (path.type === 'Conveyor') { - return path.points.flatMap(point => - point.connections.targets.map((target, index) => { - const targetPath = simulationStates.find(p => p.modeluuid === target.modelUUID); - if (targetPath?.type !== 'Conveyor' && targetPath?.type !== 'ArmBot') return null; + if (sphereIntersects.length > 0) { + const sphere = sphereIntersects[0].object; + const sphereUUID = sphere.uuid; + const spherePosition = new THREE.Vector3(); + sphere.getWorldPosition(spherePosition); + const pathData = sphere.userData.path; + const modelUUID = pathData.modeluuid; - const fromSphere = pathsGroupRef.current?.getObjectByProperty('uuid', point.uuid); - const toSphere = pathsGroupRef.current?.getObjectByProperty('uuid', target.pointUUID); + const firstPath = simulationStates.find( + (p) => p.modeluuid === firstSelected.modelUUID + ); + const secondPath = simulationStates.find( + (p) => p.modeluuid === modelUUID + ); + const isVehicleToVehicle = + firstPath?.type === "Vehicle" && secondPath?.type === "Vehicle"; - if (fromSphere && toSphere) { - const fromWorldPosition = new THREE.Vector3(); - const toWorldPosition = new THREE.Vector3(); - fromSphere.getWorldPosition(fromWorldPosition); - toSphere.getWorldPosition(toWorldPosition); + // Inside the useFrame hook, where we check for snapped spheres: + const isConnectable = + (pathData.type === "Vehicle" || + pathData.type === "ArmBot" || + (pathData.points.length > 0 && + (sphereUUID === pathData.points[0].uuid || + sphereUUID === + pathData.points[pathData.points.length - 1].uuid || + (pathData.type === "Conveyor" && + firstPath?.type === "ArmBot")))) && // Allow ArmBot to connect to middle points + !isVehicleToVehicle && + !( + firstPath?.type === "Conveyor" && + pathData.type === "Conveyor" && + !firstSelected.isCorner + ); - const distance = fromWorldPosition.distanceTo(toWorldPosition); - const heightFactor = Math.max(0.5, distance * 0.2); - const midPoint = new THREE.Vector3((fromWorldPosition.x + toWorldPosition.x) / 2, Math.max(fromWorldPosition.y, toWorldPosition.y) + heightFactor, (fromWorldPosition.z + toWorldPosition.z) / 2); + // Check for duplicate connection (regardless of path type) + const isDuplicateConnection = simulationStates.some((path) => { + if (path.modeluuid === firstSelected.modelUUID) { + if (path.type === "Conveyor") { + const point = path.points.find( + (p) => p.uuid === firstSelected.sphereUUID + ); + return point?.connections.targets.some( + (t) => t.modelUUID === modelUUID && t.pointUUID === sphereUUID + ); + } else if (path.type === "Vehicle") { + return path.points.connections.targets.some( + (t) => t.modelUUID === modelUUID && t.pointUUID === sphereUUID + ); + } + } + return false; + }); - return ( - (groupRefs.current[`${point.uuid}-${target.pointUUID}-${index}`] = el!)} - start={fromWorldPosition.toArray()} - end={toWorldPosition.toArray()} - mid={midPoint.toArray()} - color={ - deleteTool && hoveredLineKey === `${point.uuid}-${target.pointUUID}-${index}` - ? 'red' - : targetPath?.type === 'ArmBot' - ? '#42a5f5' - : 'white' - } - lineWidth={4} - dashed={(deleteTool && hoveredLineKey === `${point.uuid}-${target.pointUUID}-${index}`) ? false : true} - dashSize={0.75} - dashScale={20} - onPointerOver={() => setHoveredLineKey(`${point.uuid}-${target.pointUUID}-${index}`)} - onPointerOut={() => setHoveredLineKey(null)} - onClick={() => { - if (deleteTool) { + // For non-Vehicle paths, check if already connected + const isNonVehicleAlreadyConnected = + pathData.type !== "Vehicle" && + simulationStates.some((path) => { + if (path.type === "Conveyor") { + return path.points.some( + (point) => + point.uuid === sphereUUID && + point.connections.targets.length > 0 + ); + } + return false; + }); - const connection1 = { model: path.modeluuid, point: point.uuid } - const connection2 = { model: target.modelUUID, point: target.pointUUID } + // Check vehicle connection rules + const isVehicleAtMaxConnections = + pathData.type === "Vehicle" && + pathData.points.connections.targets.length >= 1; + const isVehicleConnectingToNonConveyor = + (firstPath?.type === "Vehicle" && secondPath?.type !== "Conveyor") || + (secondPath?.type === "Vehicle" && firstPath?.type !== "Conveyor"); - removeConnections(connection1, connection2) + // Check if StaticMachine is connecting to non-ArmBot + const isStaticMachineToNonArmBot = + (firstPath?.type === "StaticMachine" && + secondPath?.type !== "ArmBot") || + (secondPath?.type === "StaticMachine" && + firstPath?.type !== "ArmBot"); - } - }} - userData={target} - /> - ); - } - return null; - }) + // Check if StaticMachine already has a connection + const isStaticMachineAtMaxConnections = + (firstPath?.type === "StaticMachine" && + firstPath.points.connections.targets.length >= 1) || + (secondPath?.type === "StaticMachine" && + secondPath.points.connections.targets.length >= 1); + + // Check if ArmBot is connecting to StaticMachine + const isArmBotToStaticMachine = + (firstPath?.type === "ArmBot" && + secondPath?.type === "StaticMachine") || + (secondPath?.type === "ArmBot" && + firstPath?.type === "StaticMachine"); + + // Prevent multiple StaticMachine connections to ArmBot + let isArmBotAlreadyConnectedToStatic = false; + if (isArmBotToStaticMachine) { + const armBotPath = + firstPath?.type === "ArmBot" ? firstPath : secondPath; + isArmBotAlreadyConnectedToStatic = + armBotPath.points.connections.targets.some((target) => { + const targetPath = simulationStates.find( + (p) => p.modeluuid === target.modelUUID + ); + return targetPath?.type === "StaticMachine"; + }); + } + + // Prevent ArmBot to ArmBot + const isArmBotToArmBot = + firstPath?.type === "ArmBot" && secondPath?.type === "ArmBot"; + + // If ArmBot is involved, other must be Conveyor or StaticMachine + const isArmBotToInvalidType = + (firstPath?.type === "ArmBot" || secondPath?.type === "ArmBot") && + !( + firstPath?.type === "Conveyor" || + firstPath?.type === "StaticMachine" || + secondPath?.type === "Conveyor" || + secondPath?.type === "StaticMachine" + ); + + if ( + !isDuplicateConnection && + !isVehicleToVehicle && + !isNonVehicleAlreadyConnected && + !isVehicleAtMaxConnections && + !isVehicleConnectingToNonConveyor && + !isStaticMachineToNonArmBot && + !isStaticMachineAtMaxConnections && + !isArmBotToArmBot && + !isArmBotToInvalidType && + !isArmBotAlreadyConnectedToStatic && + firstSelected.sphereUUID !== sphereUUID && + firstSelected.modelUUID !== modelUUID && + (firstSelected.isCorner || isConnectable) && + !( + firstPath?.type === "Conveyor" && + pathData.type === "Conveyor" && + !(firstSelected.isCorner && isConnectable) + ) + ) { + snappedSphere = { + sphereUUID, + position: spherePosition, + modelUUID, + isCorner: isConnectable, + }; + } else { + isInvalidConnection = true; + } + } + + if (snappedSphere) { + point = snappedSphere.position; + } + + if (point) { + const distance = firstSelected.position.distanceTo(point); + const heightFactor = Math.max(0.5, distance * 0.2); + const midPoint = new THREE.Vector3( + (firstSelected.position.x + point.x) / 2, + Math.max(firstSelected.position.y, point.y) + heightFactor, + (firstSelected.position.z + point.z) / 2 + ); + + setCurrentLine({ + start: firstSelected.position, + end: point, + mid: midPoint, + }); + + if (sphereIntersects.length > 0) { + setHelperLineColor(isInvalidConnection ? "red" : "#6cf542"); + } else { + setHelperLineColor("yellow"); + } + } else { + setCurrentLine(null); + setIsConnecting(false); + } + } else { + setCurrentLine(null); + setIsConnecting(false); + } + }); + + const removeConnections = ( + connection1: { model: string; point: string }, + connection2: { model: string; point: string } + ) => { + const updatedStates = simulationStates.map((state) => { + // Handle Conveyor (which has multiple points) + if (state.type === "Conveyor") { + const updatedConveyor: Types.ConveyorEventsSchema = { + ...state, + points: state.points.map((point) => { + // Check if this point is either connection1 or connection2 + if ( + (state.modeluuid === connection1.model && + point.uuid === connection1.point) || + (state.modeluuid === connection2.model && + point.uuid === connection2.point) + ) { + return { + ...point, + connections: { + ...point.connections, + targets: point.connections.targets.filter((target) => { + // Remove the target that matches the other connection + return !( + (target.modelUUID === connection1.model && + target.pointUUID === connection1.point) || + (target.modelUUID === connection2.model && + target.pointUUID === connection2.point) ); - } + }), + }, + }; + } + return point; + }), + }; + return updatedConveyor; + } + // Handle Vehicle + else if (state.type === "Vehicle") { + if ( + (state.modeluuid === connection1.model && + state.points.uuid === connection1.point) || + (state.modeluuid === connection2.model && + state.points.uuid === connection2.point) + ) { + const updatedVehicle: Types.VehicleEventsSchema = { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + targets: state.points.connections.targets.filter((target) => { + return !( + (target.modelUUID === connection1.model && + target.pointUUID === connection1.point) || + (target.modelUUID === connection2.model && + target.pointUUID === connection2.point) + ); + }), + }, + // Ensure all required Vehicle point properties are included + speed: state.points.speed, + actions: state.points.actions, + }, + }; + return updatedVehicle; + } + } + // Handle StaticMachine + else if (state.type === "StaticMachine") { + if ( + (state.modeluuid === connection1.model && + state.points.uuid === connection1.point) || + (state.modeluuid === connection2.model && + state.points.uuid === connection2.point) + ) { + const updatedStaticMachine: Types.StaticMachineEventsSchema = { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + targets: state.points.connections.targets.filter((target) => { + return !( + (target.modelUUID === connection1.model && + target.pointUUID === connection1.point) || + (target.modelUUID === connection2.model && + target.pointUUID === connection2.point) + ); + }), + }, + // Ensure all required StaticMachine point properties are included + actions: state.points.actions, + triggers: state.points.triggers, + }, + }; + return updatedStaticMachine; + } + } + // Handle ArmBot + else if (state.type === "ArmBot") { + if ( + (state.modeluuid === connection1.model && + state.points.uuid === connection1.point) || + (state.modeluuid === connection2.model && + state.points.uuid === connection2.point) + ) { + const updatedArmBot: Types.ArmBotEventsSchema = { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + targets: state.points.connections.targets.filter((target) => { + return !( + (target.modelUUID === connection1.model && + target.pointUUID === connection1.point) || + (target.modelUUID === connection2.model && + target.pointUUID === connection2.point) + ); + }), + }, + actions: { + ...state.points.actions, + processes: + state.points.actions.processes?.filter((process) => { + return !( + process.startPoint === connection1.point || + process.endPoint === connection1.point || + process.startPoint === connection2.point || + process.endPoint === connection2.point + ); + }) || [], + }, + triggers: state.points.triggers, + }, + }; + return updatedArmBot; + } + } + return state; + }); - if (path.type === 'Vehicle') { - return path.points.connections.targets.map((target, index) => { - const fromSphere = pathsGroupRef.current?.getObjectByProperty('uuid', path.points.uuid); - const toSphere = pathsGroupRef.current?.getObjectByProperty('uuid', target.pointUUID); - - if (fromSphere && toSphere) { - const fromWorldPosition = new THREE.Vector3(); - const toWorldPosition = new THREE.Vector3(); - fromSphere.getWorldPosition(fromWorldPosition); - toSphere.getWorldPosition(toWorldPosition); - - const distance = fromWorldPosition.distanceTo(toWorldPosition); - const heightFactor = Math.max(0.5, distance * 0.2); - const midPoint = new THREE.Vector3((fromWorldPosition.x + toWorldPosition.x) / 2, Math.max(fromWorldPosition.y, toWorldPosition.y) + heightFactor, (fromWorldPosition.z + toWorldPosition.z) / 2); - - return ( - (groupRefs.current[`${path.points.uuid}-${target.pointUUID}-${index}`] = el!)} - start={fromWorldPosition.toArray()} - end={toWorldPosition.toArray()} - mid={midPoint.toArray()} - color={ - deleteTool && hoveredLineKey === `${path.points.uuid}-${target.pointUUID}-${index}` - ? 'red' - : 'orange' - } - lineWidth={4} - dashed={(deleteTool && hoveredLineKey === `${path.points.uuid}-${target.pointUUID}-${index}`) ? false : true} - dashSize={0.75} - dashScale={20} - onPointerOver={() => setHoveredLineKey(`${path.points.uuid}-${target.pointUUID}-${index}`)} - onPointerOut={() => setHoveredLineKey(null)} - onClick={() => { - if (deleteTool) { - - const connection1 = { model: path.modeluuid, point: path.points.uuid } - const connection2 = { model: target.modelUUID, point: target.pointUUID } - - removeConnections(connection1, connection2) - } - }} - userData={target} - /> - ); - } - return null; - }); - } - - if (path.type === 'StaticMachine') { - return path.points.connections.targets.map((target, index) => { - const targetPath = simulationStates.find(p => p.modeluuid === target.modelUUID); - if (targetPath?.type !== 'ArmBot') return null; - - const fromSphere = pathsGroupRef.current?.getObjectByProperty('uuid', path.points.uuid); - const toSphere = pathsGroupRef.current?.getObjectByProperty('uuid', target.pointUUID); - - if (fromSphere && toSphere) { - const fromWorldPosition = new THREE.Vector3(); - const toWorldPosition = new THREE.Vector3(); - fromSphere.getWorldPosition(fromWorldPosition); - toSphere.getWorldPosition(toWorldPosition); - - const distance = fromWorldPosition.distanceTo(toWorldPosition); - const heightFactor = Math.max(0.5, distance * 0.2); - const midPoint = new THREE.Vector3((fromWorldPosition.x + toWorldPosition.x) / 2, Math.max(fromWorldPosition.y, toWorldPosition.y) + heightFactor, (fromWorldPosition.z + toWorldPosition.z) / 2); - - return ( - (groupRefs.current[`${path.points.uuid}-${target.pointUUID}-${index}`] = el!)} - start={fromWorldPosition.toArray()} - end={toWorldPosition.toArray()} - mid={midPoint.toArray()} - color={ - deleteTool && hoveredLineKey === `${path.points.uuid}-${target.pointUUID}-${index}` - ? 'red' - : '#42a5f5' - } - lineWidth={4} - dashed={(deleteTool && hoveredLineKey === `${path.points.uuid}-${target.pointUUID}-${index}`) ? false : true} - dashSize={0.75} - dashScale={20} - onPointerOver={() => setHoveredLineKey(`${path.points.uuid}-${target.pointUUID}-${index}`)} - onPointerOut={() => setHoveredLineKey(null)} - onClick={() => { - if (deleteTool) { - - const connection1 = { model: path.modeluuid, point: path.points.uuid } - const connection2 = { model: target.modelUUID, point: target.pointUUID } - - removeConnections(connection1, connection2) - - } - }} - userData={target} - /> - ); - } - return null; - }); - } - - return []; - })} - - {currentLine && ( - - )} - + const updatedPaths = updatedStates.filter( + (state) => + state.modeluuid === connection1.model || + state.modeluuid === connection2.model ); + console.log("updatedPaths: ", updatedPaths); + updateBackend(updatedPaths); + + setSimulationStates(updatedStates); + }; + + return ( + + {simulationStates.flatMap((path) => { + if (path.type === "Conveyor") { + return path.points.flatMap((point) => + point.connections.targets.map((target, index) => { + const targetPath = simulationStates.find( + (p) => p.modeluuid === target.modelUUID + ); + if ( + targetPath?.type !== "Conveyor" && + targetPath?.type !== "ArmBot" + ) + return null; + + const fromSphere = pathsGroupRef.current?.getObjectByProperty( + "uuid", + point.uuid + ); + const toSphere = pathsGroupRef.current?.getObjectByProperty( + "uuid", + target.pointUUID + ); + + if (fromSphere && toSphere) { + const fromWorldPosition = new THREE.Vector3(); + const toWorldPosition = new THREE.Vector3(); + fromSphere.getWorldPosition(fromWorldPosition); + toSphere.getWorldPosition(toWorldPosition); + + const distance = fromWorldPosition.distanceTo(toWorldPosition); + const heightFactor = Math.max(0.5, distance * 0.2); + const midPoint = new THREE.Vector3( + (fromWorldPosition.x + toWorldPosition.x) / 2, + Math.max(fromWorldPosition.y, toWorldPosition.y) + + heightFactor, + (fromWorldPosition.z + toWorldPosition.z) / 2 + ); + + return ( + + (groupRefs.current[ + `${point.uuid}-${target.pointUUID}-${index}` + ] = el!) + } + start={fromWorldPosition.toArray()} + end={toWorldPosition.toArray()} + mid={midPoint.toArray()} + color={ + deleteTool && + hoveredLineKey === + `${point.uuid}-${target.pointUUID}-${index}` + ? "red" + : targetPath?.type === "ArmBot" + ? "#42a5f5" + : "white" + } + lineWidth={4} + dashed={ + deleteTool && + hoveredLineKey === + `${point.uuid}-${target.pointUUID}-${index}` + ? false + : true + } + dashSize={0.75} + dashScale={20} + onPointerOver={() => + setHoveredLineKey( + `${point.uuid}-${target.pointUUID}-${index}` + ) + } + onPointerOut={() => setHoveredLineKey(null)} + onClick={() => { + if (deleteTool) { + const connection1 = { + model: path.modeluuid, + point: point.uuid, + }; + const connection2 = { + model: target.modelUUID, + point: target.pointUUID, + }; + + removeConnections(connection1, connection2); + } + }} + userData={target} + /> + ); + } + return null; + }) + ); + } + + if (path.type === "Vehicle") { + return path.points.connections.targets.map((target, index) => { + const fromSphere = pathsGroupRef.current?.getObjectByProperty( + "uuid", + path.points.uuid + ); + const toSphere = pathsGroupRef.current?.getObjectByProperty( + "uuid", + target.pointUUID + ); + + if (fromSphere && toSphere) { + const fromWorldPosition = new THREE.Vector3(); + const toWorldPosition = new THREE.Vector3(); + fromSphere.getWorldPosition(fromWorldPosition); + toSphere.getWorldPosition(toWorldPosition); + + const distance = fromWorldPosition.distanceTo(toWorldPosition); + const heightFactor = Math.max(0.5, distance * 0.2); + const midPoint = new THREE.Vector3( + (fromWorldPosition.x + toWorldPosition.x) / 2, + Math.max(fromWorldPosition.y, toWorldPosition.y) + heightFactor, + (fromWorldPosition.z + toWorldPosition.z) / 2 + ); + + return ( + + (groupRefs.current[ + `${path.points.uuid}-${target.pointUUID}-${index}` + ] = el!) + } + start={fromWorldPosition.toArray()} + end={toWorldPosition.toArray()} + mid={midPoint.toArray()} + color={ + deleteTool && + hoveredLineKey === + `${path.points.uuid}-${target.pointUUID}-${index}` + ? "red" + : "orange" + } + lineWidth={4} + dashed={ + deleteTool && + hoveredLineKey === + `${path.points.uuid}-${target.pointUUID}-${index}` + ? false + : true + } + dashSize={0.75} + dashScale={20} + onPointerOver={() => + setHoveredLineKey( + `${path.points.uuid}-${target.pointUUID}-${index}` + ) + } + onPointerOut={() => setHoveredLineKey(null)} + onClick={() => { + if (deleteTool) { + const connection1 = { + model: path.modeluuid, + point: path.points.uuid, + }; + const connection2 = { + model: target.modelUUID, + point: target.pointUUID, + }; + + removeConnections(connection1, connection2); + } + }} + userData={target} + /> + ); + } + return null; + }); + } + + if (path.type === "StaticMachine") { + return path.points.connections.targets.map((target, index) => { + const targetPath = simulationStates.find( + (p) => p.modeluuid === target.modelUUID + ); + if (targetPath?.type !== "ArmBot") return null; + + const fromSphere = pathsGroupRef.current?.getObjectByProperty( + "uuid", + path.points.uuid + ); + const toSphere = pathsGroupRef.current?.getObjectByProperty( + "uuid", + target.pointUUID + ); + + if (fromSphere && toSphere) { + const fromWorldPosition = new THREE.Vector3(); + const toWorldPosition = new THREE.Vector3(); + fromSphere.getWorldPosition(fromWorldPosition); + toSphere.getWorldPosition(toWorldPosition); + + const distance = fromWorldPosition.distanceTo(toWorldPosition); + const heightFactor = Math.max(0.5, distance * 0.2); + const midPoint = new THREE.Vector3( + (fromWorldPosition.x + toWorldPosition.x) / 2, + Math.max(fromWorldPosition.y, toWorldPosition.y) + heightFactor, + (fromWorldPosition.z + toWorldPosition.z) / 2 + ); + + return ( + + (groupRefs.current[ + `${path.points.uuid}-${target.pointUUID}-${index}` + ] = el!) + } + start={fromWorldPosition.toArray()} + end={toWorldPosition.toArray()} + mid={midPoint.toArray()} + color={ + deleteTool && + hoveredLineKey === + `${path.points.uuid}-${target.pointUUID}-${index}` + ? "red" + : "#42a5f5" + } + lineWidth={4} + dashed={ + deleteTool && + hoveredLineKey === + `${path.points.uuid}-${target.pointUUID}-${index}` + ? false + : true + } + dashSize={0.75} + dashScale={20} + onPointerOver={() => + setHoveredLineKey( + `${path.points.uuid}-${target.pointUUID}-${index}` + ) + } + onPointerOut={() => setHoveredLineKey(null)} + onClick={() => { + if (deleteTool) { + const connection1 = { + model: path.modeluuid, + point: path.points.uuid, + }; + const connection2 = { + model: target.modelUUID, + point: target.pointUUID, + }; + + removeConnections(connection1, connection2); + } + }} + userData={target} + /> + ); + } + return null; + }); + } + + return []; + })} + + {currentLine && ( + + )} + + ); } -export default PathConnector; \ No newline at end of file +export default PathConnector; From 344650730725600b882ee4fa33885dfe3fcfa0fa Mon Sep 17 00:00:00 2001 From: Poovizhi99 Date: Tue, 15 Apr 2025 10:05:53 +0530 Subject: [PATCH 02/12] removed targets based on condition for armbot --- .../controls/selection/selectionControls.tsx | 1300 +++++++++-------- 1 file changed, 712 insertions(+), 588 deletions(-) diff --git a/app/src/modules/scene/controls/selection/selectionControls.tsx b/app/src/modules/scene/controls/selection/selectionControls.tsx index d1eed1e..80a7518 100644 --- a/app/src/modules/scene/controls/selection/selectionControls.tsx +++ b/app/src/modules/scene/controls/selection/selectionControls.tsx @@ -3,7 +3,13 @@ import { useEffect, useMemo, useRef, useState } from "react"; import { SelectionBox } from "three/examples/jsm/interactive/SelectionBox"; import { SelectionHelper } from "./selectionHelper"; import { useFrame, useThree } from "@react-three/fiber"; -import { useFloorItems, useSelectedAssets, useSimulationStates, useSocketStore, useToggleView, } from "../../../../store/store"; +import { + useFloorItems, + useSelectedAssets, + useSimulationStates, + useSocketStore, + useToggleView, +} from "../../../../store/store"; import BoundingBox from "./boundingBoxHelper"; import { toast } from "react-toastify"; // import { deleteFloorItem } from '../../../../services/factoryBuilder/assest/floorAsset/deleteFloorItemApi'; @@ -17,622 +23,740 @@ import RotateControls from "./rotateControls"; import useModuleStore from "../../../../store/useModuleStore"; const SelectionControls: React.FC = () => { - const { camera, controls, gl, scene, pointer } = useThree(); - const itemsGroupRef = useRef(undefined); - const selectionGroup = useRef() as Types.RefGroup; - const { toggleView } = useToggleView(); - const { simulationStates, setSimulationStates } = useSimulationStates(); - const { selectedAssets, setSelectedAssets } = useSelectedAssets(); - const [movedObjects, setMovedObjects] = useState([]); - const [rotatedObjects, setRotatedObjects] = useState([]); - const [copiedObjects, setCopiedObjects] = useState([]); - const [pastedObjects, setpastedObjects] = useState([]); - const [duplicatedObjects, setDuplicatedObjects] = useState([]); - const boundingBoxRef = useRef(); - const { floorItems, setFloorItems } = useFloorItems(); - const { activeModule } = useModuleStore(); - const { socket } = useSocketStore(); - const selectionBox = useMemo(() => new SelectionBox(camera, scene), [camera, scene]); + const { camera, controls, gl, scene, pointer } = useThree(); + const itemsGroupRef = useRef(undefined); + const selectionGroup = useRef() as Types.RefGroup; + const { toggleView } = useToggleView(); + const { simulationStates, setSimulationStates } = useSimulationStates(); + const { selectedAssets, setSelectedAssets } = useSelectedAssets(); + const [movedObjects, setMovedObjects] = useState([]); + const [rotatedObjects, setRotatedObjects] = useState([]); + const [copiedObjects, setCopiedObjects] = useState([]); + const [pastedObjects, setpastedObjects] = useState([]); + const [duplicatedObjects, setDuplicatedObjects] = useState( + [] + ); + const boundingBoxRef = useRef(); + const { floorItems, setFloorItems } = useFloorItems(); + const { activeModule } = useModuleStore(); + const { socket } = useSocketStore(); + const selectionBox = useMemo( + () => new SelectionBox(camera, scene), + [camera, scene] + ); - useEffect(() => { - if (!camera || !scene || toggleView) return; + useEffect(() => { + if (!camera || !scene || toggleView) return; - const canvasElement = gl.domElement; - canvasElement.tabIndex = 0; + const canvasElement = gl.domElement; + canvasElement.tabIndex = 0; - const itemsGroup: any = scene.getObjectByName("itemsGroup"); - itemsGroupRef.current = itemsGroup; + const itemsGroup: any = scene.getObjectByName("itemsGroup"); + itemsGroupRef.current = itemsGroup; - let isSelecting = false; - let isRightClick = false; - let rightClickMoved = false; - let isCtrlSelecting = false; + let isSelecting = false; + let isRightClick = false; + let rightClickMoved = false; + let isCtrlSelecting = false; - const helper = new SelectionHelper(gl); + const helper = new SelectionHelper(gl); - if (!itemsGroup) { - toast.warn("itemsGroup not found in the scene."); - return; + if (!itemsGroup) { + toast.warn("itemsGroup not found in the scene."); + return; + } + + const onPointerDown = (event: PointerEvent) => { + if (event.button === 2) { + isRightClick = true; + rightClickMoved = false; + } else if (event.button === 0) { + isSelecting = false; + isCtrlSelecting = event.ctrlKey; + if (event.ctrlKey && duplicatedObjects.length === 0) { + if (controls) (controls as any).enabled = false; + selectionBox.startPoint.set(pointer.x, pointer.y, 0); } + } + }; - const onPointerDown = (event: PointerEvent) => { - if (event.button === 2) { - isRightClick = true; - rightClickMoved = false; - } else if (event.button === 0) { - isSelecting = false; - isCtrlSelecting = event.ctrlKey; - if (event.ctrlKey && duplicatedObjects.length === 0) { - if (controls) (controls as any).enabled = false; - selectionBox.startPoint.set(pointer.x, pointer.y, 0); - } - } - }; + const onPointerMove = (event: PointerEvent) => { + if (isRightClick) { + rightClickMoved = true; + } + isSelecting = true; + if ( + helper.isDown && + event.ctrlKey && + duplicatedObjects.length === 0 && + isCtrlSelecting + ) { + selectionBox.endPoint.set(pointer.x, pointer.y, 0); + } + }; - const onPointerMove = (event: PointerEvent) => { - if (isRightClick) { - rightClickMoved = true; - } - isSelecting = true; - if (helper.isDown && event.ctrlKey && duplicatedObjects.length === 0 && isCtrlSelecting) { - selectionBox.endPoint.set(pointer.x, pointer.y, 0); - } - }; - - const onPointerUp = (event: PointerEvent) => { - if (event.button === 2) { - isRightClick = false; - if (!rightClickMoved) { - clearSelection(); - } - return; - } - - if (isSelecting && isCtrlSelecting) { - isCtrlSelecting = false; - isSelecting = false; - if (event.ctrlKey && duplicatedObjects.length === 0) { - selectAssets(); - } - } else if (!isSelecting && selectedAssets.length > 0 && ((pastedObjects.length === 0 && duplicatedObjects.length === 0 && movedObjects.length === 0 && rotatedObjects.length === 0) || event.button !== 0)) { - clearSelection(); - helper.enabled = true; - isCtrlSelecting = false; - } - }; - - const onKeyDown = (event: KeyboardEvent) => { - if (movedObjects.length > 0 || rotatedObjects.length > 0) return; - if (event.key.toLowerCase() === "escape") { - event.preventDefault(); - clearSelection(); - } - if (event.key.toLowerCase() === "delete") { - event.preventDefault(); - deleteSelection(); - } - }; - - const onContextMenu = (event: MouseEvent) => { - event.preventDefault(); - if (!rightClickMoved) { - clearSelection(); - } - }; - - if (!toggleView && activeModule === "builder") { - helper.enabled = true; - if (duplicatedObjects.length === 0 && pastedObjects.length === 0) { - canvasElement.addEventListener("pointerdown", onPointerDown); - canvasElement.addEventListener("pointermove", onPointerMove); - canvasElement.addEventListener("pointerup", onPointerUp); - } else { - helper.enabled = false; - helper.dispose(); - } - canvasElement.addEventListener("contextmenu", onContextMenu); - canvasElement.addEventListener("keydown", onKeyDown); - } else { - helper.enabled = false; - helper.dispose(); + const onPointerUp = (event: PointerEvent) => { + if (event.button === 2) { + isRightClick = false; + if (!rightClickMoved) { + clearSelection(); } + return; + } - return () => { - canvasElement.removeEventListener("pointerdown", onPointerDown); - canvasElement.removeEventListener("pointermove", onPointerMove); - canvasElement.removeEventListener("contextmenu", onContextMenu); - canvasElement.removeEventListener("pointerup", onPointerUp); - canvasElement.removeEventListener("keydown", onKeyDown); - helper.enabled = false; - helper.dispose(); - }; - }, [camera, controls, scene, toggleView, selectedAssets, copiedObjects, pastedObjects, duplicatedObjects, movedObjects, socket, floorItems, rotatedObjects, activeModule,]); - - useEffect(() => { - if (activeModule !== "builder") { - clearSelection(); + if (isSelecting && isCtrlSelecting) { + isCtrlSelecting = false; + isSelecting = false; + if (event.ctrlKey && duplicatedObjects.length === 0) { + selectAssets(); } - }, [activeModule]); + } else if ( + !isSelecting && + selectedAssets.length > 0 && + ((pastedObjects.length === 0 && + duplicatedObjects.length === 0 && + movedObjects.length === 0 && + rotatedObjects.length === 0) || + event.button !== 0) + ) { + clearSelection(); + helper.enabled = true; + isCtrlSelecting = false; + } + }; - useFrame(() => { - if (pastedObjects.length === 0 && duplicatedObjects.length === 0 && movedObjects.length === 0 && rotatedObjects.length === 0) { - selectionGroup.current.position.set(0, 0, 0); + const onKeyDown = (event: KeyboardEvent) => { + if (movedObjects.length > 0 || rotatedObjects.length > 0) return; + if (event.key.toLowerCase() === "escape") { + event.preventDefault(); + clearSelection(); + } + if (event.key.toLowerCase() === "delete") { + event.preventDefault(); + deleteSelection(); + } + }; + + const onContextMenu = (event: MouseEvent) => { + event.preventDefault(); + if (!rightClickMoved) { + clearSelection(); + } + }; + + if (!toggleView && activeModule === "builder") { + helper.enabled = true; + if (duplicatedObjects.length === 0 && pastedObjects.length === 0) { + canvasElement.addEventListener("pointerdown", onPointerDown); + canvasElement.addEventListener("pointermove", onPointerMove); + canvasElement.addEventListener("pointerup", onPointerUp); + } else { + helper.enabled = false; + helper.dispose(); + } + canvasElement.addEventListener("contextmenu", onContextMenu); + canvasElement.addEventListener("keydown", onKeyDown); + } else { + helper.enabled = false; + helper.dispose(); + } + + return () => { + canvasElement.removeEventListener("pointerdown", onPointerDown); + canvasElement.removeEventListener("pointermove", onPointerMove); + canvasElement.removeEventListener("contextmenu", onContextMenu); + canvasElement.removeEventListener("pointerup", onPointerUp); + canvasElement.removeEventListener("keydown", onKeyDown); + helper.enabled = false; + helper.dispose(); + }; + }, [ + camera, + controls, + scene, + toggleView, + selectedAssets, + copiedObjects, + pastedObjects, + duplicatedObjects, + movedObjects, + socket, + floorItems, + rotatedObjects, + activeModule, + ]); + + useEffect(() => { + if (activeModule !== "builder") { + clearSelection(); + } + }, [activeModule]); + + useFrame(() => { + if ( + pastedObjects.length === 0 && + duplicatedObjects.length === 0 && + movedObjects.length === 0 && + rotatedObjects.length === 0 + ) { + selectionGroup.current.position.set(0, 0, 0); + } + }); + + const selectAssets = () => { + selectionBox.endPoint.set(pointer.x, pointer.y, 0); + if (controls) (controls as any).enabled = true; + + let selectedObjects = selectionBox.select(); + let Objects = new Set(); + + selectedObjects.map((object) => { + let currentObject: THREE.Object3D | null = object; + while (currentObject) { + if (currentObject.userData.modelId) { + Objects.add(currentObject); + break; } + currentObject = currentObject.parent || null; + } }); - const selectAssets = () => { - selectionBox.endPoint.set(pointer.x, pointer.y, 0); - if (controls) (controls as any).enabled = true; + if (Objects.size === 0) { + clearSelection(); + return; + } - let selectedObjects = selectionBox.select(); - let Objects = new Set(); + const updatedSelections = new Set(selectedAssets); + Objects.forEach((obj) => { + updatedSelections.has(obj) + ? updatedSelections.delete(obj) + : updatedSelections.add(obj); + }); - selectedObjects.map((object) => { - let currentObject: THREE.Object3D | null = object; - while (currentObject) { - if (currentObject.userData.modelId) { - Objects.add(currentObject); - break; - } - currentObject = currentObject.parent || null; - } + const selected = Array.from(updatedSelections); + + setSelectedAssets(selected); + }; + + const clearSelection = () => { + selectionGroup.current.children = []; + selectionGroup.current.position.set(0, 0, 0); + selectionGroup.current.rotation.set(0, 0, 0); + setpastedObjects([]); + setDuplicatedObjects([]); + setSelectedAssets([]); + }; + const updateBackend = async ( + updatedPaths: ( + | SimulationTypes.ConveyorEventsSchema + | SimulationTypes.VehicleEventsSchema + | SimulationTypes.StaticMachineEventsSchema + | SimulationTypes.ArmBotEventsSchema + )[] + ) => { + if (updatedPaths.length === 0) return; + const email = localStorage.getItem("email"); + const organization = email ? email.split("@")[1].split(".")[0] : ""; + + updatedPaths.forEach(async (updatedPath) => { + if (updatedPath.type === "Conveyor") { + // await setEventApi( + // organization, + // updatedPath.modeluuid, + // { type: "Conveyor", points: updatedPath.points, speed: updatedPath.speed } + // ); + + const data = { + organization: organization, + modeluuid: updatedPath.modeluuid, + eventData: { + type: "Conveyor", + points: updatedPath.points, + speed: updatedPath.speed, + }, + }; + + socket.emit("v2:model-asset:updateEventData", data); + } else if (updatedPath.type === "Vehicle") { + // await setEventApi( + // organization, + // updatedPath.modeluuid, + // { type: "Vehicle", points: updatedPath.points } + // ); + + const data = { + organization: organization, + modeluuid: updatedPath.modeluuid, + eventData: { type: "Vehicle", points: updatedPath.points }, + }; + + socket.emit("v2:model-asset:updateEventData", data); + } else if (updatedPath.type === "StaticMachine") { + // await setEventApi( + // organization, + // updatedPath.modeluuid, + // { type: "StaticMachine", points: updatedPath.points } + // ); + + const data = { + organization: organization, + modeluuid: updatedPath.modeluuid, + eventData: { type: "StaticMachine", points: updatedPath.points }, + }; + + socket.emit("v2:model-asset:updateEventData", data); + } else if (updatedPath.type === "ArmBot") { + // await setEventApi( + // organization, + // updatedPath.modeluuid, + // { type: "ArmBot", points: updatedPath.points } + // ); + + const data = { + organization: organization, + modeluuid: updatedPath.modeluuid, + eventData: { type: "ArmBot", points: updatedPath.points }, + }; + + socket.emit("v2:model-asset:updateEventData", data); + } + }); + }; + + // const removeConnection = (modelUUID: any) => { + // + // const removedPath = simulationStates?.flatMap((state) => { + // let shouldInclude = false; + + // if (state.type === "Conveyor") { + // state.points.forEach((point: any) => { + // const sourceMatch = + // point.connections?.source?.modelUUID === modelUUID; + // const targetMatch = point.connections?.targets?.some( + // (target: any) => target.modelUUID === modelUUID + // ); + + // if (sourceMatch || targetMatch) shouldInclude = true; + // }); + // } + + // if (state.type === "Vehicle") { + // const targetMatch = state.points.connections?.targets?.some( + // (target: any) => target.modelUUID === modelUUID + // ); + + // if (targetMatch) shouldInclude = true; + // } + + // if (state.type === "StaticMachine") { + // const targetMatch = state.points.connections?.targets?.some( + // (target: any) => target.modelUUID === modelUUID + // ); + + // if (targetMatch) shouldInclude = true; + // } + + // if (state.type === "ArmBot") { + // const sourceMatch = + // state.points.connections?.source?.modelUUID === modelUUID; + // const targetMatch = state.points.connections?.targets?.some( + // (target: any) => target.modelUUID === modelUUID + // ); + + // const processMatch = + // state.points.actions?.processes?.some( + // (process: any) => + // process.startPoint === modelUUID || process.endPoint === modelUUID + // ) ?? false; + + // if (sourceMatch || targetMatch || processMatch) shouldInclude = true; + // } + + // return shouldInclude ? [state] : []; + // }); + // updateBackend(removedPath); + // + // return removedPath; + // // updateBackend(updatedPaths); + + // // setSimulationStates(updatedStates); + // }; + // const removeConnection = (modelUUIDs: any[]) => { + // + // const removedPath = simulationStates?.flatMap((state) => { + // let shouldInclude = false; + + // if (state.type === "Conveyor") { + // state.points.forEach((point: any) => { + // const sourceMatch = modelUUIDs.includes( + // point.connections?.source?.modelUUID + // ); + // const targetMatch = point.connections?.targets?.some((target: any) => + // modelUUIDs.includes(target.modelUUID) + // ); + + // if (sourceMatch || targetMatch) shouldInclude = true; + // }); + // } + + // if (state.type === "Vehicle") { + // const targetMatch = state.points.connections?.targets?.some( + // (target: any) => modelUUIDs.includes(target.modelUUID) + // ); + + // if (targetMatch) shouldInclude = true; + // } + + // if (state.type === "StaticMachine") { + // const targetMatch = state.points.connections?.targets?.some( + // (target: any) => modelUUIDs.includes(target.modelUUID) + // ); + + // if (targetMatch) shouldInclude = true; + // } + + // if (state.type === "ArmBot") { + // const sourceMatch = modelUUIDs.includes( + // state.points.connections?.source?.modelUUID + // ); + // const targetMatch = state.points.connections?.targets?.some( + // (target: any) => modelUUIDs.includes(target.modelUUID) + // ); + + // const processMatch = + // state.points.actions?.processes?.some( + // (process: any) => + // modelUUIDs.includes(process.startPoint) || + // modelUUIDs.includes(process.endPoint) + // ) ?? false; + + // if (sourceMatch || targetMatch || processMatch) shouldInclude = true; + // } + + // return shouldInclude ? [state] : []; + // }); + // updateBackend(removedPath); + // + // return removedPath; + // }; + + const removeConnection = (modelUUIDs: any[]) => { + const removedPath = simulationStates?.flatMap((state: any) => { + let shouldInclude = false; + + // Conveyor type + if (state.type === "Conveyor") { + state.points.forEach((point: any) => { + const sourceMatch = modelUUIDs.includes( + point.connections?.source?.modelUUID + ); + const targetMatch = point.connections?.targets?.some((target: any) => + modelUUIDs.includes(target.modelUUID) + ); + + if (sourceMatch) { + point.connections.source = {}; + shouldInclude = true; + } + + if (targetMatch) { + point.connections.targets = []; + shouldInclude = true; + } }); + } + // Vehicle & StaticMachine types + if (state.type === "Vehicle") { + const targets = state.points?.connections?.targets || []; + const targetMatch = targets.some((target: any) => + modelUUIDs.includes(target.modelUUID) + ); - if (Objects.size === 0) { - clearSelection(); - return; + if (targetMatch) { + state.points.connections.targets = []; + shouldInclude = true; + } + } + if (state.type === "StaticMachine") { + const targets = state.points?.connections?.targets || []; + const targetMatch = targets.some((target: any) => + modelUUIDs.includes(target.modelUUID) + ); + + if (targetMatch) { + state.points.connections.targets = []; + shouldInclude = true; + } + } + + // ArmBot type + if (state.type === "ArmBot") { + const sourceMatch = modelUUIDs.includes( + state.points.connections?.source?.modelUUID + ); + console.log("model", modelUUIDs); + console.log("state.points.connections: ", state.points); + + const targetMatch = state.points.connections?.targets?.some( + (target: any) => modelUUIDs.includes(target.modelUUID) + ); + // state.points.actions.processes = state.points.actions.processes.filter( + // (process: any) => + // console.log( + // !modelUUIDs.includes(process.startPoint), + // !modelUUIDs.includes(process.endPoint), + // modelUUIDs, + // process.startPoint, + // process.endPoint + // ) + // ); + + // shouldInclude = true; + + // const processMatches = state.points.actions?.processes?.some( + // (process: any) => + // console.log( + // "process: ", + // process, + // modelUUIDs, + // process.startPoint, + // process.endPoint + // ) + // // modelUUIDs.includes(process.startPoint) || + // // modelUUIDs.includes(process.endPoint) + // ); + // const processMatch = state.points.actions?.processes?.some( + // (process: any) => + // modelUUIDs.includes(String(process.startPoint)) || + // modelUUIDs.includes(String(process.endPoint)) + // ); + + // console.log("processMatch: ", processMatch); + if (sourceMatch) { + state.points.connections.source = {}; + shouldInclude = true; } - const updatedSelections = new Set(selectedAssets); - Objects.forEach((obj) => { updatedSelections.has(obj) ? updatedSelections.delete(obj) : updatedSelections.add(obj); }); - - const selected = Array.from(updatedSelections); - - setSelectedAssets(selected); - }; - - const clearSelection = () => { - selectionGroup.current.children = []; - selectionGroup.current.position.set(0, 0, 0); - selectionGroup.current.rotation.set(0, 0, 0); - setpastedObjects([]); - setDuplicatedObjects([]); - setSelectedAssets([]); - }; - const updateBackend = async (updatedPaths: (SimulationTypes.ConveyorEventsSchema | SimulationTypes.VehicleEventsSchema | SimulationTypes.StaticMachineEventsSchema | SimulationTypes.ArmBotEventsSchema)[]) => { - if (updatedPaths.length === 0) return; - const email = localStorage.getItem("email"); - const organization = email ? email.split("@")[1].split(".")[0] : ""; - - updatedPaths.forEach(async (updatedPath) => { - - if (updatedPath.type === "Conveyor") { - // await setEventApi( - // organization, - // updatedPath.modeluuid, - // { type: "Conveyor", points: updatedPath.points, speed: updatedPath.speed } - // ); - - const data = { - organization: organization, - modeluuid: updatedPath.modeluuid, - eventData: { - type: "Conveyor", - points: updatedPath.points, - speed: updatedPath.speed, - }, - }; - - socket.emit("v2:model-asset:updateEventData", data); - - } else if (updatedPath.type === "Vehicle") { - - // await setEventApi( - // organization, - // updatedPath.modeluuid, - // { type: "Vehicle", points: updatedPath.points } - // ); - - const data = { - organization: organization, - modeluuid: updatedPath.modeluuid, - eventData: { type: "Vehicle", points: updatedPath.points }, - }; - - socket.emit("v2:model-asset:updateEventData", data); - - } else if (updatedPath.type === "StaticMachine") { - - // await setEventApi( - // organization, - // updatedPath.modeluuid, - // { type: "StaticMachine", points: updatedPath.points } - // ); - - const data = { - organization: organization, - modeluuid: updatedPath.modeluuid, - eventData: { type: "StaticMachine", points: updatedPath.points }, - }; - - socket.emit("v2:model-asset:updateEventData", data); - - } else if (updatedPath.type === "ArmBot") { - - // await setEventApi( - // organization, - // updatedPath.modeluuid, - // { type: "ArmBot", points: updatedPath.points } - // ); - - const data = { - organization: organization, - modeluuid: updatedPath.modeluuid, - eventData: { type: "ArmBot", points: updatedPath.points }, - }; - - socket.emit("v2:model-asset:updateEventData", data); - } - - }); - }; - - // const removeConnection = (modelUUID: any) => { - // - // const removedPath = simulationStates?.flatMap((state) => { - // let shouldInclude = false; - - // if (state.type === "Conveyor") { - // state.points.forEach((point: any) => { - // const sourceMatch = - // point.connections?.source?.modelUUID === modelUUID; - // const targetMatch = point.connections?.targets?.some( - // (target: any) => target.modelUUID === modelUUID - // ); - - // if (sourceMatch || targetMatch) shouldInclude = true; - // }); - // } - - // if (state.type === "Vehicle") { - // const targetMatch = state.points.connections?.targets?.some( - // (target: any) => target.modelUUID === modelUUID - // ); - - // if (targetMatch) shouldInclude = true; - // } - - // if (state.type === "StaticMachine") { - // const targetMatch = state.points.connections?.targets?.some( - // (target: any) => target.modelUUID === modelUUID - // ); - - // if (targetMatch) shouldInclude = true; - // } - - // if (state.type === "ArmBot") { - // const sourceMatch = - // state.points.connections?.source?.modelUUID === modelUUID; - // const targetMatch = state.points.connections?.targets?.some( - // (target: any) => target.modelUUID === modelUUID - // ); - - // const processMatch = - // state.points.actions?.processes?.some( - // (process: any) => - // process.startPoint === modelUUID || process.endPoint === modelUUID - // ) ?? false; - - // if (sourceMatch || targetMatch || processMatch) shouldInclude = true; - // } - - // return shouldInclude ? [state] : []; - // }); - // updateBackend(removedPath); - // - // return removedPath; - // // updateBackend(updatedPaths); - - // // setSimulationStates(updatedStates); - // }; - // const removeConnection = (modelUUIDs: any[]) => { - // - // const removedPath = simulationStates?.flatMap((state) => { - // let shouldInclude = false; - - // if (state.type === "Conveyor") { - // state.points.forEach((point: any) => { - // const sourceMatch = modelUUIDs.includes( - // point.connections?.source?.modelUUID - // ); - // const targetMatch = point.connections?.targets?.some((target: any) => - // modelUUIDs.includes(target.modelUUID) - // ); - - // if (sourceMatch || targetMatch) shouldInclude = true; - // }); - // } - - // if (state.type === "Vehicle") { - // const targetMatch = state.points.connections?.targets?.some( - // (target: any) => modelUUIDs.includes(target.modelUUID) - // ); - - // if (targetMatch) shouldInclude = true; - // } - - // if (state.type === "StaticMachine") { - // const targetMatch = state.points.connections?.targets?.some( - // (target: any) => modelUUIDs.includes(target.modelUUID) - // ); - - // if (targetMatch) shouldInclude = true; - // } - - // if (state.type === "ArmBot") { - // const sourceMatch = modelUUIDs.includes( - // state.points.connections?.source?.modelUUID - // ); - // const targetMatch = state.points.connections?.targets?.some( - // (target: any) => modelUUIDs.includes(target.modelUUID) - // ); - - // const processMatch = - // state.points.actions?.processes?.some( - // (process: any) => - // modelUUIDs.includes(process.startPoint) || - // modelUUIDs.includes(process.endPoint) - // ) ?? false; - - // if (sourceMatch || targetMatch || processMatch) shouldInclude = true; - // } - - // return shouldInclude ? [state] : []; - // }); - // updateBackend(removedPath); - // - // return removedPath; - // }; - - const removeConnection = (modelUUIDs: any[]) => { - const removedPath = simulationStates?.flatMap((state: any) => { - let shouldInclude = false; - - // Conveyor type - if (state.type === "Conveyor") { - state.points.forEach((point: any) => { - const sourceMatch = modelUUIDs.includes(point.connections?.source?.modelUUID); - const targetMatch = point.connections?.targets?.some((target: any) => modelUUIDs.includes(target.modelUUID)); - - if (sourceMatch) { - point.connections.source = {}; - shouldInclude = true; - } - - if (targetMatch) { - point.connections.targets = []; - shouldInclude = true; - } - }); - } - - // Vehicle & StaticMachine types - if (state.type === "Vehicle") { - const targets = state.points?.connections?.targets || []; - const targetMatch = targets.some((target: any) => modelUUIDs.includes(target.modelUUID)); - - if (targetMatch) { - state.points.connections.targets = []; - shouldInclude = true; - } - } - if (state.type === "StaticMachine") { - const targets = state.points?.connections?.targets || []; - const targetMatch = targets.some((target: any) => modelUUIDs.includes(target.modelUUID)); - - if (targetMatch) { - state.points.connections.targets = []; - shouldInclude = true; - } - } - - // ArmBot type - if (state.type === "ArmBot") { - const sourceMatch = modelUUIDs.includes(state.points.connections?.source?.modelUUID); - - const targetMatch = state.points.connections?.targets?.some( - (target: any) => modelUUIDs.includes(target.modelUUID) - ); - // state.points.actions.processes = state.points.actions.processes.filter( - // (process: any) => - // console.log( - // !modelUUIDs.includes(process.startPoint), - // !modelUUIDs.includes(process.endPoint), - // modelUUIDs, - // process.startPoint, - // process.endPoint - // ) - // ); - - // shouldInclude = true; - - // const processMatches = state.points.actions?.processes?.some( - // (process: any) => - // console.log( - // "process: ", - // process, - // modelUUIDs, - // process.startPoint, - // process.endPoint - // ) - // // modelUUIDs.includes(process.startPoint) || - // // modelUUIDs.includes(process.endPoint) - // ); - // const processMatch = state.points.actions?.processes?.some( - // (process: any) => - // modelUUIDs.includes(String(process.startPoint)) || - // modelUUIDs.includes(String(process.endPoint)) - // ); - - // console.log("processMatch: ", processMatch); - if (sourceMatch) { - state.points.connections.source = {}; - shouldInclude = true; - } - - if (targetMatch) { - state.points.connections.targets = - state.points.connections.targets.filter((target: any) => !modelUUIDs.includes(target.modelUUID)); - shouldInclude = true; - } - - // console.log("processMatch: ", processMatch); - // if (processMatch) { - // state.points.actions.processes = - // state.points.actions.processes.filter((process: any) => { - // const shouldRemove = - // modelUUIDs.includes(process.startPoint) || - // modelUUIDs.includes(process.endPoint); - - // console.log("shouldRemove: ", shouldRemove); - // return !shouldRemove; - // }); - // shouldInclude = true; - // } - } - - return shouldInclude ? [state] : []; - }); - - updateBackend(removedPath); - return removedPath; - }; - - const deleteSelection = () => { - if (selectedAssets.length > 0 && duplicatedObjects.length === 0) { - const email = localStorage.getItem("email"); - const organization = email!.split("@")[1].split(".")[0]; - - const storedItems = JSON.parse(localStorage.getItem("FloorItems") || "[]"); - const selectedUUIDs = selectedAssets.map((mesh: THREE.Object3D) => mesh.uuid); - - const updatedStoredItems = storedItems.filter((item: { modeluuid: string }) => !selectedUUIDs.includes(item.modeluuid)); - localStorage.setItem("FloorItems", JSON.stringify(updatedStoredItems)); - - selectedAssets.forEach((selectedMesh: THREE.Object3D) => { - //REST - - // const response = await deleteFloorItem(organization, selectedMesh.uuid, selectedMesh.userData.name); - - //SOCKET - - const data = { - organization: organization, - modeluuid: selectedMesh.uuid, - modelname: selectedMesh.userData.name, - socketId: socket.id, - }; - - socket.emit("v2:model-asset:delete", data); - - selectedMesh.traverse((child: THREE.Object3D) => { - if (child instanceof THREE.Mesh) { - if (child.geometry) child.geometry.dispose(); - if (Array.isArray(child.material)) { - child.material.forEach((material) => { - if (material.map) material.map.dispose(); - material.dispose(); - }); - } else if (child.material) { - if (child.material.map) child.material.map.dispose(); - child.material.dispose(); - } - } - }); - - setSimulationStates((prevEvents: (| SimulationTypes.ConveyorEventsSchema | SimulationTypes.VehicleEventsSchema | SimulationTypes.StaticMachineEventsSchema | SimulationTypes.ArmBotEventsSchema)[]) => { - const updatedEvents = (prevEvents || []).filter( - (event) => event.modeluuid !== selectedMesh.uuid - ); - return updatedEvents; - } - ); - - itemsGroupRef.current?.remove(selectedMesh); - }); - - const allUUIDs = selectedAssets.map((val: any) => val.uuid); - removeConnection(allUUIDs); - - // const removedPath = simulationStates?.flatMap((path: any) => { - // let shouldInclude = false; - - // if (Array.isArray(path.points)) { - // path.points.forEach((point: any) => { - // const sourceMatch = - // point.connections?.source?.modelUUID === selectedAssets[0].uuid; - // const targetMatch = point.connections?.targets?.some( - // (target: any) => target.modelUUID === selectedAssets[0].uuid - // ); - - // if (sourceMatch) { - // point.connections.source = {}; - // shouldInclude = true; - // } - - // if (targetMatch) { - // point.connections.targets = []; - // shouldInclude = true; - // } - // }); - // } else { - // const sourceMatch = - // path.connections?.source?.modelUUID === selectedAssets[0].uuid; - // const targetMatch = path.connections?.targets?.some( - // (target: any) => target.modelUUID === selectedAssets[0].uuid - // ); - - // if (sourceMatch) { - // path.connections.source = {}; - // shouldInclude = true; - // } - - // if (targetMatch) { - // path.connections.targets = []; - // shouldInclude = true; - // } - // } - - // return shouldInclude ? [path] : []; - // }); - // updateBackend(removedPath); - - const updatedItems = floorItems.filter( - (item: { modeluuid: string }) => !selectedUUIDs.includes(item.modeluuid) + if (targetMatch) { + state.points.connections.targets = + state.points.connections.targets.filter( + (target: any) => !modelUUIDs.includes(target.modelUUID) ); - setFloorItems(updatedItems); + shouldInclude = true; } - toast.success("Selected models removed!"); - clearSelection(); - }; - return ( - <> - - - - - + // console.log("processMatch: ", processMatch); + // if (processMatch) { + // state.points.actions.processes = + // state.points.actions.processes.filter((process: any) => { + // const shouldRemove = + // modelUUIDs.includes(process.startPoint) || + // modelUUIDs.includes(process.endPoint); + // console.log("shouldRemove: ", shouldRemove); + // return !shouldRemove; + // }); + // shouldInclude = true; + // } + } - + return shouldInclude ? [state] : []; + }); - + updateBackend(removedPath); + return removedPath; + }; - + const deleteSelection = () => { + if (selectedAssets.length > 0 && duplicatedObjects.length === 0) { + const email = localStorage.getItem("email"); + const organization = email!.split("@")[1].split(".")[0]; - - - ); + const storedItems = JSON.parse( + localStorage.getItem("FloorItems") || "[]" + ); + const selectedUUIDs = selectedAssets.map( + (mesh: THREE.Object3D) => mesh.uuid + ); + + const updatedStoredItems = storedItems.filter( + (item: { modeluuid: string }) => !selectedUUIDs.includes(item.modeluuid) + ); + localStorage.setItem("FloorItems", JSON.stringify(updatedStoredItems)); + + selectedAssets.forEach((selectedMesh: THREE.Object3D) => { + //REST + + // const response = await deleteFloorItem(organization, selectedMesh.uuid, selectedMesh.userData.name); + + //SOCKET + + const data = { + organization: organization, + modeluuid: selectedMesh.uuid, + modelname: selectedMesh.userData.name, + socketId: socket.id, + }; + + socket.emit("v2:model-asset:delete", data); + + selectedMesh.traverse((child: THREE.Object3D) => { + if (child instanceof THREE.Mesh) { + if (child.geometry) child.geometry.dispose(); + if (Array.isArray(child.material)) { + child.material.forEach((material) => { + if (material.map) material.map.dispose(); + material.dispose(); + }); + } else if (child.material) { + if (child.material.map) child.material.map.dispose(); + child.material.dispose(); + } + } + }); + + setSimulationStates( + ( + prevEvents: ( + | SimulationTypes.ConveyorEventsSchema + | SimulationTypes.VehicleEventsSchema + | SimulationTypes.StaticMachineEventsSchema + | SimulationTypes.ArmBotEventsSchema + )[] + ) => { + const updatedEvents = (prevEvents || []).filter( + (event) => event.modeluuid !== selectedMesh.uuid + ); + return updatedEvents; + } + ); + + itemsGroupRef.current?.remove(selectedMesh); + }); + + const allUUIDs = selectedAssets.map((val: any) => val.uuid); + removeConnection(allUUIDs); + + // const removedPath = simulationStates?.flatMap((path: any) => { + // let shouldInclude = false; + + // if (Array.isArray(path.points)) { + // path.points.forEach((point: any) => { + // const sourceMatch = + // point.connections?.source?.modelUUID === selectedAssets[0].uuid; + // const targetMatch = point.connections?.targets?.some( + // (target: any) => target.modelUUID === selectedAssets[0].uuid + // ); + + // if (sourceMatch) { + // point.connections.source = {}; + // shouldInclude = true; + // } + + // if (targetMatch) { + // point.connections.targets = []; + // shouldInclude = true; + // } + // }); + // } else { + // const sourceMatch = + // path.connections?.source?.modelUUID === selectedAssets[0].uuid; + // const targetMatch = path.connections?.targets?.some( + // (target: any) => target.modelUUID === selectedAssets[0].uuid + // ); + + // if (sourceMatch) { + // path.connections.source = {}; + // shouldInclude = true; + // } + + // if (targetMatch) { + // path.connections.targets = []; + // shouldInclude = true; + // } + // } + + // return shouldInclude ? [path] : []; + // }); + // updateBackend(removedPath); + + const updatedItems = floorItems.filter( + (item: { modeluuid: string }) => !selectedUUIDs.includes(item.modeluuid) + ); + setFloorItems(updatedItems); + } + toast.success("Selected models removed!"); + clearSelection(); + }; + + return ( + <> + + + + + + + + + + + + + + + ); }; export default SelectionControls; From 5cef9bdb8aacc1ebd29e5a28d1a4868a64e64e1f Mon Sep 17 00:00:00 2001 From: Jerald-Golden-B Date: Tue, 15 Apr 2025 14:15:39 +0530 Subject: [PATCH 03/12] Refactor simulation types and update imports - Renamed simulation type imports from `simulation` to `simulationTypes` across multiple files for consistency. - Consolidated simulation type definitions into a new `simulationTypes.d.ts` file. - Updated relevant components (e.g., `ArmBot`, `IkInstances`, `PathConnector`, etc.) to use the new type definitions. - Removed the old `simulation.d.ts` file to clean up the codebase. - Adjusted function signatures and state management in components to align with the new type structure. --- .../mechanics/ArmBotMechanics.tsx | 25 +- .../mechanics/ConveyorMechanics.tsx | 2 +- .../mechanics/StaticMachineMechanics.tsx | 2 +- .../mechanics/VehicleMechanics.tsx | 2 +- .../ui/inputs/InputWithDropDown.tsx | 5 +- .../geomentries/assets/addAssetModel.ts | 2 +- .../geomentries/assets/deleteFloorItems.ts | 2 +- .../scene/IntialLoad/loadInitialFloorItems.ts | 3 +- .../controls/selection/copyPasteControls.tsx | 2 +- .../selection/duplicationControls.tsx | 2 +- .../scene/controls/selection/moveControls.tsx | 2 +- .../controls/selection/rotateControls.tsx | 2 +- .../controls/selection/selectionControls.tsx | 3 +- app/src/modules/simulation/armbot/ArmBot.tsx | 14 +- .../simulation/armbot/ArmBotInstances.tsx | 63 +++- .../armbot/IKAnimationController.tsx | 269 ++++++++++++++---- .../modules/simulation/armbot/IkInstances.tsx | 62 ++-- .../modules/simulation/path/pathConnector.tsx | 3 +- .../modules/simulation/path/pathCreation.tsx | 42 +-- .../simulation/process/processCreator.tsx | 2 +- app/src/modules/simulation/simulation.tsx | 61 ++-- app/src/store/store.ts | 2 +- .../{simulation.d.ts => simulationTypes.d.ts} | 0 23 files changed, 383 insertions(+), 189 deletions(-) rename app/src/types/{simulation.d.ts => simulationTypes.d.ts} (100%) diff --git a/app/src/components/layout/sidebarRight/mechanics/ArmBotMechanics.tsx b/app/src/components/layout/sidebarRight/mechanics/ArmBotMechanics.tsx index e157d07..70e297b 100644 --- a/app/src/components/layout/sidebarRight/mechanics/ArmBotMechanics.tsx +++ b/app/src/components/layout/sidebarRight/mechanics/ArmBotMechanics.tsx @@ -2,7 +2,7 @@ import React, { useRef, useMemo, useCallback, useState } from "react"; import { InfoIcon, AddIcon, RemoveIcon, ResizeHeightIcon } from "../../../icons/ExportCommonIcons"; import InputWithDropDown from "../../../ui/inputs/InputWithDropDown"; import { useSelectedActionSphere, useSimulationStates, useSocketStore } from "../../../../store/store"; -import * as SimulationTypes from '../../../../types/simulation'; +import * as SimulationTypes from '../../../../types/simulationTypes'; import LabledDropdown from "../../../ui/inputs/LabledDropdown"; import { handleResize } from "../../../../functions/handleResizePannel"; @@ -224,19 +224,28 @@ const ArmBotMechanics: React.FC = () => { }, [selectedPoint, selectedProcessIndex, handleProcessChange]); const handleTriggerSelect = useCallback((displayName: string, index: number) => { - const selected = connectedTriggers.find(t => t.displayName === displayName); + const availableOptions = getFilteredTriggerOptions(index); + const selectedDisplayIndex = availableOptions.indexOf(displayName); + + const filteredTriggers = connectedTriggers.filter(trigger => + !selectedPoint?.actions.processes + ?.filter((_, i) => i !== index) + .map(p => p.triggerId) + .includes(trigger.uuid) + ); + + const selected = filteredTriggers[selectedDisplayIndex]; + if (!selected || !selectedPoint?.actions.processes) return; const oldProcess = selectedPoint.actions.processes[index]; const updatedProcesses = [...selectedPoint.actions.processes]; - - // Only reset start/end if new trigger invalidates them (your logic can expand this) updatedProcesses[index] = { ...oldProcess, triggerId: selected.uuid, - startPoint: oldProcess.startPoint || "", // preserve if exists - endPoint: oldProcess.endPoint || "" // preserve if exists + startPoint: oldProcess.startPoint || "", + endPoint: oldProcess.endPoint || "" }; handleProcessChange(updatedProcesses); @@ -298,8 +307,10 @@ const ArmBotMechanics: React.FC = () => { handleSpeedChange(parseInt(value))} + onChange={(value) => handleSpeedChange(parseFloat(value))} />
diff --git a/app/src/components/layout/sidebarRight/mechanics/ConveyorMechanics.tsx b/app/src/components/layout/sidebarRight/mechanics/ConveyorMechanics.tsx index 080aba5..5e84d10 100644 --- a/app/src/components/layout/sidebarRight/mechanics/ConveyorMechanics.tsx +++ b/app/src/components/layout/sidebarRight/mechanics/ConveyorMechanics.tsx @@ -17,7 +17,7 @@ import { useSocketStore, } from "../../../../store/store"; import * as THREE from "three"; -import * as SimulationTypes from "../../../../types/simulation"; +import * as SimulationTypes from "../../../../types/simulationTypes"; import InputToggle from "../../../ui/inputs/InputToggle"; import { setFloorItemApi } from "../../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi"; import { setEventApi } from "../../../../services/factoryBuilder/assest/floorAsset/setEventsApt"; diff --git a/app/src/components/layout/sidebarRight/mechanics/StaticMachineMechanics.tsx b/app/src/components/layout/sidebarRight/mechanics/StaticMachineMechanics.tsx index 812ed54..6342bac 100644 --- a/app/src/components/layout/sidebarRight/mechanics/StaticMachineMechanics.tsx +++ b/app/src/components/layout/sidebarRight/mechanics/StaticMachineMechanics.tsx @@ -2,7 +2,7 @@ import React, { useRef, useMemo, useCallback } from "react"; import { InfoIcon } from "../../../icons/ExportCommonIcons"; import InputWithDropDown from "../../../ui/inputs/InputWithDropDown"; import { useSelectedActionSphere, useSimulationStates, useSocketStore } from "../../../../store/store"; -import * as SimulationTypes from '../../../../types/simulation'; +import * as SimulationTypes from '../../../../types/simulationTypes'; import LabledDropdown from "../../../ui/inputs/LabledDropdown"; import { setEventApi } from "../../../../services/factoryBuilder/assest/floorAsset/setEventsApt"; diff --git a/app/src/components/layout/sidebarRight/mechanics/VehicleMechanics.tsx b/app/src/components/layout/sidebarRight/mechanics/VehicleMechanics.tsx index 73199c9..147d5cb 100644 --- a/app/src/components/layout/sidebarRight/mechanics/VehicleMechanics.tsx +++ b/app/src/components/layout/sidebarRight/mechanics/VehicleMechanics.tsx @@ -2,7 +2,7 @@ import React, { useRef, useMemo } from "react"; import { InfoIcon } from "../../../icons/ExportCommonIcons"; import InputWithDropDown from "../../../ui/inputs/InputWithDropDown"; import { useEditingPoint, useEyeDropMode, usePreviewPosition, useSelectedActionSphere, useSimulationStates, useSocketStore } from "../../../../store/store"; -import * as SimulationTypes from '../../../../types/simulation'; +import * as SimulationTypes from '../../../../types/simulationTypes'; import PositionInput from "../customInput/PositionInputs"; import { setEventApi } from "../../../../services/factoryBuilder/assest/floorAsset/setEventsApt"; import LabeledButton from "../../../ui/inputs/LabledButton"; diff --git a/app/src/components/ui/inputs/InputWithDropDown.tsx b/app/src/components/ui/inputs/InputWithDropDown.tsx index b0fc135..b672313 100644 --- a/app/src/components/ui/inputs/InputWithDropDown.tsx +++ b/app/src/components/ui/inputs/InputWithDropDown.tsx @@ -4,7 +4,8 @@ import RenameInput from "./RenameInput"; type InputWithDropDownProps = { label: string; value: string; - min?: number + min?: number; + step?: number; defaultValue?: string; options?: string[]; // Array of dropdown options activeOption?: string; // The currently active dropdown option @@ -18,6 +19,7 @@ const InputWithDropDown: React.FC = ({ label, value, min, + step, defaultValue, options, activeOption, @@ -45,6 +47,7 @@ const InputWithDropDown: React.FC = ({
{ diff --git a/app/src/modules/builder/geomentries/assets/addAssetModel.ts b/app/src/modules/builder/geomentries/assets/addAssetModel.ts index 97adec3..0db803f 100644 --- a/app/src/modules/builder/geomentries/assets/addAssetModel.ts +++ b/app/src/modules/builder/geomentries/assets/addAssetModel.ts @@ -5,7 +5,7 @@ import { toast } from 'react-toastify'; import TempLoader from './tempLoader'; import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader'; import * as Types from "../../../../types/world/worldTypes"; -import * as SimulationTypes from "../../../../types/simulation"; +import * as SimulationTypes from "../../../../types/simulationTypes"; import { retrieveGLTF, storeGLTF } from '../../../../utils/indexDB/idbUtils'; // import { setFloorItemApi } from '../../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi'; import { Socket } from 'socket.io-client'; diff --git a/app/src/modules/builder/geomentries/assets/deleteFloorItems.ts b/app/src/modules/builder/geomentries/assets/deleteFloorItems.ts index e904947..dbd7e9b 100644 --- a/app/src/modules/builder/geomentries/assets/deleteFloorItems.ts +++ b/app/src/modules/builder/geomentries/assets/deleteFloorItems.ts @@ -2,7 +2,7 @@ import { toast } from 'react-toastify'; import * as THREE from 'three'; import * as Types from "../../../../types/world/worldTypes"; -import * as SimulationTypes from "../../../../types/simulation"; +import * as SimulationTypes from "../../../../types/simulationTypes"; // import { deleteFloorItem } from '../../../../services/factoryBuilder/assest/floorAsset/deleteFloorItemApi'; import { Socket } from 'socket.io-client'; import { getFloorAssets } from '../../../../services/factoryBuilder/assest/floorAsset/getFloorItemsApi'; diff --git a/app/src/modules/scene/IntialLoad/loadInitialFloorItems.ts b/app/src/modules/scene/IntialLoad/loadInitialFloorItems.ts index 08bed84..7ca7db9 100644 --- a/app/src/modules/scene/IntialLoad/loadInitialFloorItems.ts +++ b/app/src/modules/scene/IntialLoad/loadInitialFloorItems.ts @@ -5,7 +5,7 @@ import * as THREE from 'three'; import * as CONSTANTS from '../../../types/world/worldConstants'; import { toast } from 'react-toastify'; import * as Types from "../../../types/world/worldTypes"; -import * as SimulationTypes from "../../..//types/simulation"; +import * as SimulationTypes from "../../../types/simulationTypes"; import { initializeDB, retrieveGLTF, storeGLTF } from '../../../utils/indexDB/idbUtils'; import { getCamera } from '../../../services/factoryBuilder/camera/getCameraApi'; import { getFloorAssets } from '../../../services/factoryBuilder/assest/floorAsset/getFloorItemsApi'; @@ -228,7 +228,6 @@ function processEventData(item: SimulationTypes.EventData, setSimulationStates: } else if (item.eventData?.type === 'StaticMachine') { const data: any = item.eventData; - item.eventData.points.position = [0, 1.5, 1] data.modeluuid = item.modeluuid; data.modelName = item.modelname; data.position = item.position; diff --git a/app/src/modules/scene/controls/selection/copyPasteControls.tsx b/app/src/modules/scene/controls/selection/copyPasteControls.tsx index 87ed646..84d6047 100644 --- a/app/src/modules/scene/controls/selection/copyPasteControls.tsx +++ b/app/src/modules/scene/controls/selection/copyPasteControls.tsx @@ -5,7 +5,7 @@ import { useFloorItems, useSelectedAssets, useSimulationStates, useSocketStore, import { toast } from "react-toastify"; // import { setFloorItemApi } from '../../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi'; import * as Types from "../../../../types/world/worldTypes"; -import * as SimulationTypes from "../../../../types/simulation"; +import * as SimulationTypes from "../../../../types/simulationTypes"; import { detectModifierKeys } from "../../../../utils/shortcutkeys/detectModifierKeys"; const CopyPasteControls = ({ itemsGroupRef, copiedObjects, setCopiedObjects, pastedObjects, setpastedObjects, selectionGroup, setDuplicatedObjects, movedObjects, setMovedObjects, rotatedObjects, setRotatedObjects, boundingBoxRef }: any) => { diff --git a/app/src/modules/scene/controls/selection/duplicationControls.tsx b/app/src/modules/scene/controls/selection/duplicationControls.tsx index 41bbce3..5ce0603 100644 --- a/app/src/modules/scene/controls/selection/duplicationControls.tsx +++ b/app/src/modules/scene/controls/selection/duplicationControls.tsx @@ -5,7 +5,7 @@ import { useFloorItems, useSelectedAssets, useSimulationStates, useSocketStore, import { toast } from "react-toastify"; // import { setFloorItemApi } from '../../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi'; import * as Types from "../../../../types/world/worldTypes"; -import * as SimulationTypes from "../../../../types/simulation"; +import * as SimulationTypes from "../../../../types/simulationTypes"; import { setFloorItemApi } from "../../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi"; import { detectModifierKeys } from "../../../../utils/shortcutkeys/detectModifierKeys"; diff --git a/app/src/modules/scene/controls/selection/moveControls.tsx b/app/src/modules/scene/controls/selection/moveControls.tsx index 99b9a43..d717ecb 100644 --- a/app/src/modules/scene/controls/selection/moveControls.tsx +++ b/app/src/modules/scene/controls/selection/moveControls.tsx @@ -5,7 +5,7 @@ import { useFloorItems, useSelectedAssets, useSimulationStates, useSocketStore, // import { setFloorItemApi } from '../../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi'; import { toast } from "react-toastify"; import * as Types from "../../../../types/world/worldTypes"; -import * as SimulationTypes from "../../../../types/simulation"; +import * as SimulationTypes from "../../../../types/simulationTypes"; import { detectModifierKeys } from "../../../../utils/shortcutkeys/detectModifierKeys"; function MoveControls({ movedObjects, setMovedObjects, itemsGroupRef, copiedObjects, setCopiedObjects, pastedObjects, setpastedObjects, duplicatedObjects, setDuplicatedObjects, selectionGroup, rotatedObjects, setRotatedObjects, boundingBoxRef }: any) { diff --git a/app/src/modules/scene/controls/selection/rotateControls.tsx b/app/src/modules/scene/controls/selection/rotateControls.tsx index 611d14b..f602bc4 100644 --- a/app/src/modules/scene/controls/selection/rotateControls.tsx +++ b/app/src/modules/scene/controls/selection/rotateControls.tsx @@ -5,7 +5,7 @@ import { useFloorItems, useSelectedAssets, useSimulationStates, useSocketStore, // import { setFloorItemApi } from '../../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi'; import { toast } from "react-toastify"; import * as Types from "../../../../types/world/worldTypes"; -import * as SimulationTypes from "../../../../types/simulation"; +import * as SimulationTypes from "../../../../types/simulationTypes"; import { setFloorItemApi } from "../../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi"; function RotateControls({ rotatedObjects, setRotatedObjects, movedObjects, setMovedObjects, itemsGroupRef, copiedObjects, setCopiedObjects, pastedObjects, setpastedObjects, duplicatedObjects, setDuplicatedObjects, selectionGroup, boundingBoxRef }: any) { diff --git a/app/src/modules/scene/controls/selection/selectionControls.tsx b/app/src/modules/scene/controls/selection/selectionControls.tsx index d1eed1e..d26889d 100644 --- a/app/src/modules/scene/controls/selection/selectionControls.tsx +++ b/app/src/modules/scene/controls/selection/selectionControls.tsx @@ -8,7 +8,7 @@ import BoundingBox from "./boundingBoxHelper"; import { toast } from "react-toastify"; // import { deleteFloorItem } from '../../../../services/factoryBuilder/assest/floorAsset/deleteFloorItemApi'; import * as Types from "../../../../types/world/worldTypes"; -import * as SimulationTypes from "../../../../types/simulation"; +import * as SimulationTypes from "../../../../types/simulationTypes"; import DuplicationControls from "./duplicationControls"; import CopyPasteControls from "./copyPasteControls"; @@ -199,6 +199,7 @@ const SelectionControls: React.FC = () => { setDuplicatedObjects([]); setSelectedAssets([]); }; + const updateBackend = async (updatedPaths: (SimulationTypes.ConveyorEventsSchema | SimulationTypes.VehicleEventsSchema | SimulationTypes.StaticMachineEventsSchema | SimulationTypes.ArmBotEventsSchema)[]) => { if (updatedPaths.length === 0) return; const email = localStorage.getItem("email"); diff --git a/app/src/modules/simulation/armbot/ArmBot.tsx b/app/src/modules/simulation/armbot/ArmBot.tsx index db0f956..2e77206 100644 --- a/app/src/modules/simulation/armbot/ArmBot.tsx +++ b/app/src/modules/simulation/armbot/ArmBot.tsx @@ -2,7 +2,7 @@ import React, { useEffect, useState } from "react"; import { useThree } from "@react-three/fiber"; import useModuleStore from "../../../store/useModuleStore"; import { useSimulationStates } from "../../../store/store"; -import * as SimulationTypes from '../../../types/simulation'; +import * as SimulationTypes from '../../../types/simulationTypes'; import { ArmbotInstances } from "./ArmBotInstances"; interface ArmBotState { @@ -12,14 +12,18 @@ interface ArmBotState { status: string; material: string; triggerId: string; - connections: any + actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; } -const ArmBot: React.FC = () => { +interface ArmBotProps { + armBots: ArmBotState[]; + setArmBots: React.Dispatch>; +} + +const ArmBot = ({ armBots, setArmBots }: ArmBotProps) => { const { activeModule } = useModuleStore(); const { scene } = useThree(); const { simulationStates } = useSimulationStates(); - const [armBots, setArmBots] = useState([]); useEffect(() => { const filtered = simulationStates.filter((s): s is SimulationTypes.ArmBotEventsSchema => s.type === "ArmBot"); @@ -30,7 +34,7 @@ const ArmBot: React.FC = () => { status: "idle", material: "default", triggerId: '', - connections: bot.points.connections + actions: bot.points.actions })); setArmBots(initialStates); }, [simulationStates]); diff --git a/app/src/modules/simulation/armbot/ArmBotInstances.tsx b/app/src/modules/simulation/armbot/ArmBotInstances.tsx index 6ce4e01..8a1380b 100644 --- a/app/src/modules/simulation/armbot/ArmBotInstances.tsx +++ b/app/src/modules/simulation/armbot/ArmBotInstances.tsx @@ -1,5 +1,15 @@ import IkInstances from "./IkInstances"; import armModel from "../../../assets/gltf-glb/rigged/ik_arm_4.glb"; +import { useEffect, useState } from "react"; +import { useThree } from "@react-three/fiber"; +import { Vector3 } from "three"; + +interface Process { + triggerId: string; + startPoint?: Vector3; + endPoint?: Vector3; + speed: number; +} interface ArmBotState { uuid: string; @@ -8,18 +18,65 @@ interface ArmBotState { status: string; material: string; triggerId: string; - connections: any + actions: { + uuid: string; + name: string; + speed: number; + processes: { + triggerId: string; + startPoint: string; + endPoint: string; + }[]; + }; } interface ArmbotInstancesProps { index: number; armBot: ArmBotState; - setArmBots: (armBots: ArmBotState[]) => void; + setArmBots: React.Dispatch>; } export const ArmbotInstances: React.FC = ({ index, armBot, setArmBots }) => { + const { scene } = useThree(); + const [processes, setProcesses] = useState([]); + + useEffect(() => { + + if (armBot.actions.processes.length > 0) { + const mappedProcesses = armBot.actions.processes.map((process) => { + return { + triggerId: process.triggerId, + startPoint: scene.getObjectByProperty('uuid', process.startPoint)?.getWorldPosition(new Vector3()), + endPoint: scene.getObjectByProperty('uuid', process.endPoint)?.getWorldPosition(new Vector3()), + speed: armBot.actions.speed + }; + }); + setProcesses(mappedProcesses); + } else { + setProcesses([]); + } + }, [armBot, scene]); + + const updateArmBotStatus = (status: string) => { + setArmBots((prevArmBots) => { + return prevArmBots.map(bot => { + if (bot.uuid === armBot.uuid) { + return { ...bot, status }; + } + return bot; + }); + }); + }; return ( - + ); }; \ No newline at end of file diff --git a/app/src/modules/simulation/armbot/IKAnimationController.tsx b/app/src/modules/simulation/armbot/IKAnimationController.tsx index 45d482f..538f0aa 100644 --- a/app/src/modules/simulation/armbot/IKAnimationController.tsx +++ b/app/src/modules/simulation/armbot/IKAnimationController.tsx @@ -1,96 +1,245 @@ -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useState, useRef } from "react"; import { useFrame } from "@react-three/fiber"; import * as THREE from "three"; +import { usePlayButtonStore } from "../../../store/usePlayButtonStore"; + +type IKAnimationControllerProps = { + ikSolver: any; + process: { + triggerId: string; + startPoint: THREE.Vector3; + endPoint: THREE.Vector3; + speed: number; + }[]; + selectedTrigger: string; + targetBoneName: string; + uuid: string; + logStatus: (status: string) => void; + groupRef: React.RefObject; + updateArmBotStatus: (status: string) => void; +} const IKAnimationController = ({ ikSolver, process, selectedTrigger, targetBoneName, -}: { - ikSolver: any; - process: { - trigger: string; - start: THREE.Vector3; - end: THREE.Vector3; - speed: number; - }[]; - selectedTrigger: string; - targetBoneName: string; -}) => { + uuid, + logStatus, + groupRef, + updateArmBotStatus +}: IKAnimationControllerProps) => { const [progress, setProgress] = useState(0); + const [initialProgress, setInitialProgress] = useState(0); + const [needsInitialMovement, setNeedsInitialMovement] = useState(true); + const [isInitializing, setIsInitializing] = useState(true); const restSpeed = 0.1; + const restPosition = new THREE.Vector3(0, 2, 1.6); + const { isPlaying } = usePlayButtonStore(); + + // Track previous states for comparison + const prevStateRef = useRef({ + isInitializing: true, + needsInitialMovement: true, + selectedTrigger: "", + progress: 0 + }); + + // Track previous status for comparison + const prevStatusRef = useRef(""); + + const initialCurveRef = useRef(null); + const initialStartPositionRef = useRef(null); useEffect(() => { setProgress(0); }, [selectedTrigger]); - const processedCurves = useMemo(() => { - const restPosition = new THREE.Vector3(0.2, 2.3, 1.6); - return process.map((p) => { - const mid = new THREE.Vector3( - (p.start.x + p.end.x) / 1, - Math.max(p.start.y, p.end.y) + 0.8, - (p.start.z + p.end.z) / 0.9 + useEffect(() => { + if (ikSolver) { + const targetBone = ikSolver.mesh.skeleton.bones.find( + (b: any) => b.name === targetBoneName ); - const points = [ - restPosition.clone(), - p.start.clone(), - mid.clone(), - p.end.clone(), - restPosition.clone(), - ]; - const curve = new THREE.CatmullRomCurve3(points); - const restToStartDist = points[0].distanceTo(points[1]); - const startToEndDist = points[1].distanceTo(points[3]); - const endToRestDist = points[3].distanceTo(points[4]); + if (targetBone) { + initialStartPositionRef.current = targetBone.position.clone(); + calculateInitialCurve(targetBone.position); + logStatus(`[Arm ${uuid}] Initializing IK system, starting position: ${targetBone.position.toArray()}`); + } + } + }, [ikSolver]); - const totalDist = restToStartDist + startToEndDist + endToRestDist; - const restToStartRange = [0, restToStartDist / totalDist]; - const startToEndRange = [ - restToStartRange[1], - restToStartRange[1] + startToEndDist / totalDist, - ]; - const endToRestRange = [startToEndRange[1], 1]; + // Log state changes + useEffect(() => { + const prev = prevStateRef.current; - return { - trigger: p.trigger, - curve, - speed: p.speed, - restToStartRange, - startToEndRange, - endToRestRange, - }; + if (prev.isInitializing !== isInitializing) { + if (!isInitializing) { + logStatus(`[Arm ${uuid}] Completed initialization, now at rest position`); + } + } + + if (prev.needsInitialMovement !== needsInitialMovement && !needsInitialMovement) { + logStatus(`[Arm ${uuid}] Reached rest position, ready for animation`); + } + + if (prev.selectedTrigger !== selectedTrigger) { + logStatus(`[Arm ${uuid}] Processing new trigger: ${selectedTrigger}`); + } + + // Update previous state + prevStateRef.current = { + isInitializing, + needsInitialMovement, + selectedTrigger, + progress + }; + }, [isInitializing, needsInitialMovement, selectedTrigger, progress]); + + const calculateInitialCurve = (startPosition: THREE.Vector3) => { + const direction = new THREE.Vector3().subVectors(restPosition, startPosition); + const distance = direction.length(); + direction.normalize(); + + const perpendicular = new THREE.Vector3(-direction.z, 0, direction.x).normalize(); + + const midHeight = 0.5; + const tiltAmount = 1; + const mid = new THREE.Vector3() + .addVectors(startPosition, restPosition) + .multiplyScalar(0.5) + .add(perpendicular.clone().multiplyScalar(distance * 0.3 * tiltAmount)) + .add(new THREE.Vector3(0, midHeight, 0)); + + initialCurveRef.current = new THREE.CatmullRomCurve3([ + startPosition, + new THREE.Vector3().lerpVectors(startPosition, mid, 0.33), + mid, + new THREE.Vector3().lerpVectors(mid, restPosition, 0.66), + restPosition + ]); + }; + + const processedCurves = useMemo(() => { + return process.map((p) => { + const tempLift = 0.5; + const localStart = groupRef.current?.worldToLocal(p.startPoint.clone().add(new THREE.Vector3(0, tempLift, 0))); + const localEnd = groupRef.current?.worldToLocal(p.endPoint.clone().add(new THREE.Vector3(0, tempLift, 0))); + + if (localStart && localEnd) { + + const mid = new THREE.Vector3( + (localStart.x + localEnd.x) / 1, + Math.max(localStart.y, localEnd.y) + 0.8, + (localStart.z + localEnd.z) / 0.9 + ); + + const points = [ + restPosition.clone(), + localStart.clone(), + mid.clone(), + localEnd.clone(), + restPosition.clone(), + ]; + const curve = new THREE.CatmullRomCurve3(points); + const restToStartDist = points[0].distanceTo(points[1]); + const startToEndDist = points[1].distanceTo(points[3]); + const endToRestDist = points[3].distanceTo(points[4]); + + const totalDist = restToStartDist + startToEndDist + endToRestDist; + const restToStartRange = [0, restToStartDist / totalDist]; + const startToEndRange = [ + restToStartRange[1], + restToStartRange[1] + startToEndDist / totalDist, + ]; + const endToRestRange = [startToEndRange[1], 1]; + + return { + trigger: p.triggerId, + curve, + speed: p.speed, + restToStartRange, + startToEndRange, + endToRestRange, + }; + } }); - }, [process]); + }, [process, groupRef]); const activeCurve = useMemo(() => { - return processedCurves.find((c) => c.trigger === selectedTrigger); + return processedCurves.find((c) => c?.trigger === selectedTrigger); }, [processedCurves, selectedTrigger]); + // Initial movement to rest position useFrame((_, delta) => { - if (!ikSolver || !activeCurve) return; + if (!ikSolver || !needsInitialMovement || !isInitializing || !initialCurveRef.current) return; - const { curve, speed, startToEndRange } = activeCurve; + const targetBone = ikSolver.mesh.skeleton.bones.find( + (b: any) => b.name === targetBoneName + ); + if (!targetBone) return; + + setInitialProgress((prev) => { + const next = prev + delta * 0.5; + if (next >= 1) { + targetBone.position.copy(restPosition); + setNeedsInitialMovement(false); + setIsInitializing(false); + return 1; + } + targetBone.position.copy(initialCurveRef.current!.getPoint(next)); + return next; + }); + + ikSolver.update(); + }); + + // Main animation loop + useFrame((_, delta) => { + if (!ikSolver || !activeCurve || isInitializing) return; + + const { curve, speed, restToStartRange, startToEndRange, endToRestRange } = activeCurve; const targetBone = ikSolver.mesh.skeleton.bones.find( (b: any) => b.name === targetBoneName ); if (!targetBone) return; let currentSpeed = restSpeed; - if (progress >= startToEndRange[0] && progress < startToEndRange[1]) { + let currentStatus = "idle"; // Default status + + // Determine current phase and status + if (progress < restToStartRange[1]) { + currentSpeed = restSpeed; + currentStatus = "moving"; // Moving to start point + } else if (progress >= startToEndRange[0] && progress < startToEndRange[1]) { currentSpeed = speed; + currentStatus = "moving"; // Moving between points + } else if (progress >= endToRestRange[0] && progress < 1) { + currentSpeed = restSpeed; + currentStatus = "moving"; // Returning to rest + } else if (progress >= 1) { + currentStatus = "idle"; // Completed cycle } - setProgress((prev) => { - const next = prev + delta * currentSpeed; - if (next >= 1) { - targetBone.position.copy(curve.getPoint(1)); - return 1; - } - targetBone.position.copy(curve.getPoint(next)); - return next; - }); + // Update status when it changes + if (prevStatusRef.current !== currentStatus) { + updateArmBotStatus(currentStatus); + prevStatusRef.current = currentStatus; + } + + // Only update progress if we're not already at the end + if (progress < 1) { + setProgress((prev) => { + const next = prev + delta * currentSpeed; + return Math.min(next, 1); // Cap at 1 + }); + } + + // Update bone position based on progress + if (progress < 1) { + targetBone.position.copy(curve.getPoint(progress)); + } else { + targetBone.position.copy(curve.getPoint(1)); + } ikSolver.update(); }); @@ -98,4 +247,4 @@ const IKAnimationController = ({ return null; }; -export default IKAnimationController; +export default IKAnimationController; \ No newline at end of file diff --git a/app/src/modules/simulation/armbot/IkInstances.tsx b/app/src/modules/simulation/armbot/IkInstances.tsx index b789f3a..7b02941 100644 --- a/app/src/modules/simulation/armbot/IkInstances.tsx +++ b/app/src/modules/simulation/armbot/IkInstances.tsx @@ -1,43 +1,40 @@ import * as THREE from "three"; import { useEffect, useMemo, useRef, useState } from "react"; -import { useLoader } from "@react-three/fiber"; +import { useFrame, useLoader } from "@react-three/fiber"; import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader"; import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader"; import { clone } from "three/examples/jsm/utils/SkeletonUtils"; import { CCDIKSolver, CCDIKHelper, } from "three/examples/jsm/animation/CCDIKSolver"; import IKAnimationController from "./IKAnimationController"; +import { TransformControls } from "@react-three/drei"; -const IkInstances = ({ modelUrl, position, rotation }: { modelUrl: string; position: [number, number, number]; rotation: [number, number, number]; }) => { +const IkInstances = ({ + uuid, + modelUrl, + processes, + position, + rotation, + updateArmBotStatus +}: { + uuid: string; + modelUrl: string; + processes: any; + position: [number, number, number]; + rotation: [number, number, number]; + updateArmBotStatus: (status: string) => void; +}) => { const [ikSolver, setIkSolver] = useState(null); - const [selectedTrigger, setSelectedTrigger] = useState("idle"); + const [selectedTrigger, setSelectedTrigger] = useState(""); const gltf = useLoader(GLTFLoader, modelUrl, (loader) => { const draco = new DRACOLoader(); - draco.setDecoderPath( - "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/" - ); + draco.setDecoderPath("https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/"); loader.setDRACOLoader(draco); }); const cloned = useMemo(() => clone(gltf.scene), [gltf]); const groupRef = useRef(null); - const [selectedArm, setSelectedArm] = useState(); const targetBoneName = "Target"; const skinnedMeshName = "link_0"; - const process = useMemo(() => [ - { - trigger: "Trigger1", - start: new THREE.Vector3(-0.75, 1.5, -2.2), - end: new THREE.Vector3(0, 1.2, 2.2), - speed: 0.25, - }, - { - trigger: "Trigger2", - start: new THREE.Vector3(0, 1.2, 2.2), - end: new THREE.Vector3(0.75, 1.5, -2.2), - speed: 0.22, - } - ], []); - useEffect(() => { if (!gltf) return; const OOI: any = {}; @@ -86,7 +83,7 @@ const IkInstances = ({ modelUrl, position, rotation }: { modelUrl: string; posit }, [gltf]); useEffect(() => { - const triggers = ['Trigger1', 'Trigger2']; + const triggers = ["9f4a9b8b-e60d-4754-8c99-d71979da0e71", "b77b4f0a-ce55-4fe0-a181-a43ab3d01c83"]; let index = 0; const cycleTriggers = setInterval(() => { @@ -97,30 +94,33 @@ const IkInstances = ({ modelUrl, position, rotation }: { modelUrl: string; posit return () => clearInterval(cycleTriggers); }, []); + const logStatus = (status: string) => { + // console.log(status); + } + return ( <> { - e.stopPropagation(); - setSelectedArm(groupRef.current?.getObjectByName(targetBoneName)) - }} + position={position} + rotation={rotation} > - {/* {selectedArm && } */} ); }; diff --git a/app/src/modules/simulation/path/pathConnector.tsx b/app/src/modules/simulation/path/pathConnector.tsx index 0071240..0008a73 100644 --- a/app/src/modules/simulation/path/pathConnector.tsx +++ b/app/src/modules/simulation/path/pathConnector.tsx @@ -2,7 +2,7 @@ import { useFrame, useThree } from '@react-three/fiber'; import React, { useEffect, useRef, useState } from 'react'; import * as THREE from 'three'; import * as Types from '../../../types/world/worldTypes'; -import * as SimulationTypes from '../../../types/simulation'; +import * as SimulationTypes from '../../../types/simulationTypes'; import { QuadraticBezierLine } from '@react-three/drei'; import { useDeleteTool, useIsConnecting, useRenderDistance, useSimulationStates, useSocketStore } from '../../../store/store'; import useModuleStore from '../../../store/useModuleStore'; @@ -982,7 +982,6 @@ function PathConnector({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObjec setSimulationStates(updatedStates); }; - return ( {simulationStates.flatMap(path => { diff --git a/app/src/modules/simulation/path/pathCreation.tsx b/app/src/modules/simulation/path/pathCreation.tsx index 4a8da49..1e9601d 100644 --- a/app/src/modules/simulation/path/pathCreation.tsx +++ b/app/src/modules/simulation/path/pathCreation.tsx @@ -1,5 +1,5 @@ import * as THREE from "three"; -import * as SimulationTypes from "../../../types/simulation"; +import * as SimulationTypes from "../../../types/simulationTypes"; import { useRef, useState, useEffect, useMemo } from "react"; import { Sphere, TransformControls } from "@react-three/drei"; import { @@ -66,45 +66,6 @@ function PathCreation({ pathsGroupRef, }: { pathsGroupRef: React.MutableRefObjec }); }); - const updateSimulationPaths = () => { - if (!selectedActionSphere) return; - - const updatedPaths = simulationStates.map((path) => { - if (path.type === "Conveyor") { - return { - ...path, - points: path.points.map((point) => - point.uuid === selectedActionSphere.points.uuid - ? { - ...point, - position: [ - selectedActionSphere.points.position.x, - selectedActionSphere.points.position.y, - selectedActionSphere.points.position.z, - ], - rotation: [ - selectedActionSphere.points.rotation.x, - selectedActionSphere.points.rotation.y, - selectedActionSphere.points.rotation.z, - ], - } - : point - ), - }; - } else { - return path; - } - }) as SimulationTypes.ConveyorEventsSchema[]; - - const updatedPath = updatedPaths.find( - (path) => path.type === "Conveyor" && path.points.some((point) => point.uuid === selectedActionSphere.points.uuid) - ); - - // console.log("Updated Path:", updatedPath); - - setSimulationStates(updatedPaths); - }; - useFrame(() => { if (eyeDropMode) { raycaster.setFromCamera(pointer, camera); @@ -445,7 +406,6 @@ function PathCreation({ pathsGroupRef, }: { pathsGroupRef: React.MutableRefObjec ref={transformRef} object={selectedActionSphere.points} mode={transformMode} - onMouseUp={updateSimulationPaths} /> )} diff --git a/app/src/modules/simulation/process/processCreator.tsx b/app/src/modules/simulation/process/processCreator.tsx index f7f9974..068b5ce 100644 --- a/app/src/modules/simulation/process/processCreator.tsx +++ b/app/src/modules/simulation/process/processCreator.tsx @@ -458,7 +458,7 @@ import { useThree } from "@react-three/fiber"; import { ConveyorEventsSchema, VehicleEventsSchema, -} from "../../../types/simulation"; +} from "../../../types/simulationTypes"; import { usePlayButtonStore } from "../../../store/usePlayButtonStore"; // Type definitions diff --git a/app/src/modules/simulation/simulation.tsx b/app/src/modules/simulation/simulation.tsx index b1f961e..f13fdf4 100644 --- a/app/src/modules/simulation/simulation.tsx +++ b/app/src/modules/simulation/simulation.tsx @@ -7,39 +7,50 @@ import ProcessContainer from "./process/processContainer"; import Agv from "../builder/agv/agv"; import ArmBot from "./armbot/ArmBot"; +interface ArmBotState { + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + status: string; + material: string; + triggerId: string; + actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; +} + function Simulation() { - const { activeModule } = useModuleStore(); - const pathsGroupRef = useRef() as React.MutableRefObject; - const [processes, setProcesses] = useState([]); - const agvRef = useRef([]); - const MaterialRef = useRef([]); + const { activeModule } = useModuleStore(); + const pathsGroupRef = useRef() as React.MutableRefObject; + const [armBots, setArmBots] = useState([]); + const [processes, setProcesses] = useState([]); + const agvRef = useRef([]); + const MaterialRef = useRef([]); - return ( - <> - {activeModule === "simulation" && ( + return ( <> - + {activeModule === "simulation" && ( + <> + - + - + - + + + )} + - )} - - - ); + ); } export default Simulation; diff --git a/app/src/store/store.ts b/app/src/store/store.ts index 0b15b3e..765712b 100644 --- a/app/src/store/store.ts +++ b/app/src/store/store.ts @@ -1,6 +1,6 @@ import * as THREE from "three"; import * as Types from "../types/world/worldTypes"; -import * as SimulationTypes from "../types/simulation"; +import * as SimulationTypes from "../types/simulationTypes"; import { create } from "zustand"; import { io } from "socket.io-client"; diff --git a/app/src/types/simulation.d.ts b/app/src/types/simulationTypes.d.ts similarity index 100% rename from app/src/types/simulation.d.ts rename to app/src/types/simulationTypes.d.ts From c2a29fc8930da44087e4a2532a8537b6f90c72e1 Mon Sep 17 00:00:00 2001 From: Poovizhi99 Date: Tue, 15 Apr 2025 15:37:11 +0530 Subject: [PATCH 04/12] integrated path while deleting the asset --- .../controls/selection/selectionControls.tsx | 391 +++++------------- 1 file changed, 113 insertions(+), 278 deletions(-) diff --git a/app/src/modules/scene/controls/selection/selectionControls.tsx b/app/src/modules/scene/controls/selection/selectionControls.tsx index 80a7518..8d7c4cc 100644 --- a/app/src/modules/scene/controls/selection/selectionControls.tsx +++ b/app/src/modules/scene/controls/selection/selectionControls.tsx @@ -323,247 +323,124 @@ const SelectionControls: React.FC = () => { }); }; - // const removeConnection = (modelUUID: any) => { - // - // const removedPath = simulationStates?.flatMap((state) => { - // let shouldInclude = false; - - // if (state.type === "Conveyor") { - // state.points.forEach((point: any) => { - // const sourceMatch = - // point.connections?.source?.modelUUID === modelUUID; - // const targetMatch = point.connections?.targets?.some( - // (target: any) => target.modelUUID === modelUUID - // ); - - // if (sourceMatch || targetMatch) shouldInclude = true; - // }); - // } - - // if (state.type === "Vehicle") { - // const targetMatch = state.points.connections?.targets?.some( - // (target: any) => target.modelUUID === modelUUID - // ); - - // if (targetMatch) shouldInclude = true; - // } - - // if (state.type === "StaticMachine") { - // const targetMatch = state.points.connections?.targets?.some( - // (target: any) => target.modelUUID === modelUUID - // ); - - // if (targetMatch) shouldInclude = true; - // } - - // if (state.type === "ArmBot") { - // const sourceMatch = - // state.points.connections?.source?.modelUUID === modelUUID; - // const targetMatch = state.points.connections?.targets?.some( - // (target: any) => target.modelUUID === modelUUID - // ); - - // const processMatch = - // state.points.actions?.processes?.some( - // (process: any) => - // process.startPoint === modelUUID || process.endPoint === modelUUID - // ) ?? false; - - // if (sourceMatch || targetMatch || processMatch) shouldInclude = true; - // } - - // return shouldInclude ? [state] : []; - // }); - // updateBackend(removedPath); - // - // return removedPath; - // // updateBackend(updatedPaths); - - // // setSimulationStates(updatedStates); - // }; - // const removeConnection = (modelUUIDs: any[]) => { - // - // const removedPath = simulationStates?.flatMap((state) => { - // let shouldInclude = false; - - // if (state.type === "Conveyor") { - // state.points.forEach((point: any) => { - // const sourceMatch = modelUUIDs.includes( - // point.connections?.source?.modelUUID - // ); - // const targetMatch = point.connections?.targets?.some((target: any) => - // modelUUIDs.includes(target.modelUUID) - // ); - - // if (sourceMatch || targetMatch) shouldInclude = true; - // }); - // } - - // if (state.type === "Vehicle") { - // const targetMatch = state.points.connections?.targets?.some( - // (target: any) => modelUUIDs.includes(target.modelUUID) - // ); - - // if (targetMatch) shouldInclude = true; - // } - - // if (state.type === "StaticMachine") { - // const targetMatch = state.points.connections?.targets?.some( - // (target: any) => modelUUIDs.includes(target.modelUUID) - // ); - - // if (targetMatch) shouldInclude = true; - // } - - // if (state.type === "ArmBot") { - // const sourceMatch = modelUUIDs.includes( - // state.points.connections?.source?.modelUUID - // ); - // const targetMatch = state.points.connections?.targets?.some( - // (target: any) => modelUUIDs.includes(target.modelUUID) - // ); - - // const processMatch = - // state.points.actions?.processes?.some( - // (process: any) => - // modelUUIDs.includes(process.startPoint) || - // modelUUIDs.includes(process.endPoint) - // ) ?? false; - - // if (sourceMatch || targetMatch || processMatch) shouldInclude = true; - // } - - // return shouldInclude ? [state] : []; - // }); - // updateBackend(removedPath); - // - // return removedPath; - // }; - - const removeConnection = (modelUUIDs: any[]) => { - const removedPath = simulationStates?.flatMap((state: any) => { - let shouldInclude = false; - - // Conveyor type + const removeConnections = (deletedModelUUIDs: string[]) => { + const updatedStates = simulationStates.map((state) => { + // Handle Conveyor if (state.type === "Conveyor") { - state.points.forEach((point: any) => { - const sourceMatch = modelUUIDs.includes( - point.connections?.source?.modelUUID - ); - const targetMatch = point.connections?.targets?.some((target: any) => - modelUUIDs.includes(target.modelUUID) - ); - - if (sourceMatch) { - point.connections.source = {}; - shouldInclude = true; - } - - if (targetMatch) { - point.connections.targets = []; - shouldInclude = true; - } - }); - } - // Vehicle & StaticMachine types - if (state.type === "Vehicle") { - const targets = state.points?.connections?.targets || []; - const targetMatch = targets.some((target: any) => - modelUUIDs.includes(target.modelUUID) - ); - - if (targetMatch) { - state.points.connections.targets = []; - shouldInclude = true; - } - } - if (state.type === "StaticMachine") { - const targets = state.points?.connections?.targets || []; - const targetMatch = targets.some((target: any) => - modelUUIDs.includes(target.modelUUID) - ); - - if (targetMatch) { - state.points.connections.targets = []; - shouldInclude = true; - } + const updatedConveyor: SimulationTypes.ConveyorEventsSchema = { + ...state, + points: state.points.map((point) => { + return { + ...point, + connections: { + ...point.connections, + targets: point.connections.targets.filter( + (target) => !deletedModelUUIDs.includes(target.modelUUID) + ), + }, + }; + }), + }; + return updatedConveyor; } - // ArmBot type - if (state.type === "ArmBot") { - const sourceMatch = modelUUIDs.includes( - state.points.connections?.source?.modelUUID - ); - console.log("model", modelUUIDs); - console.log("state.points.connections: ", state.points); - - const targetMatch = state.points.connections?.targets?.some( - (target: any) => modelUUIDs.includes(target.modelUUID) - ); - // state.points.actions.processes = state.points.actions.processes.filter( - // (process: any) => - // console.log( - // !modelUUIDs.includes(process.startPoint), - // !modelUUIDs.includes(process.endPoint), - // modelUUIDs, - // process.startPoint, - // process.endPoint - // ) - // ); - - // shouldInclude = true; - - // const processMatches = state.points.actions?.processes?.some( - // (process: any) => - // console.log( - // "process: ", - // process, - // modelUUIDs, - // process.startPoint, - // process.endPoint - // ) - // // modelUUIDs.includes(process.startPoint) || - // // modelUUIDs.includes(process.endPoint) - // ); - // const processMatch = state.points.actions?.processes?.some( - // (process: any) => - // modelUUIDs.includes(String(process.startPoint)) || - // modelUUIDs.includes(String(process.endPoint)) - // ); - - // console.log("processMatch: ", processMatch); - if (sourceMatch) { - state.points.connections.source = {}; - shouldInclude = true; - } - - if (targetMatch) { - state.points.connections.targets = - state.points.connections.targets.filter( - (target: any) => !modelUUIDs.includes(target.modelUUID) - ); - shouldInclude = true; - } - - // console.log("processMatch: ", processMatch); - // if (processMatch) { - // state.points.actions.processes = - // state.points.actions.processes.filter((process: any) => { - // const shouldRemove = - // modelUUIDs.includes(process.startPoint) || - // modelUUIDs.includes(process.endPoint); - // console.log("shouldRemove: ", shouldRemove); - // return !shouldRemove; - // }); - // shouldInclude = true; - // } + // Handle Vehicle + else if (state.type === "Vehicle") { + const updatedVehicle: SimulationTypes.VehicleEventsSchema = { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + targets: state.points.connections.targets.filter( + (target) => !deletedModelUUIDs.includes(target.modelUUID) + ), + }, + }, + }; + return updatedVehicle; } - return shouldInclude ? [state] : []; + // Handle StaticMachine + else if (state.type === "StaticMachine") { + const updatedStaticMachine: SimulationTypes.StaticMachineEventsSchema = + { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + targets: state.points.connections.targets.filter( + (target) => !deletedModelUUIDs.includes(target.modelUUID) + ), + }, + }, + }; + return updatedStaticMachine; + } + + // Handle ArmBot + else if (state.type === "ArmBot") { + const updatedArmBot: SimulationTypes.ArmBotEventsSchema = { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + + targets: state.points.connections.targets.filter( + (target: any) => !deletedModelUUIDs.includes(target.modelUUID) + ), + }, + actions: { + ...state.points.actions, + processes: (state.points.actions.processes = + state.points.actions.processes?.filter((process) => { + const matchedStates = simulationStates.filter((s) => + deletedModelUUIDs.includes(s.modeluuid) + ); + + if (matchedStates.length > 0) { + if (matchedStates[0]?.type === "StaticMachine") { + const trigPoints = matchedStates[0]?.points; + + return !( + process.triggerId === trigPoints?.triggers?.uuid + ); + } else if (matchedStates[0]?.type === "Conveyor") { + const trigPoints = matchedStates[0]?.points; + + if (Array.isArray(trigPoints)) { + const nonEmptyTriggers = trigPoints.filter( + (point) => + point && point.triggers && point.triggers.length > 0 + ); + + const allTriggerUUIDs = nonEmptyTriggers + .flatMap((point) => point.triggers) + .map((trigger) => trigger.uuid); + + return !allTriggerUUIDs.includes(process.triggerId); + } + } + } + return true; + })), + }, + }, + }; + return updatedArmBot; + } + + return state; }); - updateBackend(removedPath); - return removedPath; + const filteredStates = updatedStates.filter( + (state) => !deletedModelUUIDs.includes(state.modeluuid) + ); + + updateBackend(filteredStates); + setSimulationStates(filteredStates); }; const deleteSelection = () => { @@ -633,51 +510,9 @@ const SelectionControls: React.FC = () => { itemsGroupRef.current?.remove(selectedMesh); }); + console.log("selectedAssets: ", selectedAssets); const allUUIDs = selectedAssets.map((val: any) => val.uuid); - removeConnection(allUUIDs); - - // const removedPath = simulationStates?.flatMap((path: any) => { - // let shouldInclude = false; - - // if (Array.isArray(path.points)) { - // path.points.forEach((point: any) => { - // const sourceMatch = - // point.connections?.source?.modelUUID === selectedAssets[0].uuid; - // const targetMatch = point.connections?.targets?.some( - // (target: any) => target.modelUUID === selectedAssets[0].uuid - // ); - - // if (sourceMatch) { - // point.connections.source = {}; - // shouldInclude = true; - // } - - // if (targetMatch) { - // point.connections.targets = []; - // shouldInclude = true; - // } - // }); - // } else { - // const sourceMatch = - // path.connections?.source?.modelUUID === selectedAssets[0].uuid; - // const targetMatch = path.connections?.targets?.some( - // (target: any) => target.modelUUID === selectedAssets[0].uuid - // ); - - // if (sourceMatch) { - // path.connections.source = {}; - // shouldInclude = true; - // } - - // if (targetMatch) { - // path.connections.targets = []; - // shouldInclude = true; - // } - // } - - // return shouldInclude ? [path] : []; - // }); - // updateBackend(removedPath); + removeConnections(allUUIDs); const updatedItems = floorItems.filter( (item: { modeluuid: string }) => !selectedUUIDs.includes(item.modeluuid) From f62d231a79e6709fedd6ee94034ac13c53091866 Mon Sep 17 00:00:00 2001 From: Poovizhi99 Date: Tue, 15 Apr 2025 15:39:05 +0530 Subject: [PATCH 05/12] integrated the removeConnections in path connector --- .../modules/simulation/path/pathConnector.tsx | 158 +++++++++++++++--- 1 file changed, 139 insertions(+), 19 deletions(-) diff --git a/app/src/modules/simulation/path/pathConnector.tsx b/app/src/modules/simulation/path/pathConnector.tsx index 1e93bd5..fe3bb1b 100644 --- a/app/src/modules/simulation/path/pathConnector.tsx +++ b/app/src/modules/simulation/path/pathConnector.tsx @@ -1133,26 +1133,27 @@ function PathConnector({ (state.modeluuid === connection2.model && state.points.uuid === connection2.point) ) { - const updatedStaticMachine: SimulationTypes.StaticMachineEventsSchema = { - ...state, - points: { - ...state.points, - connections: { - ...state.points.connections, - targets: state.points.connections.targets.filter((target) => { - return !( - (target.modelUUID === connection1.model && - target.pointUUID === connection1.point) || - (target.modelUUID === connection2.model && - target.pointUUID === connection2.point) - ); - }), + const updatedStaticMachine: SimulationTypes.StaticMachineEventsSchema = + { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + targets: state.points.connections.targets.filter((target) => { + return !( + (target.modelUUID === connection1.model && + target.pointUUID === connection1.point) || + (target.modelUUID === connection2.model && + target.pointUUID === connection2.point) + ); + }), + }, + // Ensure all required StaticMachine point properties are included + actions: state.points.actions, + triggers: state.points.triggers, }, - // Ensure all required StaticMachine point properties are included - actions: state.points.actions, - triggers: state.points.triggers, - }, - }; + }; return updatedStaticMachine; } } @@ -1211,6 +1212,125 @@ function PathConnector({ setSimulationStates(updatedStates); }; + const removeConnection = (deletedModelUUIDs: string[]) => { + const updatedStates = simulationStates.map((state) => { + // Handle Conveyor + if (state.type === "Conveyor") { + const updatedConveyor: SimulationTypes.ConveyorEventsSchema = { + ...state, + points: state.points.map((point) => { + return { + ...point, + connections: { + ...point.connections, + targets: point.connections.targets.filter( + (target) => !deletedModelUUIDs.includes(target.modelUUID) + ), + }, + }; + }), + }; + return updatedConveyor; + } + + // Handle Vehicle + else if (state.type === "Vehicle") { + const updatedVehicle: SimulationTypes.VehicleEventsSchema = { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + targets: state.points.connections.targets.filter( + (target) => !deletedModelUUIDs.includes(target.modelUUID) + ), + }, + }, + }; + return updatedVehicle; + } + + // Handle StaticMachine + else if (state.type === "StaticMachine") { + const updatedStaticMachine: SimulationTypes.StaticMachineEventsSchema = + { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + targets: state.points.connections.targets.filter( + (target) => !deletedModelUUIDs.includes(target.modelUUID) + ), + }, + }, + }; + return updatedStaticMachine; + } + + // Handle ArmBot + else if (state.type === "ArmBot") { + const updatedArmBot: SimulationTypes.ArmBotEventsSchema = { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + + targets: state.points.connections.targets.filter( + (target: any) => !deletedModelUUIDs.includes(target.modelUUID) + ), + }, + actions: { + ...state.points.actions, + processes: (state.points.actions.processes = + state.points.actions.processes?.filter((process) => { + const matchedStates = simulationStates.filter((s) => + deletedModelUUIDs.includes(s.modeluuid) + ); + + if (matchedStates.length > 0) { + if (matchedStates[0]?.type === "StaticMachine") { + const trigPoints = matchedStates[0]?.points; + + return !( + process.triggerId === trigPoints?.triggers?.uuid + ); + } else if (matchedStates[0]?.type === "Conveyor") { + const trigPoints = matchedStates[0]?.points; + + if (Array.isArray(trigPoints)) { + const nonEmptyTriggers = trigPoints.filter( + (point) => + point && point.triggers && point.triggers.length > 0 + ); + + const allTriggerUUIDs = nonEmptyTriggers + .flatMap((point) => point.triggers) + .map((trigger) => trigger.uuid); + + return !allTriggerUUIDs.includes(process.triggerId); + } + } + } + return true; + })), + }, + }, + }; + return updatedArmBot; + } + + return state; + }); + + const filteredStates = updatedStates.filter( + (state) => !deletedModelUUIDs.includes(state.modeluuid) + ); + + updateBackend(filteredStates); + setSimulationStates(filteredStates); + }; return ( From 109f88949cbc65294c0587454ca8ca883d5b71fa Mon Sep 17 00:00:00 2001 From: gabriel Date: Tue, 15 Apr 2025 18:05:01 +0530 Subject: [PATCH 06/12] bug fix --- app/.env | 4 ++-- .../IotInputCards/BarChartInput.tsx | 4 ++++ .../FleetEfficiencyInputComponent.tsx | 4 ++++ .../IotInputCards/FlotingWidgetInput.tsx | 4 ++++ .../IotInputCards/LineGrapInput.tsx | 4 ++++ .../IotInputCards/PieChartInput.tsx | 4 ++++ .../IotInputCards/Progress1Input.tsx | 4 ++++ .../IotInputCards/Progress2Input.tsx | 4 ++++ .../WarehouseThroughputInputComponent.tsx | 4 ++++ .../IotInputCards/Widget2InputCard3D.tsx | 4 ++++ .../IotInputCards/Widget3InputCard3D.tsx | 4 ++++ .../IotInputCards/Widget4InputCard3D.tsx | 4 ++++ .../ui/inputs/MultiLevelDropDown.tsx | 23 +++++++++++-------- .../widgets/2d/DraggableWidget.tsx | 17 +++++++++++--- app/src/store/useDroppedObjectsStore.ts | 2 ++ 15 files changed, 76 insertions(+), 14 deletions(-) diff --git a/app/.env b/app/.env index c50d174..0e57725 100644 --- a/app/.env +++ b/app/.env @@ -2,10 +2,10 @@ PORT=8200 # Base URL for the server socket API, used for real-time communication (e.g., WebSockets). -REACT_APP_SERVER_SOCKET_API_BASE_URL=185.100.212.76:8000 +REACT_APP_SERVER_SOCKET_API_BASE_URL=192.168.0.102:8000 # Base URL for the server REST API, used for HTTP requests to the backend server. -REACT_APP_SERVER_REST_API_BASE_URL=185.100.212.76:5000 +REACT_APP_SERVER_REST_API_BASE_URL=192.168.0.102:5000 # Base URL for the server marketplace, used for market place model blob. REACT_APP_SERVER_MARKETPLACE_URL=185.100.212.76:50011 diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/BarChartInput.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/BarChartInput.tsx index e5debde..8e2d4f1 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/BarChartInput.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/BarChartInput.tsx @@ -21,14 +21,17 @@ const BarChartInput = (props: Props) => { const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const email = localStorage.getItem("email") || ""; const organization = email?.split("@")[1]?.split(".")[0] + const [isLoading, setLoading] = useState(true); useEffect(() => { const fetchZoneData = async () => { try { + setLoading(true) const response = await axios.get(`http://${iotApiUrl}/floatinput`); if (response.status === 200) { // console.log("dropdown data:", response.data); setDropDownData(response.data); + setLoading(false); } else { console.log("Unexpected response:", response); } @@ -148,6 +151,7 @@ const BarChartInput = (props: Props) => { onSelect={(selectedData) => handleSelect(inputKey, selectedData)} onUnselect={() => handleSelect(inputKey, null)} selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} />
diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/FleetEfficiencyInputComponent.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/FleetEfficiencyInputComponent.tsx index 55ae422..af6f735 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/FleetEfficiencyInputComponent.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/FleetEfficiencyInputComponent.tsx @@ -21,14 +21,17 @@ const FleetEfficiencyInputComponent = (props: Props) => { const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const email = localStorage.getItem("email") || ""; const organization = email?.split("@")[1]?.split(".")[0] + const [isLoading, setLoading] = useState(true); useEffect(() => { const fetchZoneData = async () => { try { const response = await axios.get(`http://${iotApiUrl}/floatinput`); + setLoading(true) if (response.status === 200) { // console.log("dropdown data:", response.data); setDropDownData(response.data); + setLoading(false) } else { console.log("Unexpected response:", response); } @@ -149,6 +152,7 @@ const FleetEfficiencyInputComponent = (props: Props) => { onSelect={(selectedData) => handleSelect(inputKey, selectedData)} onUnselect={() => handleSelect(inputKey, null)} selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} />
diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/FlotingWidgetInput.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/FlotingWidgetInput.tsx index 1164a84..53ddbcc 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/FlotingWidgetInput.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/FlotingWidgetInput.tsx @@ -21,14 +21,17 @@ const FlotingWidgetInput = (props: Props) => { const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const email = localStorage.getItem("email") || ""; const organization = email?.split("@")[1]?.split(".")[0] + const [isLoading, setLoading] = useState(true); useEffect(() => { const fetchZoneData = async () => { try { + setLoading(true) const response = await axios.get(`http://${iotApiUrl}/floatinput`); if (response.status === 200) { // console.log("dropdown data:", response.data); setDropDownData(response.data); + setLoading(false); } else { console.log("Unexpected response:", response); } @@ -149,6 +152,7 @@ const FlotingWidgetInput = (props: Props) => { onSelect={(selectedData) => handleSelect(inputKey, selectedData)} onUnselect={() => handleSelect(inputKey, null)} selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} />
diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/LineGrapInput.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/LineGrapInput.tsx index 6ab5ec3..3cf647e 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/LineGrapInput.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/LineGrapInput.tsx @@ -140,14 +140,17 @@ const LineGrapInput = (props: Props) => { const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const email = localStorage.getItem("email") || ""; const organization = email?.split("@")[1]?.split(".")[0] + const [isLoading, setLoading] = useState(true); useEffect(() => { const fetchZoneData = async () => { try { + setLoading(true) const response = await axios.get(`http://${iotApiUrl}/floatinput`); if (response.status === 200) { // console.log("dropdown data:", response.data); setDropDownData(response.data); + setLoading(false) } else { console.log("Unexpected response:", response); } @@ -267,6 +270,7 @@ const LineGrapInput = (props: Props) => { onSelect={(selectedData) => handleSelect(inputKey, selectedData)} onUnselect={() => handleSelect(inputKey, null)} selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} />
diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/PieChartInput.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/PieChartInput.tsx index 56ef990..1d16358 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/PieChartInput.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/PieChartInput.tsx @@ -21,14 +21,17 @@ const PieChartInput = (props: Props) => { const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const email = localStorage.getItem("email") || ""; const organization = email?.split("@")[1]?.split(".")[0] + const [isLoading, setLoading] = useState(true); useEffect(() => { const fetchZoneData = async () => { try { + setLoading(true) const response = await axios.get(`http://${iotApiUrl}/floatinput`); if (response.status === 200) { // console.log("dropdown data:", response.data); setDropDownData(response.data); + setLoading(false) } else { console.log("Unexpected response:", response); } @@ -148,6 +151,7 @@ const PieChartInput = (props: Props) => { onSelect={(selectedData) => handleSelect(inputKey, selectedData)} onUnselect={() => handleSelect(inputKey, null)} selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} />
diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Progress1Input.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Progress1Input.tsx index cd347b3..5d9dd58 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Progress1Input.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Progress1Input.tsx @@ -21,14 +21,17 @@ const Progress1Input = (props: Props) => { const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const email = localStorage.getItem("email") || ""; const organization = email?.split("@")[1]?.split(".")[0] + const [isLoading, setLoading] = useState(true); useEffect(() => { const fetchZoneData = async () => { try { + setLoading(true) const response = await axios.get(`http://${iotApiUrl}/floatinput`); if (response.status === 200) { // console.log("dropdown data:", response.data); setDropDownData(response.data); + setLoading(false) } else { console.log("Unexpected response:", response); } @@ -142,6 +145,7 @@ const Progress1Input = (props: Props) => { onSelect={(selectedData) => handleSelect(inputKey, selectedData)} onUnselect={() => handleSelect(inputKey, null)} selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} />
diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Progress2Input.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Progress2Input.tsx index ba56e27..bc6059c 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Progress2Input.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Progress2Input.tsx @@ -21,14 +21,17 @@ const Progress2Input = (props: Props) => { const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const email = localStorage.getItem("email") || ""; const organization = email?.split("@")[1]?.split(".")[0] + const [isLoading, setLoading] = useState(true); useEffect(() => { const fetchZoneData = async () => { try { + setLoading(true) const response = await axios.get(`http://${iotApiUrl}/floatinput`); if (response.status === 200) { // console.log("dropdown data:", response.data); setDropDownData(response.data); + setLoading(false) } else { console.log("Unexpected response:", response); } @@ -142,6 +145,7 @@ const Progress2Input = (props: Props) => { onSelect={(selectedData) => handleSelect(inputKey, selectedData)} onUnselect={() => handleSelect(inputKey, null)} selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} />
diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/WarehouseThroughputInputComponent.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/WarehouseThroughputInputComponent.tsx index d3ed377..8d5e717 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/WarehouseThroughputInputComponent.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/WarehouseThroughputInputComponent.tsx @@ -21,14 +21,17 @@ const WarehouseThroughputInputComponent = (props: Props) => { const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const email = localStorage.getItem("email") || ""; const organization = email?.split("@")[1]?.split(".")[0] + const [isLoading, setLoading] = useState(true); useEffect(() => { const fetchZoneData = async () => { try { + setLoading(true) const response = await axios.get(`http://${iotApiUrl}/floatinput`); if (response.status === 200) { // console.log("dropdown data:", response.data); setDropDownData(response.data); + setLoading(false) } else { console.log("Unexpected response:", response); } @@ -149,6 +152,7 @@ const WarehouseThroughputInputComponent = (props: Props) => { onSelect={(selectedData) => handleSelect(inputKey, selectedData)} onUnselect={() => handleSelect(inputKey, null)} selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} />
diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget2InputCard3D.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget2InputCard3D.tsx index a32d227..a1b4360 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget2InputCard3D.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget2InputCard3D.tsx @@ -21,14 +21,17 @@ const Widget2InputCard3D = (props: Props) => { const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const email = localStorage.getItem("email") || ""; const organization = email?.split("@")[1]?.split(".")[0] + const [isLoading, setLoading] = useState(true); useEffect(() => { const fetchZoneData = async () => { try { + setLoading(true) const response = await axios.get(`http://${iotApiUrl}/floatinput`); if (response.status === 200) { // console.log("dropdown data:", response.data); setDropDownData(response.data); + setLoading(false) } else { console.log("Unexpected response:", response); } @@ -147,6 +150,7 @@ const Widget2InputCard3D = (props: Props) => { onSelect={(selectedData) => handleSelect(inputKey, selectedData)} onUnselect={() => handleSelect(inputKey, null)} selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} />
diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget3InputCard3D.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget3InputCard3D.tsx index 95fdc33..43f8e55 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget3InputCard3D.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget3InputCard3D.tsx @@ -19,14 +19,17 @@ const Widget3InputCard3D = () => { const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const email = localStorage.getItem("email") || ""; const organization = email?.split("@")[1]?.split(".")[0] + const [isLoading, setLoading] = useState(true); useEffect(() => { const fetchZoneData = async () => { try { + setLoading(true) const response = await axios.get(`http://${iotApiUrl}/getinput`); if (response.status === 200) { // console.log("dropdown data:", response.data); setDropDownData(response.data); + setLoading(false) } else { console.log("Unexpected response:", response); } @@ -140,6 +143,7 @@ const Widget3InputCard3D = () => { onSelect={(selectedData) => handleSelect(inputKey, selectedData)} onUnselect={() => handleSelect(inputKey, null)} selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} />
diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget4InputCard3D.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget4InputCard3D.tsx index bfd2edd..4aa9855 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget4InputCard3D.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget4InputCard3D.tsx @@ -21,14 +21,17 @@ const Widget4InputCard3D = (props: Props) => { const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const email = localStorage.getItem("email") || ""; const organization = email?.split("@")[1]?.split(".")[0] + const [isLoading, setLoading] = useState(true); useEffect(() => { const fetchZoneData = async () => { try { + setLoading(true) const response = await axios.get(`http://${iotApiUrl}/floatinput`); if (response.status === 200) { // console.log("dropdown data:", response.data); setDropDownData(response.data); + setLoading(false) } else { console.log("Unexpected response:", response); } @@ -147,6 +150,7 @@ const Widget4InputCard3D = (props: Props) => { onSelect={(selectedData) => handleSelect(inputKey, selectedData)} onUnselect={() => handleSelect(inputKey, null)} selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} />
diff --git a/app/src/components/ui/inputs/MultiLevelDropDown.tsx b/app/src/components/ui/inputs/MultiLevelDropDown.tsx index f2be121..1293e4a 100644 --- a/app/src/components/ui/inputs/MultiLevelDropDown.tsx +++ b/app/src/components/ui/inputs/MultiLevelDropDown.tsx @@ -203,6 +203,7 @@ interface MultiLevelDropdownProps { onSelect: (selectedData: { name: string; fields: string }) => void; onUnselect: () => void; selectedValue?: { name: string; fields: string }; + isLoading?: boolean; } // Main Multi-Level Dropdown Component @@ -211,6 +212,7 @@ const MultiLevelDropdown = ({ onSelect, onUnselect, selectedValue, + isLoading = false, }: MultiLevelDropdownProps) => { const [open, setOpen] = useState(false); const dropdownRef = useRef(null); @@ -261,19 +263,22 @@ const MultiLevelDropdown = ({
{/* loading list */} - {/*
*/} + {/* Unselect Option */} {/* Nested Dropdown Items */} - {Object.entries(data).map(([key, value]) => ( - - ))} + { + isLoading ?
: + Object.entries(data).map(([key, value]) => ( + + )) + }
)} diff --git a/app/src/modules/visualization/widgets/2d/DraggableWidget.tsx b/app/src/modules/visualization/widgets/2d/DraggableWidget.tsx index 7e6ad6d..f865719 100644 --- a/app/src/modules/visualization/widgets/2d/DraggableWidget.tsx +++ b/app/src/modules/visualization/widgets/2d/DraggableWidget.tsx @@ -100,6 +100,8 @@ export const DraggableWidget = ({ const deleteSelectedChart = async () => { try { + console.log("delete"); + const email = localStorage.getItem("email") || ""; const organization = email?.split("@")[1]?.split(".")[0]; let deleteWidget = { @@ -109,7 +111,9 @@ export const DraggableWidget = ({ }; if (visualizationSocket) { + setSelectedChartId(null) visualizationSocket.emit("v2:viz-widget:delete", deleteWidget); + console.log("delete widget",selectedChartId); } const updatedWidgets = selectedZone.widgets.filter( (w: Widget) => w.id !== widget.id @@ -120,7 +124,6 @@ export const DraggableWidget = ({ widgets: updatedWidgets, })); setOpenKebabId(null); - // const response = await deleteWidgetApi(widget.id, organization); // if (response?.message === "Widget deleted successfully") { // const updatedWidgets = selectedZone.widgets.filter( @@ -175,6 +178,7 @@ export const DraggableWidget = ({ const duplicatedWidget: Widget = { ...widget, + title: name === '' ? widget.title : name, Data: { duration: duration, measurements: { ...measurements }, @@ -187,6 +191,7 @@ export const DraggableWidget = ({ zoneId: selectedZone.zoneId, widget: duplicatedWidget, }; + if (visualizationSocket) { visualizationSocket.emit("v2:viz-widget:add", duplicateWidget); } @@ -306,7 +311,10 @@ export const DraggableWidget = ({ : undefined, }} ref={chartWidget} - onClick={() => setSelectedChartId(widget)} + onClick={() => {setSelectedChartId(widget) + console.log('click'); + + }} > {/* Kebab Icon */}
@@ -327,7 +335,10 @@ export const DraggableWidget = ({
Duplicate
-
+
{ + e.stopPropagation() + deleteSelectedChart(); + }}>
diff --git a/app/src/store/useDroppedObjectsStore.ts b/app/src/store/useDroppedObjectsStore.ts index ca39d9f..0c03eec 100644 --- a/app/src/store/useDroppedObjectsStore.ts +++ b/app/src/store/useDroppedObjectsStore.ts @@ -101,6 +101,7 @@ export const useDroppedObjectsStore = create((set) => ({ let visualizationSocket = socketState.visualizationSocket; let iotMeasurements = iotData.flotingMeasurements; let iotDuration = iotData.flotingDuration; + let iotHeader = iotData.header if (!zone) return; @@ -117,6 +118,7 @@ export const useDroppedObjectsStore = create((set) => ({ measurements: iotMeasurements, duration: iotDuration, }, + header: iotHeader, id: `${originalObject.id}-copy-${Date.now()}`, // Unique ID position: { ...originalObject.position, From e2fd4ef15d173e8a9ec98dbec498ff6f24ed1897 Mon Sep 17 00:00:00 2001 From: gabriel Date: Tue, 15 Apr 2025 18:06:31 +0530 Subject: [PATCH 07/12] updated ip --- app/.env | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/.env b/app/.env index 0e57725..c50d174 100644 --- a/app/.env +++ b/app/.env @@ -2,10 +2,10 @@ PORT=8200 # Base URL for the server socket API, used for real-time communication (e.g., WebSockets). -REACT_APP_SERVER_SOCKET_API_BASE_URL=192.168.0.102:8000 +REACT_APP_SERVER_SOCKET_API_BASE_URL=185.100.212.76:8000 # Base URL for the server REST API, used for HTTP requests to the backend server. -REACT_APP_SERVER_REST_API_BASE_URL=192.168.0.102:5000 +REACT_APP_SERVER_REST_API_BASE_URL=185.100.212.76:5000 # Base URL for the server marketplace, used for market place model blob. REACT_APP_SERVER_MARKETPLACE_URL=185.100.212.76:50011 From 5b42bd9c40f080af2db06d25e42e883d672f477b Mon Sep 17 00:00:00 2001 From: Jerald-Golden-B Date: Tue, 15 Apr 2025 18:34:43 +0530 Subject: [PATCH 08/12] feat: Enhance simulation with StaticMachine integration and ArmBot updates - Added StaticMachine component to manage static machine states and interactions. - Implemented StaticMachineInstances for handling individual machine behaviors. - Updated ArmBot and related components to support interactions with static machines. - Refactored process handling to include ArmBot actions and trigger management. - Improved type definitions for simulation types to accommodate new features. --- .../geomentries/assets/addAssetModel.ts | 3 +- .../controls/selection/copyPasteControls.tsx | 27 ++-- .../selection/duplicationControls.tsx | 29 ++-- app/src/modules/simulation/armbot/ArmBot.tsx | 32 ++-- .../simulation/armbot/ArmBotInstances.tsx | 16 +- .../armbot/IKAnimationController.tsx | 149 +++++++++++++----- .../modules/simulation/armbot/IkInstances.tsx | 47 ++++-- .../simulation/process/processAnimator.tsx | 16 +- .../simulation/process/processContainer.tsx | 16 ++ app/src/modules/simulation/process/types.ts | 14 +- .../process/useProcessAnimations.tsx | 94 +++++++---- app/src/modules/simulation/simulation.tsx | 15 +- .../staticMachine/staticMachine.tsx | 77 +++++++++ .../staticMachine/staticMachineInstances.tsx | 33 ++++ app/src/types/simulationTypes.d.ts | 4 +- 15 files changed, 437 insertions(+), 135 deletions(-) create mode 100644 app/src/modules/simulation/staticMachine/staticMachine.tsx create mode 100644 app/src/modules/simulation/staticMachine/staticMachineInstances.tsx diff --git a/app/src/modules/builder/geomentries/assets/addAssetModel.ts b/app/src/modules/builder/geomentries/assets/addAssetModel.ts index 0db803f..29b0627 100644 --- a/app/src/modules/builder/geomentries/assets/addAssetModel.ts +++ b/app/src/modules/builder/geomentries/assets/addAssetModel.ts @@ -225,7 +225,6 @@ async function handleModelLoad( eventData as SimulationTypes.ConveyorEventsSchema ]); - console.log('data: ', data); socket.emit("v2:model-asset:add", data); } else if (res.type === "Vehicle") { @@ -365,7 +364,7 @@ async function handleModelLoad( uuid: pointUUID, position: res.points.position as [number, number, number], rotation: res.points.rotation as [number, number, number], - actions: { uuid: THREE.MathUtils.generateUUID(), name: 'Action 1', speed: 1, processes: [] }, + actions: { uuid: THREE.MathUtils.generateUUID(), name: 'Action 1', speed: 0.2, processes: [] }, triggers: { uuid: THREE.MathUtils.generateUUID(), name: 'Trigger 1', type: 'OnComplete' }, connections: { source: { modelUUID: model.uuid, pointUUID: pointUUID }, targets: [] }, } diff --git a/app/src/modules/scene/controls/selection/copyPasteControls.tsx b/app/src/modules/scene/controls/selection/copyPasteControls.tsx index 84d6047..1f83513 100644 --- a/app/src/modules/scene/controls/selection/copyPasteControls.tsx +++ b/app/src/modules/scene/controls/selection/copyPasteControls.tsx @@ -332,8 +332,8 @@ const CopyPasteControls = ({ itemsGroupRef, copiedObjects, setCopiedObjects, pas } else if (eventData.type === 'StaticMachine' && eventData) { const createStaticMachinePoint = () => { const pointUUID = THREE.MathUtils.generateUUID(); - const vehiclePoint = (eventData as SimulationTypes.StaticMachineEventsSchema)?.points; - const hasActions = vehiclePoint?.actions !== undefined; + const staticMachinePoint = (eventData as SimulationTypes.StaticMachineEventsSchema)?.points; + const hasActions = staticMachinePoint?.actions !== undefined; const defaultAction = { uuid: THREE.MathUtils.generateUUID(), @@ -344,11 +344,11 @@ const CopyPasteControls = ({ itemsGroupRef, copiedObjects, setCopiedObjects, pas return { uuid: pointUUID, - position: vehiclePoint?.position, - // rotation: vehiclePoint?.rotation, + position: staticMachinePoint?.position, + rotation: staticMachinePoint?.rotation, actions: hasActions ? { - ...vehiclePoint.actions, + ...staticMachinePoint.actions, uuid: THREE.MathUtils.generateUUID() } : defaultAction, @@ -410,8 +410,8 @@ const CopyPasteControls = ({ itemsGroupRef, copiedObjects, setCopiedObjects, pas } else if (eventData.type === 'ArmBot' && eventData) { const createArmBotPoint = () => { const pointUUID = THREE.MathUtils.generateUUID(); - const vehiclePoint = (eventData as SimulationTypes.ArmBotEventsSchema)?.points; - const hasActions = vehiclePoint?.actions !== undefined; + const armBotPoint = (eventData as SimulationTypes.ArmBotEventsSchema)?.points; + const hasActions = armBotPoint?.actions !== undefined; const defaultAction = { uuid: THREE.MathUtils.generateUUID(), @@ -422,18 +422,19 @@ const CopyPasteControls = ({ itemsGroupRef, copiedObjects, setCopiedObjects, pas return { uuid: pointUUID, - position: vehiclePoint?.position, - // rotation: vehiclePoint?.rotation, + position: armBotPoint?.position, + rotation: armBotPoint?.rotation, actions: hasActions ? { - ...vehiclePoint.actions, - uuid: THREE.MathUtils.generateUUID() + ...armBotPoint.actions, + uuid: THREE.MathUtils.generateUUID(), + processes: [] } : defaultAction, triggers: { uuid: THREE.MathUtils.generateUUID(), - name: vehiclePoint.triggers.name, - type: vehiclePoint.triggers.type, + name: armBotPoint.triggers.name, + type: armBotPoint.triggers.type, }, connections: { source: { modelUUID: obj.uuid, pointUUID }, diff --git a/app/src/modules/scene/controls/selection/duplicationControls.tsx b/app/src/modules/scene/controls/selection/duplicationControls.tsx index 5ce0603..915cb61 100644 --- a/app/src/modules/scene/controls/selection/duplicationControls.tsx +++ b/app/src/modules/scene/controls/selection/duplicationControls.tsx @@ -246,7 +246,7 @@ const DuplicationControls = ({ itemsGroupRef, duplicatedObjects, setDuplicatedOb return { uuid: pointUUID, position: vehiclePoint?.position, - // rotation: vehiclePoint?.rotation, + rotation: vehiclePoint?.rotation, actions: hasActions ? { ...vehiclePoint.actions, @@ -311,8 +311,8 @@ const DuplicationControls = ({ itemsGroupRef, duplicatedObjects, setDuplicatedOb } else if (eventData.type === 'StaticMachine' && eventData) { const createStaticMachinePoint = () => { const pointUUID = THREE.MathUtils.generateUUID(); - const vehiclePoint = (eventData as SimulationTypes.StaticMachineEventsSchema)?.points; - const hasActions = vehiclePoint?.actions !== undefined; + const staticMachinePoint = (eventData as SimulationTypes.StaticMachineEventsSchema)?.points; + const hasActions = staticMachinePoint?.actions !== undefined; const defaultAction = { uuid: THREE.MathUtils.generateUUID(), @@ -323,11 +323,11 @@ const DuplicationControls = ({ itemsGroupRef, duplicatedObjects, setDuplicatedOb return { uuid: pointUUID, - position: vehiclePoint?.position, - // rotation: vehiclePoint?.rotation, + position: staticMachinePoint?.position, + rotation: staticMachinePoint?.rotation, actions: hasActions ? { - ...vehiclePoint.actions, + ...staticMachinePoint.actions, uuid: THREE.MathUtils.generateUUID() } : defaultAction, @@ -389,8 +389,8 @@ const DuplicationControls = ({ itemsGroupRef, duplicatedObjects, setDuplicatedOb } else if (eventData.type === 'ArmBot' && eventData) { const createArmBotPoint = () => { const pointUUID = THREE.MathUtils.generateUUID(); - const vehiclePoint = (eventData as SimulationTypes.ArmBotEventsSchema)?.points; - const hasActions = vehiclePoint?.actions !== undefined; + const armBotPoint = (eventData as SimulationTypes.ArmBotEventsSchema)?.points; + const hasActions = armBotPoint?.actions !== undefined; const defaultAction = { uuid: THREE.MathUtils.generateUUID(), @@ -401,18 +401,19 @@ const DuplicationControls = ({ itemsGroupRef, duplicatedObjects, setDuplicatedOb return { uuid: pointUUID, - position: vehiclePoint?.position, - // rotation: vehiclePoint?.rotation, + position: armBotPoint?.position, + rotation: armBotPoint?.rotation, actions: hasActions ? { - ...vehiclePoint.actions, - uuid: THREE.MathUtils.generateUUID() + ...armBotPoint.actions, + uuid: THREE.MathUtils.generateUUID(), + processes: [] } : defaultAction, triggers: { uuid: THREE.MathUtils.generateUUID(), - name: vehiclePoint.triggers.name, - type: vehiclePoint.triggers.type, + name: armBotPoint.triggers.name, + type: armBotPoint.triggers.type, }, connections: { source: { modelUUID: obj.uuid, pointUUID }, diff --git a/app/src/modules/simulation/armbot/ArmBot.tsx b/app/src/modules/simulation/armbot/ArmBot.tsx index 2e77206..a6d8d23 100644 --- a/app/src/modules/simulation/armbot/ArmBot.tsx +++ b/app/src/modules/simulation/armbot/ArmBot.tsx @@ -15,27 +15,38 @@ interface ArmBotState { actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; } +interface StaticMachineState { + uuid: string; + status: string; + actions: { uuid: string; name: string; buffer: number; material: string; }; + machineTriggerId: string; + connectedArmBot: string; +} + interface ArmBotProps { armBots: ArmBotState[]; setArmBots: React.Dispatch>; + setStaticMachines: React.Dispatch>; } -const ArmBot = ({ armBots, setArmBots }: ArmBotProps) => { +const ArmBot = ({ armBots, setArmBots, setStaticMachines }: ArmBotProps) => { const { activeModule } = useModuleStore(); const { scene } = useThree(); const { simulationStates } = useSimulationStates(); useEffect(() => { const filtered = simulationStates.filter((s): s is SimulationTypes.ArmBotEventsSchema => s.type === "ArmBot"); - const initialStates: ArmBotState[] = filtered.map(bot => ({ - uuid: bot.modeluuid, - position: bot.position, - rotation: bot.rotation, - status: "idle", - material: "default", - triggerId: '', - actions: bot.points.actions - })); + const initialStates: ArmBotState[] = filtered + .filter(bot => bot.points.connections.targets.length > 0) + .map(bot => ({ + uuid: bot.modeluuid, + position: bot.position, + rotation: bot.rotation, + status: "idle", + material: "default", + triggerId: '', + actions: bot.points.actions + })); setArmBots(initialStates); }, [simulationStates]); @@ -57,6 +68,7 @@ const ArmBot = ({ armBots, setArmBots }: ArmBotProps) => { index={i} armBot={bot} setArmBots={setArmBots} + setStaticMachines={setStaticMachines} /> ))} diff --git a/app/src/modules/simulation/armbot/ArmBotInstances.tsx b/app/src/modules/simulation/armbot/ArmBotInstances.tsx index 8a1380b..10a49f6 100644 --- a/app/src/modules/simulation/armbot/ArmBotInstances.tsx +++ b/app/src/modules/simulation/armbot/ArmBotInstances.tsx @@ -30,13 +30,22 @@ interface ArmBotState { }; } +interface StaticMachineState { + uuid: string; + status: string; + actions: { uuid: string; name: string; buffer: number; material: string; }; + machineTriggerId: string; + connectedArmBot: string; +} + interface ArmbotInstancesProps { index: number; armBot: ArmBotState; setArmBots: React.Dispatch>; + setStaticMachines: React.Dispatch>; } -export const ArmbotInstances: React.FC = ({ index, armBot, setArmBots }) => { +export const ArmbotInstances: React.FC = ({ index, armBot, setArmBots, setStaticMachines }) => { const { scene } = useThree(); const [processes, setProcesses] = useState([]); @@ -61,7 +70,7 @@ export const ArmbotInstances: React.FC = ({ index, armBot, setArmBots((prevArmBots) => { return prevArmBots.map(bot => { if (bot.uuid === armBot.uuid) { - return { ...bot, status }; + return { ...bot, status, triggerId: status === 'idle' ? '' : armBot.triggerId }; } return bot; }); @@ -72,10 +81,13 @@ export const ArmbotInstances: React.FC = ({ index, armBot, ); diff --git a/app/src/modules/simulation/armbot/IKAnimationController.tsx b/app/src/modules/simulation/armbot/IKAnimationController.tsx index 538f0aa..1044540 100644 --- a/app/src/modules/simulation/armbot/IKAnimationController.tsx +++ b/app/src/modules/simulation/armbot/IKAnimationController.tsx @@ -2,6 +2,35 @@ import { useEffect, useMemo, useState, useRef } from "react"; import { useFrame } from "@react-three/fiber"; import * as THREE from "three"; import { usePlayButtonStore } from "../../../store/usePlayButtonStore"; +import { useSimulationStates } from "../../../store/store"; + + +interface StaticMachineState { + uuid: string; + status: string; + actions: { uuid: string; name: string; buffer: number; material: string; }; + machineTriggerId: string; + connectedArmBot: string; +} + +interface ArmBotState { + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + status: string; + material: string; + triggerId: string; + actions: { + uuid: string; + name: string; + speed: number; + processes: { + triggerId: string; + startPoint: string; + endPoint: string; + }[]; + }; +} type IKAnimationControllerProps = { ikSolver: any; @@ -16,6 +45,8 @@ type IKAnimationControllerProps = { uuid: string; logStatus: (status: string) => void; groupRef: React.RefObject; + armBot: ArmBotState; + setStaticMachines: React.Dispatch>; updateArmBotStatus: (status: string) => void; } @@ -27,6 +58,8 @@ const IKAnimationController = ({ uuid, logStatus, groupRef, + armBot, + setStaticMachines, updateArmBotStatus }: IKAnimationControllerProps) => { const [progress, setProgress] = useState(0); @@ -36,6 +69,7 @@ const IKAnimationController = ({ const restSpeed = 0.1; const restPosition = new THREE.Vector3(0, 2, 1.6); const { isPlaying } = usePlayButtonStore(); + const { simulationStates } = useSimulationStates(); // Track previous states for comparison const prevStateRef = useRef({ @@ -120,54 +154,56 @@ const IKAnimationController = ({ }; const processedCurves = useMemo(() => { - return process.map((p) => { - const tempLift = 0.5; - const localStart = groupRef.current?.worldToLocal(p.startPoint.clone().add(new THREE.Vector3(0, tempLift, 0))); - const localEnd = groupRef.current?.worldToLocal(p.endPoint.clone().add(new THREE.Vector3(0, tempLift, 0))); + if (isPlaying) + return process.map((p) => { + const tempLift = 0.5; + const localStart = groupRef.current?.worldToLocal(p.startPoint.clone().add(new THREE.Vector3(0, tempLift, 0))); + const localEnd = groupRef.current?.worldToLocal(p.endPoint.clone().add(new THREE.Vector3(0, tempLift, 0))); - if (localStart && localEnd) { + if (localStart && localEnd) { - const mid = new THREE.Vector3( - (localStart.x + localEnd.x) / 1, - Math.max(localStart.y, localEnd.y) + 0.8, - (localStart.z + localEnd.z) / 0.9 - ); + const mid = new THREE.Vector3( + (localStart.x + localEnd.x) / 1, + Math.max(localStart.y, localEnd.y) + 0.8, + (localStart.z + localEnd.z) / 0.9 + ); - const points = [ - restPosition.clone(), - localStart.clone(), - mid.clone(), - localEnd.clone(), - restPosition.clone(), - ]; - const curve = new THREE.CatmullRomCurve3(points); - const restToStartDist = points[0].distanceTo(points[1]); - const startToEndDist = points[1].distanceTo(points[3]); - const endToRestDist = points[3].distanceTo(points[4]); + const points = [ + restPosition.clone(), + localStart.clone(), + mid.clone(), + localEnd.clone(), + restPosition.clone(), + ]; + const curve = new THREE.CatmullRomCurve3(points); + const restToStartDist = points[0].distanceTo(points[1]); + const startToEndDist = points[1].distanceTo(points[3]); + const endToRestDist = points[3].distanceTo(points[4]); - const totalDist = restToStartDist + startToEndDist + endToRestDist; - const restToStartRange = [0, restToStartDist / totalDist]; - const startToEndRange = [ - restToStartRange[1], - restToStartRange[1] + startToEndDist / totalDist, - ]; - const endToRestRange = [startToEndRange[1], 1]; + const totalDist = restToStartDist + startToEndDist + endToRestDist; + const restToStartRange = [0, restToStartDist / totalDist]; + const startToEndRange = [ + restToStartRange[1], + restToStartRange[1] + startToEndDist / totalDist, + ]; + const endToRestRange = [startToEndRange[1], 1]; - return { - trigger: p.triggerId, - curve, - speed: p.speed, - restToStartRange, - startToEndRange, - endToRestRange, - }; - } - }); - }, [process, groupRef]); + return { + trigger: p.triggerId, + curve, + speed: p.speed, + restToStartRange, + startToEndRange, + endToRestRange, + }; + } + }); + }, [process, groupRef, isPlaying]); const activeCurve = useMemo(() => { - return processedCurves.find((c) => c?.trigger === selectedTrigger); - }, [processedCurves, selectedTrigger]); + if (isPlaying && processedCurves) + return processedCurves.find((c) => c?.trigger === selectedTrigger); + }, [processedCurves, selectedTrigger, isPlaying]); // Initial movement to rest position useFrame((_, delta) => { @@ -195,7 +231,7 @@ const IKAnimationController = ({ // Main animation loop useFrame((_, delta) => { - if (!ikSolver || !activeCurve || isInitializing) return; + if (!ikSolver || !activeCurve || isInitializing || !isPlaying) return; const { curve, speed, restToStartRange, startToEndRange, endToRestRange } = activeCurve; const targetBone = ikSolver.mesh.skeleton.bones.find( @@ -213,6 +249,35 @@ const IKAnimationController = ({ } else if (progress >= startToEndRange[0] && progress < startToEndRange[1]) { currentSpeed = speed; currentStatus = "moving"; // Moving between points + if (1 - progress < 0.05) { + // Find the process that matches the current trigger + const currentProcess = process.find(p => p.triggerId === selectedTrigger); + if (currentProcess) { + const triggerId = currentProcess.triggerId; + + const endPoint = armBot.actions.processes.find((process) => process.triggerId === triggerId)?.endPoint; + + // Search simulationStates for a StaticMachine that has a point matching this endPointId + const matchedStaticMachine = simulationStates.find( + (state) => + state.type === "StaticMachine" && + state.points?.uuid === endPoint// check for static machine with matching point uuid + ) as any; + + if (matchedStaticMachine) { + setStaticMachines((machines) => { + return machines.map((machine) => { + if (machine.uuid === matchedStaticMachine.modeluuid) { + return { ...machine, status: "running" }; + } else { + return machine; + } + }); + }); + } + } + + } } else if (progress >= endToRestRange[0] && progress < 1) { currentSpeed = restSpeed; currentStatus = "moving"; // Returning to rest diff --git a/app/src/modules/simulation/armbot/IkInstances.tsx b/app/src/modules/simulation/armbot/IkInstances.tsx index 7b02941..50b8ffb 100644 --- a/app/src/modules/simulation/armbot/IkInstances.tsx +++ b/app/src/modules/simulation/armbot/IkInstances.tsx @@ -8,23 +8,55 @@ import { CCDIKSolver, CCDIKHelper, } from "three/examples/jsm/animation/CCDIKSol import IKAnimationController from "./IKAnimationController"; import { TransformControls } from "@react-three/drei"; +interface StaticMachineState { + uuid: string; + status: string; + actions: { uuid: string; name: string; buffer: number; material: string; }; + machineTriggerId: string; + connectedArmBot: string; +} + +interface ArmBotState { + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + status: string; + material: string; + triggerId: string; + actions: { + uuid: string; + name: string; + speed: number; + processes: { + triggerId: string; + startPoint: string; + endPoint: string; + }[]; + }; +} + const IkInstances = ({ uuid, + selectedTrigger, modelUrl, processes, position, rotation, + armBot, + setStaticMachines, updateArmBotStatus }: { uuid: string; + selectedTrigger: string; modelUrl: string; processes: any; position: [number, number, number]; rotation: [number, number, number]; + armBot: ArmBotState; + setStaticMachines: React.Dispatch>; updateArmBotStatus: (status: string) => void; }) => { const [ikSolver, setIkSolver] = useState(null); - const [selectedTrigger, setSelectedTrigger] = useState(""); const gltf = useLoader(GLTFLoader, modelUrl, (loader) => { const draco = new DRACOLoader(); draco.setDecoderPath("https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/"); @@ -82,17 +114,6 @@ const IkInstances = ({ }, [gltf]); - useEffect(() => { - const triggers = ["9f4a9b8b-e60d-4754-8c99-d71979da0e71", "b77b4f0a-ce55-4fe0-a181-a43ab3d01c83"]; - let index = 0; - - const cycleTriggers = setInterval(() => { - setSelectedTrigger(triggers[index]); - index = (index + 1) % triggers.length; - }, 10000); - - return () => clearInterval(cycleTriggers); - }, []); const logStatus = (status: string) => { // console.log(status); @@ -119,6 +140,8 @@ const IkInstances = ({ uuid={uuid} logStatus={logStatus} groupRef={groupRef} + armBot={armBot} + setStaticMachines={setStaticMachines} updateArmBotStatus={updateArmBotStatus} /> diff --git a/app/src/modules/simulation/process/processAnimator.tsx b/app/src/modules/simulation/process/processAnimator.tsx index c1063c3..460de49 100644 --- a/app/src/modules/simulation/process/processAnimator.tsx +++ b/app/src/modules/simulation/process/processAnimator.tsx @@ -11,11 +11,23 @@ import { ProcessData } from "./types"; import { useSimulationStates } from "../../../store/store"; import { retrieveGLTF } from "../../../utils/indexDB/idbUtils"; +interface ArmBotState { + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + status: string; + material: string; + triggerId: string; + actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; +} + interface ProcessContainerProps { processes: ProcessData[]; setProcesses: React.Dispatch>; agvRef: any; MaterialRef: any; + armBots: ArmBotState[]; + setArmBots: React.Dispatch>; } const ProcessAnimator: React.FC = ({ @@ -23,6 +35,8 @@ const ProcessAnimator: React.FC = ({ setProcesses, agvRef, MaterialRef, + armBots, + setArmBots }) => { const gltf = useLoader(GLTFLoader, crate) as GLTF; const groupRef = useRef(null); @@ -42,7 +56,7 @@ const ProcessAnimator: React.FC = ({ getPointDataForAnimationIndex, processes: processedProcesses, checkAndCountTriggers, - } = useProcessAnimation(processes, setProcesses, agvRef); + } = useProcessAnimation(processes, setProcesses, agvRef, armBots, setArmBots); const baseMaterials = useMemo(() => ({ Box: new THREE.MeshStandardMaterial({ color: 0x8b4513 }), diff --git a/app/src/modules/simulation/process/processContainer.tsx b/app/src/modules/simulation/process/processContainer.tsx index 1cbc75b..4cc7edf 100644 --- a/app/src/modules/simulation/process/processContainer.tsx +++ b/app/src/modules/simulation/process/processContainer.tsx @@ -2,11 +2,23 @@ import React, { useState } from "react"; import ProcessCreator from "./processCreator"; import ProcessAnimator from "./processAnimator"; +interface ArmBotState { + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + status: string; + material: string; + triggerId: string; + actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; +} + interface ProcessContainerProps { processes: any[]; setProcesses: React.Dispatch>; agvRef: any; MaterialRef: any; + armBots: ArmBotState[]; + setArmBots: React.Dispatch>; } const ProcessContainer: React.FC = ({ @@ -14,6 +26,8 @@ const ProcessContainer: React.FC = ({ setProcesses, agvRef, MaterialRef, + armBots, + setArmBots }) => { return ( <> @@ -23,6 +37,8 @@ const ProcessContainer: React.FC = ({ setProcesses={setProcesses} agvRef={agvRef} MaterialRef={MaterialRef} + armBots={armBots} + setArmBots={setArmBots} /> ); diff --git a/app/src/modules/simulation/process/types.ts b/app/src/modules/simulation/process/types.ts index 6f935fc..9c9a1bc 100644 --- a/app/src/modules/simulation/process/types.ts +++ b/app/src/modules/simulation/process/types.ts @@ -21,15 +21,15 @@ export interface PointAction { } export interface ProcessPoint { - uuid: string; + uuid: string; position: number[]; - rotation: number[]; - actions: PointAction[]; + rotation: number[]; + actions: PointAction[]; connections: { - source: { modelUUID: string; pointUUID: string }; - targets: { modelUUID: string; pointUUID: string }[]; + source: { modelUUID: string; pointUUID: string }; + targets: { modelUUID: string; pointUUID: string }[]; }; - triggers?: Trigger[]; + triggers?: Trigger[]; } export interface ProcessPath { modeluuid: string; @@ -38,7 +38,7 @@ export interface ProcessPath { pathPosition: number[]; pathRotation: number[]; speed: number; - type: "Conveyor" | "Vehicle"; + type: "Conveyor" | "Vehicle" | "ArmBot"; isActive: boolean } diff --git a/app/src/modules/simulation/process/useProcessAnimations.tsx b/app/src/modules/simulation/process/useProcessAnimations.tsx index 032d013..8c0f20d 100644 --- a/app/src/modules/simulation/process/useProcessAnimations.tsx +++ b/app/src/modules/simulation/process/useProcessAnimations.tsx @@ -39,10 +39,22 @@ interface PlayAgvState { setPlayAgv: (data: any) => void; } +interface ArmBotState { + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + status: string; + material: string; + triggerId: string; + actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; +} + export const useProcessAnimation = ( processes: ProcessData[], setProcesses: React.Dispatch>, - agvRef: any + agvRef: any, + armBots: ArmBotState[], + setArmBots: React.Dispatch> ) => { // State and refs initialization const { isPlaying, setIsPlaying } = usePlayButtonStore(); @@ -438,6 +450,8 @@ export const useProcessAnimation = ( [handleMaterialSwap] ); + const deferredArmBotUpdates = useRef<{ uuid: string; triggerId: string }[]>([]); + // Trigger counting system const checkAndCountTriggers = useCallback( ( @@ -457,46 +471,54 @@ export const useProcessAnimation = ( const point = getPointDataForAnimationIndex(process, currentPointIndex); if (!point?.triggers) return prev; - const onHitTriggers = point.triggers.filter( - (t: Trigger) => t.type === "On-Hit" && t.isUsed - ); + const onHitTriggers = point.triggers.filter((t: Trigger) => t.type === "On-Hit" && t.isUsed); + if (onHitTriggers.length === 0) return prev; let newTriggerCounts = { ...processState.triggerCounts }; const newTriggerLogs = [...processState.triggerLogs]; let shouldLog = false; - // Find all vehicle paths for this process - const vehiclePaths = process.paths.filter( - (path) => path.type === "Vehicle" - ); + const vehiclePaths = process.paths.filter((path) => path.type === "Vehicle"); + const armBotPaths = process.paths.filter((path) => path.type === "ArmBot"); - // Check if any vehicle is active for this process - const activeVehicles = vehiclePaths.filter(path => { + const activeVehicles = vehiclePaths.filter((path) => { const vehicleId = path.modeluuid; - const vehicleEntry = agvRef.current.find( - (v: any) => v.vehicleId === vehicleId && v.processId === processId - ); + const vehicleEntry = agvRef.current.find((v: any) => v.vehicleId === vehicleId && v.processId === processId); return vehicleEntry?.isActive; }); - // Only count triggers if no vehicles are active for this process + // Check if any ArmBot is active for this process + // const activeArmBots = armBotPaths.filter((path) => { + // const armBotId = path.modeluuid; + // const armBotEntry = armBots.find((a: any) => a.uuid === armBotId); + // return armBotEntry; + // }); + + // Only count triggers if no vehicles and no ArmBots are active for this process + if (activeVehicles.length === 0) { onHitTriggers.forEach((trigger: Trigger) => { - const triggerKey = `${point.uuid}-${trigger.uuid}`; - newTriggerCounts[triggerKey] = (newTriggerCounts[triggerKey] || 0) + 1; - shouldLog = true; - newTriggerLogs.push({ - timestamp: currentTime, - pointId: point.uuid, - objectId, - triggerId: trigger.uuid, + const connections = point.connections?.targets || []; + + connections.forEach((connection) => { + const connectedModelUUID = connection.modelUUID; + + const matchingArmPath = armBotPaths.find((path) => path.modeluuid === connectedModelUUID); + + if (matchingArmPath) { + deferredArmBotUpdates.current.push({ + uuid: connectedModelUUID, + triggerId: trigger.uuid, + }); + } }); }); } let processTotalHits = Object.values(newTriggerCounts).reduce((a, b) => a + b, 0); + // Handle logic for vehicles and ArmBots when a trigger is hit if (shouldLog) { vehiclePaths.forEach((vehiclePath) => { if (vehiclePath.points?.length > 0) { @@ -506,7 +528,10 @@ export const useProcessAnimation = ( if (maxHitCount !== undefined) { const vehicleId = vehiclePath.modeluuid; - let vehicleEntry = agvRef.current.find((v: any) => v.vehicleId === vehicleId && v.processId === processId); + let vehicleEntry = agvRef.current.find( + (v: any) => + v.vehicleId === vehicleId && v.processId === processId + ); if (!vehicleEntry) { vehicleEntry = { @@ -515,14 +540,13 @@ export const useProcessAnimation = ( maxHitCount: maxHitCount, isActive: false, hitCount: 0, - status: 'stationed' + status: "stationed", }; agvRef.current.push(vehicleEntry); } - // if (!vehicleEntry.isActive && vehicleEntry.status === 'picking') { if (!vehicleEntry.isActive) { - vehicleEntry.hitCount = processTotalHits; + vehicleEntry.hitCount++; vehicleEntry.lastUpdated = currentTime; if (vehicleEntry.hitCount >= vehicleEntry.maxHitCount) { @@ -546,9 +570,21 @@ export const useProcessAnimation = ( }, }; }); - }, - [] - ); + }, []); + + useEffect(() => { + if (deferredArmBotUpdates.current.length > 0) { + const updates = [...deferredArmBotUpdates.current]; + deferredArmBotUpdates.current = []; + + setArmBots((prev) => + prev.map((bot) => { + const update = updates.find((u) => u.uuid === bot.uuid); + return update ? { ...bot, triggerId: update.triggerId } : bot; + }) + ); + } + }, [animationStates]); // Utility functions const hasNonInheritActions = useCallback( diff --git a/app/src/modules/simulation/simulation.tsx b/app/src/modules/simulation/simulation.tsx index f13fdf4..2f66ab8 100644 --- a/app/src/modules/simulation/simulation.tsx +++ b/app/src/modules/simulation/simulation.tsx @@ -6,6 +6,7 @@ import useModuleStore from "../../store/useModuleStore"; import ProcessContainer from "./process/processContainer"; import Agv from "../builder/agv/agv"; import ArmBot from "./armbot/ArmBot"; +import StaticMachine from "./staticMachine/staticMachine"; interface ArmBotState { uuid: string; @@ -17,10 +18,19 @@ interface ArmBotState { actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; } +interface StaticMachineState { + uuid: string; + status: string; + actions: { uuid: string; name: string; buffer: number; material: string; }; + machineTriggerId: string; + connectedArmBot: string; +} + function Simulation() { const { activeModule } = useModuleStore(); const pathsGroupRef = useRef() as React.MutableRefObject; const [armBots, setArmBots] = useState([]); + const [staticMachines, setStaticMachines] = useState([]); const [processes, setProcesses] = useState([]); const agvRef = useRef([]); const MaterialRef = useRef([]); @@ -38,6 +48,8 @@ function Simulation() { setProcesses={setProcesses} agvRef={agvRef} MaterialRef={MaterialRef} + armBots={armBots} + setArmBots={setArmBots} /> )} - + + ); } diff --git a/app/src/modules/simulation/staticMachine/staticMachine.tsx b/app/src/modules/simulation/staticMachine/staticMachine.tsx new file mode 100644 index 0000000..ba9b4f0 --- /dev/null +++ b/app/src/modules/simulation/staticMachine/staticMachine.tsx @@ -0,0 +1,77 @@ +import React, { useEffect } from 'react' +import * as SimulationTypes from '../../../types/simulationTypes'; +import { useSimulationStates } from '../../../store/store'; +import StaticMachineInstances from './staticMachineInstances'; + +interface ArmBotState { + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + status: string; + material: string; + triggerId: string; + actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; +} + +interface StaticMachineState { + uuid: string; + status: string; + actions: { uuid: string; name: string; buffer: number; material: string; }; + machineTriggerId: string; + connectedArmBot: string; +} + +type StaticMachineProps = { + setArmBots: React.Dispatch>; + staticMachines: StaticMachineState[]; + setStaticMachines: React.Dispatch>; +} + +function StaticMachine({ setArmBots, staticMachines, setStaticMachines }: StaticMachineProps) { + + const { simulationStates } = useSimulationStates(); + + useEffect(() => { + const filtered = simulationStates.filter((s): s is SimulationTypes.StaticMachineEventsSchema => s.type === "StaticMachine"); + const initialStates: StaticMachineState[] = filtered + .filter(machine => machine.points.connections.targets.length > 0) + .map(machine => ({ + uuid: machine.modeluuid, + status: "idle", + actions: machine.points.actions, + machineTriggerId: machine.points.triggers.uuid, + connectedArmBot: machine.points.connections.targets[0].modelUUID + })); + setStaticMachines(initialStates); + }, [simulationStates]); + + const updateArmBotTriggerAndMachineStatus = (armBotUuid: string, triggerId: string, machineId: string) => { + setArmBots((prevArmBots) => { + return prevArmBots.map(bot => { + if (bot.uuid === armBotUuid) { + return { ...bot, triggerId: triggerId }; + } + return bot; + }); + }); + setStaticMachines((prevStaticMachines) => { + return prevStaticMachines.map(machine => { + if (machine.uuid === machineId) { + return { ...machine, status: "idle" }; + } else { + return machine; + } + }); + }); + } + + return ( + <> + {staticMachines.map((machine, index) => ( + + ))} + + ) +} + +export default StaticMachine; \ No newline at end of file diff --git a/app/src/modules/simulation/staticMachine/staticMachineInstances.tsx b/app/src/modules/simulation/staticMachine/staticMachineInstances.tsx new file mode 100644 index 0000000..94a2faa --- /dev/null +++ b/app/src/modules/simulation/staticMachine/staticMachineInstances.tsx @@ -0,0 +1,33 @@ +import React, { useEffect } from 'react' +import { useAnimationPlaySpeed } from '../../../store/usePlayButtonStore'; + +interface StaticMachineState { + uuid: string; + status: string; + actions: { uuid: string; name: string; buffer: number; material: string; }; + machineTriggerId: string; + connectedArmBot: string; +} + +type StaticMachineInstancesProps = { + machine: StaticMachineState, + updateArmBotTriggerAndMachineStatus: (armBotUuid: string, triggerId: string, machineId: string) => void; +} + +function StaticMachineInstances({ machine, updateArmBotTriggerAndMachineStatus }: StaticMachineInstancesProps) { + const { speed } = useAnimationPlaySpeed(); + + useEffect(() => { + if (machine.status === 'running') { + setTimeout(() => { + updateArmBotTriggerAndMachineStatus(machine.connectedArmBot, machine.machineTriggerId, machine.uuid); + }, machine.actions.buffer * 1000 * speed); + } + }, [machine]) + + return ( + <> + ) +} + +export default StaticMachineInstances \ No newline at end of file diff --git a/app/src/types/simulationTypes.d.ts b/app/src/types/simulationTypes.d.ts index bea52fa..75efcd3 100644 --- a/app/src/types/simulationTypes.d.ts +++ b/app/src/types/simulationTypes.d.ts @@ -64,7 +64,7 @@ interface StaticMachineEventsSchema { uuid: string; position: [number, number, number]; rotation: [number, number, number]; - actions: { uuid: string; name: string; buffer: number | string; material: string; isUsed: boolean; }; + actions: { uuid: string; name: string; buffer: number; material: string; }; triggers: { uuid: string; name: string; type: string }; connections: { source: { modelUUID: string; pointUUID: string }; @@ -103,7 +103,7 @@ export type EventData = { isLocked: boolean; isVisible: boolean; eventData?: - | { + { type: "Conveyor"; points: { uuid: string; From a26e0dacd08d743bcfd55a9e2169e45bb0eed921 Mon Sep 17 00:00:00 2001 From: Jerald-Golden-B Date: Wed, 16 Apr 2025 10:03:01 +0530 Subject: [PATCH 09/12] Implement code changes to enhance functionality and improve performance --- .../controls/selection/selectionControls.tsx | 978 +++--- .../modules/simulation/path/pathConnector.tsx | 2784 ++++++++--------- 2 files changed, 1646 insertions(+), 2116 deletions(-) diff --git a/app/src/modules/scene/controls/selection/selectionControls.tsx b/app/src/modules/scene/controls/selection/selectionControls.tsx index aa2bca4..ece6924 100644 --- a/app/src/modules/scene/controls/selection/selectionControls.tsx +++ b/app/src/modules/scene/controls/selection/selectionControls.tsx @@ -3,13 +3,7 @@ import { useEffect, useMemo, useRef, useState } from "react"; import { SelectionBox } from "three/examples/jsm/interactive/SelectionBox"; import { SelectionHelper } from "./selectionHelper"; import { useFrame, useThree } from "@react-three/fiber"; -import { - useFloorItems, - useSelectedAssets, - useSimulationStates, - useSocketStore, - useToggleView, -} from "../../../../store/store"; +import { useFloorItems, useSelectedAssets, useSimulationStates, useSocketStore, useToggleView, } from "../../../../store/store"; import BoundingBox from "./boundingBoxHelper"; import { toast } from "react-toastify"; // import { deleteFloorItem } from '../../../../services/factoryBuilder/assest/floorAsset/deleteFloorItemApi'; @@ -23,574 +17,446 @@ import RotateControls from "./rotateControls"; import useModuleStore from "../../../../store/useModuleStore"; const SelectionControls: React.FC = () => { - const { camera, controls, gl, scene, pointer } = useThree(); - const itemsGroupRef = useRef(undefined); - const selectionGroup = useRef() as Types.RefGroup; - const { toggleView } = useToggleView(); - const { simulationStates, setSimulationStates } = useSimulationStates(); - const { selectedAssets, setSelectedAssets } = useSelectedAssets(); - const [movedObjects, setMovedObjects] = useState([]); - const [rotatedObjects, setRotatedObjects] = useState([]); - const [copiedObjects, setCopiedObjects] = useState([]); - const [pastedObjects, setpastedObjects] = useState([]); - const [duplicatedObjects, setDuplicatedObjects] = useState( - [] - ); - const boundingBoxRef = useRef(); - const { floorItems, setFloorItems } = useFloorItems(); - const { activeModule } = useModuleStore(); - const { socket } = useSocketStore(); - const selectionBox = useMemo( - () => new SelectionBox(camera, scene), - [camera, scene] - ); + const { camera, controls, gl, scene, pointer } = useThree(); + const itemsGroupRef = useRef(undefined); + const selectionGroup = useRef() as Types.RefGroup; + const { toggleView } = useToggleView(); + const { simulationStates, setSimulationStates } = useSimulationStates(); + const { selectedAssets, setSelectedAssets } = useSelectedAssets(); + const [movedObjects, setMovedObjects] = useState([]); + const [rotatedObjects, setRotatedObjects] = useState([]); + const [copiedObjects, setCopiedObjects] = useState([]); + const [pastedObjects, setpastedObjects] = useState([]); + const [duplicatedObjects, setDuplicatedObjects] = useState([]); + const boundingBoxRef = useRef(); + const { floorItems, setFloorItems } = useFloorItems(); + const { activeModule } = useModuleStore(); + const { socket } = useSocketStore(); + const selectionBox = useMemo(() => new SelectionBox(camera, scene), [camera, scene]); - useEffect(() => { - if (!camera || !scene || toggleView) return; + useEffect(() => { + if (!camera || !scene || toggleView) return; - const canvasElement = gl.domElement; - canvasElement.tabIndex = 0; + const canvasElement = gl.domElement; + canvasElement.tabIndex = 0; - const itemsGroup: any = scene.getObjectByName("itemsGroup"); - itemsGroupRef.current = itemsGroup; + const itemsGroup: any = scene.getObjectByName("itemsGroup"); + itemsGroupRef.current = itemsGroup; - let isSelecting = false; - let isRightClick = false; - let rightClickMoved = false; - let isCtrlSelecting = false; + let isSelecting = false; + let isRightClick = false; + let rightClickMoved = false; + let isCtrlSelecting = false; - const helper = new SelectionHelper(gl); + const helper = new SelectionHelper(gl); - if (!itemsGroup) { - toast.warn("itemsGroup not found in the scene."); - return; - } - - const onPointerDown = (event: PointerEvent) => { - if (event.button === 2) { - isRightClick = true; - rightClickMoved = false; - } else if (event.button === 0) { - isSelecting = false; - isCtrlSelecting = event.ctrlKey; - if (event.ctrlKey && duplicatedObjects.length === 0) { - if (controls) (controls as any).enabled = false; - selectionBox.startPoint.set(pointer.x, pointer.y, 0); + if (!itemsGroup) { + toast.warn("itemsGroup not found in the scene."); + return; } - } - }; - const onPointerMove = (event: PointerEvent) => { - if (isRightClick) { - rightClickMoved = true; - } - isSelecting = true; - if ( - helper.isDown && - event.ctrlKey && - duplicatedObjects.length === 0 && - isCtrlSelecting - ) { - selectionBox.endPoint.set(pointer.x, pointer.y, 0); - } - }; - - const onPointerUp = (event: PointerEvent) => { - if (event.button === 2) { - isRightClick = false; - if (!rightClickMoved) { - clearSelection(); - } - return; - } - - if (isSelecting && isCtrlSelecting) { - isCtrlSelecting = false; - isSelecting = false; - if (event.ctrlKey && duplicatedObjects.length === 0) { - selectAssets(); - } - } else if ( - !isSelecting && - selectedAssets.length > 0 && - ((pastedObjects.length === 0 && - duplicatedObjects.length === 0 && - movedObjects.length === 0 && - rotatedObjects.length === 0) || - event.button !== 0) - ) { - clearSelection(); - helper.enabled = true; - isCtrlSelecting = false; - } - }; - - const onKeyDown = (event: KeyboardEvent) => { - if (movedObjects.length > 0 || rotatedObjects.length > 0) return; - if (event.key.toLowerCase() === "escape") { - event.preventDefault(); - clearSelection(); - } - if (event.key.toLowerCase() === "delete") { - event.preventDefault(); - deleteSelection(); - } - }; - - const onContextMenu = (event: MouseEvent) => { - event.preventDefault(); - if (!rightClickMoved) { - clearSelection(); - } - }; - - if (!toggleView && activeModule === "builder") { - helper.enabled = true; - if (duplicatedObjects.length === 0 && pastedObjects.length === 0) { - canvasElement.addEventListener("pointerdown", onPointerDown); - canvasElement.addEventListener("pointermove", onPointerMove); - canvasElement.addEventListener("pointerup", onPointerUp); - } else { - helper.enabled = false; - helper.dispose(); - } - canvasElement.addEventListener("contextmenu", onContextMenu); - canvasElement.addEventListener("keydown", onKeyDown); - } else { - helper.enabled = false; - helper.dispose(); - } - - return () => { - canvasElement.removeEventListener("pointerdown", onPointerDown); - canvasElement.removeEventListener("pointermove", onPointerMove); - canvasElement.removeEventListener("contextmenu", onContextMenu); - canvasElement.removeEventListener("pointerup", onPointerUp); - canvasElement.removeEventListener("keydown", onKeyDown); - helper.enabled = false; - helper.dispose(); - }; - }, [ - camera, - controls, - scene, - toggleView, - selectedAssets, - copiedObjects, - pastedObjects, - duplicatedObjects, - movedObjects, - socket, - floorItems, - rotatedObjects, - activeModule, - ]); - - useEffect(() => { - if (activeModule !== "builder") { - clearSelection(); - } - }, [activeModule]); - - useFrame(() => { - if ( - pastedObjects.length === 0 && - duplicatedObjects.length === 0 && - movedObjects.length === 0 && - rotatedObjects.length === 0 - ) { - selectionGroup.current.position.set(0, 0, 0); - } - }); - - const selectAssets = () => { - selectionBox.endPoint.set(pointer.x, pointer.y, 0); - if (controls) (controls as any).enabled = true; - - let selectedObjects = selectionBox.select(); - let Objects = new Set(); - - selectedObjects.map((object) => { - let currentObject: THREE.Object3D | null = object; - while (currentObject) { - if (currentObject.userData.modelId) { - Objects.add(currentObject); - break; - } - currentObject = currentObject.parent || null; - } - }); - - if (Objects.size === 0) { - clearSelection(); - return; - } - - const updatedSelections = new Set(selectedAssets); - Objects.forEach((obj) => { - updatedSelections.has(obj) - ? updatedSelections.delete(obj) - : updatedSelections.add(obj); - }); - - const selected = Array.from(updatedSelections); - - setSelectedAssets(selected); - }; - - const clearSelection = () => { - selectionGroup.current.children = []; - selectionGroup.current.position.set(0, 0, 0); - selectionGroup.current.rotation.set(0, 0, 0); - setpastedObjects([]); - setDuplicatedObjects([]); - setSelectedAssets([]); - }; - const updateBackend = async ( - updatedPaths: ( - | SimulationTypes.ConveyorEventsSchema - | SimulationTypes.VehicleEventsSchema - | SimulationTypes.StaticMachineEventsSchema - | SimulationTypes.ArmBotEventsSchema - )[] - ) => { - if (updatedPaths.length === 0) return; - const email = localStorage.getItem("email"); - const organization = email ? email.split("@")[1].split(".")[0] : ""; - - updatedPaths.forEach(async (updatedPath) => { - if (updatedPath.type === "Conveyor") { - // await setEventApi( - // organization, - // updatedPath.modeluuid, - // { type: "Conveyor", points: updatedPath.points, speed: updatedPath.speed } - // ); - - const data = { - organization: organization, - modeluuid: updatedPath.modeluuid, - eventData: { - type: "Conveyor", - points: updatedPath.points, - speed: updatedPath.speed, - }, - }; - - socket.emit("v2:model-asset:updateEventData", data); - } else if (updatedPath.type === "Vehicle") { - // await setEventApi( - // organization, - // updatedPath.modeluuid, - // { type: "Vehicle", points: updatedPath.points } - // ); - - const data = { - organization: organization, - modeluuid: updatedPath.modeluuid, - eventData: { type: "Vehicle", points: updatedPath.points }, - }; - - socket.emit("v2:model-asset:updateEventData", data); - } else if (updatedPath.type === "StaticMachine") { - // await setEventApi( - // organization, - // updatedPath.modeluuid, - // { type: "StaticMachine", points: updatedPath.points } - // ); - - const data = { - organization: organization, - modeluuid: updatedPath.modeluuid, - eventData: { type: "StaticMachine", points: updatedPath.points }, - }; - - socket.emit("v2:model-asset:updateEventData", data); - } else if (updatedPath.type === "ArmBot") { - // await setEventApi( - // organization, - // updatedPath.modeluuid, - // { type: "ArmBot", points: updatedPath.points } - // ); - - const data = { - organization: organization, - modeluuid: updatedPath.modeluuid, - eventData: { type: "ArmBot", points: updatedPath.points }, - }; - - socket.emit("v2:model-asset:updateEventData", data); - } - }); - }; - - const removeConnections = (deletedModelUUIDs: string[]) => { - const updatedStates = simulationStates.map((state) => { - // Handle Conveyor - if (state.type === "Conveyor") { - const updatedConveyor: SimulationTypes.ConveyorEventsSchema = { - ...state, - points: state.points.map((point) => { - return { - ...point, - connections: { - ...point.connections, - targets: point.connections.targets.filter( - (target) => !deletedModelUUIDs.includes(target.modelUUID) - ), - }, - }; - }), - }; - return updatedConveyor; - } - - // Handle Vehicle - else if (state.type === "Vehicle") { - const updatedVehicle: SimulationTypes.VehicleEventsSchema = { - ...state, - points: { - ...state.points, - connections: { - ...state.points.connections, - targets: state.points.connections.targets.filter( - (target) => !deletedModelUUIDs.includes(target.modelUUID) - ), - }, - }, - }; - return updatedVehicle; - } - - // Handle StaticMachine - else if (state.type === "StaticMachine") { - const updatedStaticMachine: SimulationTypes.StaticMachineEventsSchema = - { - ...state, - points: { - ...state.points, - connections: { - ...state.points.connections, - targets: state.points.connections.targets.filter( - (target) => !deletedModelUUIDs.includes(target.modelUUID) - ), - }, - }, - }; - return updatedStaticMachine; - } - - // Handle ArmBot - else if (state.type === "ArmBot") { - const updatedArmBot: SimulationTypes.ArmBotEventsSchema = { - ...state, - points: { - ...state.points, - connections: { - ...state.points.connections, - - targets: state.points.connections.targets.filter( - (target: any) => !deletedModelUUIDs.includes(target.modelUUID) - ), - }, - actions: { - ...state.points.actions, - processes: (state.points.actions.processes = - state.points.actions.processes?.filter((process) => { - const matchedStates = simulationStates.filter((s) => - deletedModelUUIDs.includes(s.modeluuid) - ); - - if (matchedStates.length > 0) { - if (matchedStates[0]?.type === "StaticMachine") { - const trigPoints = matchedStates[0]?.points; - - return !( - process.triggerId === trigPoints?.triggers?.uuid - ); - } else if (matchedStates[0]?.type === "Conveyor") { - const trigPoints = matchedStates[0]?.points; - - if (Array.isArray(trigPoints)) { - const nonEmptyTriggers = trigPoints.filter( - (point) => - point && point.triggers && point.triggers.length > 0 - ); - - const allTriggerUUIDs = nonEmptyTriggers - .flatMap((point) => point.triggers) - .map((trigger) => trigger.uuid); - - return !allTriggerUUIDs.includes(process.triggerId); - } - } - } - return true; - })), - }, - }, - }; - return updatedArmBot; - } - - return state; - }); - - const filteredStates = updatedStates.filter( - (state) => !deletedModelUUIDs.includes(state.modeluuid) - ); - - updateBackend(filteredStates); - setSimulationStates(filteredStates); - }; - - const deleteSelection = () => { - if (selectedAssets.length > 0 && duplicatedObjects.length === 0) { - const email = localStorage.getItem("email"); - const organization = email!.split("@")[1].split(".")[0]; - - const storedItems = JSON.parse( - localStorage.getItem("FloorItems") || "[]" - ); - const selectedUUIDs = selectedAssets.map( - (mesh: THREE.Object3D) => mesh.uuid - ); - - const updatedStoredItems = storedItems.filter( - (item: { modeluuid: string }) => !selectedUUIDs.includes(item.modeluuid) - ); - localStorage.setItem("FloorItems", JSON.stringify(updatedStoredItems)); - - selectedAssets.forEach((selectedMesh: THREE.Object3D) => { - //REST - - // const response = await deleteFloorItem(organization, selectedMesh.uuid, selectedMesh.userData.name); - - //SOCKET - - const data = { - organization: organization, - modeluuid: selectedMesh.uuid, - modelname: selectedMesh.userData.name, - socketId: socket.id, - }; - - socket.emit("v2:model-asset:delete", data); - - selectedMesh.traverse((child: THREE.Object3D) => { - if (child instanceof THREE.Mesh) { - if (child.geometry) child.geometry.dispose(); - if (Array.isArray(child.material)) { - child.material.forEach((material) => { - if (material.map) material.map.dispose(); - material.dispose(); - }); - } else if (child.material) { - if (child.material.map) child.material.map.dispose(); - child.material.dispose(); + const onPointerDown = (event: PointerEvent) => { + if (event.button === 2) { + isRightClick = true; + rightClickMoved = false; + } else if (event.button === 0) { + isSelecting = false; + isCtrlSelecting = event.ctrlKey; + if (event.ctrlKey && duplicatedObjects.length === 0) { + if (controls) (controls as any).enabled = false; + selectionBox.startPoint.set(pointer.x, pointer.y, 0); + } + } + }; + + const onPointerMove = (event: PointerEvent) => { + if (isRightClick) { + rightClickMoved = true; + } + isSelecting = true; + if (helper.isDown && event.ctrlKey && duplicatedObjects.length === 0 && isCtrlSelecting) { + selectionBox.endPoint.set(pointer.x, pointer.y, 0); + } + }; + + const onPointerUp = (event: PointerEvent) => { + if (event.button === 2) { + isRightClick = false; + if (!rightClickMoved) { + clearSelection(); + } + return; + } + + if (isSelecting && isCtrlSelecting) { + isCtrlSelecting = false; + isSelecting = false; + if (event.ctrlKey && duplicatedObjects.length === 0) { + selectAssets(); + } + } else if (!isSelecting && selectedAssets.length > 0 && ((pastedObjects.length === 0 && duplicatedObjects.length === 0 && movedObjects.length === 0 && rotatedObjects.length === 0) || event.button !== 0)) { + clearSelection(); + helper.enabled = true; + isCtrlSelecting = false; + } + }; + + const onKeyDown = (event: KeyboardEvent) => { + if (movedObjects.length > 0 || rotatedObjects.length > 0) return; + if (event.key.toLowerCase() === "escape") { + event.preventDefault(); + clearSelection(); + } + if (event.key.toLowerCase() === "delete") { + event.preventDefault(); + deleteSelection(); + } + }; + + const onContextMenu = (event: MouseEvent) => { + event.preventDefault(); + if (!rightClickMoved) { + clearSelection(); + } + }; + + if (!toggleView && activeModule === "builder") { + helper.enabled = true; + if (duplicatedObjects.length === 0 && pastedObjects.length === 0) { + canvasElement.addEventListener("pointerdown", onPointerDown); + canvasElement.addEventListener("pointermove", onPointerMove); + canvasElement.addEventListener("pointerup", onPointerUp); + } else { + helper.enabled = false; + helper.dispose(); + } + canvasElement.addEventListener("contextmenu", onContextMenu); + canvasElement.addEventListener("keydown", onKeyDown); + } else { + helper.enabled = false; + helper.dispose(); + } + + return () => { + canvasElement.removeEventListener("pointerdown", onPointerDown); + canvasElement.removeEventListener("pointermove", onPointerMove); + canvasElement.removeEventListener("contextmenu", onContextMenu); + canvasElement.removeEventListener("pointerup", onPointerUp); + canvasElement.removeEventListener("keydown", onKeyDown); + helper.enabled = false; + helper.dispose(); + }; + }, [camera, controls, scene, toggleView, selectedAssets, copiedObjects, pastedObjects, duplicatedObjects, movedObjects, socket, floorItems, rotatedObjects, activeModule,]); + + useEffect(() => { + if (activeModule !== "builder") { + clearSelection(); + } + }, [activeModule]); + + useFrame(() => { + if (pastedObjects.length === 0 && duplicatedObjects.length === 0 && movedObjects.length === 0 && rotatedObjects.length === 0) { + selectionGroup.current.position.set(0, 0, 0); + } + }); + + const selectAssets = () => { + selectionBox.endPoint.set(pointer.x, pointer.y, 0); + if (controls) (controls as any).enabled = true; + + let selectedObjects = selectionBox.select(); + let Objects = new Set(); + + selectedObjects.map((object) => { + let currentObject: THREE.Object3D | null = object; + while (currentObject) { + if (currentObject.userData.modelId) { + Objects.add(currentObject); + break; + } + currentObject = currentObject.parent || null; } - } }); - setSimulationStates( - ( - prevEvents: ( - | SimulationTypes.ConveyorEventsSchema - | SimulationTypes.VehicleEventsSchema - | SimulationTypes.StaticMachineEventsSchema - | SimulationTypes.ArmBotEventsSchema - )[] - ) => { - const updatedEvents = (prevEvents || []).filter( - (event) => event.modeluuid !== selectedMesh.uuid - ); - return updatedEvents; - } - ); + if (Objects.size === 0) { + clearSelection(); + return; + } - itemsGroupRef.current?.remove(selectedMesh); - }); + const updatedSelections = new Set(selectedAssets); + Objects.forEach((obj) => { updatedSelections.has(obj) ? updatedSelections.delete(obj) : updatedSelections.add(obj); }); - const allUUIDs = selectedAssets.map((val: any) => val.uuid); - removeConnections(allUUIDs); + const selected = Array.from(updatedSelections); - const updatedItems = floorItems.filter( - (item: { modeluuid: string }) => !selectedUUIDs.includes(item.modeluuid) - ); - setFloorItems(updatedItems); - } - toast.success("Selected models removed!"); - clearSelection(); - }; + setSelectedAssets(selected); + }; - return ( - <> - - - - - + const clearSelection = () => { + selectionGroup.current.children = []; + selectionGroup.current.position.set(0, 0, 0); + selectionGroup.current.rotation.set(0, 0, 0); + setpastedObjects([]); + setDuplicatedObjects([]); + setSelectedAssets([]); + }; + const updateBackend = async (updatedPaths: (SimulationTypes.ConveyorEventsSchema | SimulationTypes.VehicleEventsSchema | SimulationTypes.StaticMachineEventsSchema | SimulationTypes.ArmBotEventsSchema)[]) => { + if (updatedPaths.length === 0) return; + const email = localStorage.getItem("email"); + const organization = email ? email.split("@")[1].split(".")[0] : ""; - + updatedPaths.forEach(async (updatedPath) => { + if (updatedPath.type === "Conveyor") { + // await setEventApi( + // organization, + // updatedPath.modeluuid, + // { type: "Conveyor", points: updatedPath.points, speed: updatedPath.speed } + // ); - + const data = { + organization: organization, + modeluuid: updatedPath.modeluuid, + eventData: { + type: "Conveyor", + points: updatedPath.points, + speed: updatedPath.speed, + }, + }; - + socket.emit("v2:model-asset:updateEventData", data); + } else if (updatedPath.type === "Vehicle") { + // await setEventApi( + // organization, + // updatedPath.modeluuid, + // { type: "Vehicle", points: updatedPath.points } + // ); - - - ); + const data = { + organization: organization, + modeluuid: updatedPath.modeluuid, + eventData: { type: "Vehicle", points: updatedPath.points }, + }; + + socket.emit("v2:model-asset:updateEventData", data); + } else if (updatedPath.type === "StaticMachine") { + // await setEventApi( + // organization, + // updatedPath.modeluuid, + // { type: "StaticMachine", points: updatedPath.points } + // ); + + const data = { + organization: organization, + modeluuid: updatedPath.modeluuid, + eventData: { type: "StaticMachine", points: updatedPath.points }, + }; + + socket.emit("v2:model-asset:updateEventData", data); + } else if (updatedPath.type === "ArmBot") { + // await setEventApi( + // organization, + // updatedPath.modeluuid, + // { type: "ArmBot", points: updatedPath.points } + // ); + + const data = { + organization: organization, + modeluuid: updatedPath.modeluuid, + eventData: { type: "ArmBot", points: updatedPath.points }, + }; + + socket.emit("v2:model-asset:updateEventData", data); + } + }); + }; + + const removeConnections = (deletedModelUUIDs: string[]) => { + const updatedStates = simulationStates.map((state) => { + // Handle Conveyor + if (state.type === "Conveyor") { + const updatedConveyor: SimulationTypes.ConveyorEventsSchema = { + ...state, + points: state.points.map((point) => { + return { + ...point, + connections: { + ...point.connections, + targets: point.connections.targets.filter( + (target) => !deletedModelUUIDs.includes(target.modelUUID) + ), + }, + }; + }), + }; + return updatedConveyor; + } + + // Handle Vehicle + else if (state.type === "Vehicle") { + const updatedVehicle: SimulationTypes.VehicleEventsSchema = { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + targets: state.points.connections.targets.filter( + (target) => !deletedModelUUIDs.includes(target.modelUUID) + ), + }, + }, + }; + return updatedVehicle; + } + + // Handle StaticMachine + else if (state.type === "StaticMachine") { + const updatedStaticMachine: SimulationTypes.StaticMachineEventsSchema = + { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + targets: state.points.connections.targets.filter( + (target) => !deletedModelUUIDs.includes(target.modelUUID) + ), + }, + }, + }; + return updatedStaticMachine; + } + + // Handle ArmBot + else if (state.type === "ArmBot") { + const updatedArmBot: SimulationTypes.ArmBotEventsSchema = { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + + targets: state.points.connections.targets.filter( + (target: any) => !deletedModelUUIDs.includes(target.modelUUID) + ), + }, + actions: { + ...state.points.actions, + processes: (state.points.actions.processes = + state.points.actions.processes?.filter((process) => { + const matchedStates = simulationStates.filter((s) => deletedModelUUIDs.includes(s.modeluuid)); + + if (matchedStates.length > 0) { + if (matchedStates[0]?.type === "StaticMachine") { + const trigPoints = matchedStates[0]?.points; + + return !( + process.triggerId === trigPoints?.triggers?.uuid + ); + } else if (matchedStates[0]?.type === "Conveyor") { + const trigPoints = matchedStates[0]?.points; + + if (Array.isArray(trigPoints)) { + const nonEmptyTriggers = trigPoints.filter((point) => point && point.triggers && point.triggers.length > 0); + + const allTriggerUUIDs = nonEmptyTriggers.flatMap((point) => point.triggers).map((trigger) => trigger.uuid); + + return !allTriggerUUIDs.includes(process.triggerId); + } + } + } + return true; + })), + }, + }, + }; + return updatedArmBot; + } + + return state; + }); + + const filteredStates = updatedStates.filter((state) => !deletedModelUUIDs.includes(state.modeluuid)); + + updateBackend(filteredStates); + setSimulationStates(filteredStates); + }; + + const deleteSelection = () => { + if (selectedAssets.length > 0 && duplicatedObjects.length === 0) { + const email = localStorage.getItem("email"); + const organization = email!.split("@")[1].split(".")[0]; + + const storedItems = JSON.parse(localStorage.getItem("FloorItems") || "[]"); + const selectedUUIDs = selectedAssets.map((mesh: THREE.Object3D) => mesh.uuid); + + const updatedStoredItems = storedItems.filter((item: { modeluuid: string }) => !selectedUUIDs.includes(item.modeluuid)); + localStorage.setItem("FloorItems", JSON.stringify(updatedStoredItems)); + + selectedAssets.forEach((selectedMesh: THREE.Object3D) => { + //REST + + // const response = await deleteFloorItem(organization, selectedMesh.uuid, selectedMesh.userData.name); + + //SOCKET + + const data = { + organization: organization, + modeluuid: selectedMesh.uuid, + modelname: selectedMesh.userData.name, + socketId: socket.id, + }; + + socket.emit("v2:model-asset:delete", data); + + selectedMesh.traverse((child: THREE.Object3D) => { + if (child instanceof THREE.Mesh) { + if (child.geometry) child.geometry.dispose(); + if (Array.isArray(child.material)) { + child.material.forEach((material) => { + if (material.map) material.map.dispose(); + material.dispose(); + }); + } else if (child.material) { + if (child.material.map) child.material.map.dispose(); + child.material.dispose(); + } + } + }); + + setSimulationStates((prevEvents: (| SimulationTypes.ConveyorEventsSchema | SimulationTypes.VehicleEventsSchema | SimulationTypes.StaticMachineEventsSchema | SimulationTypes.ArmBotEventsSchema)[]) => { + const updatedEvents = (prevEvents || []).filter((event) => event.modeluuid !== selectedMesh.uuid); + return updatedEvents; + }); + + itemsGroupRef.current?.remove(selectedMesh); + }); + + const allUUIDs = selectedAssets.map((val: any) => val.uuid); + removeConnections(allUUIDs); + + const updatedItems = floorItems.filter((item: { modeluuid: string }) => !selectedUUIDs.includes(item.modeluuid)); + setFloorItems(updatedItems); + } + toast.success("Selected models removed!"); + clearSelection(); + }; + + return ( + <> + + + + + + + + + + + + + + + ); }; export default SelectionControls; diff --git a/app/src/modules/simulation/path/pathConnector.tsx b/app/src/modules/simulation/path/pathConnector.tsx index 9a49f39..4ca12a2 100644 --- a/app/src/modules/simulation/path/pathConnector.tsx +++ b/app/src/modules/simulation/path/pathConnector.tsx @@ -4,1616 +4,1280 @@ import * as THREE from "three"; import * as Types from "../../../types/world/worldTypes"; import * as SimulationTypes from "../../../types/simulationTypes"; import { QuadraticBezierLine } from "@react-three/drei"; -import { - useDeleteTool, - useIsConnecting, - useRenderDistance, - useSimulationStates, - useSocketStore, -} from "../../../store/store"; +import { useDeleteTool, useIsConnecting, useRenderDistance, useSimulationStates, useSocketStore, } from "../../../store/store"; import useModuleStore from "../../../store/useModuleStore"; import { usePlayButtonStore } from "../../../store/usePlayButtonStore"; import { setEventApi } from "../../../services/factoryBuilder/assest/floorAsset/setEventsApt"; -function PathConnector({ - pathsGroupRef, -}: { - pathsGroupRef: React.MutableRefObject; -}) { - const { activeModule } = useModuleStore(); - const { gl, raycaster, scene, pointer, camera } = useThree(); - const { deleteTool } = useDeleteTool(); - const { renderDistance } = useRenderDistance(); - const { setIsConnecting } = useIsConnecting(); - const { simulationStates, setSimulationStates } = useSimulationStates(); - const { isPlaying } = usePlayButtonStore(); - const { socket } = useSocketStore(); - const groupRefs = useRef<{ [key: string]: any }>({}); +function PathConnector({ pathsGroupRef, }: { pathsGroupRef: React.MutableRefObject; }) { + const { activeModule } = useModuleStore(); + const { gl, raycaster, scene, pointer, camera } = useThree(); + const { deleteTool } = useDeleteTool(); + const { renderDistance } = useRenderDistance(); + const { setIsConnecting } = useIsConnecting(); + const { simulationStates, setSimulationStates } = useSimulationStates(); + const { isPlaying } = usePlayButtonStore(); + const { socket } = useSocketStore(); + const groupRefs = useRef<{ [key: string]: any }>({}); - const [firstSelected, setFirstSelected] = useState<{ - modelUUID: string; - sphereUUID: string; - position: THREE.Vector3; - isCorner: boolean; - } | null>(null); - const [currentLine, setCurrentLine] = useState<{ - start: THREE.Vector3; - end: THREE.Vector3; - mid: THREE.Vector3; - } | null>(null); - const [helperlineColor, setHelperLineColor] = useState("red"); - const [hoveredLineKey, setHoveredLineKey] = useState(null); + const [firstSelected, setFirstSelected] = useState<{ modelUUID: string; sphereUUID: string; position: THREE.Vector3; isCorner: boolean; } | null>(null); + const [currentLine, setCurrentLine] = useState<{ start: THREE.Vector3; end: THREE.Vector3; mid: THREE.Vector3; } | null>(null); + const [helperlineColor, setHelperLineColor] = useState("red"); + const [hoveredLineKey, setHoveredLineKey] = useState(null); - const updatePathConnections = ( - fromModelUUID: string, - fromPointUUID: string, - toModelUUID: string, - toPointUUID: string - ) => { - const updatedPaths = simulationStates.map((path) => { - if (path.type === "Conveyor") { - // Handle outgoing connections from Conveyor - if (path.modeluuid === fromModelUUID) { - return { - ...path, - points: path.points.map((point) => { - if (point.uuid === fromPointUUID) { - const newTarget = { - modelUUID: toModelUUID, - pointUUID: toPointUUID, - }; - const existingTargets = point.connections.targets || []; + const updatePathConnections = (fromModelUUID: string, fromPointUUID: string, toModelUUID: string, toPointUUID: string) => { + const updatedPaths = simulationStates.map((path) => { + if (path.type === "Conveyor") { + // Handle outgoing connections from Conveyor + if (path.modeluuid === fromModelUUID) { + return { + ...path, + points: path.points.map((point) => { + if (point.uuid === fromPointUUID) { + const newTarget = { + modelUUID: toModelUUID, + pointUUID: toPointUUID, + }; + const existingTargets = point.connections.targets || []; - if ( - !existingTargets.some( - (target) => - target.modelUUID === newTarget.modelUUID && - target.pointUUID === newTarget.pointUUID - ) - ) { - return { - ...point, - connections: { - ...point.connections, - targets: [...existingTargets, newTarget], - }, - }; + if (!existingTargets.some((target) => target.modelUUID === newTarget.modelUUID && target.pointUUID === newTarget.pointUUID)) { + return { + ...point, + connections: { + ...point.connections, + targets: [...existingTargets, newTarget], + }, + }; + } + } + return point; + }), + }; } - } - return point; - }), - }; - } - // Handle incoming connections to Conveyor - else if (path.modeluuid === toModelUUID) { - return { - ...path, - points: path.points.map((point) => { - if (point.uuid === toPointUUID) { - const reverseTarget = { - modelUUID: fromModelUUID, - pointUUID: fromPointUUID, - }; - const existingTargets = point.connections.targets || []; + // Handle incoming connections to Conveyor + else if (path.modeluuid === toModelUUID) { + return { + ...path, + points: path.points.map((point) => { + if (point.uuid === toPointUUID) { + const reverseTarget = { + modelUUID: fromModelUUID, + pointUUID: fromPointUUID, + }; + const existingTargets = point.connections.targets || []; - if ( - !existingTargets.some( - (target) => - target.modelUUID === reverseTarget.modelUUID && - target.pointUUID === reverseTarget.pointUUID - ) - ) { - return { - ...point, - connections: { - ...point.connections, - targets: [...existingTargets, reverseTarget], - }, - }; + if (!existingTargets.some((target) => target.modelUUID === reverseTarget.modelUUID && target.pointUUID === reverseTarget.pointUUID)) { + return { + ...point, + connections: { + ...point.connections, + targets: [...existingTargets, reverseTarget], + }, + }; + } + } + return point; + }), + }; } - } - return point; - }), - }; - } - } else if (path.type === "Vehicle") { - // Handle outgoing connections from Vehicle - if ( - path.modeluuid === fromModelUUID && - path.points.uuid === fromPointUUID - ) { - const newTarget = { - modelUUID: toModelUUID, - pointUUID: toPointUUID, - }; - const existingTargets = path.points.connections.targets || []; + } else if (path.type === "Vehicle") { + // Handle outgoing connections from Vehicle + if (path.modeluuid === fromModelUUID && path.points.uuid === fromPointUUID) { + const newTarget = { + modelUUID: toModelUUID, + pointUUID: toPointUUID, + }; + const existingTargets = path.points.connections.targets || []; - // Check if target is a Conveyor - const toPath = simulationStates.find( - (p) => p.modeluuid === toModelUUID - ); - if (toPath?.type !== "Conveyor") { - console.log("Vehicle can only connect to Conveyors"); - return path; - } - - // Check if already has a connection - if (existingTargets.length >= 1) { - console.log("Vehicle can have only one connection"); - return path; - } - - if ( - !existingTargets.some( - (target) => - target.modelUUID === newTarget.modelUUID && - target.pointUUID === newTarget.pointUUID - ) - ) { - return { - ...path, - points: { - ...path.points, - connections: { - ...path.points.connections, - targets: [...existingTargets, newTarget], - }, - }, - }; - } - } - // Handle incoming connections to Vehicle - else if ( - path.modeluuid === toModelUUID && - path.points.uuid === toPointUUID - ) { - const reverseTarget = { - modelUUID: fromModelUUID, - pointUUID: fromPointUUID, - }; - const existingTargets = path.points.connections.targets || []; - - // Check if source is a Conveyor - const fromPath = simulationStates.find( - (p) => p.modeluuid === fromModelUUID - ); - if (fromPath?.type !== "Conveyor") { - console.log("Vehicle can only connect to Conveyors"); - return path; - } - - // Check if already has a connection - if (existingTargets.length >= 1) { - console.log("Vehicle can have only one connection"); - return path; - } - - if ( - !existingTargets.some( - (target) => - target.modelUUID === reverseTarget.modelUUID && - target.pointUUID === reverseTarget.pointUUID - ) - ) { - return { - ...path, - points: { - ...path.points, - connections: { - ...path.points.connections, - targets: [...existingTargets, reverseTarget], - }, - }, - }; - } - } - return path; - } else if (path.type === "StaticMachine") { - // Handle outgoing connections from StaticMachine - if ( - path.modeluuid === fromModelUUID && - path.points.uuid === fromPointUUID - ) { - const newTarget = { - modelUUID: toModelUUID, - pointUUID: toPointUUID, - }; - - // Ensure target is an ArmBot - const toPath = simulationStates.find( - (p) => p.modeluuid === toModelUUID - ); - if (toPath?.type !== "ArmBot") { - console.log("StaticMachine can only connect to ArmBot"); - return path; - } - - const existingTargets = path.points.connections.targets || []; - - // Allow only one connection - if (existingTargets.length >= 1) { - console.log("StaticMachine can only have one connection"); - return path; - } - - if ( - !existingTargets.some( - (target) => - target.modelUUID === newTarget.modelUUID && - target.pointUUID === newTarget.pointUUID - ) - ) { - return { - ...path, - points: { - ...path.points, - connections: { - ...path.points.connections, - targets: [...existingTargets, newTarget], - }, - }, - }; - } - } - - // Handle incoming connections to StaticMachine - else if ( - path.modeluuid === toModelUUID && - path.points.uuid === toPointUUID - ) { - const reverseTarget = { - modelUUID: fromModelUUID, - pointUUID: fromPointUUID, - }; - - const fromPath = simulationStates.find( - (p) => p.modeluuid === fromModelUUID - ); - if (fromPath?.type !== "ArmBot") { - console.log("StaticMachine can only be connected from ArmBot"); - return path; - } - - const existingTargets = path.points.connections.targets || []; - - if (existingTargets.length >= 1) { - console.log("StaticMachine can only have one connection"); - return path; - } - - if ( - !existingTargets.some( - (target) => - target.modelUUID === reverseTarget.modelUUID && - target.pointUUID === reverseTarget.pointUUID - ) - ) { - return { - ...path, - points: { - ...path.points, - connections: { - ...path.points.connections, - targets: [...existingTargets, reverseTarget], - }, - }, - }; - } - } - return path; - } else if (path.type === "ArmBot") { - // Handle outgoing connections from ArmBot - if ( - path.modeluuid === fromModelUUID && - path.points.uuid === fromPointUUID - ) { - const newTarget = { - modelUUID: toModelUUID, - pointUUID: toPointUUID, - }; - - const toPath = simulationStates.find( - (p) => p.modeluuid === toModelUUID - ); - if (!toPath) return path; - - const existingTargets = path.points.connections.targets || []; - - // Check if connecting to a StaticMachine and already connected to one - const alreadyConnectedToStatic = existingTargets.some((target) => { - const targetPath = simulationStates.find( - (p) => p.modeluuid === target.modelUUID - ); - return targetPath?.type === "StaticMachine"; - }); - - if (toPath.type === "StaticMachine") { - if (alreadyConnectedToStatic) { - console.log("ArmBot can only connect to one StaticMachine"); - return path; - } - } - - if ( - !existingTargets.some( - (target) => - target.modelUUID === newTarget.modelUUID && - target.pointUUID === newTarget.pointUUID - ) - ) { - return { - ...path, - points: { - ...path.points, - connections: { - ...path.points.connections, - targets: [...existingTargets, newTarget], - }, - }, - }; - } - } - - // Handle incoming connections to ArmBot - else if ( - path.modeluuid === toModelUUID && - path.points.uuid === toPointUUID - ) { - const reverseTarget = { - modelUUID: fromModelUUID, - pointUUID: fromPointUUID, - }; - - const fromPath = simulationStates.find( - (p) => p.modeluuid === fromModelUUID - ); - if (!fromPath) return path; - - const existingTargets = path.points.connections.targets || []; - - const alreadyConnectedFromStatic = existingTargets.some((target) => { - const targetPath = simulationStates.find( - (p) => p.modeluuid === target.modelUUID - ); - return targetPath?.type === "StaticMachine"; - }); - - if (fromPath.type === "StaticMachine") { - if (alreadyConnectedFromStatic) { - console.log( - "ArmBot can only be connected from one StaticMachine" - ); - return path; - } - } - - if ( - !existingTargets.some( - (target) => - target.modelUUID === reverseTarget.modelUUID && - target.pointUUID === reverseTarget.pointUUID - ) - ) { - return { - ...path, - points: { - ...path.points, - connections: { - ...path.points.connections, - targets: [...existingTargets, reverseTarget], - }, - }, - }; - } - } - return path; - } - - return path; - }); - - setSimulationStates(updatedPaths); - - const updatedPathDetails = updatedPaths.filter( - (path) => - path.modeluuid === fromModelUUID || path.modeluuid === toModelUUID - ); - - updateBackend(updatedPathDetails); - }; - - const updateBackend = async ( - updatedPaths: ( - | SimulationTypes.ConveyorEventsSchema - | SimulationTypes.VehicleEventsSchema - | SimulationTypes.StaticMachineEventsSchema - | SimulationTypes.ArmBotEventsSchema - )[] - ) => { - if (updatedPaths.length === 0) return; - const email = localStorage.getItem("email"); - const organization = email ? email.split("@")[1].split(".")[0] : ""; - - updatedPaths.forEach(async (updatedPath) => { - if (updatedPath.type === "Conveyor") { - // await setEventApi( - // organization, - // updatedPath.modeluuid, - // { type: "Conveyor", points: updatedPath.points, speed: updatedPath.speed } - // ); - - const data = { - organization: organization, - modeluuid: updatedPath.modeluuid, - eventData: { - type: "Conveyor", - points: updatedPath.points, - speed: updatedPath.speed, - }, - }; - - socket.emit("v2:model-asset:updateEventData", data); - } else if (updatedPath.type === "Vehicle") { - // await setEventApi( - // organization, - // updatedPath.modeluuid, - // { type: "Vehicle", points: updatedPath.points } - // ); - - const data = { - organization: organization, - modeluuid: updatedPath.modeluuid, - eventData: { type: "Vehicle", points: updatedPath.points }, - }; - - socket.emit("v2:model-asset:updateEventData", data); - } else if (updatedPath.type === "StaticMachine") { - // await setEventApi( - // organization, - // updatedPath.modeluuid, - // { type: "StaticMachine", points: updatedPath.points } - // ); - - const data = { - organization: organization, - modeluuid: updatedPath.modeluuid, - eventData: { type: "StaticMachine", points: updatedPath.points }, - }; - - socket.emit("v2:model-asset:updateEventData", data); - } else if (updatedPath.type === "ArmBot") { - // await setEventApi( - // organization, - // updatedPath.modeluuid, - // { type: "ArmBot", points: updatedPath.points } - // ); - - const data = { - organization: organization, - modeluuid: updatedPath.modeluuid, - eventData: { type: "ArmBot", points: updatedPath.points }, - }; - - socket.emit("v2:model-asset:updateEventData", data); - } - }); - }; - - const handleAddConnection = ( - fromModelUUID: string, - fromUUID: string, - toModelUUID: string, - toUUID: string - ) => { - updatePathConnections(fromModelUUID, fromUUID, toModelUUID, toUUID); - setFirstSelected(null); - setCurrentLine(null); - setIsConnecting(false); - }; - - useEffect(() => { - const canvasElement = gl.domElement; - let drag = false; - let MouseDown = false; - - const onMouseDown = () => { - MouseDown = true; - drag = false; - }; - - const onMouseUp = () => { - MouseDown = false; - }; - - const onMouseMove = () => { - if (MouseDown) { - drag = true; - } - }; - - const onContextMenu = (evt: MouseEvent) => { - evt.preventDefault(); - if (drag || evt.button === 0) return; - - raycaster.setFromCamera(pointer, camera); - const intersects = raycaster.intersectObjects( - pathsGroupRef.current.children, - true - ); - - if (intersects.length > 0) { - const intersected = intersects[0].object; - - if (intersected.name.includes("events-sphere")) { - const modelUUID = intersected.userData.path.modeluuid; - const sphereUUID = intersected.uuid; - const worldPosition = new THREE.Vector3(); - intersected.getWorldPosition(worldPosition); - - let isStartOrEnd = false; - - if ( - intersected.userData.path.points && - intersected.userData.path.points.length > 1 - ) { - isStartOrEnd = - intersected.userData.path.points.length > 0 && - (sphereUUID === intersected.userData.path.points[0].uuid || - sphereUUID === - intersected.userData.path.points[ - intersected.userData.path.points.length - 1 - ].uuid); - } else if (intersected.userData.path.points) { - isStartOrEnd = sphereUUID === intersected.userData.path.points.uuid; - } - - if (modelUUID) { - const firstPath = simulationStates.find( - (p) => p.modeluuid === firstSelected?.modelUUID - ); - const secondPath = simulationStates.find( - (p) => p.modeluuid === modelUUID - ); - - // Prevent vehicle-to-vehicle connections - if ( - firstPath && - secondPath && - firstPath.type === "Vehicle" && - secondPath.type === "Vehicle" - ) { - console.log("Cannot connect two vehicle paths together"); - return; - } - - // Prevent conveyor middle point to conveyor connections - if ( - firstPath && - secondPath && - firstPath.type === "Conveyor" && - secondPath.type === "Conveyor" && - (!firstSelected?.isCorner || !isStartOrEnd) - ) { - console.log( - "Conveyor connections must be between start/end points" - ); - return; - } - - // Check if this specific connection already exists - const isDuplicateConnection = firstSelected - ? simulationStates.some((path) => { - if (path.modeluuid === firstSelected.modelUUID) { - if (path.type === "Conveyor") { - const point = path.points.find( - (p) => p.uuid === firstSelected.sphereUUID - ); - return point?.connections.targets.some( - (t) => - t.modelUUID === modelUUID && - t.pointUUID === sphereUUID - ); - } else if (path.type === "Vehicle") { - return path.points.connections.targets.some( - (t) => - t.modelUUID === modelUUID && - t.pointUUID === sphereUUID - ); + // Check if target is a Conveyor + const toPath = simulationStates.find((p) => p.modeluuid === toModelUUID); + if (toPath?.type !== "Conveyor") { + console.log("Vehicle can only connect to Conveyors"); + return path; } - } - return false; - }) - : false; - if (isDuplicateConnection) { - console.log("These points are already connected. Ignoring."); - return; + // Check if already has a connection + if (existingTargets.length >= 1) { + console.log("Vehicle can have only one connection"); + return path; + } + + if (!existingTargets.some((target) => target.modelUUID === newTarget.modelUUID && target.pointUUID === newTarget.pointUUID)) { + return { + ...path, + points: { + ...path.points, + connections: { + ...path.points.connections, + targets: [...existingTargets, newTarget], + }, + }, + }; + } + } + // Handle incoming connections to Vehicle + else if (path.modeluuid === toModelUUID && path.points.uuid === toPointUUID) { + const reverseTarget = { + modelUUID: fromModelUUID, + pointUUID: fromPointUUID, + }; + const existingTargets = path.points.connections.targets || []; + + // Check if source is a Conveyor + const fromPath = simulationStates.find((p) => p.modeluuid === fromModelUUID); + if (fromPath?.type !== "Conveyor") { + console.log("Vehicle can only connect to Conveyors"); + return path; + } + + // Check if already has a connection + if (existingTargets.length >= 1) { + console.log("Vehicle can have only one connection"); + return path; + } + + if (!existingTargets.some((target) => target.modelUUID === reverseTarget.modelUUID && target.pointUUID === reverseTarget.pointUUID)) { + return { + ...path, + points: { + ...path.points, + connections: { + ...path.points.connections, + targets: [...existingTargets, reverseTarget], + }, + }, + }; + } + } + return path; + } else if (path.type === "StaticMachine") { + // Handle outgoing connections from StaticMachine + if (path.modeluuid === fromModelUUID && path.points.uuid === fromPointUUID) { + const newTarget = { + modelUUID: toModelUUID, + pointUUID: toPointUUID, + }; + + // Ensure target is an ArmBot + const toPath = simulationStates.find((p) => p.modeluuid === toModelUUID); + if (toPath?.type !== "ArmBot") { + console.log("StaticMachine can only connect to ArmBot"); + return path; + } + + const existingTargets = path.points.connections.targets || []; + + // Allow only one connection + if (existingTargets.length >= 1) { + console.log("StaticMachine can only have one connection"); + return path; + } + + if (!existingTargets.some((target) => target.modelUUID === newTarget.modelUUID && target.pointUUID === newTarget.pointUUID)) { + return { + ...path, + points: { + ...path.points, + connections: { + ...path.points.connections, + targets: [...existingTargets, newTarget], + }, + }, + }; + } + } + + // Handle incoming connections to StaticMachine + else if (path.modeluuid === toModelUUID && path.points.uuid === toPointUUID) { + const reverseTarget = { + modelUUID: fromModelUUID, + pointUUID: fromPointUUID, + }; + + const fromPath = simulationStates.find((p) => p.modeluuid === fromModelUUID); + if (fromPath?.type !== "ArmBot") { + console.log("StaticMachine can only be connected from ArmBot"); + return path; + } + + const existingTargets = path.points.connections.targets || []; + + if (existingTargets.length >= 1) { + console.log("StaticMachine can only have one connection"); + return path; + } + + if (!existingTargets.some((target) => target.modelUUID === reverseTarget.modelUUID && target.pointUUID === reverseTarget.pointUUID)) { + return { + ...path, + points: { + ...path.points, + connections: { + ...path.points.connections, + targets: [...existingTargets, reverseTarget], + }, + }, + }; + } + } + return path; + } else if (path.type === "ArmBot") { + // Handle outgoing connections from ArmBot + if (path.modeluuid === fromModelUUID && path.points.uuid === fromPointUUID) { + const newTarget = { + modelUUID: toModelUUID, + pointUUID: toPointUUID, + }; + + const toPath = simulationStates.find((p) => p.modeluuid === toModelUUID); + if (!toPath) return path; + + const existingTargets = path.points.connections.targets || []; + + // Check if connecting to a StaticMachine and already connected to one + const alreadyConnectedToStatic = existingTargets.some((target) => { + const targetPath = simulationStates.find((p) => p.modeluuid === target.modelUUID); + return targetPath?.type === "StaticMachine"; + }); + + if (toPath.type === "StaticMachine") { + if (alreadyConnectedToStatic) { + console.log("ArmBot can only connect to one StaticMachine"); + return path; + } + } + + if (!existingTargets.some((target) => target.modelUUID === newTarget.modelUUID && target.pointUUID === newTarget.pointUUID)) { + return { + ...path, + points: { + ...path.points, + connections: { + ...path.points.connections, + targets: [...existingTargets, newTarget], + }, + }, + }; + } + } + + // Handle incoming connections to ArmBot + else if (path.modeluuid === toModelUUID && path.points.uuid === toPointUUID) { + const reverseTarget = { + modelUUID: fromModelUUID, + pointUUID: fromPointUUID, + }; + + const fromPath = simulationStates.find((p) => p.modeluuid === fromModelUUID); + if (!fromPath) return path; + + const existingTargets = path.points.connections.targets || []; + + const alreadyConnectedFromStatic = existingTargets.some((target) => { + const targetPath = simulationStates.find((p) => p.modeluuid === target.modelUUID); + return targetPath?.type === "StaticMachine"; + }); + + if (fromPath.type === "StaticMachine") { + if (alreadyConnectedFromStatic) { + console.log( + "ArmBot can only be connected from one StaticMachine" + ); + return path; + } + } + + if (!existingTargets.some((target) => target.modelUUID === reverseTarget.modelUUID && target.pointUUID === reverseTarget.pointUUID)) { + return { + ...path, + points: { + ...path.points, + connections: { + ...path.points.connections, + targets: [...existingTargets, reverseTarget], + }, + }, + }; + } + } + return path; } - // For Vehicles, check if they're already connected to anything - if (intersected.userData.path.type === "Vehicle") { - const vehicleConnections = - intersected.userData.path.points.connections.targets.length; - if (vehicleConnections >= 1) { - console.log("Vehicle can only have one connection"); - return; - } + return path; + }); + + setSimulationStates(updatedPaths); + + const updatedPathDetails = updatedPaths.filter((path) => path.modeluuid === fromModelUUID || path.modeluuid === toModelUUID); + + updateBackend(updatedPathDetails); + }; + + const updateBackend = async (updatedPaths: (| SimulationTypes.ConveyorEventsSchema | SimulationTypes.VehicleEventsSchema | SimulationTypes.StaticMachineEventsSchema | SimulationTypes.ArmBotEventsSchema)[]) => { + if (updatedPaths.length === 0) return; + const email = localStorage.getItem("email"); + const organization = email ? email.split("@")[1].split(".")[0] : ""; + + updatedPaths.forEach(async (updatedPath) => { + if (updatedPath.type === "Conveyor") { + // await setEventApi( + // organization, + // updatedPath.modeluuid, + // { type: "Conveyor", points: updatedPath.points, speed: updatedPath.speed } + // ); + + const data = { + organization: organization, + modeluuid: updatedPath.modeluuid, + eventData: { + type: "Conveyor", + points: updatedPath.points, + speed: updatedPath.speed, + }, + }; + + socket.emit("v2:model-asset:updateEventData", data); + } else if (updatedPath.type === "Vehicle") { + // await setEventApi( + // organization, + // updatedPath.modeluuid, + // { type: "Vehicle", points: updatedPath.points } + // ); + + const data = { + organization: organization, + modeluuid: updatedPath.modeluuid, + eventData: { type: "Vehicle", points: updatedPath.points }, + }; + + socket.emit("v2:model-asset:updateEventData", data); + } else if (updatedPath.type === "StaticMachine") { + // await setEventApi( + // organization, + // updatedPath.modeluuid, + // { type: "StaticMachine", points: updatedPath.points } + // ); + + const data = { + organization: organization, + modeluuid: updatedPath.modeluuid, + eventData: { type: "StaticMachine", points: updatedPath.points }, + }; + + socket.emit("v2:model-asset:updateEventData", data); + } else if (updatedPath.type === "ArmBot") { + // await setEventApi( + // organization, + // updatedPath.modeluuid, + // { type: "ArmBot", points: updatedPath.points } + // ); + + const data = { + organization: organization, + modeluuid: updatedPath.modeluuid, + eventData: { type: "ArmBot", points: updatedPath.points }, + }; + + socket.emit("v2:model-asset:updateEventData", data); } + }); + }; - // For non-Vehicle paths, check if already connected - if (intersected.userData.path.type !== "Vehicle") { - const isAlreadyConnected = simulationStates.some((path) => { - if (path.type === "Conveyor") { - return path.points.some( - (point) => - point.uuid === sphereUUID && - point.connections.targets.length > 0 - ); - } - return false; - }); - - if (isAlreadyConnected) { - console.log("Conveyor point is already connected. Ignoring."); - return; - } - } - - if (firstSelected) { - // Check if trying to connect Vehicle to non-Conveyor - if ( - (firstPath?.type === "Vehicle" && - secondPath?.type !== "Conveyor") || - (secondPath?.type === "Vehicle" && - firstPath?.type !== "Conveyor") - ) { - console.log("Vehicle can only connect to Conveyors"); - return; - } - - // Prevent same-path connections - if (firstSelected.modelUUID === modelUUID) { - console.log("Cannot connect spheres on the same path."); - return; - } - - // Check if StaticMachine is involved in the connection - if ( - (firstPath?.type === "StaticMachine" && - secondPath?.type !== "ArmBot") || - (secondPath?.type === "StaticMachine" && - firstPath?.type !== "ArmBot") - ) { - console.log("StaticMachine can only connect to ArmBot"); - return; - } - - // Check if StaticMachine already has a connection - if (firstPath?.type === "StaticMachine") { - const staticConnections = - firstPath.points.connections.targets.length; - if (staticConnections >= 1) { - console.log("StaticMachine can only have one connection"); - return; - } - } - if (secondPath?.type === "StaticMachine") { - const staticConnections = - secondPath.points.connections.targets.length; - if (staticConnections >= 1) { - console.log("StaticMachine can only have one connection"); - return; - } - } - - // Check if ArmBot is involved - if ( - (firstPath?.type === "ArmBot" && - secondPath?.type === "StaticMachine") || - (secondPath?.type === "ArmBot" && - firstPath?.type === "StaticMachine") - ) { - const armBotPath = - firstPath?.type === "ArmBot" ? firstPath : secondPath; - const staticPath = - firstPath?.type === "StaticMachine" ? firstPath : secondPath; - - const armBotConnections = - armBotPath.points.connections.targets || []; - const alreadyConnectedToStatic = armBotConnections.some( - (target) => { - const targetPath = simulationStates.find( - (p) => p.modeluuid === target.modelUUID - ); - return targetPath?.type === "StaticMachine"; - } - ); - - if (alreadyConnectedToStatic) { - console.log("ArmBot can only connect to one StaticMachine"); - return; - } - - const staticConnections = - staticPath.points.connections.targets.length; - if (staticConnections >= 1) { - console.log("StaticMachine can only have one connection"); - return; - } - } - - // Prevent ArmBot ↔ ArmBot - if ( - firstPath?.type === "ArmBot" && - secondPath?.type === "ArmBot" - ) { - console.log("Cannot connect two ArmBots together"); - return; - } - - // If one is ArmBot, ensure the other is StaticMachine or Conveyor - if ( - firstPath?.type === "ArmBot" || - secondPath?.type === "ArmBot" - ) { - const otherType = - firstPath?.type === "ArmBot" - ? secondPath?.type - : firstPath?.type; - if (otherType !== "StaticMachine" && otherType !== "Conveyor") { - console.log( - "ArmBot can only connect to Conveyors or one StaticMachine" - ); - return; - } - } - - // At least one must be start/end point - if (!firstSelected.isCorner && !isStartOrEnd) { - console.log( - "At least one of the selected spheres must be a start or end point." - ); - return; - } - - // All checks passed - make the connection - handleAddConnection( - firstSelected.modelUUID, - firstSelected.sphereUUID, - modelUUID, - sphereUUID - ); - } else { - // First selection - just store it - setFirstSelected({ - modelUUID, - sphereUUID, - position: worldPosition, - isCorner: isStartOrEnd, - }); - setIsConnecting(true); - } - } - } - } else { - // Clicked outside - cancel connection + const handleAddConnection = (fromModelUUID: string, fromUUID: string, toModelUUID: string, toUUID: string) => { + updatePathConnections(fromModelUUID, fromUUID, toModelUUID, toUUID); setFirstSelected(null); setCurrentLine(null); setIsConnecting(false); - } }; - if (activeModule === "simulation" && !deleteTool) { - canvasElement.addEventListener("mousedown", onMouseDown); - canvasElement.addEventListener("mouseup", onMouseUp); - canvasElement.addEventListener("mousemove", onMouseMove); - canvasElement.addEventListener("contextmenu", onContextMenu); - } else { - setFirstSelected(null); - setCurrentLine(null); - setIsConnecting(false); - } + useEffect(() => { + const canvasElement = gl.domElement; + let drag = false; + let MouseDown = false; - return () => { - canvasElement.removeEventListener("mousedown", onMouseDown); - canvasElement.removeEventListener("mouseup", onMouseUp); - canvasElement.removeEventListener("mousemove", onMouseMove); - canvasElement.removeEventListener("contextmenu", onContextMenu); - }; - }, [camera, scene, raycaster, firstSelected, simulationStates, deleteTool]); - - useFrame(() => { - Object.values(groupRefs.current).forEach((group) => { - if (group) { - const distance = new THREE.Vector3( - ...group.position.toArray() - ).distanceTo(camera.position); - group.visible = distance <= renderDistance && !isPlaying; - } - }); - }); - - useFrame(() => { - if (firstSelected) { - raycaster.setFromCamera(pointer, camera); - const intersects = raycaster - .intersectObjects(scene.children, true) - .filter( - (intersect) => - !intersect.object.name.includes("Roof") && - !intersect.object.name.includes("agv-collider") && - !intersect.object.name.includes("MeasurementReference") && - !intersect.object.userData.isPathObject && - !(intersect.object.type === "GridHelper") - ); - - let point: THREE.Vector3 | null = null; - let snappedSphere: { - sphereUUID: string; - position: THREE.Vector3; - modelUUID: string; - isCorner: boolean; - } | null = null; - let isInvalidConnection = false; - - if (intersects.length > 0) { - point = intersects[0].point; - if (point.y < 0.05) { - point = new THREE.Vector3(point.x, 0.05, point.z); - } - } - - const sphereIntersects = raycaster - .intersectObjects(pathsGroupRef.current.children, true) - .filter((obj) => obj.object.name.includes("events-sphere")); - - if (sphereIntersects.length > 0) { - const sphere = sphereIntersects[0].object; - const sphereUUID = sphere.uuid; - const spherePosition = new THREE.Vector3(); - sphere.getWorldPosition(spherePosition); - const pathData = sphere.userData.path; - const modelUUID = pathData.modeluuid; - - const firstPath = simulationStates.find( - (p) => p.modeluuid === firstSelected.modelUUID - ); - const secondPath = simulationStates.find( - (p) => p.modeluuid === modelUUID - ); - const isVehicleToVehicle = - firstPath?.type === "Vehicle" && secondPath?.type === "Vehicle"; - - // Inside the useFrame hook, where we check for snapped spheres: - const isConnectable = - (pathData.type === "Vehicle" || - pathData.type === "ArmBot" || - (pathData.points.length > 0 && - (sphereUUID === pathData.points[0].uuid || - sphereUUID === - pathData.points[pathData.points.length - 1].uuid || - (pathData.type === "Conveyor" && - firstPath?.type === "ArmBot")))) && // Allow ArmBot to connect to middle points - !isVehicleToVehicle && - !( - firstPath?.type === "Conveyor" && - pathData.type === "Conveyor" && - !firstSelected.isCorner - ); - - // Check for duplicate connection (regardless of path type) - const isDuplicateConnection = simulationStates.some((path) => { - if (path.modeluuid === firstSelected.modelUUID) { - if (path.type === "Conveyor") { - const point = path.points.find( - (p) => p.uuid === firstSelected.sphereUUID - ); - return point?.connections.targets.some( - (t) => t.modelUUID === modelUUID && t.pointUUID === sphereUUID - ); - } else if (path.type === "Vehicle") { - return path.points.connections.targets.some( - (t) => t.modelUUID === modelUUID && t.pointUUID === sphereUUID - ); - } - } - return false; - }); - - // For non-Vehicle paths, check if already connected - const isNonVehicleAlreadyConnected = - pathData.type !== "Vehicle" && - simulationStates.some((path) => { - if (path.type === "Conveyor") { - return path.points.some( - (point) => - point.uuid === sphereUUID && - point.connections.targets.length > 0 - ); - } - return false; - }); - - // Check vehicle connection rules - const isVehicleAtMaxConnections = - pathData.type === "Vehicle" && - pathData.points.connections.targets.length >= 1; - const isVehicleConnectingToNonConveyor = - (firstPath?.type === "Vehicle" && secondPath?.type !== "Conveyor") || - (secondPath?.type === "Vehicle" && firstPath?.type !== "Conveyor"); - - // Check if StaticMachine is connecting to non-ArmBot - const isStaticMachineToNonArmBot = - (firstPath?.type === "StaticMachine" && - secondPath?.type !== "ArmBot") || - (secondPath?.type === "StaticMachine" && - firstPath?.type !== "ArmBot"); - - // Check if StaticMachine already has a connection - const isStaticMachineAtMaxConnections = - (firstPath?.type === "StaticMachine" && - firstPath.points.connections.targets.length >= 1) || - (secondPath?.type === "StaticMachine" && - secondPath.points.connections.targets.length >= 1); - - // Check if ArmBot is connecting to StaticMachine - const isArmBotToStaticMachine = - (firstPath?.type === "ArmBot" && - secondPath?.type === "StaticMachine") || - (secondPath?.type === "ArmBot" && - firstPath?.type === "StaticMachine"); - - // Prevent multiple StaticMachine connections to ArmBot - let isArmBotAlreadyConnectedToStatic = false; - if (isArmBotToStaticMachine) { - const armBotPath = - firstPath?.type === "ArmBot" ? firstPath : secondPath; - isArmBotAlreadyConnectedToStatic = - armBotPath.points.connections.targets.some((target) => { - const targetPath = simulationStates.find( - (p) => p.modeluuid === target.modelUUID - ); - return targetPath?.type === "StaticMachine"; - }); - } - - // Prevent ArmBot to ArmBot - const isArmBotToArmBot = - firstPath?.type === "ArmBot" && secondPath?.type === "ArmBot"; - - // If ArmBot is involved, other must be Conveyor or StaticMachine - const isArmBotToInvalidType = - (firstPath?.type === "ArmBot" || secondPath?.type === "ArmBot") && - !( - firstPath?.type === "Conveyor" || - firstPath?.type === "StaticMachine" || - secondPath?.type === "Conveyor" || - secondPath?.type === "StaticMachine" - ); - - if ( - !isDuplicateConnection && - !isVehicleToVehicle && - !isNonVehicleAlreadyConnected && - !isVehicleAtMaxConnections && - !isVehicleConnectingToNonConveyor && - !isStaticMachineToNonArmBot && - !isStaticMachineAtMaxConnections && - !isArmBotToArmBot && - !isArmBotToInvalidType && - !isArmBotAlreadyConnectedToStatic && - firstSelected.sphereUUID !== sphereUUID && - firstSelected.modelUUID !== modelUUID && - (firstSelected.isCorner || isConnectable) && - !( - firstPath?.type === "Conveyor" && - pathData.type === "Conveyor" && - !(firstSelected.isCorner && isConnectable) - ) - ) { - snappedSphere = { - sphereUUID, - position: spherePosition, - modelUUID, - isCorner: isConnectable, - }; - } else { - isInvalidConnection = true; - } - } - - if (snappedSphere) { - point = snappedSphere.position; - } - - if (point) { - const distance = firstSelected.position.distanceTo(point); - const heightFactor = Math.max(0.5, distance * 0.2); - const midPoint = new THREE.Vector3( - (firstSelected.position.x + point.x) / 2, - Math.max(firstSelected.position.y, point.y) + heightFactor, - (firstSelected.position.z + point.z) / 2 - ); - - setCurrentLine({ - start: firstSelected.position, - end: point, - mid: midPoint, - }); - - if (sphereIntersects.length > 0) { - setHelperLineColor(isInvalidConnection ? "red" : "#6cf542"); - } else { - setHelperLineColor("yellow"); - } - } else { - setCurrentLine(null); - setIsConnecting(false); - } - } else { - setCurrentLine(null); - setIsConnecting(false); - } - }); - - const removeConnections = ( - connection1: { model: string; point: string }, - connection2: { model: string; point: string } - ) => { - const updatedStates = simulationStates.map((state) => { - // Handle Conveyor (which has multiple points) - if (state.type === "Conveyor") { - const updatedConveyor: SimulationTypes.ConveyorEventsSchema = { - ...state, - points: state.points.map((point) => { - // Check if this point is either connection1 or connection2 - if ( - (state.modeluuid === connection1.model && - point.uuid === connection1.point) || - (state.modeluuid === connection2.model && - point.uuid === connection2.point) - ) { - return { - ...point, - connections: { - ...point.connections, - targets: point.connections.targets.filter((target) => { - // Remove the target that matches the other connection - return !( - (target.modelUUID === connection1.model && - target.pointUUID === connection1.point) || - (target.modelUUID === connection2.model && - target.pointUUID === connection2.point) - ); - }), - }, - }; - } - return point; - }), + const onMouseDown = () => { + MouseDown = true; + drag = false; }; - return updatedConveyor; - } - // Handle Vehicle - else if (state.type === "Vehicle") { - if ( - (state.modeluuid === connection1.model && - state.points.uuid === connection1.point) || - (state.modeluuid === connection2.model && - state.points.uuid === connection2.point) - ) { - const updatedVehicle: SimulationTypes.VehicleEventsSchema = { - ...state, - points: { - ...state.points, - connections: { - ...state.points.connections, - targets: state.points.connections.targets.filter((target) => { - return !( - (target.modelUUID === connection1.model && - target.pointUUID === connection1.point) || - (target.modelUUID === connection2.model && - target.pointUUID === connection2.point) - ); - }), - }, - // Ensure all required Vehicle point properties are included - speed: state.points.speed, - actions: state.points.actions, - }, - }; - return updatedVehicle; - } - } - // Handle StaticMachine - else if (state.type === "StaticMachine") { - if ( - (state.modeluuid === connection1.model && - state.points.uuid === connection1.point) || - (state.modeluuid === connection2.model && - state.points.uuid === connection2.point) - ) { - const updatedStaticMachine: SimulationTypes.StaticMachineEventsSchema = - { - ...state, - points: { - ...state.points, - connections: { - ...state.points.connections, - targets: state.points.connections.targets.filter((target) => { - return !( - (target.modelUUID === connection1.model && - target.pointUUID === connection1.point) || - (target.modelUUID === connection2.model && - target.pointUUID === connection2.point) - ); - }), - }, - // Ensure all required StaticMachine point properties are included - actions: state.points.actions, - triggers: state.points.triggers, - }, - }; - return updatedStaticMachine; - } - } - // Handle ArmBot - else if (state.type === "ArmBot") { - if ( - (state.modeluuid === connection1.model && - state.points.uuid === connection1.point) || - (state.modeluuid === connection2.model && - state.points.uuid === connection2.point) - ) { - const updatedArmBot: SimulationTypes.ArmBotEventsSchema = { - ...state, - points: { - ...state.points, - connections: { - ...state.points.connections, - targets: state.points.connections.targets.filter((target) => { - return !( - (target.modelUUID === connection1.model && - target.pointUUID === connection1.point) || - (target.modelUUID === connection2.model && - target.pointUUID === connection2.point) - ); - }), - }, - actions: { - ...state.points.actions, - processes: - state.points.actions.processes?.filter((process) => { - return !( - process.startPoint === connection1.point || - process.endPoint === connection1.point || - process.startPoint === connection2.point || - process.endPoint === connection2.point - ); - }) || [], - }, - triggers: state.points.triggers, - }, - }; - return updatedArmBot; - } - } - return state; - }); - const updatedPaths = updatedStates.filter( - (state) => - state.modeluuid === connection1.model || - state.modeluuid === connection2.model - ); - - console.log("updatedPaths: ", updatedPaths); - updateBackend(updatedPaths); - - setSimulationStates(updatedStates); - }; - const removeConnection = (deletedModelUUIDs: string[]) => { - const updatedStates = simulationStates.map((state) => { - // Handle Conveyor - if (state.type === "Conveyor") { - const updatedConveyor: SimulationTypes.ConveyorEventsSchema = { - ...state, - points: state.points.map((point) => { - return { - ...point, - connections: { - ...point.connections, - targets: point.connections.targets.filter( - (target) => !deletedModelUUIDs.includes(target.modelUUID) - ), - }, - }; - }), + const onMouseUp = () => { + MouseDown = false; }; - return updatedConveyor; - } - // Handle Vehicle - else if (state.type === "Vehicle") { - const updatedVehicle: SimulationTypes.VehicleEventsSchema = { - ...state, - points: { - ...state.points, - connections: { - ...state.points.connections, - targets: state.points.connections.targets.filter( - (target) => !deletedModelUUIDs.includes(target.modelUUID) - ), - }, - }, + const onMouseMove = () => { + if (MouseDown) { + drag = true; + } }; - return updatedVehicle; - } - // Handle StaticMachine - else if (state.type === "StaticMachine") { - const updatedStaticMachine: SimulationTypes.StaticMachineEventsSchema = - { - ...state, - points: { - ...state.points, - connections: { - ...state.points.connections, - targets: state.points.connections.targets.filter( - (target) => !deletedModelUUIDs.includes(target.modelUUID) - ), - }, - }, - }; - return updatedStaticMachine; - } + const onContextMenu = (evt: MouseEvent) => { + evt.preventDefault(); + if (drag || evt.button === 0) return; - // Handle ArmBot - else if (state.type === "ArmBot") { - const updatedArmBot: SimulationTypes.ArmBotEventsSchema = { - ...state, - points: { - ...state.points, - connections: { - ...state.points.connections, + raycaster.setFromCamera(pointer, camera); + const intersects = raycaster.intersectObjects( + pathsGroupRef.current.children, + true + ); - targets: state.points.connections.targets.filter( - (target: any) => !deletedModelUUIDs.includes(target.modelUUID) - ), - }, - actions: { - ...state.points.actions, - processes: (state.points.actions.processes = - state.points.actions.processes?.filter((process) => { - const matchedStates = simulationStates.filter((s) => - deletedModelUUIDs.includes(s.modeluuid) - ); + if (intersects.length > 0) { + const intersected = intersects[0].object; - if (matchedStates.length > 0) { - if (matchedStates[0]?.type === "StaticMachine") { - const trigPoints = matchedStates[0]?.points; + if (intersected.name.includes("events-sphere")) { + const modelUUID = intersected.userData.path.modeluuid; + const sphereUUID = intersected.uuid; + const worldPosition = new THREE.Vector3(); + intersected.getWorldPosition(worldPosition); - return !( - process.triggerId === trigPoints?.triggers?.uuid - ); - } else if (matchedStates[0]?.type === "Conveyor") { - const trigPoints = matchedStates[0]?.points; + let isStartOrEnd = false; - if (Array.isArray(trigPoints)) { - const nonEmptyTriggers = trigPoints.filter( - (point) => - point && point.triggers && point.triggers.length > 0 - ); - - const allTriggerUUIDs = nonEmptyTriggers - .flatMap((point) => point.triggers) - .map((trigger) => trigger.uuid); - - return !allTriggerUUIDs.includes(process.triggerId); - } + if (intersected.userData.path.points && intersected.userData.path.points.length > 1) { + isStartOrEnd = intersected.userData.path.points.length > 0 + && (sphereUUID === intersected.userData.path.points[0].uuid || sphereUUID === intersected.userData.path.points[intersected.userData.path.points.length - 1].uuid); + } else if (intersected.userData.path.points) { + isStartOrEnd = sphereUUID === intersected.userData.path.points.uuid; } - } - return true; - })), - }, - }, - }; - return updatedArmBot; - } - return state; + if (modelUUID) { + const firstPath = simulationStates.find((p) => p.modeluuid === firstSelected?.modelUUID); + const secondPath = simulationStates.find((p) => p.modeluuid === modelUUID); + + // Prevent vehicle-to-vehicle connections + if (firstPath && secondPath && firstPath.type === "Vehicle" && secondPath.type === "Vehicle") { + console.log("Cannot connect two vehicle paths together"); + return; + } + + // Prevent conveyor middle point to conveyor connections + if (firstPath && secondPath && firstPath.type === "Conveyor" && secondPath.type === "Conveyor" && (!firstSelected?.isCorner || !isStartOrEnd)) { + console.log("Conveyor connections must be between start/end points"); + return; + } + + // Check if this specific connection already exists + const isDuplicateConnection = firstSelected + ? simulationStates.some((path) => { + if (path.modeluuid === firstSelected.modelUUID) { + if (path.type === "Conveyor") { + const point = path.points.find( + (p) => p.uuid === firstSelected.sphereUUID + ); + return point?.connections.targets.some( + (t) => + t.modelUUID === modelUUID && + t.pointUUID === sphereUUID + ); + } else if (path.type === "Vehicle") { + return path.points.connections.targets.some( + (t) => + t.modelUUID === modelUUID && + t.pointUUID === sphereUUID + ); + } + } + return false; + }) + : false; + + if (isDuplicateConnection) { + console.log("These points are already connected. Ignoring."); + return; + } + + // For Vehicles, check if they're already connected to anything + if (intersected.userData.path.type === "Vehicle") { + const vehicleConnections = + intersected.userData.path.points.connections.targets.length; + if (vehicleConnections >= 1) { + console.log("Vehicle can only have one connection"); + return; + } + } + + // For non-Vehicle paths, check if already connected + if (intersected.userData.path.type !== "Vehicle") { + const isAlreadyConnected = simulationStates.some((path) => { + if (path.type === "Conveyor") { + return path.points.some( + (point) => + point.uuid === sphereUUID && + point.connections.targets.length > 0 + ); + } + return false; + }); + + if (isAlreadyConnected) { + console.log("Conveyor point is already connected. Ignoring."); + return; + } + } + + if (firstSelected) { + // Check if trying to connect Vehicle to non-Conveyor + if ((firstPath?.type === "Vehicle" && secondPath?.type !== "Conveyor") || (secondPath?.type === "Vehicle" && firstPath?.type !== "Conveyor")) { + console.log("Vehicle can only connect to Conveyors"); + return; + } + + // Prevent same-path connections + if (firstSelected.modelUUID === modelUUID) { + console.log("Cannot connect spheres on the same path."); + return; + } + + // Check if StaticMachine is involved in the connection + if ((firstPath?.type === "StaticMachine" && secondPath?.type !== "ArmBot") || (secondPath?.type === "StaticMachine" && firstPath?.type !== "ArmBot")) { + console.log("StaticMachine can only connect to ArmBot"); + return; + } + + // Check if StaticMachine already has a connection + if (firstPath?.type === "StaticMachine") { + const staticConnections = firstPath.points.connections.targets.length; + if (staticConnections >= 1) { + console.log("StaticMachine can only have one connection"); + return; + } + } + if (secondPath?.type === "StaticMachine") { + const staticConnections = secondPath.points.connections.targets.length; + if (staticConnections >= 1) { + console.log("StaticMachine can only have one connection"); + return; + } + } + + // Check if ArmBot is involved + if ((firstPath?.type === "ArmBot" && secondPath?.type === "StaticMachine") || (secondPath?.type === "ArmBot" && firstPath?.type === "StaticMachine")) { + const armBotPath = firstPath?.type === "ArmBot" ? firstPath : secondPath; + const staticPath = firstPath?.type === "StaticMachine" ? firstPath : secondPath; + + const armBotConnections = armBotPath.points.connections.targets || []; + const alreadyConnectedToStatic = armBotConnections.some( + (target) => { + const targetPath = simulationStates.find((p) => p.modeluuid === target.modelUUID); + return targetPath?.type === "StaticMachine"; + } + ); + + if (alreadyConnectedToStatic) { + console.log("ArmBot can only connect to one StaticMachine"); + return; + } + + const staticConnections = staticPath.points.connections.targets.length; + if (staticConnections >= 1) { + console.log("StaticMachine can only have one connection"); + return; + } + } + + // Prevent ArmBot ↔ ArmBot + if (firstPath?.type === "ArmBot" && secondPath?.type === "ArmBot") { + console.log("Cannot connect two ArmBots together"); + return; + } + + // If one is ArmBot, ensure the other is StaticMachine or Conveyor + if (firstPath?.type === "ArmBot" || secondPath?.type === "ArmBot") { + const otherType = firstPath?.type === "ArmBot" ? secondPath?.type : firstPath?.type; + if (otherType !== "StaticMachine" && otherType !== "Conveyor") { + console.log("ArmBot can only connect to Conveyors or one StaticMachine"); + return; + } + } + + // At least one must be start/end point + if (!firstSelected.isCorner && !isStartOrEnd) { + console.log("At least one of the selected spheres must be a start or end point."); + return; + } + + // All checks passed - make the connection + handleAddConnection(firstSelected.modelUUID, firstSelected.sphereUUID, modelUUID, sphereUUID); + } else { + // First selection - just store it + setFirstSelected({ modelUUID, sphereUUID, position: worldPosition, isCorner: isStartOrEnd }); + setIsConnecting(true); + } + } + } + } else { + // Clicked outside - cancel connection + setFirstSelected(null); + setCurrentLine(null); + setIsConnecting(false); + } + }; + + if (activeModule === "simulation" && !deleteTool) { + canvasElement.addEventListener("mousedown", onMouseDown); + canvasElement.addEventListener("mouseup", onMouseUp); + canvasElement.addEventListener("mousemove", onMouseMove); + canvasElement.addEventListener("contextmenu", onContextMenu); + } else { + setFirstSelected(null); + setCurrentLine(null); + setIsConnecting(false); + } + + return () => { + canvasElement.removeEventListener("mousedown", onMouseDown); + canvasElement.removeEventListener("mouseup", onMouseUp); + canvasElement.removeEventListener("mousemove", onMouseMove); + canvasElement.removeEventListener("contextmenu", onContextMenu); + }; + }, [camera, scene, raycaster, firstSelected, simulationStates, deleteTool]); + + useFrame(() => { + Object.values(groupRefs.current).forEach((group) => { + if (group) { + const distance = new THREE.Vector3(...group.position.toArray()).distanceTo(camera.position); + group.visible = distance <= renderDistance && !isPlaying; + } + }); }); - const filteredStates = updatedStates.filter( - (state) => !deletedModelUUIDs.includes(state.modeluuid) - ); + useFrame(() => { + if (firstSelected) { + raycaster.setFromCamera(pointer, camera); + const intersects = raycaster.intersectObjects(scene.children, true).filter( + (intersect) => + !intersect.object.name.includes("Roof") && + !intersect.object.name.includes("agv-collider") && + !intersect.object.name.includes("MeasurementReference") && + !intersect.object.userData.isPathObject && + !(intersect.object.type === "GridHelper") + ); - updateBackend(filteredStates); - setSimulationStates(filteredStates); - }; + let point: THREE.Vector3 | null = null; + let snappedSphere: { sphereUUID: string; position: THREE.Vector3; modelUUID: string; isCorner: boolean; } | null = null; + let isInvalidConnection = false; - return ( - - {simulationStates.flatMap((path) => { - if (path.type === "Conveyor") { - return path.points.flatMap((point) => - point.connections.targets.map((target, index) => { - const targetPath = simulationStates.find( - (p) => p.modeluuid === target.modelUUID - ); - if ( - targetPath?.type !== "Conveyor" && - targetPath?.type !== "ArmBot" - ) - return null; + if (intersects.length > 0) { + point = intersects[0].point; + if (point.y < 0.05) { + point = new THREE.Vector3(point.x, 0.05, point.z); + } + } - const fromSphere = pathsGroupRef.current?.getObjectByProperty( - "uuid", - point.uuid - ); - const toSphere = pathsGroupRef.current?.getObjectByProperty( - "uuid", - target.pointUUID - ); + const sphereIntersects = raycaster.intersectObjects(pathsGroupRef.current.children, true).filter((obj) => obj.object.name.includes("events-sphere")); - if (fromSphere && toSphere) { - const fromWorldPosition = new THREE.Vector3(); - const toWorldPosition = new THREE.Vector3(); - fromSphere.getWorldPosition(fromWorldPosition); - toSphere.getWorldPosition(toWorldPosition); + if (sphereIntersects.length > 0) { + const sphere = sphereIntersects[0].object; + const sphereUUID = sphere.uuid; + const spherePosition = new THREE.Vector3(); + sphere.getWorldPosition(spherePosition); + const pathData = sphere.userData.path; + const modelUUID = pathData.modeluuid; - const distance = fromWorldPosition.distanceTo(toWorldPosition); + const firstPath = simulationStates.find((p) => p.modeluuid === firstSelected.modelUUID); + const secondPath = simulationStates.find((p) => p.modeluuid === modelUUID); + const isVehicleToVehicle = firstPath?.type === "Vehicle" && secondPath?.type === "Vehicle"; + + // Inside the useFrame hook, where we check for snapped spheres: + const isConnectable = ( + pathData.type === 'Vehicle' || + pathData.type === 'ArmBot' || + (pathData.points.length > 0 && ( + sphereUUID === pathData.points[0].uuid || + sphereUUID === pathData.points[pathData.points.length - 1].uuid || + (pathData.type === 'Conveyor' && firstPath?.type === 'ArmBot') // Allow ArmBot to connect to middle points + )) + ) && + !isVehicleToVehicle && + !( + firstPath?.type === 'Conveyor' && + pathData.type === 'Conveyor' && + !firstSelected.isCorner + ); + + // Check for duplicate connection (regardless of path type) + const isDuplicateConnection = simulationStates.some(path => { + if (path.modeluuid === firstSelected.modelUUID) { + if (path.type === 'Conveyor') { + const point = path.points.find(p => p.uuid === firstSelected.sphereUUID); + return point?.connections.targets.some(t => + t.modelUUID === modelUUID && t.pointUUID === sphereUUID + ); + } else if (path.type === 'Vehicle') { + return path.points.connections.targets.some(t => + t.modelUUID === modelUUID && t.pointUUID === sphereUUID + ); + } + } + return false; + }); + + // For non-Vehicle paths, check if already connected + const isNonVehicleAlreadyConnected = pathData.type !== 'Vehicle' && + simulationStates.some(path => { + if (path.type === 'Conveyor') { + return path.points.some(point => + point.uuid === sphereUUID && + point.connections.targets.length > 0 + ); + } + return false; + }); + + // Check vehicle connection rules + const isVehicleAtMaxConnections = pathData.type === 'Vehicle' && + pathData.points.connections.targets.length >= 1; + const isVehicleConnectingToNonConveyor = + (firstPath?.type === 'Vehicle' && secondPath?.type !== 'Conveyor') || + (secondPath?.type === 'Vehicle' && firstPath?.type !== 'Conveyor'); + + // Check if StaticMachine is connecting to non-ArmBot + const isStaticMachineToNonArmBot = + (firstPath?.type === 'StaticMachine' && secondPath?.type !== 'ArmBot') || + (secondPath?.type === 'StaticMachine' && firstPath?.type !== 'ArmBot'); + + // Check if StaticMachine already has a connection + const isStaticMachineAtMaxConnections = + (firstPath?.type === 'StaticMachine' && firstPath.points.connections.targets.length >= 1) || + (secondPath?.type === 'StaticMachine' && secondPath.points.connections.targets.length >= 1); + + // Check if ArmBot is connecting to StaticMachine + const isArmBotToStaticMachine = + (firstPath?.type === 'ArmBot' && secondPath?.type === 'StaticMachine') || + (secondPath?.type === 'ArmBot' && firstPath?.type === 'StaticMachine'); + + // Prevent multiple StaticMachine connections to ArmBot + let isArmBotAlreadyConnectedToStatic = false; + if (isArmBotToStaticMachine) { + const armBotPath = firstPath?.type === 'ArmBot' ? firstPath : secondPath; + isArmBotAlreadyConnectedToStatic = armBotPath.points.connections.targets.some(target => { + const targetPath = simulationStates.find(p => p.modeluuid === target.modelUUID); + return targetPath?.type === 'StaticMachine'; + }); + } + + // Prevent ArmBot to ArmBot + const isArmBotToArmBot = firstPath?.type === 'ArmBot' && secondPath?.type === 'ArmBot'; + + // If ArmBot is involved, other must be Conveyor or StaticMachine + const isArmBotToInvalidType = (firstPath?.type === 'ArmBot' || secondPath?.type === 'ArmBot') && + !(firstPath?.type === 'Conveyor' || firstPath?.type === 'StaticMachine' || + secondPath?.type === 'Conveyor' || secondPath?.type === 'StaticMachine'); + + if ( + !isDuplicateConnection && + !isVehicleToVehicle && + !isNonVehicleAlreadyConnected && + !isVehicleAtMaxConnections && + !isVehicleConnectingToNonConveyor && + !isStaticMachineToNonArmBot && + !isStaticMachineAtMaxConnections && + !isArmBotToArmBot && + !isArmBotToInvalidType && + !isArmBotAlreadyConnectedToStatic && + firstSelected.sphereUUID !== sphereUUID && + firstSelected.modelUUID !== modelUUID && + (firstSelected.isCorner || isConnectable) && + !(firstPath?.type === 'Conveyor' && + pathData.type === 'Conveyor' && + !(firstSelected.isCorner && isConnectable)) + ) { + snappedSphere = { + sphereUUID, + position: spherePosition, + modelUUID, + isCorner: isConnectable + }; + } else { + isInvalidConnection = true; + } + } + + if (snappedSphere) { + point = snappedSphere.position; + } + + if (point) { + const distance = firstSelected.position.distanceTo(point); const heightFactor = Math.max(0.5, distance * 0.2); const midPoint = new THREE.Vector3( - (fromWorldPosition.x + toWorldPosition.x) / 2, - Math.max(fromWorldPosition.y, toWorldPosition.y) + - heightFactor, - (fromWorldPosition.z + toWorldPosition.z) / 2 + (firstSelected.position.x + point.x) / 2, + Math.max(firstSelected.position.y, point.y) + heightFactor, + (firstSelected.position.z + point.z) / 2 ); - return ( - - (groupRefs.current[ - `${point.uuid}-${target.pointUUID}-${index}` - ] = el!) - } - start={fromWorldPosition.toArray()} - end={toWorldPosition.toArray()} - mid={midPoint.toArray()} - color={ - deleteTool && - hoveredLineKey === - `${point.uuid}-${target.pointUUID}-${index}` - ? "red" - : targetPath?.type === "ArmBot" - ? "#42a5f5" - : "white" - } + setCurrentLine({ + start: firstSelected.position, + end: point, + mid: midPoint, + }); + + if (sphereIntersects.length > 0) { + setHelperLineColor(isInvalidConnection ? "red" : "#6cf542"); + } else { + setHelperLineColor("yellow"); + } + } else { + setCurrentLine(null); + setIsConnecting(false); + } + } else { + setCurrentLine(null); + setIsConnecting(false); + } + }); + + const removeConnection = (connection1: { model: string; point: string }, connection2: { model: string; point: string }) => { + const updatedStates = simulationStates.map((state) => { + + // Handle Conveyor (which has multiple points) + if (state.type === "Conveyor") { + const updatedConveyor: SimulationTypes.ConveyorEventsSchema = { + ...state, + points: state.points.map((point) => { + // Check if this point is either connection1 or connection2 + if ((state.modeluuid === connection1.model && point.uuid === connection1.point) || (state.modeluuid === connection2.model && point.uuid === connection2.point)) { + return { + ...point, + connections: { + ...point.connections, + targets: point.connections.targets.filter((target) => { + // Remove the target that matches the other connection + return !( + (target.modelUUID === connection1.model && + target.pointUUID === connection1.point) || + (target.modelUUID === connection2.model && + target.pointUUID === connection2.point) + ); + }), + }, + }; + } + return point; + }), + }; + return updatedConveyor; + } + + // Handle Vehicle + else if (state.type === "Vehicle") { + if ((state.modeluuid === connection1.model && state.points.uuid === connection1.point) || (state.modeluuid === connection2.model && state.points.uuid === connection2.point)) { + const updatedVehicle: SimulationTypes.VehicleEventsSchema = { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + targets: state.points.connections.targets.filter((target) => { + return !( + (target.modelUUID === connection1.model && + target.pointUUID === connection1.point) || + (target.modelUUID === connection2.model && + target.pointUUID === connection2.point) + ); + }), + }, + // Ensure all required Vehicle point properties are included + speed: state.points.speed, + actions: state.points.actions, + }, + }; + return updatedVehicle; + } + } + + // Handle StaticMachine + else if (state.type === "StaticMachine") { + if ((state.modeluuid === connection1.model && state.points.uuid === connection1.point) || (state.modeluuid === connection2.model && state.points.uuid === connection2.point)) { + const updatedStaticMachine: SimulationTypes.StaticMachineEventsSchema = + { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + targets: state.points.connections.targets.filter((target) => { + return !( + (target.modelUUID === connection1.model && + target.pointUUID === connection1.point) || + (target.modelUUID === connection2.model && + target.pointUUID === connection2.point) + ); + }), + }, + // Ensure all required StaticMachine point properties are included + actions: state.points.actions, + triggers: state.points.triggers, + }, + }; + return updatedStaticMachine; + } + } + + // Handle ArmBot + else if (state.type === "ArmBot") { + if ((state.modeluuid === connection1.model && state.points.uuid === connection1.point) || (state.modeluuid === connection2.model && state.points.uuid === connection2.point)) { + const updatedArmBot: SimulationTypes.ArmBotEventsSchema = { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + targets: state.points.connections.targets.filter((target) => { + return !( + (target.modelUUID === connection1.model && + target.pointUUID === connection1.point) || + (target.modelUUID === connection2.model && + target.pointUUID === connection2.point) + ); + }), + }, + actions: { + ...state.points.actions, + processes: + state.points.actions.processes?.filter((process) => { + return !( + process.startPoint === connection1.point || + process.endPoint === connection1.point || + process.startPoint === connection2.point || + process.endPoint === connection2.point + ); + }) || [], + }, + triggers: state.points.triggers, + }, + }; + return updatedArmBot; + } + } + return state; + }); + + const updatedPaths = updatedStates.filter( + (state) => + state.modeluuid === connection1.model || + state.modeluuid === connection2.model + ); + + console.log("updatedPaths: ", updatedPaths); + updateBackend(updatedPaths); + + setSimulationStates(updatedStates); + }; + + const removeConnections = (deletedModelUUIDs: string[]) => { + const updatedStates = simulationStates.map((state) => { + + // Handle Conveyor + if (state.type === "Conveyor") { + const updatedConveyor: SimulationTypes.ConveyorEventsSchema = { + ...state, + points: state.points.map((point) => { + return { + ...point, + connections: { + ...point.connections, + targets: point.connections.targets.filter( + (target) => !deletedModelUUIDs.includes(target.modelUUID) + ), + }, + }; + }), + }; + return updatedConveyor; + } + + // Handle Vehicle + else if (state.type === "Vehicle") { + const updatedVehicle: SimulationTypes.VehicleEventsSchema = { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + targets: state.points.connections.targets.filter( + (target) => !deletedModelUUIDs.includes(target.modelUUID) + ), + }, + }, + }; + return updatedVehicle; + } + + // Handle StaticMachine + else if (state.type === "StaticMachine") { + const updatedStaticMachine: SimulationTypes.StaticMachineEventsSchema = + { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + targets: state.points.connections.targets.filter( + (target) => !deletedModelUUIDs.includes(target.modelUUID) + ), + }, + }, + }; + return updatedStaticMachine; + } + + // Handle ArmBot + else if (state.type === "ArmBot") { + const updatedArmBot: SimulationTypes.ArmBotEventsSchema = { + ...state, + points: { + ...state.points, + connections: { + ...state.points.connections, + + targets: state.points.connections.targets.filter( + (target: any) => !deletedModelUUIDs.includes(target.modelUUID) + ), + }, + actions: { + ...state.points.actions, + processes: (state.points.actions.processes = + state.points.actions.processes?.filter((process) => { + const matchedStates = simulationStates.filter((s) => + deletedModelUUIDs.includes(s.modeluuid) + ); + + if (matchedStates.length > 0) { + if (matchedStates[0]?.type === "StaticMachine") { + const trigPoints = matchedStates[0]?.points; + + return !( + process.triggerId === trigPoints?.triggers?.uuid + ); + } else if (matchedStates[0]?.type === "Conveyor") { + const trigPoints = matchedStates[0]?.points; + + if (Array.isArray(trigPoints)) { + const nonEmptyTriggers = trigPoints.filter( + (point) => + point && point.triggers && point.triggers.length > 0 + ); + + const allTriggerUUIDs = nonEmptyTriggers + .flatMap((point) => point.triggers) + .map((trigger) => trigger.uuid); + + return !allTriggerUUIDs.includes(process.triggerId); + } + } + } + return true; + })), + }, + }, + }; + return updatedArmBot; + } + + return state; + }); + + const filteredStates = updatedStates.filter( + (state) => !deletedModelUUIDs.includes(state.modeluuid) + ); + + updateBackend(filteredStates); + setSimulationStates(filteredStates); + }; + + return ( + + {simulationStates.flatMap((path) => { + if (path.type === "Conveyor") { + return path.points.flatMap((point) => + point.connections.targets.map((target, index) => { + const targetPath = simulationStates.find((p) => p.modeluuid === target.modelUUID); + if (targetPath?.type !== "Conveyor" && targetPath?.type !== "ArmBot") return null; + + const fromSphere = pathsGroupRef.current?.getObjectByProperty("uuid", point.uuid); + const toSphere = pathsGroupRef.current?.getObjectByProperty("uuid", target.pointUUID); + + if (fromSphere && toSphere) { + const fromWorldPosition = new THREE.Vector3(); + const toWorldPosition = new THREE.Vector3(); + fromSphere.getWorldPosition(fromWorldPosition); + toSphere.getWorldPosition(toWorldPosition); + + const distance = fromWorldPosition.distanceTo(toWorldPosition); + const heightFactor = Math.max(0.5, distance * 0.2); + const midPoint = new THREE.Vector3( + (fromWorldPosition.x + toWorldPosition.x) / 2, + Math.max(fromWorldPosition.y, toWorldPosition.y) + + heightFactor, + (fromWorldPosition.z + toWorldPosition.z) / 2 + ); + + return ( + (groupRefs.current[`${point.uuid}-${target.pointUUID}-${index}`] = el!)} + start={fromWorldPosition.toArray()} + end={toWorldPosition.toArray()} + mid={midPoint.toArray()} + color={deleteTool && hoveredLineKey === `${point.uuid}-${target.pointUUID}-${index}` ? "red" : targetPath?.type === "ArmBot" ? "#42a5f5" : "white"} + lineWidth={4} + dashed={deleteTool && hoveredLineKey === `${point.uuid}-${target.pointUUID}-${index}` ? false : true} + dashSize={0.75} + dashScale={20} + onPointerOver={() => setHoveredLineKey(`${point.uuid}-${target.pointUUID}-${index}`)} + onPointerOut={() => setHoveredLineKey(null)} + onClick={() => { + if (deleteTool) { + const connection1 = { + model: path.modeluuid, + point: point.uuid, + }; + const connection2 = { + model: target.modelUUID, + point: target.pointUUID, + }; + + removeConnection(connection1, connection2); + } + }} + userData={target} + /> + ); + } + return null; + }) + ); + } + + if (path.type === "Vehicle") { + return path.points.connections.targets.map((target, index) => { + const fromSphere = pathsGroupRef.current?.getObjectByProperty("uuid", path.points.uuid); + const toSphere = pathsGroupRef.current?.getObjectByProperty("uuid", target.pointUUID); + + if (fromSphere && toSphere) { + const fromWorldPosition = new THREE.Vector3(); + const toWorldPosition = new THREE.Vector3(); + fromSphere.getWorldPosition(fromWorldPosition); + toSphere.getWorldPosition(toWorldPosition); + + const distance = fromWorldPosition.distanceTo(toWorldPosition); + const heightFactor = Math.max(0.5, distance * 0.2); + const midPoint = new THREE.Vector3( + (fromWorldPosition.x + toWorldPosition.x) / 2, + Math.max(fromWorldPosition.y, toWorldPosition.y) + heightFactor, + (fromWorldPosition.z + toWorldPosition.z) / 2 + ); + + return ( + (groupRefs.current[`${path.points.uuid}-${target.pointUUID}-${index}`] = el!)} + start={fromWorldPosition.toArray()} + end={toWorldPosition.toArray()} + mid={midPoint.toArray()} + color={deleteTool && hoveredLineKey === `${path.points.uuid}-${target.pointUUID}-${index}` ? "red" : "orange"} + lineWidth={4} + dashed={deleteTool && hoveredLineKey === `${path.points.uuid}-${target.pointUUID}-${index}` ? false : true} + dashSize={0.75} + dashScale={20} + onPointerOver={() => setHoveredLineKey(`${path.points.uuid}-${target.pointUUID}-${index}`)} + onPointerOut={() => setHoveredLineKey(null)} + onClick={() => { + if (deleteTool) { + const connection1 = { + model: path.modeluuid, + point: path.points.uuid, + }; + const connection2 = { + model: target.modelUUID, + point: target.pointUUID, + }; + + removeConnection(connection1, connection2); + } + }} + userData={target} + /> + ); + } + return null; + }); + } + + if (path.type === "StaticMachine") { + return path.points.connections.targets.map((target, index) => { + const targetPath = simulationStates.find((p) => p.modeluuid === target.modelUUID); + if (targetPath?.type !== "ArmBot") return null; + + const fromSphere = pathsGroupRef.current?.getObjectByProperty("uuid", path.points.uuid); + const toSphere = pathsGroupRef.current?.getObjectByProperty("uuid", target.pointUUID); + + if (fromSphere && toSphere) { + const fromWorldPosition = new THREE.Vector3(); + const toWorldPosition = new THREE.Vector3(); + fromSphere.getWorldPosition(fromWorldPosition); + toSphere.getWorldPosition(toWorldPosition); + + const distance = fromWorldPosition.distanceTo(toWorldPosition); + const heightFactor = Math.max(0.5, distance * 0.2); + const midPoint = new THREE.Vector3( + (fromWorldPosition.x + toWorldPosition.x) / 2, + Math.max(fromWorldPosition.y, toWorldPosition.y) + heightFactor, + (fromWorldPosition.z + toWorldPosition.z) / 2 + ); + + return ( + (groupRefs.current[`${path.points.uuid}-${target.pointUUID}-${index}`] = el!)} + start={fromWorldPosition.toArray()} + end={toWorldPosition.toArray()} + mid={midPoint.toArray()} + color={deleteTool && hoveredLineKey === `${path.points.uuid}-${target.pointUUID}-${index}` ? "red" : "#42a5f5"} + lineWidth={4} + dashed={deleteTool && hoveredLineKey === `${path.points.uuid}-${target.pointUUID}-${index}` ? false : true} + dashSize={0.75} + dashScale={20} + onPointerOver={() => setHoveredLineKey(`${path.points.uuid}-${target.pointUUID}-${index}`)} + onPointerOut={() => setHoveredLineKey(null)} + onClick={() => { + if (deleteTool) { + const connection1 = { + model: path.modeluuid, + point: path.points.uuid, + }; + const connection2 = { + model: target.modelUUID, + point: target.pointUUID, + }; + + removeConnection(connection1, connection2); + } + }} + userData={target} + /> + ); + } + return null; + }); + } + + return []; + })} + + {currentLine && ( + - setHoveredLineKey( - `${point.uuid}-${target.pointUUID}-${index}` - ) - } - onPointerOut={() => setHoveredLineKey(null)} - onClick={() => { - if (deleteTool) { - const connection1 = { - model: path.modeluuid, - point: point.uuid, - }; - const connection2 = { - model: target.modelUUID, - point: target.pointUUID, - }; - - removeConnections(connection1, connection2); - } - }} - userData={target} - /> - ); - } - return null; - }) - ); - } - - if (path.type === "Vehicle") { - return path.points.connections.targets.map((target, index) => { - const fromSphere = pathsGroupRef.current?.getObjectByProperty( - "uuid", - path.points.uuid - ); - const toSphere = pathsGroupRef.current?.getObjectByProperty( - "uuid", - target.pointUUID - ); - - if (fromSphere && toSphere) { - const fromWorldPosition = new THREE.Vector3(); - const toWorldPosition = new THREE.Vector3(); - fromSphere.getWorldPosition(fromWorldPosition); - toSphere.getWorldPosition(toWorldPosition); - - const distance = fromWorldPosition.distanceTo(toWorldPosition); - const heightFactor = Math.max(0.5, distance * 0.2); - const midPoint = new THREE.Vector3( - (fromWorldPosition.x + toWorldPosition.x) / 2, - Math.max(fromWorldPosition.y, toWorldPosition.y) + heightFactor, - (fromWorldPosition.z + toWorldPosition.z) / 2 - ); - - return ( - - (groupRefs.current[ - `${path.points.uuid}-${target.pointUUID}-${index}` - ] = el!) - } - start={fromWorldPosition.toArray()} - end={toWorldPosition.toArray()} - mid={midPoint.toArray()} - color={ - deleteTool && - hoveredLineKey === - `${path.points.uuid}-${target.pointUUID}-${index}` - ? "red" - : "orange" - } - lineWidth={4} - dashed={ - deleteTool && - hoveredLineKey === - `${path.points.uuid}-${target.pointUUID}-${index}` - ? false - : true - } - dashSize={0.75} - dashScale={20} - onPointerOver={() => - setHoveredLineKey( - `${path.points.uuid}-${target.pointUUID}-${index}` - ) - } - onPointerOut={() => setHoveredLineKey(null)} - onClick={() => { - if (deleteTool) { - const connection1 = { - model: path.modeluuid, - point: path.points.uuid, - }; - const connection2 = { - model: target.modelUUID, - point: target.pointUUID, - }; - - removeConnections(connection1, connection2); - } - }} - userData={target} /> - ); - } - return null; - }); - } - - if (path.type === "StaticMachine") { - return path.points.connections.targets.map((target, index) => { - const targetPath = simulationStates.find( - (p) => p.modeluuid === target.modelUUID - ); - if (targetPath?.type !== "ArmBot") return null; - - const fromSphere = pathsGroupRef.current?.getObjectByProperty( - "uuid", - path.points.uuid - ); - const toSphere = pathsGroupRef.current?.getObjectByProperty( - "uuid", - target.pointUUID - ); - - if (fromSphere && toSphere) { - const fromWorldPosition = new THREE.Vector3(); - const toWorldPosition = new THREE.Vector3(); - fromSphere.getWorldPosition(fromWorldPosition); - toSphere.getWorldPosition(toWorldPosition); - - const distance = fromWorldPosition.distanceTo(toWorldPosition); - const heightFactor = Math.max(0.5, distance * 0.2); - const midPoint = new THREE.Vector3( - (fromWorldPosition.x + toWorldPosition.x) / 2, - Math.max(fromWorldPosition.y, toWorldPosition.y) + heightFactor, - (fromWorldPosition.z + toWorldPosition.z) / 2 - ); - - return ( - - (groupRefs.current[ - `${path.points.uuid}-${target.pointUUID}-${index}` - ] = el!) - } - start={fromWorldPosition.toArray()} - end={toWorldPosition.toArray()} - mid={midPoint.toArray()} - color={ - deleteTool && - hoveredLineKey === - `${path.points.uuid}-${target.pointUUID}-${index}` - ? "red" - : "#42a5f5" - } - lineWidth={4} - dashed={ - deleteTool && - hoveredLineKey === - `${path.points.uuid}-${target.pointUUID}-${index}` - ? false - : true - } - dashSize={0.75} - dashScale={20} - onPointerOver={() => - setHoveredLineKey( - `${path.points.uuid}-${target.pointUUID}-${index}` - ) - } - onPointerOut={() => setHoveredLineKey(null)} - onClick={() => { - if (deleteTool) { - const connection1 = { - model: path.modeluuid, - point: path.points.uuid, - }; - const connection2 = { - model: target.modelUUID, - point: target.pointUUID, - }; - - removeConnections(connection1, connection2); - } - }} - userData={target} - /> - ); - } - return null; - }); - } - - return []; - })} - - {currentLine && ( - - )} - - ); + )} + + ); } export default PathConnector; From 83f92d4b015507c7b88d67ee77fb1d29f783b925 Mon Sep 17 00:00:00 2001 From: Jerald-Golden-B Date: Wed, 16 Apr 2025 10:16:54 +0530 Subject: [PATCH 10/12] feat: Enhance connection removal logic to handle deleted models and their points --- .../controls/selection/selectionControls.tsx | 61 ++++++++++------ .../modules/simulation/path/pathConnector.tsx | 73 ++++++++++--------- 2 files changed, 79 insertions(+), 55 deletions(-) diff --git a/app/src/modules/scene/controls/selection/selectionControls.tsx b/app/src/modules/scene/controls/selection/selectionControls.tsx index ece6924..8998bc9 100644 --- a/app/src/modules/scene/controls/selection/selectionControls.tsx +++ b/app/src/modules/scene/controls/selection/selectionControls.tsx @@ -270,6 +270,20 @@ const SelectionControls: React.FC = () => { }; const removeConnections = (deletedModelUUIDs: string[]) => { + + const deletedPointUUIDs = new Set(); + simulationStates.forEach(state => { + if (deletedModelUUIDs.includes(state.modeluuid)) { + if (state.type === "Conveyor" && state.points) { + state.points.forEach(point => { + deletedPointUUIDs.add(point.uuid); + }); + } else if (state.points && 'uuid' in state.points) { + deletedPointUUIDs.add(state.points.uuid); + } + } + }); + const updatedStates = simulationStates.map((state) => { // Handle Conveyor if (state.type === "Conveyor") { @@ -333,38 +347,41 @@ const SelectionControls: React.FC = () => { ...state.points, connections: { ...state.points.connections, - targets: state.points.connections.targets.filter( (target: any) => !deletedModelUUIDs.includes(target.modelUUID) ), }, actions: { ...state.points.actions, - processes: (state.points.actions.processes = - state.points.actions.processes?.filter((process) => { - const matchedStates = simulationStates.filter((s) => deletedModelUUIDs.includes(s.modeluuid)); + processes: state.points.actions.processes?.filter((process) => { + // Check if trigger is from deleted model + const matchedStates = simulationStates.filter((s) => deletedModelUUIDs.includes(s.modeluuid)); - if (matchedStates.length > 0) { - if (matchedStates[0]?.type === "StaticMachine") { - const trigPoints = matchedStates[0]?.points; - - return !( - process.triggerId === trigPoints?.triggers?.uuid - ); - } else if (matchedStates[0]?.type === "Conveyor") { - const trigPoints = matchedStates[0]?.points; - - if (Array.isArray(trigPoints)) { - const nonEmptyTriggers = trigPoints.filter((point) => point && point.triggers && point.triggers.length > 0); - - const allTriggerUUIDs = nonEmptyTriggers.flatMap((point) => point.triggers).map((trigger) => trigger.uuid); - - return !allTriggerUUIDs.includes(process.triggerId); + if (matchedStates.length > 0) { + if (matchedStates[0]?.type === "StaticMachine") { + const trigPoints = matchedStates[0]?.points; + if (process.triggerId === trigPoints?.triggers?.uuid) { + return false; + } + } else if (matchedStates[0]?.type === "Conveyor") { + const trigPoints = matchedStates[0]?.points; + if (Array.isArray(trigPoints)) { + const nonEmptyTriggers = trigPoints.filter((point) => point && point.triggers && point.triggers.length > 0); + const allTriggerUUIDs = nonEmptyTriggers.flatMap((point) => point.triggers).map((trigger) => trigger.uuid); + if (allTriggerUUIDs.includes(process.triggerId)) { + return false; } } } - return true; - })), + } + + // Check if startPoint or endPoint is from deleted model + if (deletedPointUUIDs.has(process.startPoint) || deletedPointUUIDs.has(process.endPoint)) { + return false; + } + + return true; + }), }, }, }; diff --git a/app/src/modules/simulation/path/pathConnector.tsx b/app/src/modules/simulation/path/pathConnector.tsx index 4ca12a2..3e35925 100644 --- a/app/src/modules/simulation/path/pathConnector.tsx +++ b/app/src/modules/simulation/path/pathConnector.tsx @@ -964,8 +964,21 @@ function PathConnector({ pathsGroupRef, }: { pathsGroupRef: React.MutableRefObje }; const removeConnections = (deletedModelUUIDs: string[]) => { - const updatedStates = simulationStates.map((state) => { + const deletedPointUUIDs = new Set(); + simulationStates.forEach(state => { + if (deletedModelUUIDs.includes(state.modeluuid)) { + if (state.type === "Conveyor" && state.points) { + state.points.forEach(point => { + deletedPointUUIDs.add(point.uuid); + }); + } else if (state.points && 'uuid' in state.points) { + deletedPointUUIDs.add(state.points.uuid); + } + } + }); + + const updatedStates = simulationStates.map((state) => { // Handle Conveyor if (state.type === "Conveyor") { const updatedConveyor: SimulationTypes.ConveyorEventsSchema = { @@ -1028,45 +1041,41 @@ function PathConnector({ pathsGroupRef, }: { pathsGroupRef: React.MutableRefObje ...state.points, connections: { ...state.points.connections, - targets: state.points.connections.targets.filter( (target: any) => !deletedModelUUIDs.includes(target.modelUUID) ), }, actions: { ...state.points.actions, - processes: (state.points.actions.processes = - state.points.actions.processes?.filter((process) => { - const matchedStates = simulationStates.filter((s) => - deletedModelUUIDs.includes(s.modeluuid) - ); + processes: state.points.actions.processes?.filter((process) => { + // Check if trigger is from deleted model + const matchedStates = simulationStates.filter((s) => deletedModelUUIDs.includes(s.modeluuid)); - if (matchedStates.length > 0) { - if (matchedStates[0]?.type === "StaticMachine") { - const trigPoints = matchedStates[0]?.points; - - return !( - process.triggerId === trigPoints?.triggers?.uuid - ); - } else if (matchedStates[0]?.type === "Conveyor") { - const trigPoints = matchedStates[0]?.points; - - if (Array.isArray(trigPoints)) { - const nonEmptyTriggers = trigPoints.filter( - (point) => - point && point.triggers && point.triggers.length > 0 - ); - - const allTriggerUUIDs = nonEmptyTriggers - .flatMap((point) => point.triggers) - .map((trigger) => trigger.uuid); - - return !allTriggerUUIDs.includes(process.triggerId); + if (matchedStates.length > 0) { + if (matchedStates[0]?.type === "StaticMachine") { + const trigPoints = matchedStates[0]?.points; + if (process.triggerId === trigPoints?.triggers?.uuid) { + return false; + } + } else if (matchedStates[0]?.type === "Conveyor") { + const trigPoints = matchedStates[0]?.points; + if (Array.isArray(trigPoints)) { + const nonEmptyTriggers = trigPoints.filter((point) => point && point.triggers && point.triggers.length > 0); + const allTriggerUUIDs = nonEmptyTriggers.flatMap((point) => point.triggers).map((trigger) => trigger.uuid); + if (allTriggerUUIDs.includes(process.triggerId)) { + return false; } } } - return true; - })), + } + + // Check if startPoint or endPoint is from deleted model + if (deletedPointUUIDs.has(process.startPoint) || deletedPointUUIDs.has(process.endPoint)) { + return false; + } + + return true; + }), }, }, }; @@ -1076,9 +1085,7 @@ function PathConnector({ pathsGroupRef, }: { pathsGroupRef: React.MutableRefObje return state; }); - const filteredStates = updatedStates.filter( - (state) => !deletedModelUUIDs.includes(state.modeluuid) - ); + const filteredStates = updatedStates.filter((state) => !deletedModelUUIDs.includes(state.modeluuid)); updateBackend(filteredStates); setSimulationStates(filteredStates); From 5c24d7ca71f82d474851c3b89e1c328e19f1f8ea Mon Sep 17 00:00:00 2001 From: Jerald-Golden-B Date: Wed, 16 Apr 2025 10:47:12 +0530 Subject: [PATCH 11/12] feat: Improve trigger processing and static machine status updates in IKAnimationController --- .../armbot/IKAnimationController.tsx | 57 +++++++++---------- 1 file changed, 28 insertions(+), 29 deletions(-) diff --git a/app/src/modules/simulation/armbot/IKAnimationController.tsx b/app/src/modules/simulation/armbot/IKAnimationController.tsx index 1044540..9f19797 100644 --- a/app/src/modules/simulation/armbot/IKAnimationController.tsx +++ b/app/src/modules/simulation/armbot/IKAnimationController.tsx @@ -114,10 +114,38 @@ const IKAnimationController = ({ if (prev.needsInitialMovement !== needsInitialMovement && !needsInitialMovement) { logStatus(`[Arm ${uuid}] Reached rest position, ready for animation`); + } if (prev.selectedTrigger !== selectedTrigger) { logStatus(`[Arm ${uuid}] Processing new trigger: ${selectedTrigger}`); + + + const currentProcess = process.find(p => p.triggerId === prev.selectedTrigger); + if (currentProcess) { + const triggerId = currentProcess.triggerId; + + const endPoint = armBot.actions.processes.find((process) => process.triggerId === triggerId)?.endPoint; + + // Search simulationStates for a StaticMachine that has a point matching this endPointId + const matchedStaticMachine = simulationStates.find( + (state) => + state.type === "StaticMachine" && + state.points?.uuid === endPoint// check for static machine with matching point uuid + ) as any; + + if (matchedStaticMachine) { + setStaticMachines((machines) => { + return machines.map((machine) => { + if (machine.uuid === matchedStaticMachine.modeluuid) { + return { ...machine, status: "running" }; + } else { + return machine; + } + }); + }); + } + } } // Update previous state @@ -249,35 +277,6 @@ const IKAnimationController = ({ } else if (progress >= startToEndRange[0] && progress < startToEndRange[1]) { currentSpeed = speed; currentStatus = "moving"; // Moving between points - if (1 - progress < 0.05) { - // Find the process that matches the current trigger - const currentProcess = process.find(p => p.triggerId === selectedTrigger); - if (currentProcess) { - const triggerId = currentProcess.triggerId; - - const endPoint = armBot.actions.processes.find((process) => process.triggerId === triggerId)?.endPoint; - - // Search simulationStates for a StaticMachine that has a point matching this endPointId - const matchedStaticMachine = simulationStates.find( - (state) => - state.type === "StaticMachine" && - state.points?.uuid === endPoint// check for static machine with matching point uuid - ) as any; - - if (matchedStaticMachine) { - setStaticMachines((machines) => { - return machines.map((machine) => { - if (machine.uuid === matchedStaticMachine.modeluuid) { - return { ...machine, status: "running" }; - } else { - return machine; - } - }); - }); - } - } - - } } else if (progress >= endToRestRange[0] && progress < 1) { currentSpeed = restSpeed; currentStatus = "moving"; // Returning to rest From e0082cb55a4ea64a7562f97ee16c10f763776445 Mon Sep 17 00:00:00 2001 From: Jerald-Golden-B Date: Wed, 16 Apr 2025 11:39:03 +0530 Subject: [PATCH 12/12] feat: Enhance ArmBotState with connections and isActive properties - Updated ArmBotState interface across multiple files to include connections (source and targets) and isActive properties. - Implemented logic in ProcessAnimator to check if processes are connected to active ArmBots, preventing future spawns if connected. - Adjusted animation state handling to account for active ArmBots, stopping animations and resetting states as necessary. - Refactored related functions for better clarity and maintainability. --- app/src/modules/simulation/armbot/ArmBot.tsx | 8 +- .../simulation/armbot/ArmBotInstances.tsx | 15 +- .../armbot/IKAnimationController.tsx | 79 +- .../modules/simulation/armbot/IkInstances.tsx | 17 +- .../simulation/process/processAnimator.tsx | 84 +- .../simulation/process/processContainer.tsx | 5 + .../process/useProcessAnimations.tsx | 1174 +++++++++-------- app/src/modules/simulation/simulation.tsx | 5 + .../staticMachine/staticMachine.tsx | 6 +- 9 files changed, 755 insertions(+), 638 deletions(-) diff --git a/app/src/modules/simulation/armbot/ArmBot.tsx b/app/src/modules/simulation/armbot/ArmBot.tsx index a6d8d23..1c7bb83 100644 --- a/app/src/modules/simulation/armbot/ArmBot.tsx +++ b/app/src/modules/simulation/armbot/ArmBot.tsx @@ -12,7 +12,12 @@ interface ArmBotState { status: string; material: string; triggerId: string; + connections: { + source: { modelUUID: string; pointUUID: string }; + targets: { modelUUID: string; pointUUID: string }[]; + }; actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; + isActive?: boolean; } interface StaticMachineState { @@ -45,7 +50,8 @@ const ArmBot = ({ armBots, setArmBots, setStaticMachines }: ArmBotProps) => { status: "idle", material: "default", triggerId: '', - actions: bot.points.actions + actions: bot.points.actions, + connections: bot.points.connections })); setArmBots(initialStates); }, [simulationStates]); diff --git a/app/src/modules/simulation/armbot/ArmBotInstances.tsx b/app/src/modules/simulation/armbot/ArmBotInstances.tsx index 10a49f6..8d20a87 100644 --- a/app/src/modules/simulation/armbot/ArmBotInstances.tsx +++ b/app/src/modules/simulation/armbot/ArmBotInstances.tsx @@ -18,16 +18,12 @@ interface ArmBotState { status: string; material: string; triggerId: string; - actions: { - uuid: string; - name: string; - speed: number; - processes: { - triggerId: string; - startPoint: string; - endPoint: string; - }[]; + connections: { + source: { modelUUID: string; pointUUID: string }; + targets: { modelUUID: string; pointUUID: string }[]; }; + actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; + isActive?: boolean; } interface StaticMachineState { @@ -87,6 +83,7 @@ export const ArmbotInstances: React.FC = ({ index, armBot, rotation={armBot.rotation} processes={processes} armBot={armBot} + setArmBots={setArmBots} setStaticMachines={setStaticMachines} updateArmBotStatus={updateArmBotStatus} /> diff --git a/app/src/modules/simulation/armbot/IKAnimationController.tsx b/app/src/modules/simulation/armbot/IKAnimationController.tsx index 9f19797..d0aaec1 100644 --- a/app/src/modules/simulation/armbot/IKAnimationController.tsx +++ b/app/src/modules/simulation/armbot/IKAnimationController.tsx @@ -20,16 +20,12 @@ interface ArmBotState { status: string; material: string; triggerId: string; - actions: { - uuid: string; - name: string; - speed: number; - processes: { - triggerId: string; - startPoint: string; - endPoint: string; - }[]; + connections: { + source: { modelUUID: string; pointUUID: string }; + targets: { modelUUID: string; pointUUID: string }[]; }; + actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; + isActive?: boolean; } type IKAnimationControllerProps = { @@ -46,6 +42,7 @@ type IKAnimationControllerProps = { logStatus: (status: string) => void; groupRef: React.RefObject; armBot: ArmBotState; + setArmBots: React.Dispatch>; setStaticMachines: React.Dispatch>; updateArmBotStatus: (status: string) => void; } @@ -59,6 +56,7 @@ const IKAnimationController = ({ logStatus, groupRef, armBot, + setArmBots, setStaticMachines, updateArmBotStatus }: IKAnimationControllerProps) => { @@ -120,30 +118,61 @@ const IKAnimationController = ({ if (prev.selectedTrigger !== selectedTrigger) { logStatus(`[Arm ${uuid}] Processing new trigger: ${selectedTrigger}`); - const currentProcess = process.find(p => p.triggerId === prev.selectedTrigger); if (currentProcess) { const triggerId = currentProcess.triggerId; const endPoint = armBot.actions.processes.find((process) => process.triggerId === triggerId)?.endPoint; - // Search simulationStates for a StaticMachine that has a point matching this endPointId - const matchedStaticMachine = simulationStates.find( - (state) => - state.type === "StaticMachine" && - state.points?.uuid === endPoint// check for static machine with matching point uuid - ) as any; + // Search simulationStates for a StaticMachine or Conveyor that has a point matching this endPointId + const matchedMachine = simulationStates.find((state) => { + if (state.type === "Conveyor") { + // For Conveyor, points is an array + return (state).points.some( + (point) => point.uuid === endPoint + ); + } else if (state.type === "StaticMachine") { + // For StaticMachine, points is an object + return state.points.uuid === endPoint; + } + return false; + }); - if (matchedStaticMachine) { - setStaticMachines((machines) => { - return machines.map((machine) => { - if (machine.uuid === matchedStaticMachine.modeluuid) { - return { ...machine, status: "running" }; - } else { - return machine; - } + if (matchedMachine) { + // Log if the end point is a conveyor + if (matchedMachine.type === "Conveyor") { + logStatus(`[Arm ${uuid}] Reached end point which is a conveyor (${matchedMachine.modelName})`); + } else { + logStatus(`[Arm ${uuid}] Reached end point which is a static machine (${matchedMachine.modelName})`); + } + + if (matchedMachine.type === "StaticMachine") { + setStaticMachines((machines) => { + return machines.map((machine) => { + if (machine.uuid === matchedMachine.modeluuid) { + return { ...machine, status: "running" }; + } else { + return machine; + } + }); }); - }); + } + + if (matchedMachine.type === "Conveyor") { + setArmBots((prev) => + prev.map((arm) => { + if (arm.uuid === uuid) { + return { + ...arm, + isActive: false + }; + } + else { + return arm; + } + }) + ); + } } } } diff --git a/app/src/modules/simulation/armbot/IkInstances.tsx b/app/src/modules/simulation/armbot/IkInstances.tsx index 50b8ffb..5a0d23b 100644 --- a/app/src/modules/simulation/armbot/IkInstances.tsx +++ b/app/src/modules/simulation/armbot/IkInstances.tsx @@ -23,16 +23,12 @@ interface ArmBotState { status: string; material: string; triggerId: string; - actions: { - uuid: string; - name: string; - speed: number; - processes: { - triggerId: string; - startPoint: string; - endPoint: string; - }[]; + connections: { + source: { modelUUID: string; pointUUID: string }; + targets: { modelUUID: string; pointUUID: string }[]; }; + actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; + isActive?: boolean; } const IkInstances = ({ @@ -43,6 +39,7 @@ const IkInstances = ({ position, rotation, armBot, + setArmBots, setStaticMachines, updateArmBotStatus }: { @@ -53,6 +50,7 @@ const IkInstances = ({ position: [number, number, number]; rotation: [number, number, number]; armBot: ArmBotState; + setArmBots: React.Dispatch>; setStaticMachines: React.Dispatch>; updateArmBotStatus: (status: string) => void; }) => { @@ -141,6 +139,7 @@ const IkInstances = ({ logStatus={logStatus} groupRef={groupRef} armBot={armBot} + setArmBots={setArmBots} setStaticMachines={setStaticMachines} updateArmBotStatus={updateArmBotStatus} /> diff --git a/app/src/modules/simulation/process/processAnimator.tsx b/app/src/modules/simulation/process/processAnimator.tsx index 460de49..f01e799 100644 --- a/app/src/modules/simulation/process/processAnimator.tsx +++ b/app/src/modules/simulation/process/processAnimator.tsx @@ -1,4 +1,4 @@ -import React, { useRef, useEffect, useMemo } from "react"; +import React, { useRef, useEffect, useMemo, useCallback } from "react"; import { useLoader, useFrame } from "@react-three/fiber"; import { GLTFLoader } from "three-stdlib"; import * as THREE from "three"; @@ -18,9 +18,13 @@ interface ArmBotState { status: string; material: string; triggerId: string; + connections: { + source: { modelUUID: string; pointUUID: string }; + targets: { modelUUID: string; pointUUID: string }[]; + }; actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; + isActive?: boolean; } - interface ProcessContainerProps { processes: ProcessData[]; setProcesses: React.Dispatch>; @@ -103,9 +107,33 @@ const ProcessAnimator: React.FC = ({ // In processAnimator.tsx - only the relevant spawn logic part that needs fixes + + // Add this function to ProcessAnimator component + const isConnectedToActiveArmBot = useCallback( + (processId: any) => { + // Check if any active armbot is connected to this process + return armBots.some((armbot) => { + if (!armbot.isActive) return false; + + // Check if this armbot is connected to the process + return armbot.connections?.targets?.some((connection: any) => { + // Find the process that owns this modelUUID + const connectedProcess = processes.find((p) => + p.paths?.some((path) => path.modeluuid === connection.modelUUID) + ); + return connectedProcess?.id === processId; + }); + }); + }, + [armBots, processes] + ); + + // In processAnimator.tsx - only the relevant spawn logic part that needs fixes + useFrame(() => { // Spawn logic frame - const currentTime = clockRef.current.getElapsedTime() - elapsedBeforePauseRef.current; + const currentTime = + clockRef.current.getElapsedTime() - elapsedBeforePauseRef.current; setAnimationStates((prev) => { const newStates = { ...prev }; @@ -119,6 +147,14 @@ const ProcessAnimator: React.FC = ({ return; } + if (isConnectedToActiveArmBot(process.id)) { + newStates[process.id] = { + ...processState, + nextSpawnTime: Infinity, // Prevent future spawns + }; + return; + } + const spawnPoint = findSpawnPoint(process); if (!spawnPoint || !spawnPoint.actions) return; @@ -133,7 +169,10 @@ const ProcessAnimator: React.FC = ({ : parseFloat(spawnAction.spawnInterval as string) || 0; // Check if this is a zero interval spawn and we already spawned an object - if (spawnInterval === 0 && processState.hasSpawnedZeroIntervalObject === true) { + if ( + spawnInterval === 0 && + processState.hasSpawnedZeroIntervalObject === true + ) { return; // Don't spawn more objects for zero interval } @@ -183,6 +222,29 @@ const ProcessAnimator: React.FC = ({ const processState = newStates[process.id]; if (!processState) return; + if (isConnectedToActiveArmBot(process.id)) { + newStates[process.id] = { + ...processState, + spawnedObjects: Object.entries(processState.spawnedObjects).reduce( + (acc, [id, obj]) => ({ + ...acc, + [id]: { + ...obj, + state: { + ...obj.state, + isAnimating: false, // Stop animation + isDelaying: false, // Clear delays + delayComplete: false, // Reset delays + progress: 0, // Reset progress + }, + }, + }), + {} + ), + }; + return; + } + if (processState.isProcessDelaying) { const effectiveDelayTime = processState.processDelayDuration / speedRef.current; @@ -338,10 +400,13 @@ const ProcessAnimator: React.FC = ({ if (isLastPoint) { const isAgvPicking = agvRef.current.some( - (agv: any) => agv.processId === process.id && agv.status === "picking" + (agv: any) => + agv.processId === process.id && agv.status === "picking" ); - const shouldHide = !currentPointData?.actions || !hasNonInheritActions(currentPointData.actions); + const shouldHide = + !currentPointData?.actions || + !hasNonInheritActions(currentPointData.actions); if (shouldHide) { if (isAgvPicking) { @@ -372,7 +437,8 @@ const ProcessAnimator: React.FC = ({ if (tempStackedObjectsRef.current[objectId]) { const isAgvPicking = agvRef.current.some( - (agv: any) => agv.processId === process.id && agv.status === "picking" + (agv: any) => + agv.processId === process.id && agv.status === "picking" ); if (isAgvPicking) { @@ -391,7 +457,8 @@ const ProcessAnimator: React.FC = ({ if (!isLastPoint) { const nextPoint = path[nextPointIdx]; - const distance = path[stateRef.currentIndex].distanceTo(nextPoint); + const distance = + path[stateRef.currentIndex].distanceTo(nextPoint); const effectiveSpeed = stateRef.speed * speedRef.current; const movement = effectiveSpeed * delta; @@ -442,7 +509,6 @@ const ProcessAnimator: React.FC = ({ return newStates; }); }); - if (!processedProcesses || processedProcesses.length === 0) { return null; } diff --git a/app/src/modules/simulation/process/processContainer.tsx b/app/src/modules/simulation/process/processContainer.tsx index 4cc7edf..0bcdb13 100644 --- a/app/src/modules/simulation/process/processContainer.tsx +++ b/app/src/modules/simulation/process/processContainer.tsx @@ -9,7 +9,12 @@ interface ArmBotState { status: string; material: string; triggerId: string; + connections: { + source: { modelUUID: string; pointUUID: string }; + targets: { modelUUID: string; pointUUID: string }[]; + }; actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; + isActive?: boolean; } interface ProcessContainerProps { diff --git a/app/src/modules/simulation/process/useProcessAnimations.tsx b/app/src/modules/simulation/process/useProcessAnimations.tsx index 8c0f20d..5fc96dc 100644 --- a/app/src/modules/simulation/process/useProcessAnimations.tsx +++ b/app/src/modules/simulation/process/useProcessAnimations.tsx @@ -1,645 +1,651 @@ import { useCallback, useEffect, useRef, useState } from "react"; import * as THREE from "three"; import { - ProcessData, - ProcessAnimationState, - SpawnedObject, - AnimationState, - ProcessPoint, - PointAction, - Trigger, + ProcessData, + ProcessAnimationState, + SpawnedObject, + AnimationState, + ProcessPoint, + PointAction, + Trigger, } from "./types"; import { - useAnimationPlaySpeed, - usePauseButtonStore, - usePlayButtonStore, - useResetButtonStore, + useAnimationPlaySpeed, + usePauseButtonStore, + usePlayButtonStore, + useResetButtonStore, } from "../../../store/usePlayButtonStore"; import { usePlayAgv } from "../../../store/store"; // Enhanced ProcessAnimationState with trigger tracking interface EnhancedProcessAnimationState extends ProcessAnimationState { - triggerCounts: Record; - triggerLogs: Array<{ - timestamp: number; - pointId: string; - objectId: string; - triggerId: string; - }>; + triggerCounts: Record; + triggerLogs: Array<{ + timestamp: number; + pointId: string; + objectId: string; + triggerId: string; + }>; } interface ProcessContainerProps { - processes: ProcessData[]; - setProcesses: React.Dispatch>; - agvRef: any; + processes: ProcessData[]; + setProcesses: React.Dispatch>; + agvRef: any; } interface PlayAgvState { - playAgv: Record; - setPlayAgv: (data: any) => void; + playAgv: Record; + setPlayAgv: (data: any) => void; } interface ArmBotState { - uuid: string; - position: [number, number, number]; - rotation: [number, number, number]; - status: string; - material: string; - triggerId: string; - actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + status: string; + material: string; + triggerId: string; + connections: { + source: { modelUUID: string; pointUUID: string }; + targets: { modelUUID: string; pointUUID: string }[]; + }; + actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; + isActive?: boolean; } export const useProcessAnimation = ( - processes: ProcessData[], - setProcesses: React.Dispatch>, - agvRef: any, - armBots: ArmBotState[], - setArmBots: React.Dispatch> + processes: ProcessData[], + setProcesses: React.Dispatch>, + agvRef: any, + armBots: ArmBotState[], + setArmBots: React.Dispatch> ) => { - // State and refs initialization - const { isPlaying, setIsPlaying } = usePlayButtonStore(); - const { isPaused, setIsPaused } = usePauseButtonStore(); - const { isReset, setReset } = useResetButtonStore(); - const debugRef = useRef(false); - const clockRef = useRef(new THREE.Clock()); - const pauseTimeRef = useRef(0); - const elapsedBeforePauseRef = useRef(0); - const animationStatesRef = useRef>({}); - const { speed } = useAnimationPlaySpeed(); - const prevIsPlaying = useRef(null); - const [internalResetFlag, setInternalResetFlag] = useState(false); - const [animationStates, setAnimationStates] = useState>({}); - const speedRef = useRef(speed); - const { PlayAgv, setPlayAgv } = usePlayAgv(); + // State and refs initialization + const { isPlaying, setIsPlaying } = usePlayButtonStore(); + const { isPaused, setIsPaused } = usePauseButtonStore(); + const { isReset, setReset } = useResetButtonStore(); + const debugRef = useRef(false); + const clockRef = useRef(new THREE.Clock()); + const pauseTimeRef = useRef(0); + const elapsedBeforePauseRef = useRef(0); + const animationStatesRef = useRef>({}); + const { speed } = useAnimationPlaySpeed(); + const prevIsPlaying = useRef(null); + const [internalResetFlag, setInternalResetFlag] = useState(false); + const [animationStates, setAnimationStates] = useState>({}); + const speedRef = useRef(speed); + const { PlayAgv, setPlayAgv } = usePlayAgv(); - // Effect hooks - useEffect(() => { - speedRef.current = speed; - }, [speed]); + // Effect hooks + useEffect(() => { + speedRef.current = speed; + }, [speed]); - useEffect(() => { - if (prevIsPlaying.current !== null || !isPlaying) { - setAnimationStates({}); - } - prevIsPlaying.current = isPlaying; - }, [isPlaying]); + useEffect(() => { + if (prevIsPlaying.current !== null || !isPlaying) { + setAnimationStates({}); + } + prevIsPlaying.current = isPlaying; + }, [isPlaying]); - useEffect(() => { - animationStatesRef.current = animationStates; - }, [animationStates]); + useEffect(() => { + animationStatesRef.current = animationStates; + }, [animationStates]); - // Reset handler - useEffect(() => { - if (isReset) { - setInternalResetFlag(true); - setIsPlaying(false); - setIsPaused(false); - setAnimationStates({}); - animationStatesRef.current = {}; - clockRef.current = new THREE.Clock(); - elapsedBeforePauseRef.current = 0; - pauseTimeRef.current = 0; - setReset(false); - setTimeout(() => { - setInternalResetFlag(false); - setIsPlaying(true); - }, 0); - } - }, [isReset, setReset, setIsPlaying, setIsPaused]); + // Reset handler + useEffect(() => { + if (isReset) { + setInternalResetFlag(true); + setIsPlaying(false); + setIsPaused(false); + setAnimationStates({}); + animationStatesRef.current = {}; + clockRef.current = new THREE.Clock(); + elapsedBeforePauseRef.current = 0; + pauseTimeRef.current = 0; + setReset(false); + setTimeout(() => { + setInternalResetFlag(false); + setIsPlaying(true); + }, 0); + } + }, [isReset, setReset, setIsPlaying, setIsPaused]); - // Pause handler - useEffect(() => { - if (isPaused) { - pauseTimeRef.current = clockRef.current.getElapsedTime(); - } else if (pauseTimeRef.current > 0) { - const pausedDuration = clockRef.current.getElapsedTime() - pauseTimeRef.current; - elapsedBeforePauseRef.current += pausedDuration; - } - }, [isPaused]); + // Pause handler + useEffect(() => { + if (isPaused) { + pauseTimeRef.current = clockRef.current.getElapsedTime(); + } else if (pauseTimeRef.current > 0) { + const pausedDuration = clockRef.current.getElapsedTime() - pauseTimeRef.current; + elapsedBeforePauseRef.current += pausedDuration; + } + }, [isPaused]); - // Initialize animation states with trigger tracking - useEffect(() => { - if (isPlaying && !internalResetFlag) { - const newStates: Record = {}; + // Initialize animation states with trigger tracking + useEffect(() => { + if (isPlaying && !internalResetFlag) { + const newStates: Record = {}; - processes.forEach((process) => { - const triggerCounts: Record = {}; + processes.forEach((process) => { + const triggerCounts: Record = {}; - // Initialize trigger counts for all On-Hit triggers - process.paths?.forEach((path) => { - path.points?.forEach((point) => { - point.triggers?.forEach((trigger: Trigger) => { - if (trigger.type === "On-Hit" && trigger.isUsed) { - triggerCounts[`${point.uuid}-${trigger.uuid}`] = 0; - } - }); - }); - }); - - newStates[process.id] = { - spawnedObjects: {}, - nextSpawnTime: 0, - objectIdCounter: 0, - isProcessDelaying: false, - processDelayStartTime: 0, - processDelayDuration: 0, - triggerCounts, - triggerLogs: [], - }; + // Initialize trigger counts for all On-Hit triggers + process.paths?.forEach((path) => { + path.points?.forEach((point) => { + point.triggers?.forEach((trigger: Trigger) => { + if (trigger.type === "On-Hit" && trigger.isUsed) { + triggerCounts[`${point.uuid}-${trigger.uuid}`] = 0; + } }); + }); + }); - setAnimationStates(newStates); - animationStatesRef.current = newStates; - clockRef.current.start(); - } - }, [isPlaying, processes, internalResetFlag]); + newStates[process.id] = { + spawnedObjects: {}, + nextSpawnTime: 0, + objectIdCounter: 0, + isProcessDelaying: false, + processDelayStartTime: 0, + processDelayDuration: 0, + triggerCounts, + triggerLogs: [], + }; + }); - useEffect(() => { - if (isPlaying && !internalResetFlag) { - const newStates: Record = {}; + setAnimationStates(newStates); + animationStatesRef.current = newStates; + clockRef.current.start(); + } + }, [isPlaying, processes, internalResetFlag]); - // Initialize AGVs for each process first - processes.forEach((process) => { - // Find all vehicle paths for this process - const vehiclePaths = process.paths?.filter( - (path) => path.type === "Vehicle" - ) || []; + useEffect(() => { + if (isPlaying && !internalResetFlag) { + const newStates: Record = {}; - // Initialize AGVs for each vehicle path - vehiclePaths.forEach((vehiclePath) => { - if (vehiclePath.points?.length > 0) { - const vehiclePoint = vehiclePath.points[0]; - const action = vehiclePoint.actions?.[0]; - const maxHitCount = action?.hitCount; + // Initialize AGVs for each process first + processes.forEach((process) => { + // Find all vehicle paths for this process + const vehiclePaths = process.paths?.filter( + (path) => path.type === "Vehicle" + ) || []; - const vehicleId = vehiclePath.modeluuid; - const processId = process.id; + // Initialize AGVs for each vehicle path + vehiclePaths.forEach((vehiclePath) => { + if (vehiclePath.points?.length > 0) { + const vehiclePoint = vehiclePath.points[0]; + const action = vehiclePoint.actions?.[0]; + const maxHitCount = action?.hitCount; - // Check if this AGV already exists - const existingAgv = agvRef.current.find( - (v: any) => v.vehicleId === vehicleId && v.processId === processId - ); + const vehicleId = vehiclePath.modeluuid; + const processId = process.id; - if (!existingAgv) { - // Initialize the AGV in a stationed state - agvRef.current.push({ - processId, - vehicleId, - maxHitCount: maxHitCount || 0, - isActive: false, - hitCount: 0, - status: 'stationed', - lastUpdated: 0 - }); - } - } - }); + // Check if this AGV already exists + const existingAgv = agvRef.current.find( + (v: any) => v.vehicleId === vehicleId && v.processId === processId + ); - // Then initialize trigger counts as before - const triggerCounts: Record = {}; - process.paths?.forEach((path) => { - path.points?.forEach((point) => { - point.triggers?.forEach((trigger: Trigger) => { - if (trigger.type === "On-Hit" && trigger.isUsed) { - triggerCounts[`${point.uuid}-${trigger.uuid}`] = 0; - } - }); - }); - }); + if (!existingAgv) { + // Initialize the AGV in a stationed state + agvRef.current.push({ + processId, + vehicleId, + maxHitCount: maxHitCount || 0, + isActive: false, + hitCount: 0, + status: 'stationed', + lastUpdated: 0 + }); + } + } + }); - newStates[process.id] = { - spawnedObjects: {}, - nextSpawnTime: 0, - objectIdCounter: 0, - isProcessDelaying: false, - processDelayStartTime: 0, - processDelayDuration: 0, - triggerCounts, - triggerLogs: [], - }; + // Then initialize trigger counts as before + const triggerCounts: Record = {}; + process.paths?.forEach((path) => { + path.points?.forEach((point) => { + point.triggers?.forEach((trigger: Trigger) => { + if (trigger.type === "On-Hit" && trigger.isUsed) { + triggerCounts[`${point.uuid}-${trigger.uuid}`] = 0; + } }); + }); + }); - setAnimationStates(newStates); - animationStatesRef.current = newStates; - clockRef.current.start(); - } - }, [isPlaying, processes, internalResetFlag]); + newStates[process.id] = { + spawnedObjects: {}, + nextSpawnTime: 0, + objectIdCounter: 0, + isProcessDelaying: false, + processDelayStartTime: 0, + processDelayDuration: 0, + triggerCounts, + triggerLogs: [], + }; + }); - // Helper functions - const findSpawnPoint = (process: ProcessData): ProcessPoint | null => { - for (const path of process.paths || []) { - for (const point of path.points || []) { - const spawnAction = point.actions?.find( - (a) => a.isUsed && a.type === "Spawn" - ); - if (spawnAction) { - return point; - } - } - } - return null; - }; + setAnimationStates(newStates); + animationStatesRef.current = newStates; + clockRef.current.start(); + } + }, [isPlaying, processes, internalResetFlag]); - const findAnimationPathPoint = ( - process: ProcessData, - spawnPoint: ProcessPoint - ): THREE.Vector3 => { - if (process.animationPath && process.animationPath.length > 0) { - let pointIndex = 0; - for (const path of process.paths || []) { - for (let i = 0; i < (path.points?.length || 0); i++) { - const point = path.points?.[i]; - if (point && point.uuid === spawnPoint.uuid) { - if (process.animationPath[pointIndex]) { - const p = process.animationPath[pointIndex]; - return new THREE.Vector3(p.x, p.y, p.z); - } - } - pointIndex++; - } - } - } - return new THREE.Vector3( - spawnPoint.position[0], - spawnPoint.position[1], - spawnPoint.position[2] + // Helper functions + const findSpawnPoint = (process: ProcessData): ProcessPoint | null => { + for (const path of process.paths || []) { + for (const point of path.points || []) { + const spawnAction = point.actions?.find( + (a) => a.isUsed && a.type === "Spawn" ); - }; - - // Optimized object creation - const createSpawnedObject = useCallback( - ( - process: ProcessData, - currentTime: number, - materialType: string, - spawnPoint: ProcessPoint, - baseMaterials: Record - ): SpawnedObject => { - const processMaterials = { - ...baseMaterials, - ...(process.customMaterials || {}), - }; - - const spawnPosition = findAnimationPathPoint(process, spawnPoint); - const material = - processMaterials[materialType as keyof typeof processMaterials] || - baseMaterials.Default; - - return { - ref: { current: null }, - state: { - currentIndex: 0, - progress: 0, - isAnimating: true, - speed: process.speed || 1, - isDelaying: false, - delayStartTime: 0, - currentDelayDuration: 0, - delayComplete: false, - currentPathIndex: 0, - }, - visible: true, - material: material, - currentMaterialType: materialType, - spawnTime: currentTime, - position: spawnPosition, - }; - }, - [] - ); - - // Material handling - const handleMaterialSwap = useCallback( - ( - processId: string, - objectId: string, - materialType: string, - processes: ProcessData[], - baseMaterials: Record - ) => { - setAnimationStates((prev) => { - const processState = prev[processId]; - if (!processState || !processState.spawnedObjects[objectId]) - return prev; - - const process = processes.find((p) => p.id === processId); - if (!process) return prev; - - const processMaterials = { - ...baseMaterials, - ...(process.customMaterials || {}), - }; - - const newMaterial = - processMaterials[materialType as keyof typeof processMaterials]; - if (!newMaterial) return prev; - - return { - ...prev, - [processId]: { - ...processState, - spawnedObjects: { - ...processState.spawnedObjects, - [objectId]: { - ...processState.spawnedObjects[objectId], - material: newMaterial, - currentMaterialType: materialType, - }, - }, - }, - }; - }); - }, - [] - ); - - // Point action handler with trigger counting - const handlePointActions = useCallback( - ( - processId: string, - objectId: string, - actions: PointAction[] = [], - currentTime: number, - processes: ProcessData[], - baseMaterials: Record - ): boolean => { - let shouldStopAnimation = false; - - actions.forEach((action) => { - if (!action.isUsed) return; - - switch (action.type) { - case "Delay": - setAnimationStates((prev) => { - const processState = prev[processId]; - if (!processState || processState.isProcessDelaying) return prev; - - const delayDuration = - typeof action.delay === "number" - ? action.delay - : parseFloat(action.delay as string) || 0; - - if (delayDuration > 0) { - return { - ...prev, - [processId]: { - ...processState, - isProcessDelaying: true, - processDelayStartTime: currentTime, - processDelayDuration: delayDuration, - spawnedObjects: { - ...processState.spawnedObjects, - [objectId]: { - ...processState.spawnedObjects[objectId], - state: { - ...processState.spawnedObjects[objectId].state, - isAnimating: false, - isDelaying: true, - delayStartTime: currentTime, - currentDelayDuration: delayDuration, - delayComplete: false, - }, - }, - }, - }, - }; - } - return prev; - }); - shouldStopAnimation = true; - break; - - case "Despawn": - setAnimationStates((prev) => { - const processState = prev[processId]; - if (!processState) return prev; - - const newSpawnedObjects = { ...processState.spawnedObjects }; - delete newSpawnedObjects[objectId]; - - return { - ...prev, - [processId]: { - ...processState, - spawnedObjects: newSpawnedObjects, - }, - }; - }); - shouldStopAnimation = true; - break; - - case "Swap": - if (action.material) { - handleMaterialSwap( - processId, - objectId, - action.material, - processes, - baseMaterials - ); - } - break; - - default: - break; - } - }); - - return shouldStopAnimation; - }, - [handleMaterialSwap] - ); - - const deferredArmBotUpdates = useRef<{ uuid: string; triggerId: string }[]>([]); - - // Trigger counting system - const checkAndCountTriggers = useCallback( - ( - processId: string, - objectId: string, - currentPointIndex: number, - processes: ProcessData[], - currentTime: number - ) => { - setAnimationStates((prev) => { - const processState = prev[processId]; - if (!processState) return prev; - - const process = processes.find((p) => p.id === processId); - if (!process) return prev; - - const point = getPointDataForAnimationIndex(process, currentPointIndex); - if (!point?.triggers) return prev; - - const onHitTriggers = point.triggers.filter((t: Trigger) => t.type === "On-Hit" && t.isUsed); - - if (onHitTriggers.length === 0) return prev; - - let newTriggerCounts = { ...processState.triggerCounts }; - const newTriggerLogs = [...processState.triggerLogs]; - let shouldLog = false; - - const vehiclePaths = process.paths.filter((path) => path.type === "Vehicle"); - const armBotPaths = process.paths.filter((path) => path.type === "ArmBot"); - - const activeVehicles = vehiclePaths.filter((path) => { - const vehicleId = path.modeluuid; - const vehicleEntry = agvRef.current.find((v: any) => v.vehicleId === vehicleId && v.processId === processId); - return vehicleEntry?.isActive; - }); - - // Check if any ArmBot is active for this process - // const activeArmBots = armBotPaths.filter((path) => { - // const armBotId = path.modeluuid; - // const armBotEntry = armBots.find((a: any) => a.uuid === armBotId); - // return armBotEntry; - // }); - - // Only count triggers if no vehicles and no ArmBots are active for this process - - if (activeVehicles.length === 0) { - onHitTriggers.forEach((trigger: Trigger) => { - const connections = point.connections?.targets || []; - - connections.forEach((connection) => { - const connectedModelUUID = connection.modelUUID; - - const matchingArmPath = armBotPaths.find((path) => path.modeluuid === connectedModelUUID); - - if (matchingArmPath) { - deferredArmBotUpdates.current.push({ - uuid: connectedModelUUID, - triggerId: trigger.uuid, - }); - } - }); - }); - } - - let processTotalHits = Object.values(newTriggerCounts).reduce((a, b) => a + b, 0); - - // Handle logic for vehicles and ArmBots when a trigger is hit - if (shouldLog) { - vehiclePaths.forEach((vehiclePath) => { - if (vehiclePath.points?.length > 0) { - const vehiclePoint = vehiclePath.points[0]; - const action = vehiclePoint.actions?.[0]; - const maxHitCount = action?.hitCount; - - if (maxHitCount !== undefined) { - const vehicleId = vehiclePath.modeluuid; - let vehicleEntry = agvRef.current.find( - (v: any) => - v.vehicleId === vehicleId && v.processId === processId - ); - - if (!vehicleEntry) { - vehicleEntry = { - processId, - vehicleId, - maxHitCount: maxHitCount, - isActive: false, - hitCount: 0, - status: "stationed", - }; - agvRef.current.push(vehicleEntry); - } - - if (!vehicleEntry.isActive) { - vehicleEntry.hitCount++; - vehicleEntry.lastUpdated = currentTime; - - if (vehicleEntry.hitCount >= vehicleEntry.maxHitCount) { - vehicleEntry.isActive = true; - newTriggerCounts = {}; - processTotalHits = 0; - } - } - } - } - }); - } - - return { - ...prev, - [processId]: { - ...processState, - triggerCounts: newTriggerCounts, - triggerLogs: newTriggerLogs, - totalHits: processTotalHits, - }, - }; - }); - }, []); - - useEffect(() => { - if (deferredArmBotUpdates.current.length > 0) { - const updates = [...deferredArmBotUpdates.current]; - deferredArmBotUpdates.current = []; - - setArmBots((prev) => - prev.map((bot) => { - const update = updates.find((u) => u.uuid === bot.uuid); - return update ? { ...bot, triggerId: update.triggerId } : bot; - }) - ); + if (spawnAction) { + return point; } - }, [animationStates]); + } + } + return null; + }; - // Utility functions - const hasNonInheritActions = useCallback( - (actions: PointAction[] = []): boolean => { - return actions.some( - (action) => action.isUsed && action.type !== "Inherit" - ); - }, - [] + const findAnimationPathPoint = ( + process: ProcessData, + spawnPoint: ProcessPoint + ): THREE.Vector3 => { + if (process.animationPath && process.animationPath.length > 0) { + let pointIndex = 0; + for (const path of process.paths || []) { + for (let i = 0; i < (path.points?.length || 0); i++) { + const point = path.points?.[i]; + if (point && point.uuid === spawnPoint.uuid) { + if (process.animationPath[pointIndex]) { + const p = process.animationPath[pointIndex]; + return new THREE.Vector3(p.x, p.y, p.z); + } + } + pointIndex++; + } + } + } + return new THREE.Vector3( + spawnPoint.position[0], + spawnPoint.position[1], + spawnPoint.position[2] ); + }; - const getPointDataForAnimationIndex = useCallback( - (process: ProcessData, index: number): ProcessPoint | null => { - if (!process.paths) return null; + // Optimized object creation + const createSpawnedObject = useCallback( + ( + process: ProcessData, + currentTime: number, + materialType: string, + spawnPoint: ProcessPoint, + baseMaterials: Record + ): SpawnedObject => { + const processMaterials = { + ...baseMaterials, + ...(process.customMaterials || {}), + }; - let cumulativePoints = 0; - for (const path of process.paths) { - const pointCount = path.points?.length || 0; + const spawnPosition = findAnimationPathPoint(process, spawnPoint); + const material = + processMaterials[materialType as keyof typeof processMaterials] || + baseMaterials.Default; - if (index < cumulativePoints + pointCount) { - const pointIndex = index - cumulativePoints; - return path.points?.[pointIndex] || null; + return { + ref: { current: null }, + state: { + currentIndex: 0, + progress: 0, + isAnimating: true, + speed: process.speed || 1, + isDelaying: false, + delayStartTime: 0, + currentDelayDuration: 0, + delayComplete: false, + currentPathIndex: 0, + }, + visible: true, + material: material, + currentMaterialType: materialType, + spawnTime: currentTime, + position: spawnPosition, + }; + }, + [] + ); + + // Material handling + const handleMaterialSwap = useCallback( + ( + processId: string, + objectId: string, + materialType: string, + processes: ProcessData[], + baseMaterials: Record + ) => { + setAnimationStates((prev) => { + const processState = prev[processId]; + if (!processState || !processState.spawnedObjects[objectId]) + return prev; + + const process = processes.find((p) => p.id === processId); + if (!process) return prev; + + const processMaterials = { + ...baseMaterials, + ...(process.customMaterials || {}), + }; + + const newMaterial = + processMaterials[materialType as keyof typeof processMaterials]; + if (!newMaterial) return prev; + + return { + ...prev, + [processId]: { + ...processState, + spawnedObjects: { + ...processState.spawnedObjects, + [objectId]: { + ...processState.spawnedObjects[objectId], + material: newMaterial, + currentMaterialType: materialType, + }, + }, + }, + }; + }); + }, + [] + ); + + // Point action handler with trigger counting + const handlePointActions = useCallback( + ( + processId: string, + objectId: string, + actions: PointAction[] = [], + currentTime: number, + processes: ProcessData[], + baseMaterials: Record + ): boolean => { + let shouldStopAnimation = false; + + actions.forEach((action) => { + if (!action.isUsed) return; + + switch (action.type) { + case "Delay": + setAnimationStates((prev) => { + const processState = prev[processId]; + if (!processState || processState.isProcessDelaying) return prev; + + const delayDuration = + typeof action.delay === "number" + ? action.delay + : parseFloat(action.delay as string) || 0; + + if (delayDuration > 0) { + return { + ...prev, + [processId]: { + ...processState, + isProcessDelaying: true, + processDelayStartTime: currentTime, + processDelayDuration: delayDuration, + spawnedObjects: { + ...processState.spawnedObjects, + [objectId]: { + ...processState.spawnedObjects[objectId], + state: { + ...processState.spawnedObjects[objectId].state, + isAnimating: false, + isDelaying: true, + delayStartTime: currentTime, + currentDelayDuration: delayDuration, + delayComplete: false, + }, + }, + }, + }, + }; + } + return prev; + }); + shouldStopAnimation = true; + break; + + case "Despawn": + setAnimationStates((prev) => { + const processState = prev[processId]; + if (!processState) return prev; + + const newSpawnedObjects = { ...processState.spawnedObjects }; + delete newSpawnedObjects[objectId]; + + return { + ...prev, + [processId]: { + ...processState, + spawnedObjects: newSpawnedObjects, + }, + }; + }); + shouldStopAnimation = true; + break; + + case "Swap": + if (action.material) { + handleMaterialSwap( + processId, + objectId, + action.material, + processes, + baseMaterials + ); + } + break; + + default: + break; + } + }); + + return shouldStopAnimation; + }, + [handleMaterialSwap] + ); + + const deferredArmBotUpdates = useRef<{ uuid: string; triggerId: string }[]>([]); + + // Trigger counting system + const checkAndCountTriggers = useCallback( + ( + processId: string, + objectId: string, + currentPointIndex: number, + processes: ProcessData[], + currentTime: number + ) => { + setAnimationStates((prev) => { + const processState = prev[processId]; + if (!processState) return prev; + + const process = processes.find((p) => p.id === processId); + if (!process) return prev; + + const point = getPointDataForAnimationIndex(process, currentPointIndex); + if (!point?.triggers) return prev; + + const onHitTriggers = point.triggers.filter((t: Trigger) => t.type === "On-Hit" && t.isUsed); + + if (onHitTriggers.length === 0) return prev; + + let newTriggerCounts = { ...processState.triggerCounts }; + const newTriggerLogs = [...processState.triggerLogs]; + let shouldLog = false; + + const vehiclePaths = process.paths.filter((path) => path.type === "Vehicle"); + const armBotPaths = process.paths.filter((path) => path.type === "ArmBot"); + + const activeVehicles = vehiclePaths.filter((path) => { + const vehicleId = path.modeluuid; + const vehicleEntry = agvRef.current.find((v: any) => v.vehicleId === vehicleId && v.processId === processId); + return vehicleEntry?.isActive; + }); + + // Check if any ArmBot is active for this process + // const activeArmBots = armBotPaths.filter((path) => { + // const armBotId = path.modeluuid; + // const armBotEntry = armBots.find((a: any) => a.uuid === armBotId); + // return armBotEntry; + // }); + + // Only count triggers if no vehicles and no ArmBots are active for this process + + if (activeVehicles.length === 0) { + onHitTriggers.forEach((trigger: Trigger) => { + const connections = point.connections?.targets || []; + + connections.forEach((connection) => { + const connectedModelUUID = connection.modelUUID; + + const matchingArmPath = armBotPaths.find((path) => path.modeluuid === connectedModelUUID); + + if (matchingArmPath) { + deferredArmBotUpdates.current.push({ + uuid: connectedModelUUID, + triggerId: trigger.uuid, + }); + } + }); + }); + } + + let processTotalHits = Object.values(newTriggerCounts).reduce((a, b) => a + b, 0); + + // Handle logic for vehicles and ArmBots when a trigger is hit + if (shouldLog) { + vehiclePaths.forEach((vehiclePath) => { + if (vehiclePath.points?.length > 0) { + const vehiclePoint = vehiclePath.points[0]; + const action = vehiclePoint.actions?.[0]; + const maxHitCount = action?.hitCount; + + if (maxHitCount !== undefined) { + const vehicleId = vehiclePath.modeluuid; + let vehicleEntry = agvRef.current.find( + (v: any) => + v.vehicleId === vehicleId && v.processId === processId + ); + + if (!vehicleEntry) { + vehicleEntry = { + processId, + vehicleId, + maxHitCount: maxHitCount, + isActive: false, + hitCount: 0, + status: "stationed", + }; + agvRef.current.push(vehicleEntry); } - cumulativePoints += pointCount; + if (!vehicleEntry.isActive) { + vehicleEntry.hitCount++; + vehicleEntry.lastUpdated = currentTime; + + if (vehicleEntry.hitCount >= vehicleEntry.maxHitCount) { + vehicleEntry.isActive = true; + newTriggerCounts = {}; + processTotalHits = 0; + } + } + } } + }); + } - return null; - }, - [] - ); - - const getTriggerCounts = useCallback((processId: string) => { - return animationStatesRef.current[processId]?.triggerCounts || {}; + return { + ...prev, + [processId]: { + ...processState, + triggerCounts: newTriggerCounts, + triggerLogs: newTriggerLogs, + totalHits: processTotalHits, + }, + }; + }); }, []); - const getTriggerLogs = useCallback((processId: string) => { - return animationStatesRef.current[processId]?.triggerLogs || []; + useEffect(() => { + if (deferredArmBotUpdates.current.length > 0) { + const updates = [...deferredArmBotUpdates.current]; + deferredArmBotUpdates.current = []; + + setArmBots((prev) => + prev.map((bot) => { + const update = updates.find((u) => u.uuid === bot.uuid); + + return update + ? { ...bot, triggerId: update.triggerId, isActive: true } + : bot; + }) + ); + } + }, [animationStates]); + + // Utility functions + const hasNonInheritActions = useCallback( + (actions: PointAction[] = []): boolean => { + return actions.some( + (action) => action.isUsed && action.type !== "Inherit" + ); }, []); - return { - animationStates, - setAnimationStates, - clockRef, - elapsedBeforePauseRef, - speedRef, - debugRef, - findSpawnPoint, - createSpawnedObject, - handlePointActions, - hasNonInheritActions, - getPointDataForAnimationIndex, - checkAndCountTriggers, - getTriggerCounts, - getTriggerLogs, - processes, - }; + const getPointDataForAnimationIndex = useCallback( + (process: ProcessData, index: number): ProcessPoint | null => { + if (!process.paths) return null; + + let cumulativePoints = 0; + for (const path of process.paths) { + const pointCount = path.points?.length || 0; + + if (index < cumulativePoints + pointCount) { + const pointIndex = index - cumulativePoints; + return path.points?.[pointIndex] || null; + } + + cumulativePoints += pointCount; + } + + return null; + }, + [] + ); + + const getTriggerCounts = useCallback((processId: string) => { + return animationStatesRef.current[processId]?.triggerCounts || {}; + }, []); + + const getTriggerLogs = useCallback((processId: string) => { + return animationStatesRef.current[processId]?.triggerLogs || []; + }, []); + + return { + animationStates, + setAnimationStates, + clockRef, + elapsedBeforePauseRef, + speedRef, + debugRef, + findSpawnPoint, + createSpawnedObject, + handlePointActions, + hasNonInheritActions, + getPointDataForAnimationIndex, + checkAndCountTriggers, + getTriggerCounts, + getTriggerLogs, + processes, + }; }; diff --git a/app/src/modules/simulation/simulation.tsx b/app/src/modules/simulation/simulation.tsx index 2f66ab8..84d3651 100644 --- a/app/src/modules/simulation/simulation.tsx +++ b/app/src/modules/simulation/simulation.tsx @@ -15,7 +15,12 @@ interface ArmBotState { status: string; material: string; triggerId: string; + connections: { + source: { modelUUID: string; pointUUID: string }; + targets: { modelUUID: string; pointUUID: string }[]; + }; actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; + isActive?: boolean; } interface StaticMachineState { diff --git a/app/src/modules/simulation/staticMachine/staticMachine.tsx b/app/src/modules/simulation/staticMachine/staticMachine.tsx index ba9b4f0..26760eb 100644 --- a/app/src/modules/simulation/staticMachine/staticMachine.tsx +++ b/app/src/modules/simulation/staticMachine/staticMachine.tsx @@ -10,9 +10,13 @@ interface ArmBotState { status: string; material: string; triggerId: string; + connections: { + source: { modelUUID: string; pointUUID: string }; + targets: { modelUUID: string; pointUUID: string }[]; + }; actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; }; + isActive?: boolean; } - interface StaticMachineState { uuid: string; status: string;