Merge remote-tracking branch 'origin/simulation-animation' into simulation
This commit is contained in:
commit
5e97b333dc
|
@ -14,12 +14,14 @@ import {
|
|||
} from "../../../store/store";
|
||||
import { useFrame, useThree } from "@react-three/fiber";
|
||||
import { useSubModuleStore } from "../../../store/useModuleStore";
|
||||
import { usePlayButtonStore } from "../../../store/usePlayButtonStore";
|
||||
|
||||
function PathCreation({
|
||||
pathsGroupRef,
|
||||
}: {
|
||||
pathsGroupRef: React.MutableRefObject<THREE.Group>;
|
||||
}) {
|
||||
const { isPlaying } = usePlayButtonStore();
|
||||
const { renderDistance } = useRenderDistance();
|
||||
const { setSubModule } = useSubModuleStore();
|
||||
const { setSelectedActionSphere, selectedActionSphere } =
|
||||
|
@ -66,7 +68,7 @@ function PathCreation({
|
|||
const distance = new THREE.Vector3(
|
||||
...group.position.toArray()
|
||||
).distanceTo(camera.position);
|
||||
group.visible = distance <= renderDistance;
|
||||
group.visible = ((distance <= renderDistance) && !isPlaying);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
@ -193,7 +195,7 @@ function PathCreation({
|
|||
};
|
||||
|
||||
return (
|
||||
<group name="simulation-simulationPaths-group" ref={pathsGroupRef}>
|
||||
<group visible={!isPlaying} name="simulation-simulationPaths-group" ref={pathsGroupRef}>
|
||||
{simulationPaths.map((path) => {
|
||||
if (path.type === "Conveyor") {
|
||||
const points = path.points.map(
|
||||
|
|
|
@ -0,0 +1,916 @@
|
|||
// // animation-worker.js
|
||||
// // This web worker handles animation calculations off the main thread
|
||||
|
||||
// /* eslint-disable no-restricted-globals */
|
||||
// // The above disables the ESLint rule for this file since 'self' is valid in web workers
|
||||
|
||||
// // Store process data, animation states, and objects
|
||||
// let processes = [];
|
||||
// let animationStates = {};
|
||||
// let lastTimestamp = 0;
|
||||
|
||||
// // Message handler for communication with main thread
|
||||
// self.onmessage = function (event) {
|
||||
// const { type, data } = event.data;
|
||||
|
||||
// switch (type) {
|
||||
// case "initialize":
|
||||
// processes = data.processes;
|
||||
// initializeAnimationStates();
|
||||
// break;
|
||||
|
||||
// case "update":
|
||||
// const { timestamp, isPlaying } = data;
|
||||
// if (isPlaying) {
|
||||
// const delta = (timestamp - lastTimestamp) / 1000; // Convert to seconds
|
||||
// updateAnimations(delta, timestamp);
|
||||
// }
|
||||
// lastTimestamp = timestamp;
|
||||
// break;
|
||||
|
||||
// case "reset":
|
||||
// resetAnimations();
|
||||
// break;
|
||||
|
||||
// case "togglePlay":
|
||||
// // If resuming from pause, recalculate the time delta
|
||||
// lastTimestamp = data.timestamp;
|
||||
// break;
|
||||
// }
|
||||
// };
|
||||
|
||||
// // Initialize animation states for all processes
|
||||
// function initializeAnimationStates() {
|
||||
// animationStates = {};
|
||||
|
||||
// processes.forEach((process) => {
|
||||
// animationStates[process.id] = {
|
||||
// spawnedObjects: {},
|
||||
// nextSpawnTime: 0,
|
||||
// objectIdCounter: 0,
|
||||
// };
|
||||
// });
|
||||
|
||||
// // Send initial states back to main thread
|
||||
// self.postMessage({
|
||||
// type: "statesInitialized",
|
||||
// data: { animationStates },
|
||||
// });
|
||||
// }
|
||||
|
||||
// // Reset all animations
|
||||
// function resetAnimations() {
|
||||
// initializeAnimationStates();
|
||||
// }
|
||||
|
||||
// // Find spawn point in a process
|
||||
// function findSpawnPoint(process) {
|
||||
// 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, path };
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return null;
|
||||
// }
|
||||
|
||||
// // Create a new spawned object with proper initial position
|
||||
// function createSpawnedObject(process, spawnPoint, currentTime, materialType) {
|
||||
// // Extract spawn position from the actual spawn point
|
||||
// const position = spawnPoint.point.position
|
||||
// ? [...spawnPoint.point.position]
|
||||
// : [0, 0, 0];
|
||||
|
||||
// // Get the path position and add it to the spawn point position
|
||||
// const pathPosition = spawnPoint.path.pathPosition || [0, 0, 0];
|
||||
// const absolutePosition = [
|
||||
// position[0] + pathPosition[0],
|
||||
// position[1] + pathPosition[1],
|
||||
// position[2] + pathPosition[2],
|
||||
// ];
|
||||
|
||||
// return {
|
||||
// id: `obj-${process.id}-${animationStates[process.id].objectIdCounter}`,
|
||||
// position: absolutePosition,
|
||||
// state: {
|
||||
// currentIndex: 0,
|
||||
// progress: 0,
|
||||
// isAnimating: true,
|
||||
// speed: process.speed || 1,
|
||||
// isDelaying: false,
|
||||
// delayStartTime: 0,
|
||||
// currentDelayDuration: 0,
|
||||
// delayComplete: false,
|
||||
// currentPathIndex: 0,
|
||||
// // Store the spawn point index to start animation from correct path point
|
||||
// spawnPointIndex: getPointIndexInProcess(process, spawnPoint.point),
|
||||
// },
|
||||
// visible: true,
|
||||
// materialType: materialType || "Default",
|
||||
// spawnTime: currentTime,
|
||||
// };
|
||||
// }
|
||||
|
||||
// // Get the index of a point within the process animation path
|
||||
// function getPointIndexInProcess(process, point) {
|
||||
// if (!process.paths) return 0;
|
||||
|
||||
// let cumulativePoints = 0;
|
||||
// for (const path of process.paths) {
|
||||
// for (let i = 0; i < (path.points?.length || 0); i++) {
|
||||
// if (path.points[i].uuid === point.uuid) {
|
||||
// return cumulativePoints + i;
|
||||
// }
|
||||
// }
|
||||
// cumulativePoints += path.points?.length || 0;
|
||||
// }
|
||||
|
||||
// return 0;
|
||||
// }
|
||||
|
||||
// // Get point data for current animation index
|
||||
// function getPointDataForAnimationIndex(process, index) {
|
||||
// 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;
|
||||
// }
|
||||
|
||||
// // Convert process paths to Vector3 format
|
||||
// function getProcessPath(process) {
|
||||
// return process.animationPath?.map((p) => ({ x: p.x, y: p.y, z: p.z })) || [];
|
||||
// }
|
||||
|
||||
// // Handle material swap for an object
|
||||
// function handleMaterialSwap(processId, objectId, materialType) {
|
||||
// const processState = animationStates[processId];
|
||||
// if (!processState || !processState.spawnedObjects[objectId]) return;
|
||||
|
||||
// processState.spawnedObjects[objectId].materialType = materialType;
|
||||
|
||||
// // Notify main thread about material change
|
||||
// self.postMessage({
|
||||
// type: "materialChanged",
|
||||
// data: {
|
||||
// processId,
|
||||
// objectId,
|
||||
// materialType,
|
||||
// },
|
||||
// });
|
||||
// }
|
||||
|
||||
// // Handle point actions for an object
|
||||
// function handlePointActions(processId, objectId, actions = [], currentTime) {
|
||||
// let shouldStopAnimation = false;
|
||||
// const processState = animationStates[processId];
|
||||
|
||||
// if (!processState || !processState.spawnedObjects[objectId]) return false;
|
||||
|
||||
// const objectState = processState.spawnedObjects[objectId];
|
||||
|
||||
// actions.forEach((action) => {
|
||||
// if (!action.isUsed) return;
|
||||
|
||||
// switch (action.type) {
|
||||
// case "Delay":
|
||||
// if (objectState.state.isDelaying) return;
|
||||
|
||||
// const delayDuration =
|
||||
// typeof action.delay === "number"
|
||||
// ? action.delay
|
||||
// : parseFloat(action.delay || "0");
|
||||
|
||||
// if (delayDuration > 0) {
|
||||
// objectState.state.isDelaying = true;
|
||||
// objectState.state.delayStartTime = currentTime;
|
||||
// objectState.state.currentDelayDuration = delayDuration;
|
||||
// objectState.state.delayComplete = false;
|
||||
// shouldStopAnimation = true;
|
||||
// }
|
||||
// break;
|
||||
|
||||
// case "Despawn":
|
||||
// delete processState.spawnedObjects[objectId];
|
||||
// shouldStopAnimation = true;
|
||||
|
||||
// // Notify main thread about despawn
|
||||
// self.postMessage({
|
||||
// type: "objectDespawned",
|
||||
// data: {
|
||||
// processId,
|
||||
// objectId,
|
||||
// },
|
||||
// });
|
||||
// break;
|
||||
|
||||
// case "Swap":
|
||||
// if (action.material) {
|
||||
// handleMaterialSwap(processId, objectId, action.material);
|
||||
// }
|
||||
// break;
|
||||
|
||||
// default:
|
||||
// break;
|
||||
// }
|
||||
// });
|
||||
|
||||
// return shouldStopAnimation;
|
||||
// }
|
||||
|
||||
// // Check if point has non-inherit actions
|
||||
// function hasNonInheritActions(actions = []) {
|
||||
// return actions.some((action) => action.isUsed && action.type !== "Inherit");
|
||||
// }
|
||||
|
||||
// // Calculate vector lerp (linear interpolation)
|
||||
// function lerpVectors(v1, v2, alpha) {
|
||||
// return {
|
||||
// x: v1.x + (v2.x - v1.x) * alpha,
|
||||
// y: v1.y + (v2.y - v1.y) * alpha,
|
||||
// z: v1.z + (v2.z - v1.z) * alpha,
|
||||
// };
|
||||
// }
|
||||
|
||||
// // Calculate vector distance
|
||||
// function distanceBetweenVectors(v1, v2) {
|
||||
// const dx = v2.x - v1.x;
|
||||
// const dy = v2.y - v1.y;
|
||||
// const dz = v2.z - v1.z;
|
||||
// return Math.sqrt(dx * dx + dy * dy + dz * dz);
|
||||
// }
|
||||
|
||||
// // Process spawn logic
|
||||
// function processSpawns(currentTime) {
|
||||
// processes.forEach((process) => {
|
||||
// const processState = animationStates[process.id];
|
||||
// if (!processState) return;
|
||||
|
||||
// const spawnPointData = findSpawnPoint(process);
|
||||
// if (!spawnPointData || !spawnPointData.point.actions) return;
|
||||
|
||||
// const spawnAction = spawnPointData.point.actions.find(
|
||||
// (a) => a.isUsed && a.type === "Spawn"
|
||||
// );
|
||||
// if (!spawnAction) return;
|
||||
|
||||
// const spawnInterval =
|
||||
// typeof spawnAction.spawnInterval === "number"
|
||||
// ? spawnAction.spawnInterval
|
||||
// : parseFloat(spawnAction.spawnInterval || "0");
|
||||
|
||||
// if (currentTime >= processState.nextSpawnTime) {
|
||||
// const newObject = createSpawnedObject(
|
||||
// process,
|
||||
// spawnPointData,
|
||||
// currentTime,
|
||||
// spawnAction.material || "Default"
|
||||
// );
|
||||
|
||||
// processState.spawnedObjects[newObject.id] = newObject;
|
||||
// processState.objectIdCounter++;
|
||||
// processState.nextSpawnTime = currentTime + spawnInterval;
|
||||
|
||||
// // Notify main thread about new object
|
||||
// self.postMessage({
|
||||
// type: "objectSpawned",
|
||||
// data: {
|
||||
// processId: process.id,
|
||||
// object: newObject,
|
||||
// },
|
||||
// });
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
|
||||
// // Update all animations
|
||||
// function updateAnimations(delta, currentTime) {
|
||||
// // First handle spawning of new objects
|
||||
// processSpawns(currentTime);
|
||||
|
||||
// // Then animate existing objects
|
||||
// processes.forEach((process) => {
|
||||
// const processState = animationStates[process.id];
|
||||
// if (!processState) return;
|
||||
|
||||
// const path = getProcessPath(process);
|
||||
// if (path.length < 2) return;
|
||||
|
||||
// const updatedObjects = {};
|
||||
// let hasChanges = false;
|
||||
|
||||
// Object.entries(processState.spawnedObjects).forEach(([objectId, obj]) => {
|
||||
// if (!obj.visible || !obj.state.isAnimating) return;
|
||||
|
||||
// const stateRef = obj.state;
|
||||
|
||||
// // Use the spawnPointIndex as starting point if it's the initial movement
|
||||
// if (stateRef.currentIndex === 0 && stateRef.progress === 0) {
|
||||
// stateRef.currentIndex = stateRef.spawnPointIndex || 0;
|
||||
// }
|
||||
|
||||
// // Get current point data
|
||||
// const currentPointData = getPointDataForAnimationIndex(
|
||||
// process,
|
||||
// stateRef.currentIndex
|
||||
// );
|
||||
|
||||
// // Execute actions when arriving at a new point
|
||||
// if (stateRef.progress === 0 && currentPointData?.actions) {
|
||||
// const shouldStop = handlePointActions(
|
||||
// process.id,
|
||||
// objectId,
|
||||
// currentPointData.actions,
|
||||
// currentTime
|
||||
// );
|
||||
// if (shouldStop) return;
|
||||
// }
|
||||
|
||||
// // Handle delays
|
||||
// if (stateRef.isDelaying) {
|
||||
// if (
|
||||
// currentTime - stateRef.delayStartTime >=
|
||||
// stateRef.currentDelayDuration
|
||||
// ) {
|
||||
// stateRef.isDelaying = false;
|
||||
// stateRef.delayComplete = true;
|
||||
// } else {
|
||||
// updatedObjects[objectId] = { ...obj, state: { ...stateRef } };
|
||||
// return; // Keep waiting
|
||||
// }
|
||||
// }
|
||||
|
||||
// const nextPointIdx = stateRef.currentIndex + 1;
|
||||
// const isLastPoint = nextPointIdx >= path.length;
|
||||
|
||||
// if (isLastPoint) {
|
||||
// if (currentPointData?.actions) {
|
||||
// const shouldStop = !hasNonInheritActions(currentPointData.actions);
|
||||
// if (shouldStop) {
|
||||
// // Reached the end of path with no more actions
|
||||
// delete processState.spawnedObjects[objectId];
|
||||
|
||||
// // Notify main thread to remove the object
|
||||
// self.postMessage({
|
||||
// type: "objectCompleted",
|
||||
// data: {
|
||||
// processId: process.id,
|
||||
// objectId,
|
||||
// },
|
||||
// });
|
||||
// return;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// if (!isLastPoint) {
|
||||
// const currentPos = path[stateRef.currentIndex];
|
||||
// const nextPos = path[nextPointIdx];
|
||||
// const distance = distanceBetweenVectors(currentPos, nextPos);
|
||||
// const movement = stateRef.speed * delta;
|
||||
|
||||
// // Update progress based on distance and speed
|
||||
// const oldProgress = stateRef.progress;
|
||||
// stateRef.progress += movement / distance;
|
||||
|
||||
// if (stateRef.progress >= 1) {
|
||||
// // Reached next point
|
||||
// stateRef.currentIndex = nextPointIdx;
|
||||
// stateRef.progress = 0;
|
||||
// stateRef.delayComplete = false;
|
||||
// obj.position = [nextPos.x, nextPos.y, nextPos.z];
|
||||
// } else {
|
||||
// // Interpolate position
|
||||
// const lerpedPos = lerpVectors(currentPos, nextPos, stateRef.progress);
|
||||
// obj.position = [lerpedPos.x, lerpedPos.y, lerpedPos.z];
|
||||
// }
|
||||
|
||||
// // Only send updates when there's meaningful movement
|
||||
// if (Math.abs(oldProgress - stateRef.progress) > 0.01) {
|
||||
// hasChanges = true;
|
||||
// }
|
||||
// }
|
||||
|
||||
// updatedObjects[objectId] = { ...obj, state: { ...stateRef } };
|
||||
// });
|
||||
|
||||
// // Update animation state with modified objects
|
||||
// if (Object.keys(updatedObjects).length > 0) {
|
||||
// processState.spawnedObjects = {
|
||||
// ...processState.spawnedObjects,
|
||||
// ...updatedObjects,
|
||||
// };
|
||||
|
||||
// // Only send position updates when there are meaningful changes
|
||||
// if (hasChanges) {
|
||||
// self.postMessage({
|
||||
// type: "positionsUpdated",
|
||||
// data: {
|
||||
// processId: process.id,
|
||||
// objects: updatedObjects,
|
||||
// },
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
|
||||
// animation-worker.js
|
||||
// This web worker handles animation calculations off the main thread
|
||||
|
||||
/* eslint-disable no-restricted-globals */
|
||||
// The above disables the ESLint rule for this file since 'self' is valid in web workers
|
||||
|
||||
// Store process data, animation states, and objects
|
||||
let processes = [];
|
||||
let animationStates = {};
|
||||
let lastTimestamp = 0;
|
||||
let debugMode = true;
|
||||
|
||||
// Logger function for debugging
|
||||
function log(...args) {
|
||||
if (debugMode) {
|
||||
self.postMessage({
|
||||
type: "debug",
|
||||
data: { message: args.join(' ') }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Message handler for communication with main thread
|
||||
self.onmessage = function (event) {
|
||||
const { type, data } = event.data;
|
||||
log(`Worker received message: ${type}`);
|
||||
|
||||
switch (type) {
|
||||
case "initialize":
|
||||
processes = data.processes;
|
||||
log(`Initialized with ${processes.length} processes`);
|
||||
initializeAnimationStates();
|
||||
break;
|
||||
|
||||
case "update":
|
||||
const { timestamp, isPlaying } = data;
|
||||
if (isPlaying) {
|
||||
const delta = lastTimestamp === 0 ? 0.016 : (timestamp - lastTimestamp) / 1000; // Convert to seconds
|
||||
updateAnimations(delta, timestamp);
|
||||
}
|
||||
lastTimestamp = timestamp;
|
||||
break;
|
||||
|
||||
case "reset":
|
||||
log("Resetting animations");
|
||||
resetAnimations();
|
||||
break;
|
||||
|
||||
case "togglePlay":
|
||||
// If resuming from pause, recalculate the time delta
|
||||
log(`Toggle play: ${data.isPlaying}`);
|
||||
lastTimestamp = data.timestamp;
|
||||
break;
|
||||
|
||||
case "setDebug":
|
||||
debugMode = data.enabled;
|
||||
log(`Debug mode: ${debugMode}`);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
// Initialize animation states for all processes
|
||||
function initializeAnimationStates() {
|
||||
animationStates = {};
|
||||
|
||||
processes.forEach((process) => {
|
||||
if (!process || !process.id) {
|
||||
log("Invalid process found:", process);
|
||||
return;
|
||||
}
|
||||
|
||||
animationStates[process.id] = {
|
||||
spawnedObjects: {},
|
||||
nextSpawnTime: 0,
|
||||
objectIdCounter: 0,
|
||||
};
|
||||
});
|
||||
|
||||
// Send initial states back to main thread
|
||||
self.postMessage({
|
||||
type: "statesInitialized",
|
||||
data: { animationStates },
|
||||
});
|
||||
}
|
||||
|
||||
// Reset all animations
|
||||
function resetAnimations() {
|
||||
initializeAnimationStates();
|
||||
}
|
||||
|
||||
// Find spawn point in a process
|
||||
function findSpawnPoint(process) {
|
||||
if (!process || !process.paths) {
|
||||
log(`No paths found for process ${process?.id}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const path of process.paths) {
|
||||
if (!path || !path.points) continue;
|
||||
|
||||
for (const point of path.points) {
|
||||
if (!point || !point.actions) continue;
|
||||
|
||||
const spawnAction = point.actions.find(
|
||||
(a) => a && a.isUsed && a.type === "Spawn"
|
||||
);
|
||||
if (spawnAction) {
|
||||
return { point, path };
|
||||
}
|
||||
}
|
||||
}
|
||||
log(`No spawn points found for process ${process.id}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Create a new spawned object with proper initial position
|
||||
function createSpawnedObject(process, spawnPoint, currentTime, materialType) {
|
||||
// Extract spawn position from the actual spawn point
|
||||
const position = spawnPoint.point.position
|
||||
? [...spawnPoint.point.position]
|
||||
: [0, 0, 0];
|
||||
|
||||
// Get the path position and add it to the spawn point position
|
||||
const pathPosition = spawnPoint.path.pathPosition || [0, 0, 0];
|
||||
const absolutePosition = [
|
||||
position[0] + pathPosition[0],
|
||||
position[1] + pathPosition[1],
|
||||
position[2] + pathPosition[2],
|
||||
];
|
||||
|
||||
return {
|
||||
id: `obj-${process.id}-${animationStates[process.id].objectIdCounter}`,
|
||||
position: absolutePosition,
|
||||
state: {
|
||||
currentIndex: 0,
|
||||
progress: 0,
|
||||
isAnimating: true,
|
||||
speed: process.speed || 1,
|
||||
isDelaying: false,
|
||||
delayStartTime: 0,
|
||||
currentDelayDuration: 0,
|
||||
delayComplete: false,
|
||||
currentPathIndex: 0,
|
||||
// Store the spawn point index to start animation from correct path point
|
||||
spawnPointIndex: getPointIndexInProcess(process, spawnPoint.point),
|
||||
},
|
||||
visible: true,
|
||||
materialType: materialType || "Default",
|
||||
spawnTime: currentTime,
|
||||
};
|
||||
}
|
||||
|
||||
// Get the index of a point within the process animation path
|
||||
function getPointIndexInProcess(process, point) {
|
||||
if (!process.paths) return 0;
|
||||
|
||||
let cumulativePoints = 0;
|
||||
for (const path of process.paths) {
|
||||
for (let i = 0; i < (path.points?.length || 0); i++) {
|
||||
if (path.points[i].uuid === point.uuid) {
|
||||
return cumulativePoints + i;
|
||||
}
|
||||
}
|
||||
cumulativePoints += path.points?.length || 0;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Get point data for current animation index
|
||||
function getPointDataForAnimationIndex(process, index) {
|
||||
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;
|
||||
}
|
||||
|
||||
// Convert process paths to Vector3 format
|
||||
function getProcessPath(process) {
|
||||
if (!process.animationPath) {
|
||||
log(`No animation path for process ${process.id}`);
|
||||
return [];
|
||||
}
|
||||
return process.animationPath.map((p) => ({ x: p.x, y: p.y, z: p.z })) || [];
|
||||
}
|
||||
|
||||
// Handle material swap for an object
|
||||
function handleMaterialSwap(processId, objectId, materialType) {
|
||||
const processState = animationStates[processId];
|
||||
if (!processState || !processState.spawnedObjects[objectId]) return;
|
||||
|
||||
processState.spawnedObjects[objectId].materialType = materialType;
|
||||
|
||||
// Notify main thread about material change
|
||||
self.postMessage({
|
||||
type: "materialChanged",
|
||||
data: {
|
||||
processId,
|
||||
objectId,
|
||||
materialType,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Handle point actions for an object
|
||||
function handlePointActions(processId, objectId, actions = [], currentTime) {
|
||||
let shouldStopAnimation = false;
|
||||
const processState = animationStates[processId];
|
||||
|
||||
if (!processState || !processState.spawnedObjects[objectId]) return false;
|
||||
|
||||
const objectState = processState.spawnedObjects[objectId];
|
||||
|
||||
actions.forEach((action) => {
|
||||
if (!action || !action.isUsed) return;
|
||||
|
||||
switch (action.type) {
|
||||
case "Delay":
|
||||
if (objectState.state.isDelaying) return;
|
||||
|
||||
const delayDuration =
|
||||
typeof action.delay === "number"
|
||||
? action.delay
|
||||
: parseFloat(action.delay || "0");
|
||||
|
||||
if (delayDuration > 0) {
|
||||
objectState.state.isDelaying = true;
|
||||
objectState.state.delayStartTime = currentTime;
|
||||
objectState.state.currentDelayDuration = delayDuration;
|
||||
objectState.state.delayComplete = false;
|
||||
shouldStopAnimation = true;
|
||||
}
|
||||
break;
|
||||
|
||||
case "Despawn":
|
||||
delete processState.spawnedObjects[objectId];
|
||||
shouldStopAnimation = true;
|
||||
|
||||
// Notify main thread about despawn
|
||||
self.postMessage({
|
||||
type: "objectDespawned",
|
||||
data: {
|
||||
processId,
|
||||
objectId,
|
||||
},
|
||||
});
|
||||
break;
|
||||
|
||||
case "Swap":
|
||||
if (action.material) {
|
||||
handleMaterialSwap(processId, objectId, action.material);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
return shouldStopAnimation;
|
||||
}
|
||||
|
||||
// Check if point has non-inherit actions
|
||||
function hasNonInheritActions(actions = []) {
|
||||
return actions.some((action) => action && action.isUsed && action.type !== "Inherit");
|
||||
}
|
||||
|
||||
// Calculate vector lerp (linear interpolation)
|
||||
function lerpVectors(v1, v2, alpha) {
|
||||
return {
|
||||
x: v1.x + (v2.x - v1.x) * alpha,
|
||||
y: v1.y + (v2.y - v1.y) * alpha,
|
||||
z: v1.z + (v2.z - v1.z) * alpha,
|
||||
};
|
||||
}
|
||||
|
||||
// Calculate vector distance
|
||||
function distanceBetweenVectors(v1, v2) {
|
||||
const dx = v2.x - v1.x;
|
||||
const dy = v2.y - v1.y;
|
||||
const dz = v2.z - v1.z;
|
||||
return Math.sqrt(dx * dx + dy * dy + dz * dz);
|
||||
}
|
||||
|
||||
// Process spawn logic
|
||||
function processSpawns(currentTime) {
|
||||
processes.forEach((process) => {
|
||||
const processState = animationStates[process.id];
|
||||
if (!processState) return;
|
||||
|
||||
const spawnPointData = findSpawnPoint(process);
|
||||
if (!spawnPointData || !spawnPointData.point.actions) return;
|
||||
|
||||
const spawnAction = spawnPointData.point.actions.find(
|
||||
(a) => a.isUsed && a.type === "Spawn"
|
||||
);
|
||||
if (!spawnAction) return;
|
||||
|
||||
const spawnInterval =
|
||||
typeof spawnAction.spawnInterval === "number"
|
||||
? spawnAction.spawnInterval
|
||||
: parseFloat(spawnAction.spawnInterval || "2"); // Default to 2 seconds if not specified
|
||||
|
||||
if (currentTime >= processState.nextSpawnTime) {
|
||||
const newObject = createSpawnedObject(
|
||||
process,
|
||||
spawnPointData,
|
||||
currentTime,
|
||||
spawnAction.material || "Default"
|
||||
);
|
||||
|
||||
processState.spawnedObjects[newObject.id] = newObject;
|
||||
processState.objectIdCounter++;
|
||||
processState.nextSpawnTime = currentTime + spawnInterval;
|
||||
|
||||
log(`Spawned object ${newObject.id} for process ${process.id}`);
|
||||
|
||||
// Notify main thread about new object
|
||||
self.postMessage({
|
||||
type: "objectSpawned",
|
||||
data: {
|
||||
processId: process.id,
|
||||
object: newObject,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Update all animations
|
||||
function updateAnimations(delta, currentTime) {
|
||||
// First handle spawning of new objects
|
||||
processSpawns(currentTime);
|
||||
|
||||
// Then animate existing objects
|
||||
processes.forEach((process) => {
|
||||
const processState = animationStates[process.id];
|
||||
if (!processState) return;
|
||||
|
||||
const path = getProcessPath(process);
|
||||
if (path.length < 2) {
|
||||
log(`Path too short for process ${process.id}, length: ${path.length}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const updatedObjects = {};
|
||||
let hasChanges = false;
|
||||
|
||||
Object.entries(processState.spawnedObjects).forEach(([objectId, obj]) => {
|
||||
if (!obj.visible || !obj.state.isAnimating) return;
|
||||
|
||||
const stateRef = obj.state;
|
||||
|
||||
// Use the spawnPointIndex as starting point if it's the initial movement
|
||||
if (stateRef.currentIndex === 0 && stateRef.progress === 0) {
|
||||
stateRef.currentIndex = stateRef.spawnPointIndex || 0;
|
||||
}
|
||||
|
||||
// Get current point data
|
||||
const currentPointData = getPointDataForAnimationIndex(
|
||||
process,
|
||||
stateRef.currentIndex
|
||||
);
|
||||
|
||||
// Execute actions when arriving at a new point
|
||||
if (stateRef.progress === 0 && currentPointData?.actions) {
|
||||
const shouldStop = handlePointActions(
|
||||
process.id,
|
||||
objectId,
|
||||
currentPointData.actions,
|
||||
currentTime
|
||||
);
|
||||
if (shouldStop) return;
|
||||
}
|
||||
|
||||
// Handle delays
|
||||
if (stateRef.isDelaying) {
|
||||
if (
|
||||
currentTime - stateRef.delayStartTime >=
|
||||
stateRef.currentDelayDuration
|
||||
) {
|
||||
stateRef.isDelaying = false;
|
||||
stateRef.delayComplete = true;
|
||||
} else {
|
||||
updatedObjects[objectId] = { ...obj, state: { ...stateRef } };
|
||||
return; // Keep waiting
|
||||
}
|
||||
}
|
||||
|
||||
const nextPointIdx = stateRef.currentIndex + 1;
|
||||
const isLastPoint = nextPointIdx >= path.length;
|
||||
|
||||
if (isLastPoint) {
|
||||
if (currentPointData?.actions) {
|
||||
const shouldStop = !hasNonInheritActions(currentPointData.actions);
|
||||
if (shouldStop) {
|
||||
// Reached the end of path with no more actions
|
||||
delete processState.spawnedObjects[objectId];
|
||||
log(`Object ${objectId} completed path`);
|
||||
|
||||
// Notify main thread to remove the object
|
||||
self.postMessage({
|
||||
type: "objectCompleted",
|
||||
data: {
|
||||
processId: process.id,
|
||||
objectId,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!isLastPoint) {
|
||||
const currentPos = path[stateRef.currentIndex];
|
||||
const nextPos = path[nextPointIdx];
|
||||
const distance = distanceBetweenVectors(currentPos, nextPos);
|
||||
|
||||
// Ensure we don't divide by zero
|
||||
if (distance > 0) {
|
||||
const movement = stateRef.speed * delta;
|
||||
|
||||
// Update progress based on distance and speed
|
||||
const oldProgress = stateRef.progress;
|
||||
stateRef.progress += movement / distance;
|
||||
|
||||
if (stateRef.progress >= 1) {
|
||||
// Reached next point
|
||||
stateRef.currentIndex = nextPointIdx;
|
||||
stateRef.progress = 0;
|
||||
stateRef.delayComplete = false;
|
||||
obj.position = [nextPos.x, nextPos.y, nextPos.z];
|
||||
} else {
|
||||
// Interpolate position
|
||||
const lerpedPos = lerpVectors(currentPos, nextPos, stateRef.progress);
|
||||
obj.position = [lerpedPos.x, lerpedPos.y, lerpedPos.z];
|
||||
}
|
||||
|
||||
// Only send updates when there's meaningful movement
|
||||
if (Math.abs(oldProgress - stateRef.progress) > 0.01) {
|
||||
hasChanges = true;
|
||||
}
|
||||
} else {
|
||||
// Skip to next point if distance is zero
|
||||
stateRef.currentIndex = nextPointIdx;
|
||||
stateRef.progress = 0;
|
||||
obj.position = [nextPos.x, nextPos.y, nextPos.z];
|
||||
hasChanges = true;
|
||||
}
|
||||
}
|
||||
|
||||
updatedObjects[objectId] = { ...obj, state: { ...stateRef } };
|
||||
});
|
||||
|
||||
// Update animation state with modified objects
|
||||
if (Object.keys(updatedObjects).length > 0) {
|
||||
processState.spawnedObjects = {
|
||||
...processState.spawnedObjects,
|
||||
...updatedObjects,
|
||||
};
|
||||
|
||||
// Only send position updates when there are meaningful changes
|
||||
if (hasChanges) {
|
||||
self.postMessage({
|
||||
type: "positionsUpdated",
|
||||
data: {
|
||||
processId: process.id,
|
||||
objects: updatedObjects,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
import React from "react";
|
||||
|
||||
const Mesh: React.FC = () => {
|
||||
return <mesh></mesh>;
|
||||
};
|
||||
|
||||
export default Mesh;
|
File diff suppressed because it is too large
Load Diff
|
@ -10,6 +10,7 @@ const ProcessContainer: React.FC = () => {
|
|||
<>
|
||||
<ProcessCreator onProcessesCreated={setProcesses} />
|
||||
{processes.length > 0 && <ProcessAnimator processes={processes} />}
|
||||
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
|
|
@ -1,3 +1,402 @@
|
|||
// 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;
|
||||
|
||||
import React, {
|
||||
useEffect,
|
||||
useMemo,
|
||||
|
@ -156,12 +555,38 @@ function shouldReverseNextPath(
|
|||
return connectsToLast && !connectsToFirst;
|
||||
}
|
||||
|
||||
// Check if a point has a spawn action
|
||||
function hasSpawnAction(point: PathPoint): boolean {
|
||||
return point.actions.some((action) => action.type.toLowerCase() === "spawn");
|
||||
}
|
||||
|
||||
// Ensure spawn point is always at the beginning of the path
|
||||
function ensureSpawnPointIsFirst(path: SimulationPath): SimulationPath {
|
||||
if (path.points.length !== 3) return path;
|
||||
|
||||
// If the third point has spawn action and first doesn't, reverse the array
|
||||
if (hasSpawnAction(path.points[2]) && !hasSpawnAction(path.points[0])) {
|
||||
return {
|
||||
...path,
|
||||
points: [...path.points].reverse(),
|
||||
};
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
// Updated path adjustment function
|
||||
function adjustPathPointsOrder(paths: SimulationPath[]): SimulationPath[] {
|
||||
if (paths.length < 2) return paths;
|
||||
if (paths.length < 1) return paths;
|
||||
|
||||
const adjustedPaths = [...paths];
|
||||
|
||||
// First ensure all paths have spawn points at the beginning
|
||||
for (let i = 0; i < adjustedPaths.length; i++) {
|
||||
adjustedPaths[i] = ensureSpawnPointIsFirst(adjustedPaths[i]);
|
||||
}
|
||||
|
||||
// Then handle connections between paths
|
||||
for (let i = 0; i < adjustedPaths.length - 1; i++) {
|
||||
const currentPath = adjustedPaths[i];
|
||||
const nextPath = adjustedPaths[i + 1];
|
||||
|
@ -326,13 +751,17 @@ const ProcessCreator: React.FC<ProcessCreatorProps> = React.memo(
|
|||
);
|
||||
}, [simulationPaths]);
|
||||
|
||||
// Enhanced dependency tracking that includes action types
|
||||
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")
|
||||
),
|
||||
// Track all action types for each point
|
||||
actionSignature: path.points
|
||||
.map((point, index) =>
|
||||
point.actions.map((action) => `${index}-${action.type}`).join("|")
|
||||
)
|
||||
.join(","),
|
||||
connections: path.points
|
||||
.flatMap((p: PathPoint) =>
|
||||
p.connections.targets.map((t: { pathUUID: string }) => t.pathUUID)
|
||||
|
@ -341,6 +770,7 @@ const ProcessCreator: React.FC<ProcessCreatorProps> = React.memo(
|
|||
}));
|
||||
}, [convertedPaths]);
|
||||
|
||||
// Force process recreation when paths change
|
||||
useEffect(() => {
|
||||
if (!convertedPaths || convertedPaths.length === 0) {
|
||||
if (prevProcessesRef.current.length > 0) {
|
||||
|
@ -350,42 +780,16 @@ const ProcessCreator: React.FC<ProcessCreatorProps> = React.memo(
|
|||
return;
|
||||
}
|
||||
|
||||
if (areArraysEqual(prevPathsRef.current, convertedPaths)) {
|
||||
return;
|
||||
}
|
||||
|
||||
prevPathsRef.current = convertedPaths;
|
||||
// Always regenerate processes if the pathsDependency has changed
|
||||
// This ensures action type changes will be detected
|
||||
const newProcesses = createProcessesFromPaths(convertedPaths);
|
||||
prevPathsRef.current = 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;
|
||||
}
|
||||
// Always update processes when action types change
|
||||
onProcessesCreated(newProcesses);
|
||||
prevProcessesRef.current = newProcesses;
|
||||
}, [
|
||||
pathsDependency,
|
||||
pathsDependency, // This now includes action types
|
||||
onProcessesCreated,
|
||||
convertedPaths,
|
||||
createProcessesFromPaths,
|
||||
|
|
|
@ -19,7 +19,7 @@ function Simulation() {
|
|||
const [processes, setProcesses] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
// console.log('simulationPaths: ', simulationPaths);
|
||||
console.log('simulationPaths: ', simulationPaths);
|
||||
}, [simulationPaths]);
|
||||
|
||||
// useEffect(() => {
|
||||
|
|
Loading…
Reference in New Issue