Files
Dwinzo_Demo/app/src/modules/simulation/vehicle/pathCreator/pointHandler.tsx

529 lines
15 KiB
TypeScript
Raw Normal View History

import { DragControls } from "@react-three/drei";
2025-08-25 16:21:54 +05:30
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useActiveTool, useToolMode } from "../../../../store/builder/store";
import { Plane, Vector3 } from "three";
import { useThree } from "@react-three/fiber";
import { handleCanvasCursors } from "../../../../utils/mouseUtils/handleCanvasCursors";
import { getPathsByPointId, setPathPosition } from "./function/getPaths";
2025-08-25 16:21:54 +05:30
import { aStar } from "../structuredPath/functions/aStar";
type PointData = {
pointId: string;
position: [number, number, number];
isCurved?: boolean;
handleA?: [number, number, number] | null;
handleB?: [number, number, number] | null;
2025-08-26 14:06:25 +05:30
neighbors?: string[];
};
interface PathDataInterface {
pathId: string;
isActive?: boolean;
isCurved?: boolean;
pathPoints: [PointData, PointData];
}
type PathData = PathDataInterface[];
type PointHandlerProps = {
point: PointData;
hoveredPoint: PointData | null;
setPaths: React.Dispatch<React.SetStateAction<PathData>>;
paths: PathDataInterface[];
setHoveredPoint: React.Dispatch<React.SetStateAction<PointData | null>>;
hoveredLine: PathDataInterface | null;
2025-08-26 14:06:25 +05:30
pointIndex: any;
points: PointData[];
};
2025-08-26 14:06:25 +05:30
function dist(a: PointData, b: PointData): number {
return Math.sqrt(
(a.position[0] - b.position[0]) ** 2 +
(a.position[1] - b.position[1]) ** 2 +
(a.position[2] - b.position[2]) ** 2
);
}
/** --- A* Algorithm --- */
type AStarResult = {
pointIds: string[];
distance: number;
};
function aStarShortestPath(
startId: string,
goalId: string,
points: PointData[],
paths: PathData
): AStarResult | null {
const pointById = new Map(points.map((p) => [p.pointId, p]));
const start = pointById.get(startId);
const goal = pointById.get(goalId);
if (!start || !goal) return null;
const openSet = new Set<string>([startId]);
const cameFrom: Record<string, string | null> = {};
const gScore: Record<string, number> = {};
const fScore: Record<string, number> = {};
for (const p of points) {
cameFrom[p.pointId] = null;
gScore[p.pointId] = Infinity;
fScore[p.pointId] = Infinity;
}
gScore[startId] = 0;
fScore[startId] = dist(start, goal);
const neighborsOf = (id: string): { id: string; cost: number }[] => {
const me = pointById.get(id)!;
const out: { id: string; cost: number }[] = [];
for (const edge of paths) {
const [a, b] = edge.pathPoints;
if (a.pointId === id) out.push({ id: b.pointId, cost: dist(me, b) });
else if (b.pointId === id) out.push({ id: a.pointId, cost: dist(me, a) });
}
return out;
};
while (openSet.size > 0) {
let current: string = [...openSet].reduce((a, b) =>
fScore[a] < fScore[b] ? a : b
);
if (current === goalId) {
const ids: string[] = [];
let node: string | null = current;
while (node) {
ids.unshift(node);
node = cameFrom[node];
}
return { pointIds: ids, distance: gScore[goalId] };
}
openSet.delete(current);
for (const nb of neighborsOf(current)) {
const tentativeG = gScore[current] + nb.cost;
if (tentativeG < gScore[nb.id]) {
cameFrom[nb.id] = current;
gScore[nb.id] = tentativeG;
fScore[nb.id] = tentativeG + dist(pointById.get(nb.id)!, goal);
openSet.add(nb.id);
}
}
}
return null;
}
/** --- Convert node path to edges --- */
function nodePathToEdges(
pointIds: string[],
points: PointData[],
paths: PathData
): PathData {
const byId = new Map(points.map((p) => [p.pointId, p]));
const edges: PathData = [];
for (let i = 0; i < pointIds.length - 1; i++) {
const a = pointIds[i];
const b = pointIds[i + 1];
const edge = paths.find(
(p) =>
(p.pathPoints[0].pointId === a && p.pathPoints[1].pointId === b) ||
(p.pathPoints[0].pointId === b && p.pathPoints[1].pointId === a)
);
if (edge) {
const [p1, p2] = edge.pathPoints;
edges.push({
pathId: edge.pathId,
pathPoints:
p1.pointId === a
? ([p1, p2] as [PointData, PointData])
: ([p2, p1] as [PointData, PointData]),
});
} else {
const pa = byId.get(a)!;
const pb = byId.get(b)!;
edges.push({
pathId: `synthetic-${a}-${b}`,
pathPoints: [pa, pb],
});
}
}
return edges;
}
export default function PointHandler({
point,
setPaths,
paths,
setHoveredPoint,
hoveredLine,
hoveredPoint,
2025-08-26 14:06:25 +05:30
pointIndex,
points,
}: PointHandlerProps) {
const { toolMode } = useToolMode();
2025-08-25 16:21:54 +05:30
const { activeTool } = useActiveTool();
const { scene, raycaster } = useThree();
const [isHovered, setIsHovered] = useState(false);
const [dragOffset, setDragOffset] = useState<Vector3 | null>(null);
const plane = useMemo(() => new Plane(new Vector3(0, 1, 0), 0), []);
const [initialPositions, setInitialPositions] = useState<{
paths?: any;
}>({});
2025-08-25 16:21:54 +05:30
const [selectedPoints, setSelectedPoints] = useState<PointData[]>([]);
2025-08-26 14:06:25 +05:30
const [shortestEdges, setShortestEdges] = useState<PathData>([]);
const POINT_SNAP_THRESHOLD = 0.5; // Distance threshold for snapping in meters
2025-08-26 14:06:25 +05:30
const [selectedPointIndices, setSelectedPointIndices] = useState<number[]>(
[]
);
const CAN_POINT_SNAP = true;
const CAN_ANGLE_SNAP = true;
const ANGLE_SNAP_DISTANCE_THRESHOLD = 0.5;
2025-08-25 16:21:54 +05:30
const removePathByPoint = (pointId: string): PathDataInterface[] => {
const removedPaths: PathDataInterface[] = [];
setPaths((prevPaths) =>
prevPaths.filter((path) => {
const hasPoint = path.pathPoints.some((p) => p.pointId === pointId);
if (hasPoint) {
removedPaths.push(JSON.parse(JSON.stringify(path))); // keep a copy
return false; // remove this path
}
return true; // keep this path
})
);
return removedPaths;
};
2025-08-26 14:06:25 +05:30
const getConnectedPoints = (uuid: string): PointData[] => {
const connected: PointData[] = [];
for (const path of paths) {
for (const point of path.pathPoints) {
if (point.pointId === uuid) {
connected.push(
...path.pathPoints.filter((p: PointData) => p.pointId !== uuid)
);
}
}
}
return connected;
};
2025-08-26 14:06:25 +05:30
const snapPathAngle = useCallback(
(
newPosition: [number, number, number],
pointId: string
): {
position: [number, number, number];
isSnapped: boolean;
snapSources: Vector3[];
} => {
if (!pointId || !CAN_ANGLE_SNAP) {
return { position: newPosition, isSnapped: false, snapSources: [] };
}
const connectedPoints: PointData[] = getConnectedPoints(pointId) || [];
if (connectedPoints.length === 0) {
return {
position: newPosition,
isSnapped: false,
snapSources: [],
};
}
const newPos = new Vector3(...newPosition);
let closestX: { pos: Vector3; dist: number } | null = null;
let closestZ: { pos: Vector3; dist: number } | null = null;
for (const connectedPoint of connectedPoints) {
const cPos = new Vector3(...connectedPoint.position);
const xDist = Math.abs(newPos.x - cPos.x);
const zDist = Math.abs(newPos.z - cPos.z);
if (xDist < ANGLE_SNAP_DISTANCE_THRESHOLD) {
if (!closestX || xDist < closestX.dist) {
closestX = { pos: cPos, dist: xDist };
}
}
if (zDist < ANGLE_SNAP_DISTANCE_THRESHOLD) {
if (!closestZ || zDist < closestZ.dist) {
closestZ = { pos: cPos, dist: zDist };
}
}
}
const snappedPos = newPos.clone();
const snapSources: Vector3[] = [];
if (closestX) {
snappedPos.x = closestX.pos.x;
snapSources.push(closestX.pos.clone());
}
if (closestZ) {
snappedPos.z = closestZ.pos.z;
snapSources.push(closestZ.pos.clone());
}
const isSnapped = snapSources.length > 0;
return {
position: [snappedPos.x, snappedPos.y, snappedPos.z],
isSnapped,
snapSources,
};
},
[]
);
2025-08-26 14:06:25 +05:30
const getAllOtherPathPoints = useCallback((): PointData[] => {
return (
paths?.flatMap((path) =>
path.pathPoints.filter((pt) => pt.pointId !== point.pointId)
) ?? []
);
}, [paths]);
const snapPathPoint = useCallback(
(position: [number, number, number], pointId?: string) => {
if (!CAN_POINT_SNAP)
return { position: position, isSnapped: false, snappedPoint: null };
const otherPoints = getAllOtherPathPoints();
const currentVec = new Vector3(...position);
for (const point of otherPoints) {
const pointVec = new Vector3(...point.position);
const distance = currentVec.distanceTo(pointVec);
if (distance <= POINT_SNAP_THRESHOLD) {
return {
position: point.position,
isSnapped: true,
snappedPoint: point,
};
}
}
return { position: position, isSnapped: false, snappedPoint: null };
},
[getAllOtherPathPoints]
);
2025-08-26 14:06:25 +05:30
let isHandlingShiftClick = false;
// const handlePointClick = (e: any, point: PointData) => {
// if (toolMode === "3D-Delete") {
// removePathByPoint(point.pointId);
// }
// if (e.shiftKey) {
// setSelectedPointIndices((prev) => {
// if (prev.length === 0) return [pointIndex];
// if (prev.length === 1) {
// // defer shortest path calculation
// setTimeout(() => {
// console.log("points: ", points);
// const p1 = points[prev[0]];
// console.log(' p1: ', p1);
// const p2 = points[pointIndex];
// console.log('p2: ', p2);
// const result = aStarShortestPath(
// p1.pointId,
// p2.pointId,
// points,
// paths
// );
// if (result) {
// const edges = nodePathToEdges(result.pointIds, points, paths);
// console.log("edges: ", edges);
// setShortestEdges(edges);
// } else {
// setShortestEdges([]);
// }
2025-08-26 14:06:25 +05:30
// }, 0);
// return [prev[0], pointIndex];
// }
// return [pointIndex];
// });
// }
// };
const handlePointClick = (e: any, point: PointData) => {
e.stopPropagation();
if (toolMode === "3D-Delete") {
2025-08-26 14:06:25 +05:30
removePathByPoint(point.pointId);
return;
}
if (e.shiftKey) {
if (isHandlingShiftClick) return; // prevent double-handling
isHandlingShiftClick = true;
setTimeout(() => {
isHandlingShiftClick = false;
}, 100); // reset the flag after a short delay
setSelectedPointIndices((prev) => {
// console.log("Clicked point index:", pointIndex);
console.log("Previous selection:", prev);
if (prev.length === 0) {
console.log("first works");
return [pointIndex];
}
if (prev.length === 1) {
if (prev[0] === pointIndex) {
console.log("Same point selected twice — ignoring");
return prev;
}
const p1 = points[prev[0]];
const p2 = points[pointIndex];
console.log("Point 1:", p1);
console.log("Point 2:", p2);
if (p1 && p2) {
const result = aStarShortestPath(
p1.pointId,
p2.pointId,
points,
paths
);
if (result) {
const edges = nodePathToEdges(result.pointIds, points, paths);
setShortestEdges(edges);
} else {
setShortestEdges([]);
}
}
return [prev[0], pointIndex];
}
return [pointIndex];
});
}
};
2025-08-26 14:06:25 +05:30
const handleDragStart = (point: PointData) => {
2025-08-25 16:21:54 +05:30
if (activeTool !== "cursor") return;
const intersectionPoint = new Vector3();
const hit = raycaster.ray.intersectPlane(plane, intersectionPoint);
if (hit) {
const currentPosition = new Vector3(...point.position);
const offset = new Vector3().subVectors(currentPosition, hit);
setDragOffset(offset);
const pathIntersection = getPathsByPointId(point.pointId, paths);
setInitialPositions({ paths: pathIntersection });
}
};
const handleDrag = (point: PointData) => {
if (isHovered && dragOffset) {
const intersectionPoint = new Vector3();
const hit = raycaster.ray.intersectPlane(plane, intersectionPoint);
if (hit) {
// handleCanvasCursors("grabbing");
const positionWithOffset = new Vector3().addVectors(hit, dragOffset);
const newPosition: [number, number, number] = [
positionWithOffset.x,
positionWithOffset.y,
positionWithOffset.z,
];
// ✅ Pass newPosition and pointId
const pathSnapped = snapPathAngle(newPosition, point.pointId);
const finalSnapped = snapPathPoint(pathSnapped.position);
setPathPosition(point.pointId, finalSnapped.position, setPaths);
}
}
};
const handleDragEnd = (point: PointData) => {
const pathIntersection = getPathsByPointId(point.pointId, paths);
if (pathIntersection && pathIntersection.length > 0) {
pathIntersection.forEach((update) => {});
}
};
2025-08-26 14:06:25 +05:30
useEffect(() => {
console.log("selectedPoints: ", selectedPoints);
}, [selectedPoints]);
return (
<>
<DragControls
axisLock="y"
autoTransform={false}
onDragStart={() => handleDragStart(point)}
onDrag={() => handleDrag(point)}
onDragEnd={() => handleDragEnd(point)}
>
<mesh
key={point.pointId}
position={point.position}
name="Path-Point"
userData={point}
onClick={(e) => {
2025-08-26 14:06:25 +05:30
handlePointClick(e, point);
}}
onPointerOver={(e) => {
if (!hoveredPoint && e.buttons === 0 && !e.ctrlKey) {
setHoveredPoint(point);
setIsHovered(true);
2025-08-25 16:21:54 +05:30
// handleCanvasCursors("default");
}
}}
onPointerOut={() => {
if (hoveredPoint) {
setHoveredPoint(null);
if (!hoveredLine) {
// handleCanvasCursors("default");
}
}
setIsHovered(false);
}}
>
<sphereGeometry args={[0.3, 16, 16]} />
<meshBasicMaterial color="pink" />
</mesh>
</DragControls>
</>
);
}
2025-08-26 14:06:25 +05:30
// const setPathPosition = useCallback(
// (
// pointUuid: string,
// position: [number, number, number],
// setPaths: React.Dispatch<React.SetStateAction<PathData>>
// ) => {
// setPaths((prevPaths) =>
// prevPaths.map((path) => {
// if (path.pathPoints.some((p) => p.pointId === pointUuid)) {
// return {
// ...path,
// pathPoints: path.pathPoints.map((p) =>
// p.pointId === pointUuid ? { ...p, position } : p
// ) as [PointData, PointData], // 👈 force back to tuple
// };
// }
// return path;
// })
// );
// },
// [setPaths]
// );
// const getPathsByPointId = (pointId: any) => {
// return paths.filter((a) => a.pathPoints.some((p) => p.pointId === pointId));
// };