Merge branch 'main' into rtViz

This commit is contained in:
2025-04-02 19:09:50 +05:30
83 changed files with 5145 additions and 857 deletions

View File

@@ -60,7 +60,7 @@ async function addAssetModel(
if (intersectPoint.y < 0) {
intersectPoint = new THREE.Vector3(intersectPoint.x, 0, intersectPoint.z);
}
console.log('selectedItem: ', selectedItem);
// console.log('selectedItem: ', selectedItem);
const cachedModel = THREE.Cache.get(selectedItem.id);
if (cachedModel) {
// console.log(`[Cache] Fetching ${selectedItem.name}`);
@@ -145,10 +145,9 @@ async function handleModelLoad(
};
const email = localStorage.getItem("email");
const organization = email ? email.split("@")[1].split(".")[0] : "default";
const organization = email ? email.split("@")[1].split(".")[0] : "";
getAssetEventType(selectedItem.id, organization).then(async (res) => {
console.log('res: ', res);
if (res.type === "Conveyor") {
const pointUUIDs = res.points.map(() => THREE.MathUtils.generateUUID());
@@ -177,7 +176,7 @@ async function handleModelLoad(
speed: 'Inherit'
};
console.log('eventData: ', eventData);
// console.log('eventData: ', eventData);
newFloorItem.eventData = eventData;
}
@@ -215,6 +214,8 @@ async function handleModelLoad(
eventData: newFloorItem.eventData,
socketId: socket.id
};
console.log('data: ', data);
socket.emit("v2:model-asset:add", data);

View File

@@ -2,9 +2,9 @@ import { toast } from 'react-toastify';
import * as THREE from 'three';
import * as Types from "../../../../types/world/worldTypes";
import { getFloorItems } from '../../../../services/factoryBuilder/assest/floorAsset/getFloorItemsApi';
// import { deleteFloorItem } from '../../../../services/factoryBuilder/assest/floorAsset/deleteFloorItemApi';
import { Socket } from 'socket.io-client';
import { getFloorAssets } from '../../../../services/factoryBuilder/assest/floorAsset/getFloorItemsApi';
async function DeleteFloorItems(
itemsGroup: Types.RefGroup,
@@ -20,7 +20,7 @@ async function DeleteFloorItems(
const email = localStorage.getItem('email')
const organization = (email!.split("@")[1]).split(".")[0];
const items = await getFloorItems(organization);
const items = await getFloorAssets(organization);
const removedItem = items.find(
(item: { modeluuid: string }) => item.modeluuid === hoveredDeletableFloorItem.current?.uuid
);
@@ -42,7 +42,7 @@ async function DeleteFloorItems(
socketId: socket.id
}
const response = socket.emit('v1:FloorItems:delete', data)
const response = socket.emit('v2:model-asset:delete', data)
if (response) {
const updatedItems = items.filter(

View File

@@ -1,333 +1,434 @@
import { useFrame, useThree } from "@react-three/fiber";
import { useActiveTool, useAsset3dWidget, useCamMode, useDeletableFloorItem, useDeleteModels, useFloorItems, useLoadingProgress, useRenderDistance, useselectedFloorItem, useSelectedItem, useSocketStore, useToggleView, useTransformMode } from "../../../store/store";
import {
useActiveTool,
useAsset3dWidget,
useCamMode,
useDeletableFloorItem,
useDeleteModels,
useFloorItems,
useLoadingProgress,
useRenderDistance,
useselectedFloorItem,
useSelectedItem,
useSocketStore,
useToggleView,
useTransformMode,
} from "../../../store/store";
import assetVisibility from "../geomentries/assets/assetVisibility";
import { useEffect } from "react";
import * as THREE from "three";
import * as Types from "../../../types/world/worldTypes";
import assetManager, { cancelOngoingTasks } from "../geomentries/assets/assetManager";
import assetManager, {
cancelOngoingTasks,
} from "../geomentries/assets/assetManager";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
import DeletableHoveredFloorItems from "../geomentries/assets/deletableHoveredFloorItems";
import DeleteFloorItems from "../geomentries/assets/deleteFloorItems";
import loadInitialFloorItems from "../../scene/IntialLoad/loadInitialFloorItems";
import addAssetModel from "../geomentries/assets/addAssetModel";
import { getFloorItems } from "../../../services/factoryBuilder/assest/floorAsset/getFloorItemsApi";
import { getFloorAssets } from "../../../services/factoryBuilder/assest/floorAsset/getFloorItemsApi";
import useModuleStore from "../../../store/useModuleStore";
// import { retrieveGLTF } from "../../../utils/indexDB/idbUtils";
const assetManagerWorker = new Worker(new URL('../../../services/factoryBuilder/webWorkers/assetManagerWorker.js', import.meta.url));
const gltfLoaderWorker = new Worker(new URL('../../../services/factoryBuilder/webWorkers/gltfLoaderWorker.js', import.meta.url));
const assetManagerWorker = new Worker(
new URL(
"../../../services/factoryBuilder/webWorkers/assetManagerWorker.js",
import.meta.url
)
);
const gltfLoaderWorker = new Worker(
new URL(
"../../../services/factoryBuilder/webWorkers/gltfLoaderWorker.js",
import.meta.url
)
);
const FloorItemsGroup = ({ itemsGroup, hoveredDeletableFloorItem, AttachedObject, floorGroup, tempLoader, isTempLoader, plane }: any) => {
const state: Types.ThreeState = useThree();
const { raycaster, controls }: any = state;
const { renderDistance } = useRenderDistance();
const { toggleView } = useToggleView();
const { floorItems, setFloorItems } = useFloorItems();
const { camMode } = useCamMode();
const { deleteModels } = useDeleteModels();
const { setDeletableFloorItem } = useDeletableFloorItem();
const { transformMode } = useTransformMode();
const { setselectedFloorItem } = useselectedFloorItem();
const { activeTool } = useActiveTool();
const { selectedItem, setSelectedItem } = useSelectedItem();
const { setLoadingProgress } = useLoadingProgress();
const { activeModule } = useModuleStore();
const { socket } = useSocketStore();
const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
const FloorItemsGroup = ({
itemsGroup,
hoveredDeletableFloorItem,
AttachedObject,
floorGroup,
tempLoader,
isTempLoader,
plane,
}: any) => {
const state: Types.ThreeState = useThree();
const { raycaster, controls }: any = state;
const { renderDistance } = useRenderDistance();
const { toggleView } = useToggleView();
const { floorItems, setFloorItems } = useFloorItems();
const { camMode } = useCamMode();
const { deleteModels } = useDeleteModels();
const { setDeletableFloorItem } = useDeletableFloorItem();
const { transformMode } = useTransformMode();
const { setselectedFloorItem } = useselectedFloorItem();
const { activeTool } = useActiveTool();
const { selectedItem, setSelectedItem } = useSelectedItem();
const { setLoadingProgress } = useLoadingProgress();
const { activeModule } = useModuleStore();
const { socket } = useSocketStore();
const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/gltf/');
loader.setDRACOLoader(dracoLoader);
dracoLoader.setDecoderPath(
"https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/gltf/"
);
loader.setDRACOLoader(dracoLoader);
useEffect(() => {
const email = localStorage.getItem('email');
const organization = (email!.split("@")[1]).split(".")[0];
useEffect(() => {
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
let totalAssets = 0;
let loadedAssets = 0;
let totalAssets = 0;
let loadedAssets = 0;
const updateLoadingProgress = (progress: number) => {
if (progress < 100) {
setLoadingProgress(progress);
} else if (progress === 100) {
setTimeout(() => {
setLoadingProgress(100);
setTimeout(() => {
setLoadingProgress(0);
}, 1500);
}, 1000);
}
};
const updateLoadingProgress = (progress: number) => {
if (progress < 100) {
setLoadingProgress(progress);
} else if (progress === 100) {
setTimeout(() => {
setLoadingProgress(100);
setTimeout(() => {
setLoadingProgress(0);
}, 1500);
}, 1000);
}
};
getFloorItems(organization).then((data) => {
console.log('data: ', data);
const uniqueItems = (data as Types.FloorItems).filter((item, index, self) =>
index === self.findIndex((t) => t.modelfileID === item.modelfileID)
);
totalAssets = uniqueItems.length;
if (totalAssets === 0) {
updateLoadingProgress(100);
return;
}
gltfLoaderWorker.postMessage({ floorItems: data });
getFloorAssets(organization).then((data) => {
const uniqueItems = (data as Types.FloorItems).filter(
(item, index, self) =>
index === self.findIndex((t) => t.modelfileID === item.modelfileID)
);
totalAssets = uniqueItems.length;
if (totalAssets === 0) {
updateLoadingProgress(100);
return;
}
gltfLoaderWorker.postMessage({ floorItems: data });
});
gltfLoaderWorker.onmessage = async (event) => {
if (event.data.message === "gltfLoaded" && event.data.modelBlob) {
const blobUrl = URL.createObjectURL(event.data.modelBlob);
loader.load(blobUrl, (gltf) => {
URL.revokeObjectURL(blobUrl);
THREE.Cache.remove(blobUrl);
THREE.Cache.add(event.data.modelID, gltf);
loadedAssets++;
const progress = Math.round((loadedAssets / totalAssets) * 100);
updateLoadingProgress(progress);
if (loadedAssets === totalAssets) {
loadInitialFloorItems(itemsGroup, setFloorItems);
updateLoadingProgress(100);
}
});
}
};
}, []);
gltfLoaderWorker.onmessage = async (event) => {
if (event.data.message === "gltfLoaded" && event.data.modelBlob) {
const blobUrl = URL.createObjectURL(event.data.modelBlob);
useEffect(() => {
assetManagerWorker.onmessage = async (event) => {
cancelOngoingTasks(); // Cancel the ongoing process
await assetManager(event.data, itemsGroup, loader);
};
}, [assetManagerWorker]);
loader.load(blobUrl, (gltf) => {
URL.revokeObjectURL(blobUrl);
THREE.Cache.remove(blobUrl);
THREE.Cache.add(event.data.modelID, gltf);
useEffect(() => {
if (toggleView) return;
loadedAssets++;
const progress = Math.round((loadedAssets / totalAssets) * 100);
updateLoadingProgress(progress);
const uuids: string[] = [];
itemsGroup.current?.children.forEach((child: any) => {
uuids.push(child.uuid);
});
const cameraPosition = state.camera.position;
if (loadedAssets === totalAssets) {
loadInitialFloorItems(itemsGroup, setFloorItems);
updateLoadingProgress(100);
}
});
}
};
}, []);
assetManagerWorker.postMessage({
floorItems,
cameraPosition,
uuids,
renderDistance,
});
}, [camMode, renderDistance]);
useEffect(() => {
assetManagerWorker.onmessage = async (event) => {
cancelOngoingTasks(); // Cancel the ongoing process
await assetManager(event.data, itemsGroup, loader);
};
}, [assetManagerWorker]);
useEffect(() => {
const controls: any = state.controls;
const camera: any = state.camera;
useEffect(() => {
if (toggleView) return
if (controls) {
let intervalId: NodeJS.Timeout | null = null;
const handleChange = () => {
if (toggleView) return;
const uuids: string[] = [];
itemsGroup.current?.children.forEach((child: any) => {
uuids.push(child.uuid);
uuids.push(child.uuid);
});
const cameraPosition = state.camera.position;
const cameraPosition = camera.position;
assetManagerWorker.postMessage({ floorItems, cameraPosition, uuids, renderDistance });
}, [camMode, renderDistance]);
assetManagerWorker.postMessage({
floorItems,
cameraPosition,
uuids,
renderDistance,
});
};
useEffect(() => {
const controls: any = state.controls;
const camera: any = state.camera;
if (controls) {
let intervalId: NodeJS.Timeout | null = null;
const handleChange = () => {
if (toggleView) return
const uuids: string[] = [];
itemsGroup.current?.children.forEach((child: any) => {
uuids.push(child.uuid);
});
const cameraPosition = camera.position;
assetManagerWorker.postMessage({ floorItems, cameraPosition, uuids, renderDistance });
};
const startInterval = () => {
if (!intervalId) {
intervalId = setInterval(handleChange, 50);
}
};
const stopInterval = () => {
handleChange();
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
};
controls.addEventListener('rest', handleChange);
controls.addEventListener('rest', stopInterval);
controls.addEventListener('control', startInterval);
controls.addEventListener('controlend', stopInterval);
return () => {
controls.removeEventListener('rest', handleChange);
controls.removeEventListener('rest', stopInterval);
controls.removeEventListener('control', startInterval);
controls.removeEventListener('controlend', stopInterval);
if (intervalId) {
clearInterval(intervalId);
}
};
const startInterval = () => {
if (!intervalId) {
intervalId = setInterval(handleChange, 50);
}
}, [state.controls, floorItems, toggleView, renderDistance]);
};
useEffect(() => {
const canvasElement = state.gl.domElement;
let drag = false;
let isLeftMouseDown = false;
const onMouseDown = (evt: any) => {
if (evt.button === 0) {
isLeftMouseDown = true;
drag = false;
}
};
const onMouseMove = () => {
if (isLeftMouseDown) {
drag = true;
}
};
const onMouseUp = async (evt: any) => {
if (controls) {
(controls as any).enabled = true;
}
if (evt.button === 0) {
isLeftMouseDown = false;
if (drag) return;
if (deleteModels) {
DeleteFloorItems(itemsGroup, hoveredDeletableFloorItem, setFloorItems, socket);
}
const Mode = transformMode;
if (Mode !== null || activeTool === "cursor") {
if (!itemsGroup.current) return;
let intersects = raycaster.intersectObjects(itemsGroup.current.children, true);
if (intersects.length > 0 && intersects[0]?.object?.parent?.parent?.position && intersects[0]?.object?.parent?.parent?.scale && intersects[0]?.object?.parent?.parent?.rotation) {
// let currentObject = intersects[0].object;
// while (currentObject) {
// if (currentObject.name === "Scene") {
// break;
// }
// currentObject = currentObject.parent as THREE.Object3D;
// }
// if (currentObject) {
// AttachedObject.current = currentObject as any;
// setselectedFloorItem(AttachedObject.current!);
// }
} else {
const target = controls.getTarget(new THREE.Vector3());
await controls.setTarget(target.x, 0, target.z, true);
setselectedFloorItem(null);
}
}
}
};
const onDblClick = async (evt: any) => {
if (evt.button === 0) {
isLeftMouseDown = false;
if (drag) return;
const Mode = transformMode;
if (Mode !== null || activeTool === "cursor") {
if (!itemsGroup.current) return;
let intersects = raycaster.intersectObjects(itemsGroup.current.children, true);
if (intersects.length > 0 && intersects[0]?.object?.parent?.parent?.position && intersects[0]?.object?.parent?.parent?.scale && intersects[0]?.object?.parent?.parent?.rotation) {
let currentObject = intersects[0].object;
while (currentObject) {
if (currentObject.name === "Scene") {
break;
}
currentObject = currentObject.parent as THREE.Object3D;
}
if (currentObject) {
AttachedObject.current = currentObject as any;
// controls.fitToSphere(AttachedObject.current!, true);
const bbox = new THREE.Box3().setFromObject(AttachedObject.current);
const size = bbox.getSize(new THREE.Vector3());
const center = bbox.getCenter(new THREE.Vector3());
const front = new THREE.Vector3(0, 0, 1);
AttachedObject.current.localToWorld(front);
front.sub(AttachedObject.current.position).normalize();
const distance = Math.max(size.x, size.y, size.z) * 2;
const newPosition = center.clone().addScaledVector(front, distance);
controls.setPosition(newPosition.x, newPosition.y, newPosition.z, true);
controls.setTarget(center.x, center.y, center.z, true);
controls.fitToBox(AttachedObject.current!, true, { cover: true, paddingTop: 5, paddingLeft: 5, paddingBottom: 5, paddingRight: 5 });
setselectedFloorItem(AttachedObject.current!);
}
} else {
const target = controls.getTarget(new THREE.Vector3());
await controls.setTarget(target.x, 0, target.z, true);
setselectedFloorItem(null);
}
}
}
const stopInterval = () => {
handleChange();
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
};
const onDrop = (event: any) => {
controls.addEventListener("rest", handleChange);
controls.addEventListener("rest", stopInterval);
controls.addEventListener("control", startInterval);
controls.addEventListener("controlend", stopInterval);
if (!event.dataTransfer?.files[0]) return;
if (selectedItem.id !== "" && event.dataTransfer?.files[0]) {
addAssetModel(raycaster, state.camera, state.pointer, floorGroup, setFloorItems, itemsGroup, isTempLoader, tempLoader, socket, selectedItem, setSelectedItem, plane);
}
return () => {
controls.removeEventListener("rest", handleChange);
controls.removeEventListener("rest", stopInterval);
controls.removeEventListener("control", startInterval);
controls.removeEventListener("controlend", stopInterval);
if (intervalId) {
clearInterval(intervalId);
}
};
}
}, [state.controls, floorItems, toggleView, renderDistance]);
const onDragOver = (event: any) => {
event.preventDefault();
};
useEffect(() => {
const canvasElement = state.gl.domElement;
let drag = false;
let isLeftMouseDown = false;
if (activeModule === "builder") {
canvasElement.addEventListener("mousedown", onMouseDown);
canvasElement.addEventListener("mouseup", onMouseUp);
canvasElement.addEventListener("mousemove", onMouseMove);
canvasElement.addEventListener("dblclick", onDblClick);
canvasElement.addEventListener("drop", onDrop);
canvasElement.addEventListener("dragover", onDragOver);
} else {
if (controls) {
const target = controls.getTarget(new THREE.Vector3());
controls.setTarget(target.x, 0, target.z, true);
setselectedFloorItem(null);
}
}
const onMouseDown = (evt: any) => {
if (evt.button === 0) {
isLeftMouseDown = true;
drag = false;
}
};
return () => {
canvasElement.removeEventListener("mousedown", onMouseDown);
canvasElement.removeEventListener("mouseup", onMouseUp);
canvasElement.removeEventListener("mousemove", onMouseMove);
canvasElement.removeEventListener("dblclick", onDblClick);
canvasElement.removeEventListener("drop", onDrop);
canvasElement.removeEventListener("dragover", onDragOver);
};
}, [deleteModels, transformMode, controls, selectedItem, state.camera, state.pointer, activeTool, activeModule]);
const onMouseMove = () => {
if (isLeftMouseDown) {
drag = true;
}
};
useEffect(() => {
const onMouseUp = async (evt: any) => {
if (controls) {
(controls as any).enabled = true;
}
if (evt.button === 0) {
isLeftMouseDown = false;
if (drag) return;
console.log('floorItems: ', floorItems);
}, [floorItems])
useFrame(() => {
if (controls)
assetVisibility(itemsGroup, state.camera.position, renderDistance);
if (deleteModels) {
DeletableHoveredFloorItems(state, itemsGroup, hoveredDeletableFloorItem, setDeletableFloorItem);
} else if (!deleteModels) {
if (hoveredDeletableFloorItem.current) {
hoveredDeletableFloorItem.current = undefined;
setDeletableFloorItem(null);
}
DeleteFloorItems(
itemsGroup,
hoveredDeletableFloorItem,
setFloorItems,
socket
);
}
})
const Mode = transformMode;
return (
<group ref={itemsGroup} name="itemsGroup">
</group>
)
}
if (Mode !== null || activeTool === "cursor") {
if (!itemsGroup.current) return;
let intersects = raycaster.intersectObjects(
itemsGroup.current.children,
true
);
if (
intersects.length > 0 &&
intersects[0]?.object?.parent?.parent?.position &&
intersects[0]?.object?.parent?.parent?.scale &&
intersects[0]?.object?.parent?.parent?.rotation
) {
// let currentObject = intersects[0].object;
// while (currentObject) {
// if (currentObject.name === "Scene") {
// break;
// }
// currentObject = currentObject.parent as THREE.Object3D;
// }
// if (currentObject) {
// AttachedObject.current = currentObject as any;
// setselectedFloorItem(AttachedObject.current!);
// }
} else {
const target = controls.getTarget(new THREE.Vector3());
await controls.setTarget(target.x, 0, target.z, true);
setselectedFloorItem(null);
}
}
}
};
export default FloorItemsGroup;
const onDblClick = async (evt: any) => {
if (evt.button === 0) {
isLeftMouseDown = false;
if (drag) return;
const Mode = transformMode;
if (Mode !== null || activeTool === "cursor") {
if (!itemsGroup.current) return;
let intersects = raycaster.intersectObjects(
itemsGroup.current.children,
true
);
if (
intersects.length > 0 &&
intersects[0]?.object?.parent?.parent?.position &&
intersects[0]?.object?.parent?.parent?.scale &&
intersects[0]?.object?.parent?.parent?.rotation
) {
let currentObject = intersects[0].object;
while (currentObject) {
if (currentObject.name === "Scene") {
break;
}
currentObject = currentObject.parent as THREE.Object3D;
}
if (currentObject) {
AttachedObject.current = currentObject as any;
// controls.fitToSphere(AttachedObject.current!, true);
const bbox = new THREE.Box3().setFromObject(
AttachedObject.current
);
const size = bbox.getSize(new THREE.Vector3());
const center = bbox.getCenter(new THREE.Vector3());
const front = new THREE.Vector3(0, 0, 1);
AttachedObject.current.localToWorld(front);
front.sub(AttachedObject.current.position).normalize();
const distance = Math.max(size.x, size.y, size.z) * 2;
const newPosition = center
.clone()
.addScaledVector(front, distance);
controls.setPosition(
newPosition.x,
newPosition.y,
newPosition.z,
true
);
controls.setTarget(center.x, center.y, center.z, true);
controls.fitToBox(AttachedObject.current!, true, {
cover: true,
paddingTop: 5,
paddingLeft: 5,
paddingBottom: 5,
paddingRight: 5,
});
setselectedFloorItem(AttachedObject.current!);
}
} else {
const target = controls.getTarget(new THREE.Vector3());
await controls.setTarget(target.x, 0, target.z, true);
setselectedFloorItem(null);
}
}
}
};
const onDrop = (event: any) => {
if (!event.dataTransfer?.files[0]) return;
if (selectedItem.id !== "" && event.dataTransfer?.files[0]) {
addAssetModel(
raycaster,
state.camera,
state.pointer,
floorGroup,
setFloorItems,
itemsGroup,
isTempLoader,
tempLoader,
socket,
selectedItem,
setSelectedItem,
plane
);
}
};
const onDragOver = (event: any) => {
event.preventDefault();
};
if (activeModule === "builder") {
canvasElement.addEventListener("mousedown", onMouseDown);
canvasElement.addEventListener("mouseup", onMouseUp);
canvasElement.addEventListener("mousemove", onMouseMove);
canvasElement.addEventListener("dblclick", onDblClick);
canvasElement.addEventListener("drop", onDrop);
canvasElement.addEventListener("dragover", onDragOver);
} else {
if (controls) {
const target = controls.getTarget(new THREE.Vector3());
controls.setTarget(target.x, 0, target.z, true);
setselectedFloorItem(null);
}
}
return () => {
canvasElement.removeEventListener("mousedown", onMouseDown);
canvasElement.removeEventListener("mouseup", onMouseUp);
canvasElement.removeEventListener("mousemove", onMouseMove);
canvasElement.removeEventListener("dblclick", onDblClick);
canvasElement.removeEventListener("drop", onDrop);
canvasElement.removeEventListener("dragover", onDragOver);
};
}, [
deleteModels,
transformMode,
controls,
selectedItem,
state.camera,
state.pointer,
activeTool,
activeModule,
]);
useEffect(() => {}, [floorItems]);
useFrame(() => {
if (controls)
assetVisibility(itemsGroup, state.camera.position, renderDistance);
if (deleteModels) {
DeletableHoveredFloorItems(
state,
itemsGroup,
hoveredDeletableFloorItem,
setDeletableFloorItem
);
} else if (!deleteModels) {
if (hoveredDeletableFloorItem.current) {
hoveredDeletableFloorItem.current = undefined;
setDeletableFloorItem(null);
}
}
});
return <group ref={itemsGroup} name="itemsGroup"></group>;
};
export default FloorItemsGroup;

View File

@@ -32,7 +32,7 @@ const CamModelsGroup = () => {
if (!socket) return;
const organization = email!.split("@")[1].split(".")[0];
socket.on("userConnectRespones", (data: any) => {
socket.on("userConnectResponse", (data: any) => {
if (!groupRef.current) return;
if (data.data.userData.email === email) return;
if (socket.id === data.socketId || organization !== data.organization)
@@ -64,7 +64,11 @@ const CamModelsGroup = () => {
});
});
socket.on("userDisConnectRespones", (data: any) => {
// socket.on("users:online", (data: any) => {
// console.log('users online: ', data);
// })
socket.on("userDisConnectResponse", (data: any) => {
if (!groupRef.current) return;
if (socket.id === data.socketId || organization !== data.organization)
return;
@@ -109,6 +113,15 @@ const CamModelsGroup = () => {
};
}, [socket, activeUsers]);
// useEffect(() => {
// console.log(activeUsers);
// }, [activeUsers])
// useEffect(() => {
// console.log(models);
// }, [models])
useFrame(() => {
if (!groupRef.current) return;
Object.keys(models).forEach((uuid) => {
@@ -142,7 +155,7 @@ const CamModelsGroup = () => {
const filteredData = data.cameraDatas.filter(
(camera: any) => camera.userData.email !== email
);
let a:any = [];
let a: any = [];
if (filteredData.length > 0) {
loader.load(camModel, (gltf) => {
const newCams = filteredData.map((cam: any) => {

View File

@@ -82,14 +82,14 @@ export default function SocketResponses({
})
socket.on('model-asset:response:updates', async (data: any) => {
console.log('data: ', data);
// console.log('data: ', data);
if (socket.id === data.socketId) {
return
}
if (organization !== data.organization) {
return
}
if (data.message === "flooritem created") {
if (data.message === "Model created successfully") {
const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
@@ -101,10 +101,61 @@ export default function SocketResponses({
isTempLoader.current = true;
const cachedModel = THREE.Cache.get(data.data.modelname);
let url;
if (cachedModel) {
// console.log(`Getting ${data.data.modelname} from cache`);
url = URL.createObjectURL(cachedModel);
const model = cachedModel.scene.clone();
model.uuid = data.data.modeluuid;
model.userData = { name: data.data.modelname, modelId: data.data.modelFileID };
model.position.set(...data.data.position as [number, number, number]);
model.rotation.set(data.data.rotation.x, data.data.rotation.y, data.data.rotation.z);
model.scale.set(...CONSTANTS.assetConfig.defaultScaleBeforeGsap);
model.traverse((child: any) => {
if (child.isMesh) {
// Clone the material to ensure changes are independent
// child.material = child.material.clone();
child.castShadow = true;
child.receiveShadow = true;
}
});
itemsGroup.current.add(model);
if (tempLoader.current) {
tempLoader.current.material.dispose();
tempLoader.current.geometry.dispose();
itemsGroup.current.remove(tempLoader.current);
tempLoader.current = undefined;
}
const newFloorItem: Types.FloorItemType = {
modeluuid: data.data.modeluuid,
modelname: data.data.modelname,
modelfileID: data.data.modelfileID,
position: [...data.data.position as [number, number, number]],
rotation: {
x: model.rotation.x,
y: model.rotation.y,
z: model.rotation.z,
},
isLocked: data.data.isLocked,
isVisible: data.data.isVisible,
};
if (data.data.eventData) {
newFloorItem.eventData = data.data.eventData;
}
setFloorItems((prevItems: any) => {
const updatedItems = [...(prevItems || []), newFloorItem];
localStorage.setItem("FloorItems", JSON.stringify(updatedItems));
return updatedItems;
});
gsap.to(model.position, { y: data.data.position[1], duration: 1.5, ease: 'power2.out' });
gsap.to(model.scale, { x: 1, y: 1, z: 1, duration: 1.5, ease: 'power2.out', onComplete: () => { toast.success("Model Added!") } });
} else {
const indexedDBModel = await retrieveGLTF(data.data.modelname);
if (indexedDBModel) {
@@ -118,7 +169,9 @@ export default function SocketResponses({
}
}
loadModel(url);
if (url) {
loadModel(url);
}
} catch (error) {
console.error('Error fetching asset model:', error);
@@ -168,6 +221,10 @@ export default function SocketResponses({
isVisible: data.data.isVisible,
};
if (data.data.eventData) {
newFloorItem.eventData = data.data.eventData;
}
setFloorItems((prevItems: any) => {
const updatedItems = [...(prevItems || []), newFloorItem];
localStorage.setItem("FloorItems", JSON.stringify(updatedItems));
@@ -183,7 +240,7 @@ export default function SocketResponses({
});
}
} else if (data.message === "flooritems updated") {
} else if (data.message === "Model updated successfully") {
itemsGroup.current.children.forEach((item: THREE.Group) => {
if (item.uuid === data.data.modeluuid) {
item.position.set(...data.data.position as [number, number, number]);
@@ -212,14 +269,14 @@ export default function SocketResponses({
}
})
socket.on('FloorItemsDeleteResponse', (data: any) => {
socket.on('model-asset:response:updates', (data: any) => {
if (socket.id === data.socketId) {
return
}
if (organization !== data.organization) {
return
}
if (data.message === "flooritem deleted") {
if (data.message === "Model deleted successfully") {
const deletedUUID = data.data.modeluuid;
let items = JSON.parse(localStorage.getItem("FloorItems")!);
@@ -746,7 +803,6 @@ export default function SocketResponses({
return
}
if (data.message === "zone deleted") {
console.log('data: ', data);
const updatedZones = zones.filter((zone: any) => zone.zoneId !== data.data.zoneId);
setZones(updatedZones);
@@ -769,7 +825,7 @@ export default function SocketResponses({
return () => {
socket.off('zone:response:updates');
socket.off('zone:response:updates');
socket.off('zone:response:delete');
};
}, [socket, zones, zonePoints])

View File

@@ -57,7 +57,6 @@ const FilterSearch: React.FC<ModelsProps> = ({
const filteredModel = filteredModels?.filter((model) =>
model.filename.toLowerCase().includes(val.toLowerCase())
);
setModels(filteredModel);
};

View File

@@ -25,7 +25,6 @@ const MarketPlace = () => {
const filteredAssets = async () => {
try {
const filt = await getAssetImages("67d934ad0f42a1fdadb19aa6");
setModels(filt.items);
setFilteredModels(filt.items);
} catch {}

View File

@@ -5,9 +5,9 @@ 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 { getFloorItems } from '../../../services/factoryBuilder/assest/floorAsset/getFloorItemsApi';
import { initializeDB, retrieveGLTF, storeGLTF } from '../../../utils/indexDB/idbUtils';
import { getCamera } from '../../../services/factoryBuilder/camera/getCameraApi';
import { getFloorAssets } from '../../../services/factoryBuilder/assest/floorAsset/getFloorItemsApi';
async function loadInitialFloorItems(
itemsGroup: Types.RefGroup,
@@ -18,7 +18,7 @@ async function loadInitialFloorItems(
const email = localStorage.getItem('email');
const organization = (email!.split("@")[1]).split(".")[0];
const items = await getFloorItems(organization);
const items = await getFloorAssets(organization);
localStorage.setItem("FloorItems", JSON.stringify(items));
await initializeDB();
@@ -121,18 +121,34 @@ async function loadInitialFloorItems(
});
} else {
// console.log(`Item ${item.modelname} is not near`);
setFloorItems((prevItems) => [
...(prevItems || []),
{
modeluuid: item.modeluuid,
modelname: item.modelname,
position: item.position,
rotation: item.rotation,
modelfileID: item.modelfileID,
isLocked: item.isLocked,
isVisible: item.isVisible,
},
]);
if (item.eventData) {
setFloorItems((prevItems) => [
...(prevItems || []),
{
modeluuid: item.modeluuid,
modelname: item.modelname,
position: item.position,
rotation: item.rotation,
modelfileID: item.modelfileID,
isLocked: item.isLocked,
isVisible: item.isVisible,
// eventData: item.eventData,
},
]);
} else {
setFloorItems((prevItems) => [
...(prevItems || []),
{
modeluuid: item.modeluuid,
modelname: item.modelname,
position: item.position,
rotation: item.rotation,
modelfileID: item.modelfileID,
isLocked: item.isLocked,
isVisible: item.isVisible,
},
]);
}
modelsLoaded++;
checkLoadingCompletion(modelsLoaded, modelsToLoad, dracoLoader, () => { });
}
@@ -169,18 +185,35 @@ function processLoadedModel(
itemsGroup?.current?.add(model);
setFloorItems((prevItems) => [
...(prevItems || []),
{
modeluuid: item.modeluuid,
modelname: item.modelname,
position: item.position,
rotation: item.rotation,
modelfileID: item.modelfileID,
isLocked: item.isLocked,
isVisible: item.isVisible,
},
]);
if (item.eventData) {
setFloorItems((prevItems) => [
...(prevItems || []),
{
modeluuid: item.modeluuid,
modelname: item.modelname,
position: item.position,
rotation: item.rotation,
modelfileID: item.modelfileID,
isLocked: item.isLocked,
isVisible: item.isVisible,
// eventData: item.eventData,
},
]);
} else {
setFloorItems((prevItems) => [
...(prevItems || []),
{
modeluuid: item.modeluuid,
modelname: item.modelname,
position: item.position,
rotation: item.rotation,
modelfileID: item.modelfileID,
isLocked: item.isLocked,
isVisible: item.isVisible,
},
]);
}
gsap.to(model.position, { y: item.position[1], duration: 1.5, ease: 'power2.out' });
gsap.to(model.scale, { x: 1, y: 1, z: 1, duration: 1.5, ease: 'power2.out' });

View File

@@ -180,7 +180,7 @@ const CopyPasteControls = ({ itemsGroupRef, copiedObjects, setCopiedObjects, pas
socketId: socket.id,
};
socket.emit("v1:FloorItems:set", data);
socket.emit("v2:model-asset:add", data);
itemsGroupRef.current.add(obj);
}

View File

@@ -161,7 +161,7 @@ const DuplicationControls = ({ itemsGroupRef, duplicatedObjects, setDuplicatedOb
socketId: socket.id,
};
socket.emit("v1:FloorItems:set", data);
socket.emit("v2:model-asset:add", data);
itemsGroupRef.current.add(obj);
}

View File

@@ -209,7 +209,7 @@ function MoveControls({ movedObjects, setMovedObjects, itemsGroupRef, copiedObje
socketId: socket.id,
};
socket.emit("v1:FloorItems:set", data);
socket.emit("v2:model-asset:add", data);
itemsGroupRef.current.add(obj);
}

View File

@@ -212,7 +212,7 @@ function RotateControls({ rotatedObjects, setRotatedObjects, movedObjects, setMo
socketId: socket.id,
};
socket.emit("v1:FloorItems:set", data);
socket.emit("v2:model-asset:add", data);
itemsGroupRef.current.add(obj);
}

View File

@@ -222,7 +222,7 @@ const SelectionControls: React.FC = () => {
socketId: socket.id
};
socket.emit('v1:FloorItems:delete', data);
socket.emit('v2:model-asset:delete', data);
selectedMesh.traverse((child: THREE.Object3D) => {
if (child instanceof THREE.Mesh) {

View File

@@ -83,7 +83,7 @@ export default function TransformControl() {
socketId: socket.id
}
socket.emit('v1:FloorItems:set', data);
socket.emit('v2:model-asset:add', data);
}
localStorage.setItem("FloorItems", JSON.stringify(updatedItems));
return updatedItems;

View File

@@ -1,22 +1,52 @@
import { useToggleView } from '../../../store/store';
import * as CONSTANTS from '../../../types/world/worldConstants';
import { useTileDistance, useToggleView } from "../../../store/store";
import * as CONSTANTS from "../../../types/world/worldConstants";
const Ground = ({ grid, plane }: any) => {
const { toggleView } = useToggleView();
const savedTheme: string | null = localStorage.getItem('theme');
const { toggleView } = useToggleView();
const savedTheme: string | null = localStorage.getItem("theme");
const { planeValue, gridValue } = useTileDistance();
return (
<mesh name="Ground">
<mesh ref={grid} name="Grid" position={!toggleView ? CONSTANTS.gridConfig.position3D : CONSTANTS.gridConfig.position2D}>
<gridHelper args={[CONSTANTS.gridConfig.size, CONSTANTS.gridConfig.divisions, CONSTANTS.gridConfig.primaryColor, CONSTANTS.gridConfig.secondaryColor]} />
</mesh>
<mesh ref={plane} rotation-x={CONSTANTS.planeConfig.rotation} position={!toggleView ? CONSTANTS.planeConfig.position3D : CONSTANTS.planeConfig.position2D} name="Plane" receiveShadow>
<planeGeometry args={[CONSTANTS.planeConfig.width, CONSTANTS.planeConfig.height]} />
<meshBasicMaterial color={CONSTANTS.planeConfig.color} />
</mesh>
</mesh>
)
}
return (
<mesh name="Ground">
<mesh
ref={grid}
name="Grid"
position={
!toggleView
? CONSTANTS.gridConfig.position3D
: CONSTANTS.gridConfig.position2D
}
>
<gridHelper
args={[
gridValue.size,
gridValue.divisions,
// CONSTANTS.gridConfig.size,
// CONSTANTS.gridConfig.divisions,
CONSTANTS.gridConfig.primaryColor,
CONSTANTS.gridConfig.secondaryColor,
]}
/>
</mesh>
<mesh
ref={plane}
rotation-x={CONSTANTS.planeConfig.rotation}
position={
!toggleView
? CONSTANTS.planeConfig.position3D
: CONSTANTS.planeConfig.position2D
}
name="Plane"
receiveShadow
>
<planeGeometry
args={[planeValue.width, planeValue.height]}
// args={[CONSTANTS.planeConfig.width, CONSTANTS.planeConfig.height]}
/>
<meshBasicMaterial color={CONSTANTS.planeConfig.color} />
</mesh>
</mesh>
);
};
export default Ground;

View File

@@ -1,9 +1,22 @@
import { useRef, useEffect} from 'react';
import { useThree } from '@react-three/fiber';
import * as THREE from 'three';
import { useAzimuth, useElevation, useShadows, useSunPosition, useFloorItems, useWallItems } from '../../../store/store';
import * as CONSTANTS from '../../../types/world/worldConstants';
const shadowWorker = new Worker(new URL('../../../services/factoryBuilder/webWorkers/shadowWorker', import.meta.url));
import { useRef, useEffect } from "react";
import { useThree } from "@react-three/fiber";
import * as THREE from "three";
import {
useAzimuth,
useElevation,
useShadows,
useSunPosition,
useFloorItems,
useWallItems,
useTileDistance,
} from "../../../store/store";
import * as CONSTANTS from "../../../types/world/worldConstants";
const shadowWorker = new Worker(
new URL(
"../../../services/factoryBuilder/webWorkers/shadowWorker",
import.meta.url
)
);
export default function Shadows() {
const { shadows, setShadows } = useShadows();
@@ -15,6 +28,7 @@ export default function Shadows() {
const { azimuth, setAzimuth } = useAzimuth();
const { floorItems } = useFloorItems();
const { wallItems } = useWallItems();
const { planeValue } = useTileDistance();
useEffect(() => {
gl.shadowMap.enabled = true;
@@ -48,9 +62,9 @@ export default function Shadows() {
useEffect(() => {
if (controls && shadows) {
updateShadows();
(controls as any).addEventListener('update', updateShadows);
(controls as any).addEventListener("update", updateShadows);
return () => {
(controls as any).removeEventListener('update', updateShadows);
(controls as any).removeEventListener("update", updateShadows);
};
}
}, [controls, elevation, azimuth, shadows]);
@@ -75,10 +89,24 @@ export default function Shadows() {
shadow-normalBias={CONSTANTS.shadowConfig.shadownormalBias}
/>
<object3D ref={targetRef} />
<mesh position={CONSTANTS.shadowConfig.shadowMaterialPosition} rotation={CONSTANTS.shadowConfig.shadowMaterialRotation} receiveShadow>
<planeGeometry args={[CONSTANTS.planeConfig.width, CONSTANTS.planeConfig.height]} />
<shadowMaterial opacity={CONSTANTS.shadowConfig.shadowMaterialOpacity} transparent />
<mesh
position={CONSTANTS.shadowConfig.shadowMaterialPosition}
rotation={CONSTANTS.shadowConfig.shadowMaterialRotation}
receiveShadow
>
{/* <planeGeometry
args={[CONSTANTS.planeConfig.width, CONSTANTS.planeConfig.height]}
/>
<shadowMaterial
opacity={CONSTANTS.shadowConfig.shadowMaterialOpacity}
transparent
/> */}
<planeGeometry args={[planeValue.width, planeValue.height]} />
<shadowMaterial
opacity={CONSTANTS.shadowConfig.shadowMaterialOpacity}
transparent
/>
</mesh>
</>
);
}
}

View File

@@ -30,6 +30,8 @@ import {
useWalls,
useToolMode,
useRefTextUpdate,
useRenderDistance,
useLimitDistance,
} from "../../../store/store";
////////// 3D Function Imports //////////
@@ -117,6 +119,8 @@ export default function World() {
const { roofVisibility, setRoofVisibility } = useRoofVisibility();
const { wallVisibility, setWallVisibility } = useWallVisibility();
const { shadows, setShadows } = useShadows();
const { renderDistance, setRenderDistance } = useRenderDistance();
const { limitDistance, setLimitDistance } = useLimitDistance();
const { updateScene, setUpdateScene } = useUpdateScene();
const { walls, setWalls } = useWalls();
const { refTextupdate, setRefTextUpdate } = useRefTextUpdate();
@@ -200,6 +204,8 @@ export default function World() {
setRoofVisibility(visibility.roofVisibility);
setWallVisibility(visibility.wallVisibility);
setShadows(visibility.shadowVisibility);
setRenderDistance(visibility.renderDistance);
setLimitDistance(visibility.limitDistance);
}
}
fetchVisibility();

View File

@@ -12,14 +12,15 @@ function Behaviour() {
floorItems.forEach((item: Types.FloorItemType) => {
if (item.modelfileID === "672a090f80d91ac979f4d0bd") {
console.log('item: ', item);
const point1Position = new THREE.Vector3(0, 0.85, 2.2);
const middlePointPosition = new THREE.Vector3(0, 0.85, 0);
const point2Position = new THREE.Vector3(0, 0.85, -2.2);
const point1UUID = THREE.MathUtils.generateUUID();
const middlePointUUID = THREE.MathUtils.generateUUID();
const point2UUID = THREE.MathUtils.generateUUID();
const newPath: Types.ConveyorEventsSchema = {
modeluuid: item.modeluuid,
modelName: item.modelname,
@@ -29,7 +30,7 @@ function Behaviour() {
uuid: point1UUID,
position: [point1Position.x, point1Position.y, point1Position.z],
rotation: [0, 0, 0],
actions: [{ uuid: THREE.MathUtils.generateUUID(), name: 'Action 1', type: 'Inherit', material: 'Inherit', delay: 'Inherit', spawnInterval: 'Inherit', isUsed: false }],
actions: [{ uuid: THREE.MathUtils.generateUUID(), name: 'Action 1', type: 'Inherit', material: 'Inherit', delay: 'Inherit', spawnInterval: 'Inherit', isUsed: true }],
triggers: [],
connections: { source: { pathUUID: item.modeluuid, pointUUID: point1UUID }, targets: [] },
},
@@ -37,7 +38,7 @@ function Behaviour() {
uuid: middlePointUUID,
position: [middlePointPosition.x, middlePointPosition.y, middlePointPosition.z],
rotation: [0, 0, 0],
actions: [{ uuid: THREE.MathUtils.generateUUID(), name: 'Action 1', type: 'Inherit', material: 'Inherit', delay: 'Inherit', spawnInterval: 'Inherit', isUsed: false }],
actions: [{ uuid: THREE.MathUtils.generateUUID(), name: 'Action 1', type: 'Inherit', material: 'Inherit', delay: 'Inherit', spawnInterval: 'Inherit', isUsed: true }],
triggers: [],
connections: { source: { pathUUID: item.modeluuid, pointUUID: middlePointUUID }, targets: [] },
},
@@ -45,13 +46,13 @@ function Behaviour() {
uuid: point2UUID,
position: [point2Position.x, point2Position.y, point2Position.z],
rotation: [0, 0, 0],
actions: [{ uuid: THREE.MathUtils.generateUUID(), name: 'Action 1', type: 'Inherit', material: 'Inherit', delay: 'Inherit', spawnInterval: 'Inherit', isUsed: false }],
actions: [{ uuid: THREE.MathUtils.generateUUID(), name: 'Action 1', type: 'Inherit', material: 'Inherit', delay: 'Inherit', spawnInterval: 'Inherit', isUsed: true }],
triggers: [],
connections: { source: { pathUUID: item.modeluuid, pointUUID: point2UUID }, targets: [] },
},
],
assetPosition: [...item.position],
assetRotation: [item.rotation.x, item.rotation.y, item.rotation.z],
position: [...item.position],
rotation: [item.rotation.x, item.rotation.y, item.rotation.z],
speed: 'Inherit',
};
@@ -71,7 +72,7 @@ function Behaviour() {
connections: { source: { pathUUID: item.modeluuid, pointUUID: pointUUID }, targets: [] },
speed: 2,
},
assetPosition: [...item.position],
position: [...item.position],
};
newPaths.push(newVehiclePath);

View File

@@ -171,8 +171,8 @@ function PathCreation({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObject
name={`${path.modeluuid}-event-path`}
key={path.modeluuid}
ref={el => (groupRefs.current[path.modeluuid] = el!)}
position={path.assetPosition}
rotation={path.assetRotation}
position={path.position}
rotation={path.rotation}
onClick={(e) => {
if (isConnecting || eyeDropMode) return;
e.stopPropagation();
@@ -237,7 +237,7 @@ function PathCreation({ pathsGroupRef }: { pathsGroupRef: React.MutableRefObject
name={`${path.modeluuid}-vehicle-path`}
key={path.modeluuid}
ref={el => (groupRefs.current[path.modeluuid] = el!)}
position={path.assetPosition}
position={path.position}
onClick={(e) => {
if (isConnecting || eyeDropMode) return;
e.stopPropagation();

View File

@@ -0,0 +1,416 @@
import React, { useRef, useState, useEffect, useMemo } from "react";
import { usePlayButtonStore } from "../../../store/usePlayButtonStore";
import { GLTFLoader } from "three-stdlib";
import { useLoader, useFrame } from "@react-three/fiber";
import * as THREE from "three";
import { GLTF } from "three-stdlib";
import boxGltb from "../../../assets/gltf-glb/crate_box.glb";
interface PointAction {
uuid: string;
name: string;
type: "Inherit" | "Spawn" | "Despawn" | "Delay" | "Swap";
material: string;
delay: string | number;
spawnInterval: string | number;
isUsed: boolean;
}
interface ProcessPoint {
uuid: string;
position: number[];
rotation: number[];
actions: PointAction[];
connections: {
source: { pathUUID: string; pointUUID: string };
targets: { pathUUID: string; pointUUID: string }[];
};
}
interface ProcessPath {
modeluuid: string;
modelName: string;
points: ProcessPoint[];
pathPosition: number[];
pathRotation: number[];
speed: number;
}
interface ProcessData {
id: string;
paths: ProcessPath[];
animationPath: { x: number; y: number; z: number }[];
pointActions: PointAction[][];
speed: number;
}
interface AnimationState {
currentIndex: number;
progress: number;
isAnimating: boolean;
speed: number;
isDelaying: boolean;
delayStartTime: number;
currentDelayDuration: number;
delayComplete: boolean;
currentPathIndex: number;
spawnPoints: Record<
string,
{
position: THREE.Vector3;
interval: number;
lastSpawnTime: number;
}
>;
}
const MAX_SPAWNED_OBJECTS = 20;
const ProcessAnimator: React.FC<{ processes: ProcessData[] }> = ({
processes,
}) => {
console.log("processes: ", processes);
const gltf = useLoader(GLTFLoader, boxGltb) as GLTF;
const { isPlaying, setIsPlaying } = usePlayButtonStore();
const groupRef = useRef<THREE.Group>(null);
const meshRef = useRef<THREE.Mesh>(null);
const [visible, setVisible] = useState(false);
const spawnedObjectsRef = useRef<THREE.Object3D[]>([]);
const materials = useMemo(
() => ({
Wood: new THREE.MeshStandardMaterial({ color: 0x8b4513 }),
Box: new THREE.MeshStandardMaterial({
color: 0xcccccc,
metalness: 0.8,
roughness: 0.2,
}),
Crate: new THREE.MeshStandardMaterial({
color: 0x00aaff,
metalness: 0.1,
roughness: 0.5,
}),
Default: new THREE.MeshStandardMaterial({ color: 0x00ff00 }),
}),
[]
);
const [currentMaterial, setCurrentMaterial] = useState<THREE.Material>(
materials.Default
);
const { animationPath, currentProcess } = useMemo(() => {
const defaultProcess = {
animationPath: [],
pointActions: [],
speed: 1,
paths: [],
};
const cp = processes?.[0] || defaultProcess;
return {
animationPath:
cp.animationPath?.map((p) => new THREE.Vector3(p.x, p.y, p.z)) || [],
currentProcess: cp,
};
}, [processes]);
const animationStateRef = useRef<AnimationState>({
currentIndex: 0,
progress: 0,
isAnimating: false,
speed: currentProcess.speed,
isDelaying: false,
delayStartTime: 0,
currentDelayDuration: 0,
delayComplete: false,
currentPathIndex: 0,
spawnPoints: {},
});
const getPointDataForAnimationIndex = (index: number) => {
if (!processes[0]?.paths) return null;
if (index < 3) {
return processes[0].paths[0]?.points[index];
} else {
const path2Index = index - 3;
return processes[0].paths[1]?.points[path2Index];
}
};
useEffect(() => {
if (isPlaying) {
setVisible(true);
animationStateRef.current = {
currentIndex: 0,
progress: 0,
isAnimating: true,
speed: currentProcess.speed,
isDelaying: false,
delayStartTime: 0,
currentDelayDuration: 0,
delayComplete: false,
currentPathIndex: 0,
spawnPoints: {},
};
// Clear spawned objects
if (groupRef.current) {
spawnedObjectsRef.current.forEach((obj) => {
if (groupRef.current?.children.includes(obj)) {
groupRef.current.remove(obj);
}
if (obj instanceof THREE.Mesh) {
obj.material.dispose();
}
});
spawnedObjectsRef.current = [];
}
const currentRef = gltf?.scene ? groupRef.current : meshRef.current;
if (currentRef && animationPath.length > 0) {
currentRef.position.copy(animationPath[0]);
}
} else {
animationStateRef.current.isAnimating = false;
}
}, [isPlaying, currentProcess, animationPath]);
const handleMaterialSwap = (materialType: string) => {
const newMaterial =
materials[materialType as keyof typeof materials] || materials.Default;
setCurrentMaterial(newMaterial);
spawnedObjectsRef.current.forEach((obj) => {
if (obj instanceof THREE.Mesh) {
obj.material = newMaterial.clone();
}
});
};
const hasNonInheritActions = (actions: PointAction[] = []) => {
return actions.some((action) => action.isUsed && action.type !== "Inherit");
};
const handlePointActions = (
actions: PointAction[] = [],
currentTime: number,
currentPosition: THREE.Vector3
) => {
let shouldStopAnimation = false;
actions.forEach((action) => {
if (!action.isUsed) return;
switch (action.type) {
case "Delay":
if (
!animationStateRef.current.isDelaying &&
!animationStateRef.current.delayComplete
) {
const delayDuration =
typeof action.delay === "number"
? action.delay
: parseFloat(action.delay as string) || 0;
if (delayDuration > 0) {
animationStateRef.current.isDelaying = true;
animationStateRef.current.delayStartTime = currentTime;
animationStateRef.current.currentDelayDuration = delayDuration;
shouldStopAnimation = true;
}
}
break;
case "Despawn":
setVisible(false);
setIsPlaying(false);
animationStateRef.current.isAnimating = false;
shouldStopAnimation = true;
break;
case "Spawn":
const spawnInterval =
typeof action.spawnInterval === "number"
? action.spawnInterval
: parseFloat(action.spawnInterval as string) || 1;
const positionKey = currentPosition.toArray().join(",");
animationStateRef.current.spawnPoints[positionKey] = {
position: currentPosition.clone(),
interval: spawnInterval,
lastSpawnTime: currentTime - spawnInterval, // Force immediate spawn
};
break;
case "Swap":
if (action.material) {
handleMaterialSwap(action.material);
}
break;
case "Inherit":
break;
}
});
return shouldStopAnimation;
};
useFrame((state, delta) => {
const currentRef = gltf?.scene ? groupRef.current : meshRef.current;
if (
!currentRef ||
!animationStateRef.current.isAnimating ||
animationPath.length < 2
) {
return;
}
const currentTime = state.clock.getElapsedTime();
const path = animationPath;
const stateRef = animationStateRef.current;
if (stateRef.currentIndex === 3 && stateRef.currentPathIndex === 0) {
stateRef.currentPathIndex = 1;
}
const currentPointData = getPointDataForAnimationIndex(
stateRef.currentIndex
);
if (stateRef.progress === 0 && currentPointData?.actions) {
const shouldStop = handlePointActions(
currentPointData.actions,
currentTime,
currentRef.position
);
if (shouldStop) return;
}
if (stateRef.isDelaying) {
if (
currentTime - stateRef.delayStartTime >=
stateRef.currentDelayDuration
) {
stateRef.isDelaying = false;
stateRef.delayComplete = true;
} else {
return;
}
}
// Handle spawning - this is the key updated part
Object.entries(stateRef.spawnPoints).forEach(([key, spawnPoint]) => {
if (currentTime - spawnPoint.lastSpawnTime >= spawnPoint.interval) {
spawnPoint.lastSpawnTime = currentTime;
if (gltf?.scene && groupRef?.current) {
const newObject = gltf.scene.clone();
newObject.position.copy(spawnPoint.position);
newObject.traverse((child) => {
if (child instanceof THREE.Mesh) {
child.material = currentMaterial.clone();
}
});
groupRef.current.add(newObject);
spawnedObjectsRef.current.push(newObject);
// Clean up old objects if needed
console.log(
"spawnedObjectsRef.current.length: ",
spawnedObjectsRef.current.length
);
if (spawnedObjectsRef.current.length > MAX_SPAWNED_OBJECTS) {
const oldest = spawnedObjectsRef.current.shift();
if (oldest && groupRef.current.children.includes(oldest)) {
groupRef.current.remove(oldest);
if (oldest instanceof THREE.Mesh) {
oldest.material.dispose();
}
}
}
}
}
});
const nextPointIdx = stateRef.currentIndex + 1;
const isLastPoint = nextPointIdx >= path.length;
if (isLastPoint) {
if (currentPointData?.actions) {
const shouldStop = !hasNonInheritActions(currentPointData.actions);
if (shouldStop) {
currentRef.position.copy(path[stateRef.currentIndex]);
setIsPlaying(false);
stateRef.isAnimating = false;
return;
}
}
}
if (!isLastPoint) {
const nextPoint = path[nextPointIdx];
const distance = path[stateRef.currentIndex].distanceTo(nextPoint);
const movement = stateRef.speed * delta;
stateRef.progress += movement / distance;
if (stateRef.progress >= 1) {
stateRef.currentIndex = nextPointIdx;
stateRef.progress = 0;
stateRef.delayComplete = false;
currentRef.position.copy(nextPoint);
} else {
currentRef.position.lerpVectors(
path[stateRef.currentIndex],
nextPoint,
stateRef.progress
);
}
}
});
useEffect(() => {
return () => {
if (groupRef.current) {
spawnedObjectsRef.current.forEach((obj) => {
if (groupRef.current?.children.includes(obj)) {
groupRef.current.remove(obj);
}
if (obj instanceof THREE.Mesh) {
obj.material.dispose();
}
});
spawnedObjectsRef.current = [];
}
};
}, []);
if (!processes || processes.length === 0) {
return null;
}
if (!gltf?.scene) {
return visible ? (
<mesh ref={meshRef} material={currentMaterial}>
<boxGeometry args={[1, 1, 1]} />
</mesh>
) : null;
}
return visible ? (
<group ref={groupRef}>
<primitive
object={gltf.scene.clone()}
scale={[1, 1, 1]}
material={currentMaterial}
/>
</group>
) : null;
};
export default ProcessAnimator;

View File

@@ -0,0 +1,17 @@
import React, { useState } from "react";
import ProcessCreator from "./processCreator";
import ProcessAnimator from "./processAnimator";
const ProcessContainer: React.FC = () => {
const [processes, setProcesses] = useState<any[]>([]);
return (
<>
<ProcessCreator onProcessesCreated={setProcesses} />
{processes.length > 0 && <ProcessAnimator processes={processes} />}
</>
);
};
export default ProcessContainer;

View File

@@ -0,0 +1,398 @@
import React, {
useEffect,
useMemo,
useState,
useCallback,
useRef,
} from "react";
import { useSimulationPaths } from "../../../store/store";
import * as THREE from "three";
import { useThree } from "@react-three/fiber";
import {
ConveyorEventsSchema,
VehicleEventsSchema,
} from "../../../types/world/worldTypes";
// Type definitions
export interface PointAction {
uuid: string;
name: string;
type: string;
material: string;
delay: number | string;
spawnInterval: string | number;
isUsed: boolean;
}
export interface PathPoint {
uuid: string;
position: [number, number, number];
actions: PointAction[];
connections: {
targets: Array<{ pathUUID: string }>;
};
}
export interface SimulationPath {
modeluuid: string;
points: PathPoint[];
pathPosition: [number, number, number];
speed?: number;
}
export interface Process {
id: string;
paths: SimulationPath[];
animationPath: THREE.Vector3[];
pointActions: PointAction[][];
speed: number;
}
interface ProcessCreatorProps {
onProcessesCreated: (processes: Process[]) => void;
}
// Convert event schemas to SimulationPath
function convertToSimulationPath(
path: ConveyorEventsSchema | VehicleEventsSchema
): SimulationPath {
const { modeluuid } = path;
// Simplified normalizeAction function that preserves exact original properties
const normalizeAction = (action: any): PointAction => {
return { ...action }; // Return exact copy with no modifications
};
if (path.type === "Conveyor") {
return {
modeluuid,
points: path.points.map((point) => ({
uuid: point.uuid,
position: point.position,
actions: point.actions.map(normalizeAction), // Preserve exact actions
connections: {
targets: point.connections.targets.map((target) => ({
pathUUID: target.pathUUID,
})),
},
})),
pathPosition: path.position,
speed:
typeof path.speed === "string"
? parseFloat(path.speed) || 1
: path.speed || 1,
};
} else {
return {
modeluuid,
points: [
{
uuid: path.point.uuid,
position: path.point.position,
actions: Array.isArray(path.point.actions)
? path.point.actions.map(normalizeAction)
: [normalizeAction(path.point.actions)],
connections: {
targets: path.point.connections.targets.map((target) => ({
pathUUID: target.pathUUID,
})),
},
},
],
pathPosition: path.position,
speed: path.point.speed || 1,
};
}
}
// Custom shallow comparison for arrays
const areArraysEqual = (a: any[], b: any[]) => {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
};
// Helper function to create an empty process
const createEmptyProcess = (): Process => ({
id: `process-${Math.random().toString(36).substring(2, 11)}`,
paths: [],
animationPath: [],
pointActions: [],
speed: 1,
});
// Enhanced connection checking function
function shouldReverseNextPath(
currentPath: SimulationPath,
nextPath: SimulationPath
): boolean {
if (nextPath.points.length !== 3) return false;
const currentLastPoint = currentPath.points[currentPath.points.length - 1];
const nextFirstPoint = nextPath.points[0];
const nextLastPoint = nextPath.points[nextPath.points.length - 1];
// Check if current last connects to next last (requires reversal)
const connectsToLast = currentLastPoint.connections.targets.some(
(target) =>
target.pathUUID === nextPath.modeluuid &&
nextLastPoint.connections.targets.some(
(t) => t.pathUUID === currentPath.modeluuid
)
);
// Check if current last connects to next first (no reversal needed)
const connectsToFirst = currentLastPoint.connections.targets.some(
(target) =>
target.pathUUID === nextPath.modeluuid &&
nextFirstPoint.connections.targets.some(
(t) => t.pathUUID === currentPath.modeluuid
)
);
// Only reverse if connected to last point and not to first point
return connectsToLast && !connectsToFirst;
}
// Updated path adjustment function
function adjustPathPointsOrder(paths: SimulationPath[]): SimulationPath[] {
if (paths.length < 2) return paths;
const adjustedPaths = [...paths];
for (let i = 0; i < adjustedPaths.length - 1; i++) {
const currentPath = adjustedPaths[i];
const nextPath = adjustedPaths[i + 1];
if (shouldReverseNextPath(currentPath, nextPath)) {
const reversedPoints = [
nextPath.points[2],
nextPath.points[1],
nextPath.points[0],
];
adjustedPaths[i + 1] = {
...nextPath,
points: reversedPoints,
};
}
}
return adjustedPaths;
}
// Main hook for process creation
export function useProcessCreation() {
const { scene } = useThree();
const [processes, setProcesses] = useState<Process[]>([]);
const hasSpawnAction = useCallback((path: SimulationPath): boolean => {
return path.points.some((point) =>
point.actions.some((action) => action.type.toLowerCase() === "spawn")
);
}, []);
const createProcess = useCallback(
(paths: SimulationPath[]): Process => {
if (!paths || paths.length === 0) {
return createEmptyProcess();
}
const animationPath: THREE.Vector3[] = [];
const pointActions: PointAction[][] = [];
const processSpeed = paths[0]?.speed || 1;
for (const path of paths) {
for (const point of path.points) {
const obj = scene.getObjectByProperty("uuid", point.uuid);
if (!obj) {
console.warn(`Object with UUID ${point.uuid} not found in scene`);
continue;
}
const position = obj.getWorldPosition(new THREE.Vector3());
animationPath.push(position.clone());
pointActions.push(point.actions);
}
}
return {
id: `process-${Math.random().toString(36).substring(2, 11)}`,
paths,
animationPath,
pointActions,
speed: processSpeed,
};
},
[scene]
);
const getAllConnectedPaths = useCallback(
(
initialPath: SimulationPath,
allPaths: SimulationPath[],
visited: Set<string> = new Set()
): SimulationPath[] => {
const connectedPaths: SimulationPath[] = [];
const queue: SimulationPath[] = [initialPath];
visited.add(initialPath.modeluuid);
const pathMap = new Map<string, SimulationPath>();
allPaths.forEach((path) => pathMap.set(path.modeluuid, path));
while (queue.length > 0) {
const currentPath = queue.shift()!;
connectedPaths.push(currentPath);
// Process outgoing connections
for (const point of currentPath.points) {
for (const target of point.connections.targets) {
if (!visited.has(target.pathUUID)) {
const targetPath = pathMap.get(target.pathUUID);
if (targetPath) {
visited.add(target.pathUUID);
queue.push(targetPath);
}
}
}
}
// Process incoming connections
for (const [uuid, path] of pathMap) {
if (!visited.has(uuid)) {
const hasConnectionToCurrent = path.points.some((point) =>
point.connections.targets.some(
(t) => t.pathUUID === currentPath.modeluuid
)
);
if (hasConnectionToCurrent) {
visited.add(uuid);
queue.push(path);
}
}
}
}
return connectedPaths;
},
[]
);
const createProcessesFromPaths = useCallback(
(paths: SimulationPath[]): Process[] => {
if (!paths || paths.length === 0) return [];
const visited = new Set<string>();
const processes: Process[] = [];
const pathMap = new Map<string, SimulationPath>();
paths.forEach((path) => pathMap.set(path.modeluuid, path));
for (const path of paths) {
if (!visited.has(path.modeluuid) && hasSpawnAction(path)) {
const connectedPaths = getAllConnectedPaths(path, paths, visited);
const adjustedPaths = adjustPathPointsOrder(connectedPaths);
const process = createProcess(adjustedPaths);
processes.push(process);
}
}
return processes;
},
[createProcess, getAllConnectedPaths, hasSpawnAction]
);
return {
processes,
createProcessesFromPaths,
setProcesses,
};
}
const ProcessCreator: React.FC<ProcessCreatorProps> = React.memo(
({ onProcessesCreated }) => {
const { simulationPaths } = useSimulationPaths();
const { createProcessesFromPaths } = useProcessCreation();
const prevPathsRef = useRef<SimulationPath[]>([]);
const prevProcessesRef = useRef<Process[]>([]);
const convertedPaths = useMemo((): SimulationPath[] => {
if (!simulationPaths) return [];
return simulationPaths.map((path) =>
convertToSimulationPath(
path as ConveyorEventsSchema | VehicleEventsSchema
)
);
}, [simulationPaths]);
const pathsDependency = useMemo(() => {
if (!convertedPaths) return null;
return convertedPaths.map((path) => ({
id: path.modeluuid,
hasSpawn: path.points.some((p: PathPoint) =>
p.actions.some((a: PointAction) => a.type.toLowerCase() === "spawn")
),
connections: path.points
.flatMap((p: PathPoint) =>
p.connections.targets.map((t: { pathUUID: string }) => t.pathUUID)
)
.join(","),
}));
}, [convertedPaths]);
useEffect(() => {
if (!convertedPaths || convertedPaths.length === 0) {
if (prevProcessesRef.current.length > 0) {
onProcessesCreated([]);
prevProcessesRef.current = [];
}
return;
}
if (areArraysEqual(prevPathsRef.current, convertedPaths)) {
return;
}
prevPathsRef.current = convertedPaths;
const newProcesses = createProcessesFromPaths(convertedPaths);
// console.log("--- Action Types in Paths ---");
// convertedPaths.forEach((path) => {
// path.points.forEach((point) => {
// point.actions.forEach((action) => {
// console.log(
// `Path ${path.modeluuid}, Point ${point.uuid}: ${action.type}`
// );
// });
// });
// });
// console.log("New processes:", newProcesses);
if (
newProcesses.length !== prevProcessesRef.current.length ||
!newProcesses.every(
(proc, i) =>
proc.paths.length === prevProcessesRef.current[i]?.paths.length &&
proc.paths.every(
(path, j) =>
path.modeluuid ===
prevProcessesRef.current[i]?.paths[j]?.modeluuid
)
)
) {
onProcessesCreated(newProcesses);
// prevProcessesRef.current = newProcesses;
}
}, [
pathsDependency,
onProcessesCreated,
convertedPaths,
createProcessesFromPaths,
]);
return null;
}
);
export default ProcessCreator;

View File

@@ -5,6 +5,7 @@ import Behaviour from './behaviour/behaviour';
import PathCreation from './path/pathCreation';
import PathConnector from './path/pathConnector';
import useModuleStore from '../../store/useModuleStore';
import ProcessContainer from './process/processContainer';
function Simulation() {
const { activeModule } = useModuleStore();
@@ -13,6 +14,7 @@ function Simulation() {
const [processes, setProcesses] = useState([]);
useEffect(() => {
// console.log('simulationPaths: ', simulationPaths);
}, [simulationPaths]);
// useEffect(() => {
@@ -35,6 +37,7 @@ function Simulation() {
<>
<PathCreation pathsGroupRef={pathsGroupRef} />
<PathConnector pathsGroupRef={pathsGroupRef} />
<ProcessContainer />
</>
)}
</>