This commit is contained in:
Халимов Рустам
2026-01-11 22:12:56 +03:00
parent d9bc3bda17
commit 918d9e0ea7

View File

@@ -10,8 +10,6 @@ interface Props {
type EditMode = 'lines' | 'cells';
type Axis = 'x' | 'y';
type Limits = { min: number; max: number };
type LimitMap = Record<string, Limits>;
type DragTarget =
| { type: 'main'; axis: Axis; index: number }
@@ -61,56 +59,29 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
};
const selectedData = getSelectedPartition();
// --- SOLVER (Тот самый, рабочий) ---
const solveWallLimits = (parts: Partition[]): LimitMap => {
const limits: LimitMap = {};
parts.forEach(p => { limits[p.id] = { min: 0, max: 1 }; });
for (let pass = 0; pass < 4; pass++) {
parts.forEach(target => {
let newMin = 0;
let newMax = 1;
const center = target.offset;
parts.forEach(obstacle => {
if (target.id === obstacle.id || target.axis === obstacle.axis) return;
const obsMin = limits[obstacle.id].min;
const obsMax = limits[obstacle.id].max;
// EPSILON для надежности пересечений
const EPS = 0.002;
if (target.offset >= obsMin - EPS && target.offset <= obsMax + EPS) {
if (obstacle.offset < center) newMin = Math.max(newMin, obstacle.offset);
else if (obstacle.offset > center) newMax = Math.min(newMax, obstacle.offset);
}
});
limits[target.id] = { min: newMin, max: newMax };
});
}
return limits;
};
// --- RAYCASTING (Рабочая логика поиска коробки) ---
const getCursorBox = (lx: number, ly: number, parts: Partition[], limitMap: LimitMap) => {
// --- RAYCASTING (Надежный поиск коробки) ---
// Находит ближайшие стенки во всех 4 направлениях
const getCursorBox = (lx: number, ly: number, parts: Partition[]) => {
let minX = 0, maxX = 1;
let minY = 0, maxY = 1;
parts.forEach(p => {
const { min: pMin, max: pMax } = limitMap[p.id];
if (pMax - pMin < 0.001) return;
const EPS = 0.005; // Чувствительность к стенкам
// Используем сохраненные границы (они теперь достоверны)
const pMin = p.min ?? 0;
const pMax = p.max ?? 1;
const EPS = 0.005; // Допуск на попадание
if (p.axis === 'x') {
// Вертикальная преграда
// Вертикальная стенка. Перекрывает ли она наш Y?
if (ly >= pMin - EPS && ly <= pMax + EPS) {
// Стенка на нашем уровне. Слева или справа?
if (p.offset < lx) minX = Math.max(minX, p.offset);
if (p.offset > lx) maxX = Math.min(maxX, p.offset);
}
} else {
// Горизонтальная преграда
// Горизонтальная стенка. Перекрывает ли она наш X?
if (lx >= pMin - EPS && lx <= pMax + EPS) {
// Стенка на нашем уровне. Сверху или снизу?
if (p.offset < ly) minY = Math.max(minY, p.offset);
if (p.offset > ly) maxY = Math.min(maxY, p.offset);
}
@@ -119,15 +90,16 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
return { minX, maxX, minY, maxY };
};
// Поиск соседей для размеров
const getNeighborOffsets = (offset: number, crossPos: number, axis: Axis, parts: Partition[], limitMap: LimitMap) => {
// Поиск соседей для размеров (Та же логика, что Raycasting)
const getNeighborOffsets = (offset: number, crossPos: number, axis: Axis, parts: Partition[]) => {
let min = 0;
let max = 1;
const EPS = 0.001;
const EPS = 0.005;
parts.forEach(p => {
if (p.axis === axis) {
const { min: pMin, max: pMax } = limitMap[p.id];
const pMin = p.min ?? 0;
const pMax = p.max ?? 1;
if (crossPos >= pMin - EPS && crossPos <= pMax + EPS) {
if (p.offset < offset) min = Math.max(min, p.offset);
if (p.offset > offset) max = Math.min(max, p.offset);
@@ -218,6 +190,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
setPhantomPartition(null);
setHoveredCell(null);
// Find Cell
let cellIdx = null;
for (let i = 0; i < sortedX.length - 1; i++) {
if (nx >= sortedX[i] && nx <= sortedX[i+1]) {
@@ -233,7 +206,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
setHoveredCell(cellIdx);
const key = `${cellIdx.i}-${cellIdx.j}`;
const parts = safePartitions[key] || [];
const limitMap = solveWallLimits(parts);
const cx1 = sortedX[cellIdx.i]; const cx2 = sortedX[cellIdx.i+1];
const cy1 = sortedY[cellIdx.j]; const cy2 = sortedY[cellIdx.j+1];
@@ -241,35 +213,49 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const lx = (nx - cx1) / cw;
const ly = (ny - cy1) / ch;
// Use real mm for aspect ratio logic
const realCellW = cw * drawerW;
const realCellH = ch * drawerD;
let found = null;
const SNAP = 0.05;
for (const p of parts) {
const { min, max } = limitMap[p.id];
const pMin = p.min ?? 0;
const pMax = p.max ?? 1;
if (p.axis === 'x') {
if (ly >= min && ly <= max && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p;
if (ly >= pMin && ly <= pMax && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p;
} else {
if (lx >= min && lx <= max && Math.abs(ly - p.offset) < SNAP * (aspectRatio < 1 ? 1 : 1/aspectRatio)) found = p;
if (lx >= pMin && lx <= pMax && Math.abs(ly - p.offset) < SNAP * (aspectRatio < 1 ? 1 : 1/aspectRatio)) found = p;
}
}
if (found) {
setHoveredPartition({ id: found.id, cellKey: key });
} else {
// --- ОПРЕДЕЛЕНИЕ ФАНТОМА ---
const box = getCursorBox(lx, ly, parts, limitMap);
// --- FIND BOX ---
const box = getCursorBox(lx, ly, parts);
const width = box.maxX - box.minX;
const height = box.maxY - box.minY;
// Простейшая логика: делим длинную сторону "комнаты"
// Это работает лучше всего
const axis = width > height ? 'x' : 'y';
const boxW = (box.maxX - box.minX) * realCellW;
const boxH = (box.maxY - box.minY) * realCellH;
if ((axis === 'y' && height > 0.05) || (axis === 'x' && width > 0.05)) {
const offset = axis === 'x' ? lx : ly;
const min = axis === 'x' ? box.minY : box.minX;
const max = axis === 'x' ? box.maxY : box.maxX;
setPhantomPartition({ axis, offset, min, max });
// Default axis based on longest side
let newAxis: Axis = boxW > boxH ? 'x' : 'y';
// Override if near edges
const relL = (lx - box.minX) / (box.maxX - box.minX);
const relT = (ly - box.minY) / (box.maxY - box.minY);
const THRESHOLD = 0.2;
if (relL < THRESHOLD || relL > 1 - THRESHOLD) newAxis = 'x'; // Near vertical edge -> vertical wall
else if (relT < THRESHOLD || relT > 1 - THRESHOLD) newAxis = 'y'; // Near horiz edge -> horizontal wall
const valid = (newAxis === 'x' && (box.maxX - box.minX) > 0.05) || (newAxis === 'y' && (box.maxY - box.minY) > 0.05);
if (valid) {
const offset = newAxis === 'x' ? lx : ly;
const min = newAxis === 'x' ? box.minY : box.minX;
const max = newAxis === 'x' ? box.maxY : box.maxX;
setPhantomPartition({ axis: newAxis, offset, min, max });
}
}
}
@@ -312,16 +298,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
}
};
// --- НОВОЕ: Очистка при уходе мыши ---
const handleMouseLeave = () => {
setDragging(null);
setPhantomMainAxis(null);
setHoveredMainSplit(null);
setHoveredCell(null);
setHoveredPartition(null);
setPhantomPartition(null);
};
// --- RENDER ---
const renderCellsAndPartitions = () => {
const elements = [];
@@ -341,9 +317,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const realW = (x2 - x1) * drawerW;
const realD = (y2 - y1) * drawerD;
const limitMap = solveWallLimits(parts);
// Label
if (parts.length === 0) {
const labelX = cellX + cellW / 2;
const labelY = cellY + cellH / 2;
@@ -364,8 +337,9 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
{isAnySelected && mode === 'cells' && <rect x={cellX} y={cellY} width={cellW} height={cellH} fill="transparent" stroke="#a855f7" strokeWidth="2" className="pointer-events-none opacity-50"/>}
{parts.map(p => {
const { min, max } = limitMap[p.id];
if (max - min < 0.001) return null;
const pMin = p.min ?? 0;
const pMax = p.max ?? 1;
if (pMax - pMin < 0.001) return null;
let lx1, ly1, lx2, ly2;
let dist1 = 0, dist2 = 0;
@@ -375,18 +349,18 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
if (isVertical) {
const px = cellX + (cellW * p.offset);
lx1 = px; lx2 = px;
ly1 = cellY + (cellH * min); ly2 = cellY + (cellH * max);
ly1 = cellY + (cellH * pMin); ly2 = cellY + (cellH * pMax);
const neighbors = getNeighborOffsets(p.offset, (min + max)/2, p.axis, parts, limitMap);
const neighbors = getNeighborOffsets(p.offset, (pMin + pMax)/2, p.axis, parts);
dist1 = Math.abs((p.offset - neighbors.min) * realW) - wallThick;
dist2 = Math.abs((neighbors.max - p.offset) * realW) - wallThick;
midX = px; midY = (ly1 + ly2) / 2;
} else {
const py = cellY + (cellH * p.offset);
ly1 = py; ly2 = py;
lx1 = cellX + (cellW * min); lx2 = cellX + (cellW * max);
lx1 = cellX + (cellW * pMin); lx2 = cellX + (cellW * pMax);
const neighbors = getNeighborOffsets(p.offset, (min + max)/2, p.axis, parts, limitMap);
const neighbors = getNeighborOffsets(p.offset, (pMin + pMax)/2, p.axis, parts);
dist1 = Math.abs((p.offset - neighbors.min) * realD) - wallThick;
dist2 = Math.abs((neighbors.max - p.offset) * realD) - wallThick;
midX = (lx1 + lx2) / 2; midY = py;
@@ -456,13 +430,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
<div className="flex-1 bg-slate-800/30 flex items-center justify-center p-4 overflow-hidden relative">
<div className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden" style={{ width: aspectRatio > 1 ? 'auto' : '100%', height: aspectRatio > 1 ? '100%' : 'auto', aspectRatio: `${1/aspectRatio}`, maxHeight: '100%', maxWidth: '100%', cursor: mode === 'lines' ? (dragging ? 'grabbing' : hoveredMainSplit ? 'col-resize' : 'crosshair') : (dragging ? 'grabbing' : hoveredPartition ? 'grab' : hoveredCell ? 'crosshair' : 'default') }}>
<svg ref={svgRef} viewBox={`0 0 ${viewBoxW} ${viewBoxH}`} className="w-full h-full touch-none block"
onMouseMove={handleMouseMove}
onMouseDown={handleMouseDown}
onMouseUp={() => setDragging(null)}
onMouseLeave={handleMouseLeave}
onContextMenu={(e) => e.preventDefault()}
>
<svg ref={svgRef} viewBox={`0 0 ${viewBoxW} ${viewBoxH}`} className="w-full h-full touch-none block" onMouseMove={handleMouseMove} onMouseDown={handleMouseDown} onMouseUp={() => setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()}>
<defs><pattern id="grid" width="50" height="50" patternUnits="userSpaceOnUse"><path d="M 50 0 L 0 0 0 50" fill="none" stroke="rgba(255,255,255,0.03)" strokeWidth="1"/></pattern></defs>
<rect width="100%" height="100%" fill="url(#grid)" />
{renderCellsAndPartitions()}