From 57a5695c2a8f82387b6b11479258c8ac6588817b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sun, 11 Jan 2026 00:09:49 +0300 Subject: [PATCH 01/15] Add size --- src/components/LayoutStep.tsx | 278 ++++++++++++++++++---------------- 1 file changed, 147 insertions(+), 131 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index 1095817..25f691e 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -1,7 +1,6 @@ import React, { useRef, useState, useMemo } from 'react'; import { AppConfig, LayoutSplits, Partition } from '../types'; -// Добавил Settings, Move и прочее в импорты -import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings, Plus } from 'lucide-react'; +import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings2, Plus } from 'lucide-react'; interface Props { config: AppConfig; @@ -43,6 +42,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const drawerW = Math.max(1, config.drawer.width || 300); const drawerD = Math.max(1, config.drawer.depth || 400); const aspectRatio = drawerD / drawerW; + const thickness = config.wallThickness || 1.2; const viewBoxW = 1000; const viewBoxH = viewBoxW * aspectRatio; @@ -50,7 +50,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]); const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]); - // -- HELPER: Get Selected -- + // -- HELPERS -- const getSelectedPartition = () => { if (!selectedPartitionId) return null; for (const key in safePartitions) { @@ -61,8 +61,45 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; const selectedData = getSelectedPartition(); - // -- LOGIC: T-Junction Limits -- - // Находит ближайшие стенки, чтобы ограничить новую перегородку + // Найти ближайшие границы для перегородки (или точки) + const getNearestNeighbors = (lx: number, ly: number, axis: Axis, parts: Partition[]) => { + let min = 0; + let max = 1; + + parts.forEach(p => { + // Игнорируем саму себя, если это проверка для существующей стенки (но здесь мы передаем lx/ly точки) + + const pMin = p.min ?? 0; + const pMax = p.max ?? 1; + + // Если мы ищем границы по X (для вертикальной стенки или пространства слева/справа) + // То нас интересуют другие ВЕРТИКАЛЬНЫЕ стенки (axis === 'x'), которые перекрывают нас по Y + if (axis === 'x') { + if (p.axis === 'x') { + // Перекрываются ли диапазоны высоты? + // ly для точки - это просто координата. Для стенки это min-max. + // Здесь мы ищем границы для точки (lx, ly). + // Стенка P идет от pMin до pMax по Y. + if (ly > pMin && ly < pMax) { + if (p.offset < lx) min = Math.max(min, p.offset); + if (p.offset > lx) max = Math.min(max, p.offset); + } + } + } else { + // Ищем границы по Y (для горизонтальной стенки) + // Нас интересуют ГОРИЗОНТАЛЬНЫЕ стенки + if (p.axis === 'y') { + if (lx > pMin && lx < pMax) { + if (p.offset < ly) min = Math.max(min, p.offset); + if (p.offset > ly) max = Math.min(max, p.offset); + } + } + } + }); + return { min, max }; + }; + + // Расчет границ для НОВОЙ линии (перпендикулярной) const getHoveredBoundaries = (lx: number, ly: number, parts: Partition[]) => { let minX = 0, maxX = 1; let minY = 0, maxY = 1; @@ -72,15 +109,11 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const pMax = p.max ?? 1; if (p.axis === 'x') { - // Вертикальная стенка (x=offset, y=min..max) - // Проверяем, находится ли мышь в её диапазоне по Y if (ly >= pMin && ly <= pMax) { if (p.offset < lx) minX = Math.max(minX, p.offset); if (p.offset > lx) maxX = Math.min(maxX, p.offset); } } else { - // Горизонтальная стенка (y=offset, x=min..max) - // Проверяем, находится ли мышь в её диапазоне по X if (lx >= pMin && lx <= pMax) { if (p.offset < ly) minY = Math.max(minY, p.offset); if (p.offset > ly) maxY = Math.min(maxY, p.offset); @@ -96,14 +129,10 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const current = safePartitions[key] || []; const newPart: Partition = { id: Math.random().toString(36).substr(2, 9), - axis, - offset, - min, - max, + axis, offset, min, max, height: config.drawer.height || 80, rounded: false }; - // Обновляем стейт, но НЕ сбрасываем mode, так как ErrorBoundary теперь снаружи onChange({ ...splits, partitions: { ...safePartitions, [key]: [...current, newPart] } }); setSelectedPartitionId(newPart.id); }; @@ -152,16 +181,15 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const cellY1 = sortedY[j]; const cellY2 = sortedY[j+1]; let newOffset = 0; + // Текущие границы перетаскиваемой стенки (чтобы не выехать за пределы соседей) + // Для простоты пока используем границы ячейки (0-1), так как сложный пересчет соседей в реалтайме - это дорого + // Но визуально мы ограничим 2-98% if (dragging.axis === 'x') { newOffset = (nx - cellX1) / (cellX2 - cellX1); } else { newOffset = (ny - cellY1) / (cellY2 - cellY1); } - - // Ограничиваем в пределах "родительской" зоны (0-1) внутри ячейки - // В идеале тут тоже надо проверять коллизии, но пока просто границы ячейки newOffset = Math.max(0.02, Math.min(0.98, newOffset)); - if (!isNaN(newOffset)) { updatePartition(dragging.cellKey, dragging.id, { offset: newOffset }); } @@ -188,7 +216,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setPhantomPartition(null); setHoveredCell(null); - // 1. Находим ячейку let cellIdx = null; for (let i = 0; i < sortedX.length - 1; i++) { if (nx >= sortedX[i] && nx <= sortedX[i+1]) { @@ -212,7 +239,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const lx = (nx - cx1) / cw; const ly = (ny - cy1) / ch; - // 2. Проверяем наведение на существующие (для удаления/выделения) let found = null; const SNAP = 0.05; for (const p of parts) { @@ -227,21 +253,14 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (found) { setHoveredPartition({ id: found.id, cellKey: key }); } else { - // 3. Вычисляем T-образные границы const bounds = getHoveredBoundaries(lx, ly, parts); - - const distL = lx - bounds.minX; - const distR = bounds.maxX - lx; - const distT = ly - bounds.minY; - const distB = bounds.maxY - ly; + const distL = lx - bounds.minX; const distR = bounds.maxX - lx; + const distT = ly - bounds.minY; const distB = bounds.maxY - ly; const minX = Math.min(distL, distR); const minY = Math.min(distT, distB); - // Определяем ось перпендикулярно ближайшей стороне - const axis = minX < minY ? 'y' : 'x'; - - // Проверяем, есть ли место + const axis = minX < minY ? 'y' : 'x'; const width = bounds.maxX - bounds.minX; const height = bounds.maxY - bounds.minY; @@ -285,14 +304,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { } } else if (hoveredCell && phantomPartition) { if (e.button === 0) { - createPartition( - hoveredCell.i, - hoveredCell.j, - phantomPartition.axis, - phantomPartition.offset, - phantomPartition.min, - phantomPartition.max - ); + createPartition(hoveredCell.i, hoveredCell.j, phantomPartition.axis, phantomPartition.offset, phantomPartition.min, phantomPartition.max); } } else { setSelectedPartitionId(null); @@ -316,33 +328,98 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const isHovered = hoveredCell?.i === i && hoveredCell?.j === j && mode === 'cells'; const parts = safePartitions[key] || []; - const isAnySelected = parts.some(p => p.id === selectedPartitionId); + const isSelected = parts.some(p => p.id === selectedPartitionId); + + // Реальные размеры ячейки в мм + const realW = (x2 - x1) * drawerW; + const realD = (y2 - y1) * drawerD; + + // --- ЛЕЙБЛ РАЗМЕРА --- + // Если перегородок нет, показываем общий размер по центру + if (parts.length === 0) { + const labelX = cellX + cellW / 2; + const labelY = cellY + cellH / 2; + // Учитываем толщину внешних стенок (или соседних) + // Упрощенно: вычитаем толщину (1 раз, т.к. 0.5 с каждой стороны) + const textW = Math.max(0, realW - thickness).toFixed(0); + const textD = Math.max(0, realD - thickness).toFixed(0); + + // Рисуем текст только если есть место + if (cellH > 40 && cellW > 60) { + elements.push( + + {textW} × {textD} + + ); + } + } elements.push( {isHovered && } - {isAnySelected && mode === 'cells' && } {parts.map(p => { const pMin = p.min ?? 0; const pMax = p.max ?? 1; - let lx1, ly1, lx2, ly2; + let lx1, ly1, lx2, ly2; // Координаты линии + let tx, ty; // Координаты текста + let dist1 = 0, dist2 = 0; // Расстояния до соседей (в мм) + + // Находим соседей для расчета размеров + const neighbors = getNearestNeighbors(p.offset, (pMin + pMax)/2, p.axis, parts); if (p.axis === 'x') { const px = cellX + (cellW * p.offset); lx1 = px; lx2 = px; ly1 = cellY + (cellH * pMin); ly2 = cellY + (cellH * pMax); + + // Размеры слева и справа + const leftRatio = p.offset - neighbors.min; + const rightRatio = neighbors.max - p.offset; + dist1 = (leftRatio * realW) - thickness; // Left + dist2 = (rightRatio * realW) - thickness; // Right + + tx = px; + ty = (ly1 + ly2) / 2; } else { const py = cellY + (cellH * p.offset); ly1 = py; ly2 = py; lx1 = cellX + (cellW * pMin); lx2 = cellX + (cellW * pMax); + + // Размеры сверху и снизу + const topRatio = p.offset - neighbors.min; + const botRatio = neighbors.max - p.offset; + dist1 = (topRatio * realD) - thickness; // Top + dist2 = (botRatio * realD) - thickness; // Bottom + + tx = (lx1 + lx2) / 2; + ty = py; } + const isSel = selectedPartitionId === p.id; const isHov = hoveredPartition?.id === p.id; return ( - { e.stopPropagation(); removePartition(key, p.id); }}> - - + + {/* Сама линия */} + { e.stopPropagation(); removePartition(key, p.id); }}> + + + + + {/* Текст размеров (Слева/Справа или Сверху/Снизу) */} + + {p.axis === 'x' ? ( + <> + {dist1.toFixed(0)} + {dist2.toFixed(0)} + + ) : ( + <> + {dist1.toFixed(0)} + {dist2.toFixed(0)} + + )} + ); })} @@ -354,12 +431,10 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { let fx1, fy1, fx2, fy2; if (phantomPartition.axis === 'x') { const px = cellX + (cellW * phantomPartition.offset); - fx1 = px; fx2 = px; - fy1 = cellY + (cellH * pMin); fy2 = cellY + (cellH * pMax); + fx1 = px; fx2 = px; fy1 = cellY + (cellH * pMin); fy2 = cellY + (cellH * pMax); } else { const py = cellY + (cellH * phantomPartition.offset); - fy1 = py; fy2 = py; - fx1 = cellX + (cellW * pMin); fx2 = cellX + (cellW * pMax); + fy1 = py; fy2 = py; fx1 = cellX + (cellW * pMin); fx2 = cellX + (cellW * pMax); } return ; })()} @@ -375,138 +450,79 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return (
- {/* TOOLBAR */} + {/* HEADER */}

2. Редактор макета

-
- - + +
- - +
- {/* INFO BAR */} + {/* INFO */}
{mode === 'lines' ? ( -
- ЛКМ: Линия - ПКМ: Удалить -
+
ЛКМ: ЛинияПКМ: Удалить
) : ( -
- ЛКМ в ячейке: Стенка (T-соединения) - Драг: Двигать - 2xЛКМ: Удалить -
+
ЛКМ в ячейке: СтенкаДраг: Двигать2xЛКМ: Удалить
)}
- {/* WORKSPACE */} + {/* CANVAS */}
-
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'), - }} +
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') }} > setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()} > - - - - - + - {renderCellsAndPartitions()} - - {/* MAIN GRID X */} + {/* Main Grid X */} {safeX.map((x, i) => ( { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'x', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('x', i); }}> ))} - - {/* MAIN GRID Y */} + {/* Main Grid Y */} {safeY.map((y, i) => ( { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'y', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('y', i); }}> ))} - - {/* MAIN PHANTOMS */} - {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'x' && } - {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'y' && } + {/* Phantoms */} + {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis && ( + + )}
- {/* --- SIDEBAR FOR EDITING --- */} + {/* SIDEBAR */} {mode === 'cells' && selectedData && (
-
-

- Настройки стенки -

- -
- +

Настройки стенки

- {/* Height */}
-
- Высота {selectedData.part.height} мм -
- updatePartition(selectedData.key, selectedData.part.id, { height: parseFloat(e.target.value) })} - className="w-full h-1 bg-slate-600 rounded-lg appearance-none cursor-pointer accent-purple-500" - /> +
Высота {selectedData.part.height} мм
+ updatePartition(selectedData.key, selectedData.part.id, { height: parseFloat(e.target.value) })} className="w-full h-1 bg-slate-600 rounded-lg appearance-none cursor-pointer accent-purple-500"/>
- - {/* Rounded */}
- updatePartition(selectedData.key, selectedData.part.id, { rounded: e.target.checked })} - className="w-4 h-4 rounded bg-slate-700 border-slate-600 text-purple-500 focus:ring-0 cursor-pointer" - /> + updatePartition(selectedData.key, selectedData.part.id, { rounded: e.target.checked })} className="w-4 h-4 rounded bg-slate-700 border-slate-600 text-purple-500 focus:ring-0 cursor-pointer"/>
- - {/* Delete */} - -
- -
- Выделите стенку для настройки.
Двойной клик удаляет её. +
+
Выделите стенку для настройки.
Двойной клик удаляет её.
)}
From 621958c0d442bf9012f67741d3d21882810bb7d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sun, 11 Jan 2026 00:25:25 +0300 Subject: [PATCH 02/15] Font size for sizes --- src/components/LayoutStep.tsx | 111 ++++++++++++++++------------------ 1 file changed, 52 insertions(+), 59 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index 25f691e..4d83fec 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -61,37 +61,40 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; const selectedData = getSelectedPartition(); - // Найти ближайшие границы для перегородки (или точки) - const getNearestNeighbors = (lx: number, ly: number, axis: Axis, parts: Partition[]) => { + // --- ИСПРАВЛЕННЫЙ РАСЧЕТ СОСЕДЕЙ ДЛЯ РАЗМЕРОВ --- + // targetOffset: позиция стенки (0..1) по её основной оси + // crossPos: позиция центра стенки по перпендикулярной оси (чтобы понять, пересекаются ли они) + // axis: ось самой стенки ('x' или 'y') + const getNearestNeighbors = (targetOffset: number, crossPos: number, axis: Axis, parts: Partition[]) => { let min = 0; let max = 1; parts.forEach(p => { - // Игнорируем саму себя, если это проверка для существующей стенки (но здесь мы передаем lx/ly точки) - const pMin = p.min ?? 0; const pMax = p.max ?? 1; - // Если мы ищем границы по X (для вертикальной стенки или пространства слева/справа) - // То нас интересуют другие ВЕРТИКАЛЬНЫЕ стенки (axis === 'x'), которые перекрывают нас по Y if (axis === 'x') { + // Мы - вертикальная стенка (X). Ищем другие ВЕРТИКАЛЬНЫЕ стенки слева/справа. if (p.axis === 'x') { - // Перекрываются ли диапазоны высоты? - // ly для точки - это просто координата. Для стенки это min-max. - // Здесь мы ищем границы для точки (lx, ly). - // Стенка P идет от pMin до pMax по Y. - if (ly > pMin && ly < pMax) { - if (p.offset < lx) min = Math.max(min, p.offset); - if (p.offset > lx) max = Math.min(max, p.offset); + // Они должны перекрываться с нами по высоте (Y) + // Наша "высота" - это точка crossPos (середина). + // Стенка P занимает по Y от pMin до pMax. + if (crossPos > pMin && crossPos < pMax) { + // Стенка P находится слева от нас? + if (p.offset < targetOffset) min = Math.max(min, p.offset); + // Стенка P находится справа от нас? + if (p.offset > targetOffset) max = Math.min(max, p.offset); } } } else { - // Ищем границы по Y (для горизонтальной стенки) - // Нас интересуют ГОРИЗОНТАЛЬНЫЕ стенки + // Мы - горизонтальная стенка (Y). Ищем другие ГОРИЗОНТАЛЬНЫЕ стенки сверху/снизу. if (p.axis === 'y') { - if (lx > pMin && lx < pMax) { - if (p.offset < ly) min = Math.max(min, p.offset); - if (p.offset > ly) max = Math.min(max, p.offset); + // Они должны перекрываться с нами по ширине (X) + // Наша "ширина" - это точка crossPos (середина). + // Стенка P занимает по X от pMin до pMax. + if (crossPos > pMin && crossPos < pMax) { + if (p.offset < targetOffset) min = Math.max(min, p.offset); + if (p.offset > targetOffset) max = Math.min(max, p.offset); } } } @@ -99,7 +102,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return { min, max }; }; - // Расчет границ для НОВОЙ линии (перпендикулярной) + // Расчет границ для НОВОЙ линии (T-соединения) const getHoveredBoundaries = (lx: number, ly: number, parts: Partition[]) => { let minX = 0, maxX = 1; let minY = 0, maxY = 1; @@ -181,9 +184,8 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const cellY1 = sortedY[j]; const cellY2 = sortedY[j+1]; let newOffset = 0; - // Текущие границы перетаскиваемой стенки (чтобы не выехать за пределы соседей) - // Для простоты пока используем границы ячейки (0-1), так как сложный пересчет соседей в реалтайме - это дорого - // Но визуально мы ограничим 2-98% + // Ограничиваем перетаскивание пределами "родительской" зоны + // Для T-соединений это сложнее, но пока ограничим ячейкой (0-1) if (dragging.axis === 'x') { newOffset = (nx - cellX1) / (cellX2 - cellX1); } else { @@ -330,24 +332,19 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const parts = safePartitions[key] || []; const isSelected = parts.some(p => p.id === selectedPartitionId); - // Реальные размеры ячейки в мм + // Реальные размеры const realW = (x2 - x1) * drawerW; const realD = (y2 - y1) * drawerD; - // --- ЛЕЙБЛ РАЗМЕРА --- - // Если перегородок нет, показываем общий размер по центру + // Если перегородок нет - размер по центру if (parts.length === 0) { const labelX = cellX + cellW / 2; const labelY = cellY + cellH / 2; - // Учитываем толщину внешних стенок (или соседних) - // Упрощенно: вычитаем толщину (1 раз, т.к. 0.5 с каждой стороны) const textW = Math.max(0, realW - thickness).toFixed(0); const textD = Math.max(0, realD - thickness).toFixed(0); - - // Рисуем текст только если есть место if (cellH > 40 && cellW > 60) { elements.push( - + {textW} × {textD} ); @@ -360,11 +357,13 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { {parts.map(p => { const pMin = p.min ?? 0; const pMax = p.max ?? 1; - let lx1, ly1, lx2, ly2; // Координаты линии - let tx, ty; // Координаты текста - let dist1 = 0, dist2 = 0; // Расстояния до соседей (в мм) + let lx1, ly1, lx2, ly2; + let tx, ty; + let dist1 = 0, dist2 = 0; - // Находим соседей для расчета размеров + // Используем правильные координаты для поиска соседей + // axis='x' -> offset - это X, center - это Y + // axis='y' -> offset - это Y, center - это X const neighbors = getNearestNeighbors(p.offset, (pMin + pMax)/2, p.axis, parts); if (p.axis === 'x') { @@ -372,27 +371,23 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { lx1 = px; lx2 = px; ly1 = cellY + (cellH * pMin); ly2 = cellY + (cellH * pMax); - // Размеры слева и справа - const leftRatio = p.offset - neighbors.min; - const rightRatio = neighbors.max - p.offset; - dist1 = (leftRatio * realW) - thickness; // Left - dist2 = (rightRatio * realW) - thickness; // Right + // Distances Left/Right + // p.offset is 0..1. neighbor.min is 0..1. + // Distance = (current - neighbor) * width + dist1 = (p.offset - neighbors.min) * realW - thickness; + dist2 = (neighbors.max - p.offset) * realW - thickness; - tx = px; - ty = (ly1 + ly2) / 2; + tx = px; ty = (ly1 + ly2) / 2; } else { const py = cellY + (cellH * p.offset); ly1 = py; ly2 = py; lx1 = cellX + (cellW * pMin); lx2 = cellX + (cellW * pMax); - // Размеры сверху и снизу - const topRatio = p.offset - neighbors.min; - const botRatio = neighbors.max - p.offset; - dist1 = (topRatio * realD) - thickness; // Top - dist2 = (botRatio * realD) - thickness; // Bottom + // Distances Top/Bottom + dist1 = (p.offset - neighbors.min) * realD - thickness; + dist2 = (neighbors.max - p.offset) * realD - thickness; - tx = (lx1 + lx2) / 2; - ty = py; + tx = (lx1 + lx2) / 2; ty = py; } const isSel = selectedPartitionId === p.id; @@ -400,23 +395,22 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return ( - {/* Сама линия */} { e.stopPropagation(); removePartition(key, p.id); }}> - {/* Текст размеров (Слева/Справа или Сверху/Снизу) */} - + {/* Размеры (только если есть место) */} + {p.axis === 'x' ? ( <> - {dist1.toFixed(0)} - {dist2.toFixed(0)} + {Math.max(0, dist1).toFixed(0)} + {Math.max(0, dist2).toFixed(0)} ) : ( <> - {dist1.toFixed(0)} - {dist2.toFixed(0)} + {Math.max(0, dist1).toFixed(0)} + {Math.max(0, dist2).toFixed(0)} )} @@ -480,7 +474,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { > setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()} + onMouseMove={handleGlobalMouseMove} onMouseDown={handleMouseDown} onMouseUp={() => setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()} > @@ -500,9 +494,8 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { ))} {/* Phantoms */} - {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis && ( - - )} + {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'x' && } + {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'y' && }
From d85cac8a16990360632387ba2b958dc536a3a308 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sun, 11 Jan 2026 13:34:11 +0300 Subject: [PATCH 03/15] 1 --- src/components/LayoutStep.tsx | 192 +++++++++++++++++++--------------- 1 file changed, 105 insertions(+), 87 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index 4d83fec..0155872 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -1,6 +1,6 @@ import React, { useRef, useState, useMemo } from 'react'; import { AppConfig, LayoutSplits, Partition } from '../types'; -import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings2, Plus } from 'lucide-react'; +import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings2 } from 'lucide-react'; interface Props { config: AppConfig; @@ -18,31 +18,31 @@ type DragTarget = export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const svgRef = useRef(null); - // -- STATE -- + // --- STATE --- const [mode, setMode] = useState('lines'); const [mousePos, setMousePos] = useState({ x: 0, y: 0 }); const [dragging, setDragging] = useState(null); const [isButtonHovered, setIsButtonHovered] = useState(false); - // Main Grid Hover + // Main Grid const [phantomMainAxis, setPhantomMainAxis] = useState(null); const [hoveredMainSplit, setHoveredMainSplit] = useState<{ axis: Axis; index: number } | null>(null); - // Partition Hover + // Partitions const [hoveredCell, setHoveredCell] = useState<{ i: number; j: number } | null>(null); const [hoveredPartition, setHoveredPartition] = useState<{ id: string; cellKey: string } | null>(null); const [phantomPartition, setPhantomPartition] = useState<{ axis: Axis; offset: number; min: number; max: number } | null>(null); const [selectedPartitionId, setSelectedPartitionId] = useState(null); - // -- SAFE DATA -- + // --- SAFE DATA --- const safeX = Array.isArray(splits?.x) ? splits.x : []; const safeY = Array.isArray(splits?.y) ? splits.y : []; const safePartitions = splits?.partitions || {}; const drawerW = Math.max(1, config.drawer.width || 300); const drawerD = Math.max(1, config.drawer.depth || 400); + const wallThick = config.wallThickness || 1.2; const aspectRatio = drawerD / drawerW; - const thickness = config.wallThickness || 1.2; const viewBoxW = 1000; const viewBoxH = viewBoxW * aspectRatio; @@ -50,7 +50,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]); const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]); - // -- HELPERS -- + // --- HELPERS --- const getSelectedPartition = () => { if (!selectedPartitionId) return null; for (const key in safePartitions) { @@ -61,48 +61,29 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; const selectedData = getSelectedPartition(); - // --- ИСПРАВЛЕННЫЙ РАСЧЕТ СОСЕДЕЙ ДЛЯ РАЗМЕРОВ --- - // targetOffset: позиция стенки (0..1) по её основной оси - // crossPos: позиция центра стенки по перпендикулярной оси (чтобы понять, пересекаются ли они) - // axis: ось самой стенки ('x' или 'y') - const getNearestNeighbors = (targetOffset: number, crossPos: number, axis: Axis, parts: Partition[]) => { - let min = 0; - let max = 1; + // Поиск ближайших соседей для расчета размеров + const getNeighborOffsets = (currentOffset: number, crossPos: number, axis: Axis, parts: Partition[]) => { + let minLimit = 0; + let maxLimit = 1; parts.forEach(p => { - const pMin = p.min ?? 0; - const pMax = p.max ?? 1; - - if (axis === 'x') { - // Мы - вертикальная стенка (X). Ищем другие ВЕРТИКАЛЬНЫЕ стенки слева/справа. - if (p.axis === 'x') { - // Они должны перекрываться с нами по высоте (Y) - // Наша "высота" - это точка crossPos (середина). - // Стенка P занимает по Y от pMin до pMax. - if (crossPos > pMin && crossPos < pMax) { - // Стенка P находится слева от нас? - if (p.offset < targetOffset) min = Math.max(min, p.offset); - // Стенка P находится справа от нас? - if (p.offset > targetOffset) max = Math.min(max, p.offset); - } - } - } else { - // Мы - горизонтальная стенка (Y). Ищем другие ГОРИЗОНТАЛЬНЫЕ стенки сверху/снизу. - if (p.axis === 'y') { - // Они должны перекрываться с нами по ширине (X) - // Наша "ширина" - это точка crossPos (середина). - // Стенка P занимает по X от pMin до pMax. - if (crossPos > pMin && crossPos < pMax) { - if (p.offset < targetOffset) min = Math.max(min, p.offset); - if (p.offset > targetOffset) max = Math.min(max, p.offset); - } - } + // Если стенка параллельна нашей, мы ищем, не является ли она барьером + if (p.axis === axis) { + const pMin = p.min ?? 0; + const pMax = p.max ?? 1; + + // Проверяем, пересекаются ли они "в проекции" + // crossPos - это середина нашей стенки. Попадает ли она в диапазон соседки? + if (crossPos > pMin && crossPos < pMax) { + if (p.offset < currentOffset) minLimit = Math.max(minLimit, p.offset); + if (p.offset > currentOffset) maxLimit = Math.min(maxLimit, p.offset); + } } }); - return { min, max }; + return { min: minLimit, max: maxLimit }; }; - // Расчет границ для НОВОЙ линии (T-соединения) + // Поиск границ для НОВОЙ стенки (чтобы обрезать её до T-соединения) const getHoveredBoundaries = (lx: number, ly: number, parts: Partition[]) => { let minX = 0, maxX = 1; let minY = 0, maxY = 1; @@ -112,11 +93,13 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const pMax = p.max ?? 1; if (p.axis === 'x') { + // Вертикальная стенка. Блокирует горизонтальное движение? if (ly >= pMin && ly <= pMax) { if (p.offset < lx) minX = Math.max(minX, p.offset); if (p.offset > lx) maxX = Math.min(maxX, p.offset); } } else { + // Горизонтальная стенка if (lx >= pMin && lx <= pMax) { if (p.offset < ly) minY = Math.max(minY, p.offset); if (p.offset > ly) maxY = Math.min(maxY, p.offset); @@ -126,13 +109,16 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return { minX, maxX, minY, maxY }; }; - // -- ACTIONS -- + // --- ACTIONS --- const createPartition = (i: number, j: number, axis: Axis, offset: number, min: number, max: number) => { const key = `${i}-${j}`; const current = safePartitions[key] || []; const newPart: Partition = { id: Math.random().toString(36).substr(2, 9), - axis, offset, min, max, + axis, + offset, + min, + max, height: config.drawer.height || 80, rounded: false }; @@ -161,7 +147,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setDragging(null); }; - // -- MOUSE HANDLER -- + // --- MOUSE HANDLER --- const handleMouseMove = (e: React.MouseEvent) => { if (!svgRef.current) return; const rect = svgRef.current.getBoundingClientRect(); @@ -184,8 +170,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const cellY1 = sortedY[j]; const cellY2 = sortedY[j+1]; let newOffset = 0; - // Ограничиваем перетаскивание пределами "родительской" зоны - // Для T-соединений это сложнее, но пока ограничим ячейкой (0-1) if (dragging.axis === 'x') { newOffset = (nx - cellX1) / (cellX2 - cellX1); } else { @@ -241,6 +225,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const lx = (nx - cx1) / cw; const ly = (ny - cy1) / ch; + // Check Existing Partitions Hover let found = null; const SNAP = 0.05; for (const p of parts) { @@ -255,6 +240,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (found) { setHoveredPartition({ id: found.id, cellKey: key }); } else { + // Calculate Phantom Partition const bounds = getHoveredBoundaries(lx, ly, parts); const distL = lx - bounds.minX; const distR = bounds.maxX - lx; const distT = ly - bounds.minY; const distB = bounds.maxY - ly; @@ -322,6 +308,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const x1 = sortedX[i]; const x2 = sortedX[i + 1]; const y1 = sortedY[j]; const y2 = sortedY[j + 1]; + // !!! FIX: Проверка y2 if (y2 === undefined || x2 === undefined) continue; const cellX = x1 * viewBoxW; const cellY = y1 * viewBoxH; @@ -330,21 +317,20 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const isHovered = hoveredCell?.i === i && hoveredCell?.j === j && mode === 'cells'; const parts = safePartitions[key] || []; - const isSelected = parts.some(p => p.id === selectedPartitionId); + const isAnySelected = parts.some(p => p.id === selectedPartitionId); - // Реальные размеры const realW = (x2 - x1) * drawerW; const realD = (y2 - y1) * drawerD; - // Если перегородок нет - размер по центру + // Label if empty if (parts.length === 0) { const labelX = cellX + cellW / 2; const labelY = cellY + cellH / 2; - const textW = Math.max(0, realW - thickness).toFixed(0); - const textD = Math.max(0, realD - thickness).toFixed(0); + const textW = Math.max(0, realW - wallThick).toFixed(0); + const textD = Math.max(0, realD - wallThick).toFixed(0); if (cellH > 40 && cellW > 60) { elements.push( - + {textW} × {textD} ); @@ -354,6 +340,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { elements.push( {isHovered && } + {isAnySelected && mode === 'cells' && } {parts.map(p => { const pMin = p.min ?? 0; const pMax = p.max ?? 1; @@ -361,21 +348,17 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { let tx, ty; let dist1 = 0, dist2 = 0; - // Используем правильные координаты для поиска соседей - // axis='x' -> offset - это X, center - это Y - // axis='y' -> offset - это Y, center - это X - const neighbors = getNearestNeighbors(p.offset, (pMin + pMax)/2, p.axis, parts); - + // Ищем границы для размеров + const neighbors = getNeighborOffsets(p.offset, (pMin + pMax)/2, p.axis, parts); + if (p.axis === 'x') { const px = cellX + (cellW * p.offset); lx1 = px; lx2 = px; ly1 = cellY + (cellH * pMin); ly2 = cellY + (cellH * pMax); - // Distances Left/Right - // p.offset is 0..1. neighbor.min is 0..1. - // Distance = (current - neighbor) * width - dist1 = (p.offset - neighbors.min) * realW - thickness; - dist2 = (neighbors.max - p.offset) * realW - thickness; + // Дистанция = (Мой Оффсет - Оффсет Соседа) * Ширину Ячейки - Толщина стенки + dist1 = Math.abs((p.offset - neighbors.min) * realW) - wallThick; + dist2 = Math.abs((neighbors.max - p.offset) * realW) - wallThick; tx = px; ty = (ly1 + ly2) / 2; } else { @@ -383,9 +366,8 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { ly1 = py; ly2 = py; lx1 = cellX + (cellW * pMin); lx2 = cellX + (cellW * pMax); - // Distances Top/Bottom - dist1 = (p.offset - neighbors.min) * realD - thickness; - dist2 = (neighbors.max - p.offset) * realD - thickness; + dist1 = Math.abs((p.offset - neighbors.min) * realD) - wallThick; + dist2 = Math.abs((neighbors.max - p.offset) * realD) - wallThick; tx = (lx1 + lx2) / 2; ty = py; } @@ -400,17 +382,17 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { - {/* Размеры (только если есть место) */} - + {/* DIMENSIONS */} + {p.axis === 'x' ? ( <> - {Math.max(0, dist1).toFixed(0)} - {Math.max(0, dist2).toFixed(0)} + {Math.max(0, dist1).toFixed(0)} + {Math.max(0, dist2).toFixed(0)} ) : ( <> - {Math.max(0, dist1).toFixed(0)} - {Math.max(0, dist2).toFixed(0)} + {Math.max(0, dist1).toFixed(0)} + {Math.max(0, dist2).toFixed(0)} )} @@ -449,51 +431,82 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => {

2. Редактор макета

+
- - + +
- + + {/* INFO */}
{mode === 'lines' ? ( -
ЛКМ: ЛинияПКМ: Удалить
+
+ ЛКМ: Линия + ПКМ: Удалить +
) : ( -
ЛКМ в ячейке: СтенкаДраг: Двигать2xЛКМ: Удалить
+
+ ЛКМ в ячейке: Стенка + Драг: Двигать + 2xЛКМ: Удалить +
)}
{/* CANVAS */}
-
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') }} +
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'), + }} > setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()} + onMouseMove={handleMouseMove} onMouseDown={handleMouseDown} onMouseUp={() => setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()} > - + + + + + + {renderCellsAndPartitions()} - {/* Main Grid X */} + + {/* MAIN GRID X */} {safeX.map((x, i) => ( { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'x', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('x', i); }}> ))} - {/* Main Grid Y */} + + {/* MAIN GRID Y */} {safeY.map((y, i) => ( { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'y', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('y', i); }}> ))} - {/* Phantoms */} + + {/* PHANTOMS */} {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'x' && } {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'y' && } @@ -503,7 +516,10 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { {/* SIDEBAR */} {mode === 'cells' && selectedData && (
-

Настройки стенки

+
+

Настройки стенки

+ +
Высота {selectedData.part.height} мм
@@ -513,7 +529,9 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { updatePartition(selectedData.key, selectedData.part.id, { rounded: e.target.checked })} className="w-4 h-4 rounded bg-slate-700 border-slate-600 text-purple-500 focus:ring-0 cursor-pointer"/>
- +
Выделите стенку для настройки.
Двойной клик удаляет её.
From 438c7b661561cae255c948b9583bfc48140b5b88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sun, 11 Jan 2026 13:42:33 +0300 Subject: [PATCH 04/15] 2 --- src/components/LayoutStep.tsx | 84 ++++++++++++++++++++--------------- 1 file changed, 49 insertions(+), 35 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index 0155872..65f1872 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -67,13 +67,12 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { let maxLimit = 1; parts.forEach(p => { - // Если стенка параллельна нашей, мы ищем, не является ли она барьером + // Если стенка параллельна нашей if (p.axis === axis) { const pMin = p.min ?? 0; const pMax = p.max ?? 1; - // Проверяем, пересекаются ли они "в проекции" - // crossPos - это середина нашей стенки. Попадает ли она в диапазон соседки? + // Проверяем пересечение проекций if (crossPos > pMin && crossPos < pMax) { if (p.offset < currentOffset) minLimit = Math.max(minLimit, p.offset); if (p.offset > currentOffset) maxLimit = Math.min(maxLimit, p.offset); @@ -83,7 +82,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return { min: minLimit, max: maxLimit }; }; - // Поиск границ для НОВОЙ стенки (чтобы обрезать её до T-соединения) + // Поиск границ для НОВОЙ стенки (T-соединения) const getHoveredBoundaries = (lx: number, ly: number, parts: Partition[]) => { let minX = 0, maxX = 1; let minY = 0, maxY = 1; @@ -93,13 +92,13 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const pMax = p.max ?? 1; if (p.axis === 'x') { - // Вертикальная стенка. Блокирует горизонтальное движение? + // Вертикальная стенка. Ограничивает по X. if (ly >= pMin && ly <= pMax) { if (p.offset < lx) minX = Math.max(minX, p.offset); if (p.offset > lx) maxX = Math.min(maxX, p.offset); } } else { - // Горизонтальная стенка + // Горизонтальная стенка. Ограничивает по Y. if (lx >= pMin && lx <= pMax) { if (p.offset < ly) minY = Math.max(minY, p.offset); if (p.offset > ly) maxY = Math.min(maxY, p.offset); @@ -164,6 +163,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { newSplits[dragging.axis][dragging.index] = val; onChange(newSplits); } else { + // Dragging Partition const [iStr, jStr] = dragging.cellKey.split('-'); const i = parseInt(iStr); const j = parseInt(jStr); const cellX1 = sortedX[i]; const cellX2 = sortedX[i+1]; @@ -175,7 +175,11 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { } else { newOffset = (ny - cellY1) / (cellY2 - cellY1); } + + // Ограничиваем перетаскивание. + // В идеале нужно динамически считать соседей, но для скорости пока ограничим ячейкой (2%-98%) newOffset = Math.max(0.02, Math.min(0.98, newOffset)); + if (!isNaN(newOffset)) { updatePartition(dragging.cellKey, dragging.id, { offset: newOffset }); } @@ -240,18 +244,23 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (found) { setHoveredPartition({ id: found.id, cellKey: key }); } else { - // Calculate Phantom Partition + // Calculate Phantom Partition with T-junctions const bounds = getHoveredBoundaries(lx, ly, parts); - const distL = lx - bounds.minX; const distR = bounds.maxX - lx; - const distT = ly - bounds.minY; const distB = bounds.maxY - ly; + + const distL = lx - bounds.minX; + const distR = bounds.maxX - lx; + const distT = ly - bounds.minY; + const distB = bounds.maxY - ly; const minX = Math.min(distL, distR); const minY = Math.min(distT, distB); const axis = minX < minY ? 'y' : 'x'; + const width = bounds.maxX - bounds.minX; const height = bounds.maxY - bounds.minY; + // Рисуем фантом только если есть место (>10% ячейки) if ((axis === 'y' && height > 0.1) || (axis === 'x' && width > 0.1)) { const offset = axis === 'x' ? lx : ly; const min = axis === 'x' ? bounds.minY : bounds.minX; @@ -308,7 +317,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const x1 = sortedX[i]; const x2 = sortedX[i + 1]; const y1 = sortedY[j]; const y2 = sortedY[j + 1]; - // !!! FIX: Проверка y2 if (y2 === undefined || x2 === undefined) continue; const cellX = x1 * viewBoxW; const cellY = y1 * viewBoxH; @@ -322,15 +330,16 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const realW = (x2 - x1) * drawerW; const realD = (y2 - y1) * drawerD; - // Label if empty + // --- LABEL FOR EMPTY CELL --- if (parts.length === 0) { const labelX = cellX + cellW / 2; const labelY = cellY + cellH / 2; const textW = Math.max(0, realW - wallThick).toFixed(0); const textD = Math.max(0, realD - wallThick).toFixed(0); + // Увеличен шрифт до 16px if (cellH > 40 && cellW > 60) { elements.push( - + {textW} × {textD} ); @@ -344,36 +353,34 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { {parts.map(p => { const pMin = p.min ?? 0; const pMax = p.max ?? 1; - let lx1, ly1, lx2, ly2; - let tx, ty; - let dist1 = 0, dist2 = 0; - - // Ищем границы для размеров + let lx1, ly1, lx2, ly2; // Координаты линии + let dist1 = 0, dist2 = 0; // Расстояния + + // Ищем соседей для расчета размеров const neighbors = getNeighborOffsets(p.offset, (pMin + pMax)/2, p.axis, parts); + const isVertical = p.axis === 'x'; - if (p.axis === 'x') { + if (isVertical) { const px = cellX + (cellW * p.offset); lx1 = px; lx2 = px; ly1 = cellY + (cellH * pMin); ly2 = cellY + (cellH * pMax); - - // Дистанция = (Мой Оффсет - Оффсет Соседа) * Ширину Ячейки - Толщина стенки + // Расчет расстояний по горизонтали dist1 = Math.abs((p.offset - neighbors.min) * realW) - wallThick; dist2 = Math.abs((neighbors.max - p.offset) * realW) - wallThick; - - tx = px; ty = (ly1 + ly2) / 2; } else { const py = cellY + (cellH * p.offset); ly1 = py; ly2 = py; lx1 = cellX + (cellW * pMin); lx2 = cellX + (cellW * pMax); - + // Расчет расстояний по вертикали dist1 = Math.abs((p.offset - neighbors.min) * realD) - wallThick; dist2 = Math.abs((neighbors.max - p.offset) * realD) - wallThick; - - tx = (lx1 + lx2) / 2; ty = py; } const isSel = selectedPartitionId === p.id; const isHov = hoveredPartition?.id === p.id; + const midX = (lx1 + lx2) / 2; + const midY = (ly1 + ly2) / 2; + const textOffset = 8; // Отступ текста от линии return ( @@ -382,24 +389,31 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { - {/* DIMENSIONS */} - - {p.axis === 'x' ? ( + {/* DIMENSIONS - Увеличен шрифт до 14px */} + + {isVertical ? ( + // Для вертикальных линий: два отдельных текста слева и справа, выровненных по центру высоты <> - {Math.max(0, dist1).toFixed(0)} - {Math.max(0, dist2).toFixed(0)} + + {Math.max(0, dist1).toFixed(0)} + + + {Math.max(0, dist2).toFixed(0)} + ) : ( - <> - {Math.max(0, dist1).toFixed(0)} - {Math.max(0, dist2).toFixed(0)} - + // Для горизонтальных линий: один текст по центру с tspan сверху и снизу + + {Math.max(0, dist1).toFixed(0)} + {Math.max(0, dist2).toFixed(0)} + )} - + ); })} + {/* Phantom Line */} {isHovered && phantomPartition && !hoveredPartition && !dragging && ( {(() => { From 6cd7a5194d679290b46448080fffeed0454de6f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sun, 11 Jan 2026 13:54:10 +0300 Subject: [PATCH 05/15] 3 --- src/components/LayoutStep.tsx | 312 ++++++++++++------------------ src/services/geometryGenerator.ts | 97 +++++----- 2 files changed, 174 insertions(+), 235 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index 65f1872..a2d44b2 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -18,23 +18,21 @@ type DragTarget = export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const svgRef = useRef(null); - // --- STATE --- + // -- STATE -- const [mode, setMode] = useState('lines'); const [mousePos, setMousePos] = useState({ x: 0, y: 0 }); const [dragging, setDragging] = useState(null); const [isButtonHovered, setIsButtonHovered] = useState(false); - // Main Grid const [phantomMainAxis, setPhantomMainAxis] = useState(null); const [hoveredMainSplit, setHoveredMainSplit] = useState<{ axis: Axis; index: number } | null>(null); - // Partitions const [hoveredCell, setHoveredCell] = useState<{ i: number; j: number } | null>(null); const [hoveredPartition, setHoveredPartition] = useState<{ id: string; cellKey: string } | null>(null); const [phantomPartition, setPhantomPartition] = useState<{ axis: Axis; offset: number; min: number; max: number } | null>(null); const [selectedPartitionId, setSelectedPartitionId] = useState(null); - // --- SAFE DATA --- + // -- DATA -- const safeX = Array.isArray(splits?.x) ? splits.x : []; const safeY = Array.isArray(splits?.y) ? splits.y : []; const safePartitions = splits?.partitions || {}; @@ -50,55 +48,48 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]); const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]); - // --- HELPERS --- - const getSelectedPartition = () => { - if (!selectedPartitionId) return null; - for (const key in safePartitions) { - const part = safePartitions[key].find(p => p.id === selectedPartitionId); - if (part) return { key, part }; - } - return null; - }; - const selectedData = getSelectedPartition(); - - // Поиск ближайших соседей для расчета размеров - const getNeighborOffsets = (currentOffset: number, crossPos: number, axis: Axis, parts: Partition[]) => { - let minLimit = 0; - let maxLimit = 1; + // -- LOGIC: Dynamic Neighbors Calculation -- + // Эта функция пересчитывает реальные границы стенки на лету + const calculateDynamicLimits = (target: { axis: Axis, offset: number, min?: number, max?: number }, parts: Partition[]) => { + let min = 0; + let max = 1; + // Используем сохраненные min/max только как "подсказку" где центр стенки + const mid = ((target.min ?? 0) + (target.max ?? 1)) / 2; parts.forEach(p => { - // Если стенка параллельна нашей - if (p.axis === axis) { - const pMin = p.min ?? 0; - const pMax = p.max ?? 1; - - // Проверяем пересечение проекций - if (crossPos > pMin && crossPos < pMax) { - if (p.offset < currentOffset) minLimit = Math.max(minLimit, p.offset); - if (p.offset > currentOffset) maxLimit = Math.min(maxLimit, p.offset); - } + if (p.axis === target.axis) return; // Игнорируем параллельные + + // Границы соседки (статические, но для соседки они тоже могут быть динамическими - тут упрощение для производительности) + // В идеале нужен рекурсивный солвер, но для 2D UI достаточно проверить попадание + const pMin = p.min ?? 0; + const pMax = p.max ?? 1; + + if (target.offset > pMin && target.offset < pMax) { + if (p.offset < mid) min = Math.max(min, p.offset); + else if (p.offset > mid) max = Math.min(max, p.offset); } }); - return { min: minLimit, max: maxLimit }; + return { min, max }; }; - // Поиск границ для НОВОЙ стенки (T-соединения) + // Поиск границ для НОВОЙ стенки (под курсором) const getHoveredBoundaries = (lx: number, ly: number, parts: Partition[]) => { + return calculateDynamicLimits({ axis: 'x', offset: lx, min: ly, max: ly }, parts); // Hack: передаем ly как min/max чтобы найти соседей по Y для X-стенки? + // Нет, для новой стенки логика чуть другая - мы ищем ближайшие стенки вокруг точки (lx, ly) + let minX = 0, maxX = 1; let minY = 0, maxY = 1; parts.forEach(p => { - const pMin = p.min ?? 0; - const pMax = p.max ?? 1; + // Вычисляем ДИНАМИЧЕСКИЕ границы для соседки, чтобы знать её реальную длину + const { min: pMin, max: pMax } = calculateDynamicLimits(p, parts); if (p.axis === 'x') { - // Вертикальная стенка. Ограничивает по X. if (ly >= pMin && ly <= pMax) { if (p.offset < lx) minX = Math.max(minX, p.offset); if (p.offset > lx) maxX = Math.min(maxX, p.offset); } } else { - // Горизонтальная стенка. Ограничивает по Y. if (lx >= pMin && lx <= pMax) { if (p.offset < ly) minY = Math.max(minY, p.offset); if (p.offset > ly) maxY = Math.min(maxY, p.offset); @@ -108,18 +99,14 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return { minX, maxX, minY, maxY }; }; - // --- ACTIONS --- + // -- ACTIONS -- const createPartition = (i: number, j: number, axis: Axis, offset: number, min: number, max: number) => { const key = `${i}-${j}`; const current = safePartitions[key] || []; const newPart: Partition = { id: Math.random().toString(36).substr(2, 9), - axis, - offset, - min, - max, - height: config.drawer.height || 80, - rounded: false + axis, offset, min, max, + height: config.drawer.height || 80, rounded: false }; onChange({ ...splits, partitions: { ...safePartitions, [key]: [...current, newPart] } }); setSelectedPartitionId(newPart.id); @@ -146,12 +133,21 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setDragging(null); }; - // --- MOUSE HANDLER --- + const getSelectedPartition = () => { + if (!selectedPartitionId) return null; + for (const key in safePartitions) { + const part = safePartitions[key].find(p => p.id === selectedPartitionId); + if (part) return { key, part }; + } + return null; + }; + const selectedData = getSelectedPartition(); + + // -- MOUSE -- const handleMouseMove = (e: React.MouseEvent) => { if (!svgRef.current) return; const rect = svgRef.current.getBoundingClientRect(); if (rect.width === 0) return; - const nx = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)); const ny = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height)); setMousePos({ x: nx, y: ny }); @@ -163,26 +159,17 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { newSplits[dragging.axis][dragging.index] = val; onChange(newSplits); } else { - // Dragging Partition const [iStr, jStr] = dragging.cellKey.split('-'); const i = parseInt(iStr); const j = parseInt(jStr); const cellX1 = sortedX[i]; const cellX2 = sortedX[i+1]; const cellY1 = sortedY[j]; const cellY2 = sortedY[j+1]; let newOffset = 0; - if (dragging.axis === 'x') { - newOffset = (nx - cellX1) / (cellX2 - cellX1); - } else { - newOffset = (ny - cellY1) / (cellY2 - cellY1); - } + if (dragging.axis === 'x') newOffset = (nx - cellX1) / (cellX2 - cellX1); + else newOffset = (ny - cellY1) / (cellY2 - cellY1); - // Ограничиваем перетаскивание. - // В идеале нужно динамически считать соседей, но для скорости пока ограничим ячейкой (2%-98%) newOffset = Math.max(0.02, Math.min(0.98, newOffset)); - - if (!isNaN(newOffset)) { - updatePartition(dragging.cellKey, dragging.id, { offset: newOffset }); - } + if (!isNaN(newOffset)) updatePartition(dragging.cellKey, dragging.id, { offset: newOffset }); } return; } @@ -195,13 +182,10 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (nx > SNAP && nx < 1 - SNAP && ny > SNAP && ny < 1 - SNAP) { const closeToX = safeX.some(val => Math.abs(nx - val) < SNAP); const closeToY = safeY.some(val => Math.abs(ny - val) < SNAP); - if (!closeToX && !closeToY) { - const distRight = 1 - nx; const distBottom = 1 - ny; - setPhantomMainAxis(Math.min(nx, distRight) < Math.min(ny, distBottom) ? 'y' : 'x'); - } else { setPhantomMainAxis(null); } + if (!closeToX && !closeToY) setPhantomMainAxis(Math.min(nx, 1-nx) < Math.min(ny, 1-ny) ? 'y' : 'x'); + else setPhantomMainAxis(null); } } else { - // Cells Mode setHoveredPartition(null); setPhantomPartition(null); setHoveredCell(null); @@ -211,8 +195,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (nx >= sortedX[i] && nx <= sortedX[i+1]) { for (let j = 0; j < sortedY.length - 1; j++) { if (ny >= sortedY[j] && ny <= sortedY[j+1]) { - cellIdx = { i, j }; - break; + cellIdx = { i, j }; break; } } } @@ -229,11 +212,11 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const lx = (nx - cx1) / cw; const ly = (ny - cy1) / ch; - // Check Existing Partitions Hover let found = null; const SNAP = 0.05; for (const p of parts) { - const pMin = p.min ?? 0; const pMax = p.max ?? 1; + // Для проверки наведения тоже используем динамические границы, чтобы не кликать в пустоту + const { min: pMin, max: pMax } = calculateDynamicLimits(p, parts); if (p.axis === 'x') { if (ly >= pMin && ly <= pMax && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p; } else { @@ -244,23 +227,16 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (found) { setHoveredPartition({ id: found.id, cellKey: key }); } else { - // Calculate Phantom Partition with T-junctions const bounds = getHoveredBoundaries(lx, ly, parts); - - const distL = lx - bounds.minX; - const distR = bounds.maxX - lx; - const distT = ly - bounds.minY; - const distB = bounds.maxY - ly; - + const distL = lx - bounds.minX; const distR = bounds.maxX - lx; + const distT = ly - bounds.minY; const distB = bounds.maxY - ly; const minX = Math.min(distL, distR); const minY = Math.min(distT, distB); const axis = minX < minY ? 'y' : 'x'; - const width = bounds.maxX - bounds.minX; const height = bounds.maxY - bounds.minY; - // Рисуем фантом только если есть место (>10% ячейки) if ((axis === 'y' && height > 0.1) || (axis === 'x' && width > 0.1)) { const offset = axis === 'x' ? lx : ly; const min = axis === 'x' ? bounds.minY : bounds.minX; @@ -274,7 +250,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const handleMouseDown = (e: React.MouseEvent) => { if (isButtonHovered) return; - if (mode === 'lines') { if (hoveredMainSplit) { if (e.button === 0) setDragging({ type: 'main', ...hoveredMainSplit }); @@ -309,14 +284,12 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { } }; - // --- RENDER --- const renderCellsAndPartitions = () => { const elements = []; for (let i = 0; i < sortedX.length - 1; i++) { for (let j = 0; j < sortedY.length - 1; j++) { const x1 = sortedX[i]; const x2 = sortedX[i + 1]; const y1 = sortedY[j]; const y2 = sortedY[j + 1]; - if (y2 === undefined || x2 === undefined) continue; const cellX = x1 * viewBoxW; const cellY = y1 * viewBoxH; @@ -326,17 +299,14 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const isHovered = hoveredCell?.i === i && hoveredCell?.j === j && mode === 'cells'; const parts = safePartitions[key] || []; const isAnySelected = parts.some(p => p.id === selectedPartitionId); - const realW = (x2 - x1) * drawerW; const realD = (y2 - y1) * drawerD; - // --- LABEL FOR EMPTY CELL --- if (parts.length === 0) { const labelX = cellX + cellW / 2; const labelY = cellY + cellH / 2; const textW = Math.max(0, realW - wallThick).toFixed(0); const textD = Math.max(0, realD - wallThick).toFixed(0); - // Увеличен шрифт до 16px if (cellH > 40 && cellW > 60) { elements.push( @@ -349,38 +319,79 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { elements.push( {isHovered && } - {isAnySelected && mode === 'cells' && } {parts.map(p => { - const pMin = p.min ?? 0; const pMax = p.max ?? 1; - let lx1, ly1, lx2, ly2; // Координаты линии - let dist1 = 0, dist2 = 0; // Расстояния + // ИСПОЛЬЗУЕМ ДИНАМИЧЕСКИЙ РАСЧЕТ ГРАНИЦ ДЛЯ ОТРИСОВКИ + const { min: pMin, max: pMax } = calculateDynamicLimits(p, parts); - // Ищем соседей для расчета размеров - const neighbors = getNeighborOffsets(p.offset, (pMin + pMax)/2, p.axis, parts); + let lx1, ly1, lx2, ly2; + let dist1 = 0, dist2 = 0; + let midX, midY; + const isVertical = p.axis === 'x'; if (isVertical) { const px = cellX + (cellW * p.offset); lx1 = px; lx2 = px; ly1 = cellY + (cellH * pMin); ly2 = cellY + (cellH * pMax); - // Расчет расстояний по горизонтали - dist1 = Math.abs((p.offset - neighbors.min) * realW) - wallThick; - dist2 = Math.abs((neighbors.max - p.offset) * realW) - wallThick; + + // Для X-стенки, p.offset - это X координата. + // pMin/pMax - это границы по Y. + // Чтобы найти расстояние по бокам, нам нужны границы по X. + // Мы ищем ВЕРТИКАЛЬНЫХ соседей в диапазоне Y [pMin, pMax] + // calculateDynamicLimits дает границы ВДОЛЬ самой стенки. Это нам дало высоту. + + // Теперь найдем ширину (слева/справа). + // Мы берем точку в центре стенки и ищем ближайших вертикальных соседей + const { min: leftLim, max: rightLim } = calculateDynamicLimits({ axis: 'y', offset: (pMin + pMax)/2, min: 0, max: 1 }, parts.filter(pp => pp.axis === 'x')); + // Это хак. Правильнее: + let left = 0, right = 1; + const cy = (pMin + pMax)/2; + parts.forEach(n => { + if (n.axis === 'x') { + // Соседка перекрывает нас по высоте? + // Нужно найти её реальные границы + const { min: nMin, max: nMax } = calculateDynamicLimits(n, parts); + if (cy > nMin && cy < nMax) { + if (n.offset < p.offset) left = Math.max(left, n.offset); + if (n.offset > p.offset) right = Math.min(right, n.offset); + } + } + }); + + dist1 = (p.offset - left) * realW - wallThick; + dist2 = (right - p.offset) * realW - wallThick; + + midX = px; + midY = (ly1 + ly2) / 2; + } else { const py = cellY + (cellH * p.offset); ly1 = py; ly2 = py; lx1 = cellX + (cellW * pMin); lx2 = cellX + (cellW * pMax); - // Расчет расстояний по вертикали - dist1 = Math.abs((p.offset - neighbors.min) * realD) - wallThick; - dist2 = Math.abs((neighbors.max - p.offset) * realD) - wallThick; + + let top = 0, bot = 1; + const cx = (pMin + pMax)/2; + parts.forEach(n => { + if (n.axis === 'y') { + const { min: nMin, max: nMax } = calculateDynamicLimits(n, parts); + if (cx > nMin && cx < nMax) { + if (n.offset < p.offset) top = Math.max(top, n.offset); + if (n.offset > p.offset) bot = Math.min(bot, n.offset); + } + } + }); + + dist1 = (p.offset - top) * realD - wallThick; + dist2 = (bot - p.offset) * realD - wallThick; + + midX = (lx1 + lx2) / 2; + midY = py; } const isSel = selectedPartitionId === p.id; const isHov = hoveredPartition?.id === p.id; - const midX = (lx1 + lx2) / 2; - const midY = (ly1 + ly2) / 2; - const textOffset = 8; // Отступ текста от линии + const textOffset = 10; return ( @@ -389,35 +400,27 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { - {/* DIMENSIONS - Увеличен шрифт до 14px */} {isVertical ? ( - // Для вертикальных линий: два отдельных текста слева и справа, выровненных по центру высоты <> - - {Math.max(0, dist1).toFixed(0)} - - - {Math.max(0, dist2).toFixed(0)} - + {Math.max(0, dist1).toFixed(0)} + {Math.max(0, dist2).toFixed(0)} ) : ( - // Для горизонтальных линий: один текст по центру с tspan сверху и снизу - - {Math.max(0, dist1).toFixed(0)} - {Math.max(0, dist2).toFixed(0)} - + <> + {Math.max(0, dist1).toFixed(0)} + {Math.max(0, dist2).toFixed(0)} + )} ); })} - {/* Phantom Line */} {isHovered && phantomPartition && !hoveredPartition && !dragging && ( {(() => { - const pMin = phantomPartition.min; const pMax = phantomPartition.max; + const { min: pMin, max: pMax } = phantomPartition; let fx1, fy1, fx2, fy2; if (phantomPartition.axis === 'x') { const px = cellX + (cellW * phantomPartition.offset); @@ -439,115 +442,58 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return (
- - {/* HEADER */}
-

- 2. Редактор макета -

- +

2. Редактор макета

- - + +
- - +
- {/* INFO */}
{mode === 'lines' ? ( -
- ЛКМ: Линия - ПКМ: Удалить -
+
ЛКМ: ЛинияПКМ: Удалить
) : ( -
- ЛКМ в ячейке: Стенка - Драг: Двигать - 2xЛКМ: Удалить -
+
ЛКМ в ячейке: СтенкаДраг: Двигать2xЛКМ: Удалить
)}
- {/* CANVAS */}
-
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'), - }} - > - setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()} - > - - - - - +
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') }}> + setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()}> + - {renderCellsAndPartitions()} - - {/* MAIN GRID X */} {safeX.map((x, i) => ( { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'x', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('x', i); }}> ))} - - {/* MAIN GRID Y */} {safeY.map((y, i) => ( { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'y', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('y', i); }}> ))} - - {/* PHANTOMS */} - {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'x' && } - {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'y' && } + {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis && ( + + )}
- {/* SIDEBAR */} {mode === 'cells' && selectedData && (
-
-

Настройки стенки

- -
+

Настройки стенки

-
-
Высота {selectedData.part.height} мм
- updatePartition(selectedData.key, selectedData.part.id, { height: parseFloat(e.target.value) })} className="w-full h-1 bg-slate-600 rounded-lg appearance-none cursor-pointer accent-purple-500"/> -
-
- - updatePartition(selectedData.key, selectedData.part.id, { rounded: e.target.checked })} className="w-4 h-4 rounded bg-slate-700 border-slate-600 text-purple-500 focus:ring-0 cursor-pointer"/> -
- +
Высота {selectedData.part.height} мм
updatePartition(selectedData.key, selectedData.part.id, { height: parseFloat(e.target.value) })} className="w-full h-1 bg-slate-600 rounded-lg appearance-none cursor-pointer accent-purple-500"/>
+
updatePartition(selectedData.key, selectedData.part.id, { rounded: e.target.checked })} className="w-4 h-4 rounded bg-slate-700 border-slate-600 text-purple-500 focus:ring-0 cursor-pointer"/>
+
-
Выделите стенку для настройки.
Двойной клик удаляет её.
)}
diff --git a/src/services/geometryGenerator.ts b/src/services/geometryGenerator.ts index 354166f..96daedc 100644 --- a/src/services/geometryGenerator.ts +++ b/src/services/geometryGenerator.ts @@ -48,7 +48,6 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat // --- ГЕОМЕТРИЯ --- -// 1. Форма скругленного прямоугольника (для дна и внешних стенок) const createRoundedRectShape = (width: number, height: number, radius: number): THREE.Shape => { const shape = new THREE.Shape(); const x = -width / 2; @@ -75,35 +74,60 @@ const createRoundedRectShape = (width: number, height: number, radius: number): return shape; }; -// 2. Форма галтели (вогнутого треугольника) для углов const createFilletShape = (radius: number): THREE.Shape => { const shape = new THREE.Shape(); - // Начинаем из угла (0,0) shape.moveTo(0, 0); - // Линия вдоль одной стенки shape.lineTo(radius, 0); - // Вогнутая дуга к другой стенке - // Центр окружности (radius, radius), радиус radius. - // Рисуем дугу от 270 (-PI/2) до 180 (PI) градусов по часовой стрелке shape.absarc(radius, radius, radius, 1.5 * Math.PI, Math.PI, true); - // Замыкаем в угол shape.lineTo(0, 0); - return shape; }; +// --- УМНЫЙ РАСЧЕТ ГРАНИЦ (Fix overlapping walls) --- +const calculateDynamicLimits = (target: Partition, allParts: Partition[]) => { + let min = 0; + let max = 1; + + // Центр текущей стенки (чтобы понять, в каком мы сегменте) + const mid = ((target.min ?? 0) + (target.max ?? 1)) / 2; + + allParts.forEach(p => { + // Нас интересуют только ПЕРПЕНДИКУЛЯРНЫЕ стенки + if (p.axis === target.axis) return; + + // Определяем, пересекает ли соседка путь нашей стенки + // Для этого соседка должна "покрывать" нашу координату offset + const pMin = p.min ?? 0; + const pMax = p.max ?? 1; + + // p.offset - это позиция соседки по нашей оси движения + // target.offset - это наша позиция по оси соседки + + if (target.offset > pMin && target.offset < pMax) { + // Соседка стоит на пути. Где она? Сверху или снизу (слева или справа)? + if (p.offset < mid) { + // Соседка "перед" нами, это новая нижняя граница + min = Math.max(min, p.offset); + } else if (p.offset > mid) { + // Соседка "после" нас, это новая верхняя граница + max = Math.min(max, p.offset); + } + } + }); + + return { min, max }; +}; + export const createBinGeometry = ( width: number, depth: number, height: number, thickness: number, radius: number = 0, partitions: Partition[] = [] ): THREE.BufferGeometry => { const geometries: THREE.BufferGeometry[] = []; - // ДНО const floorShape = createRoundedRectShape(width, depth, radius); const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false, curveSegments: 12 }); floorGeo.rotateX(-Math.PI / 2); geometries.push(floorGeo); - // ВНЕШНИЕ СТЕНКИ const outerShape = createRoundedRectShape(width, depth, radius); const innerRadius = Math.max(0, radius - thickness); const innerWidth = width - (2 * thickness); @@ -120,16 +144,15 @@ export const createBinGeometry = ( wallGeo.translate(0, thickness, 0); geometries.push(wallGeo); - // ВНУТРЕННИЕ ПЕРЕГОРОДКИ И СКРУГЛЕНИЯ partitions.forEach(p => { - const pMin = p.min ?? 0; - const pMax = p.max ?? 1; + // ИСПОЛЬЗУЕМ ДИНАМИЧЕСКИЙ РАСЧЕТ ВМЕСТО p.min/p.max + const { min: pMin, max: pMax } = calculateDynamicLimits(p, partitions); + const lengthRatio = pMax - pMin; const midRatio = pMin + (lengthRatio / 2); let pWidth = 0, pDepth = 0, pX = 0, pY = 0; - // Размеры самой стенки if (p.axis === 'x') { pWidth = thickness; pDepth = lengthRatio * innerDepth; @@ -142,28 +165,21 @@ export const createBinGeometry = ( pY = (-innerDepth / 2) + (innerDepth * p.offset); } - // Создаем стенку - const partShape = createRoundedRectShape(pWidth, pDepth, 0.1); // Чуть-чуть скругляем саму стенку, чтобы не была острой + const partShape = createRoundedRectShape(pWidth, pDepth, 0.1); const partGeo = new THREE.ExtrudeGeometry(partShape, { depth: p.height, bevelEnabled: false, curveSegments: 2 }); partGeo.rotateX(-Math.PI / 2); partGeo.translate(pX, thickness, pY); geometries.push(partGeo); - // --- ДОБАВЛЕНИЕ ГАЛТЕЛЕЙ (FILLETS) --- if (p.rounded && radius > 0.5) { - // Радиус скругления такой же, как у углов ящика, но не больше разумного предела const filletR = Math.min(radius, 6); const filletShape = createFilletShape(filletR); const filletExtrudeSettings = { depth: p.height, bevelEnabled: false, curveSegments: 8 }; - // Функция для создания и позиционирования одной галтели const addFillet = (x: number, y: number, rotation: number) => { const geo = new THREE.ExtrudeGeometry(filletShape, filletExtrudeSettings); - geo.rotateX(-Math.PI / 2); // Положить на пол - geo.rotateY(rotation); // Повернуть в нужный угол - - // Корректировка позиции после вращения вокруг (0,0) - // Нам нужно сместить так, чтобы угол (0,0) галтели совпал с углом стыка + geo.rotateX(-Math.PI / 2); + geo.rotateY(rotation); geo.translate(x, thickness, y); geometries.push(geo); }; @@ -171,40 +187,17 @@ export const createBinGeometry = ( const halfThick = thickness / 2; if (p.axis === 'x') { - // Вертикальная стенка. Концы: Top (pMin) и Bottom (pMax) (в 2D координатах Y) - // Y координата начала: -innerDepth/2 + innerDepth * pMin - // Y координата конца: -innerDepth/2 + innerDepth * pMax - // X координата центра: pX - const startY = (-innerDepth / 2) + (innerDepth * pMin); const endY = (-innerDepth / 2) + (innerDepth * pMax); - - // 4 Угла: - // 1. Start Left: X = pX - halfThick, Y = startY. Rotation: 0 (смотрит вправо-вверх? нет) - // Галтель рисуется в +X, +Y квадранте от 0,0. - // Нам нужно заполнить угол между стенкой (идет вниз) и перпендикуляром. - - // Start (Top in 2D view, actually Min Y in 3D logic here usually means "Back") - // Let's assume standard plan view: - // Min Y is "Top" edge visually in SVG usually 0. In 3D Z is Y. - - // Min End (Start of wall): - addFillet(pX - halfThick, startY, 0); // Left side, pointing towards +Z (down in visual) - addFillet(pX + halfThick, startY, -Math.PI/2); // Right side - - // Max End (End of wall): - addFillet(pX - halfThick, endY, Math.PI/2); // Left side - addFillet(pX + halfThick, endY, Math.PI); // Right side + addFillet(pX - halfThick, startY, 0); + addFillet(pX + halfThick, startY, -Math.PI/2); + addFillet(pX - halfThick, endY, Math.PI/2); + addFillet(pX + halfThick, endY, Math.PI); } else { - // Горизонтальная стенка const startX = (-innerWidth / 2) + (innerWidth * pMin); const endX = (-innerWidth / 2) + (innerWidth * pMax); - - // Min End (Left side): addFillet(startX, pY + halfThick, -Math.PI/2); addFillet(startX, pY - halfThick, 0); - - // Max End (Right side): addFillet(endX, pY + halfThick, Math.PI); addFillet(endX, pY - halfThick, Math.PI/2); } From 490adb8ac62140a3da46fb104f51e07383712cee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sun, 11 Jan 2026 14:02:04 +0300 Subject: [PATCH 06/15] 4 --- src/components/LayoutStep.tsx | 189 +++++++++++++++++----------------- 1 file changed, 92 insertions(+), 97 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index a2d44b2..35ecd49 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -24,9 +24,11 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const [dragging, setDragging] = useState(null); const [isButtonHovered, setIsButtonHovered] = useState(false); + // Main Grid Hover const [phantomMainAxis, setPhantomMainAxis] = useState(null); const [hoveredMainSplit, setHoveredMainSplit] = useState<{ axis: Axis; index: number } | null>(null); + // Partition Hover const [hoveredCell, setHoveredCell] = useState<{ i: number; j: number } | null>(null); const [hoveredPartition, setHoveredPartition] = useState<{ id: string; cellKey: string } | null>(null); const [phantomPartition, setPhantomPartition] = useState<{ axis: Axis; offset: number; min: number; max: number } | null>(null); @@ -48,54 +50,82 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]); const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]); - // -- LOGIC: Dynamic Neighbors Calculation -- - // Эта функция пересчитывает реальные границы стенки на лету - const calculateDynamicLimits = (target: { axis: Axis, offset: number, min?: number, max?: number }, parts: Partition[]) => { + // -- HELPERS -- + const getSelectedPartition = () => { + if (!selectedPartitionId) return null; + for (const key in safePartitions) { + const part = safePartitions[key].find(p => p.id === selectedPartitionId); + if (part) return { key, part }; + } + return null; + }; + const selectedData = getSelectedPartition(); + + // 1. Рассчитываем реальные (динамические) границы стенки, основываясь на её соседях. + // Это нужно, чтобы отрисовать стенку "обрезанной" по соседним стенкам. + const calculateWallLimits = (target: Partition, allParts: Partition[]) => { let min = 0; let max = 1; - // Используем сохраненные min/max только как "подсказку" где центр стенки - const mid = ((target.min ?? 0) + (target.max ?? 1)) / 2; + + // Середина стенки (используем сохраненные данные как подсказку центра) + const center = ((target.min ?? 0) + (target.max ?? 1)) / 2; - parts.forEach(p => { - if (p.axis === target.axis) return; // Игнорируем параллельные + allParts.forEach(p => { + // Ищем только перпендикулярные стенки + if (p.axis === target.axis) return; - // Границы соседки (статические, но для соседки они тоже могут быть динамическими - тут упрощение для производительности) - // В идеале нужен рекурсивный солвер, но для 2D UI достаточно проверить попадание + // Проверяем, пересекает ли соседка нашу линию движения. + // Соседка P (перпендикулярная) имеет offset по своей оси (которая совпадает с нашей осью движения) + // И занимает диапазон [p.min, p.max] по нашей перпендикулярной оси. + const pMin = p.min ?? 0; const pMax = p.max ?? 1; + // target.offset - это наша позиция. Попадает ли она в диапазон длины соседки? if (target.offset > pMin && target.offset < pMax) { - if (p.offset < mid) min = Math.max(min, p.offset); - else if (p.offset > mid) max = Math.min(max, p.offset); + // Да, соседка стоит на нашем пути. + // Где она? Сзади (уменьшает min) или спереди (уменьшает max)? + if (p.offset < center) { + min = Math.max(min, p.offset); + } else if (p.offset > center) { + max = Math.min(max, p.offset); + } } }); return { min, max }; }; - // Поиск границ для НОВОЙ стенки (под курсором) - const getHoveredBoundaries = (lx: number, ly: number, parts: Partition[]) => { - return calculateDynamicLimits({ axis: 'x', offset: lx, min: ly, max: ly }, parts); // Hack: передаем ly как min/max чтобы найти соседей по Y для X-стенки? - // Нет, для новой стенки логика чуть другая - мы ищем ближайшие стенки вокруг точки (lx, ly) - + // 2. Рассчитываем "коробку" под курсором мыши для создания НОВОЙ стенки. + // Используем 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 } = calculateDynamicLimits(p, parts); + // Сначала рассчитываем актуальные границы для всех существующих стенок, + // чтобы знать их реальную длину. + const processedParts = parts.map(p => ({ + ...p, + ...calculateWallLimits(p, parts) // Добавляем min/max calculated + })); + processedParts.forEach(p => { if (p.axis === 'x') { - if (ly >= pMin && ly <= pMax) { + // Вертикальная стенка (препятствие по X) + // Проверяем, перекрывает ли она наш Y (курсор) + if (ly > p.min && ly < p.max) { if (p.offset < lx) minX = Math.max(minX, p.offset); if (p.offset > lx) maxX = Math.min(maxX, p.offset); } } else { - if (lx >= pMin && lx <= pMax) { + // Горизонтальная стенка (препятствие по Y) + // Проверяем, перекрывает ли она наш X (курсор) + if (lx > p.min && lx < p.max) { if (p.offset < ly) minY = Math.max(minY, p.offset); if (p.offset > ly) maxY = Math.min(maxY, p.offset); } } }); + return { minX, maxX, minY, maxY }; }; @@ -106,7 +136,8 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const newPart: Partition = { id: Math.random().toString(36).substr(2, 9), axis, offset, min, max, - height: config.drawer.height || 80, rounded: false + height: config.drawer.height || 80, + rounded: false }; onChange({ ...splits, partitions: { ...safePartitions, [key]: [...current, newPart] } }); setSelectedPartitionId(newPart.id); @@ -133,17 +164,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setDragging(null); }; - const getSelectedPartition = () => { - if (!selectedPartitionId) return null; - for (const key in safePartitions) { - const part = safePartitions[key].find(p => p.id === selectedPartitionId); - if (part) return { key, part }; - } - return null; - }; - const selectedData = getSelectedPartition(); - - // -- MOUSE -- + // -- MOUSE HANDLERS -- const handleMouseMove = (e: React.MouseEvent) => { if (!svgRef.current) return; const rect = svgRef.current.getBoundingClientRect(); @@ -214,33 +235,35 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { let found = null; const SNAP = 0.05; + // Check hover over existing (using dynamic limits for precision) for (const p of parts) { - // Для проверки наведения тоже используем динамические границы, чтобы не кликать в пустоту - const { min: pMin, max: pMax } = calculateDynamicLimits(p, parts); + const { min, max } = calculateWallLimits(p, parts); if (p.axis === 'x') { - if (ly >= pMin && ly <= pMax && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p; + if (ly >= min && ly <= max && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p; } else { - if (lx >= pMin && lx <= pMax && Math.abs(ly - p.offset) < SNAP * (aspectRatio < 1 ? 1 : 1/aspectRatio)) found = p; + if (lx >= min && lx <= max && Math.abs(ly - p.offset) < SNAP * (aspectRatio < 1 ? 1 : 1/aspectRatio)) found = p; } } if (found) { setHoveredPartition({ id: found.id, cellKey: key }); } else { - const bounds = getHoveredBoundaries(lx, ly, parts); - const distL = lx - bounds.minX; const distR = bounds.maxX - lx; - const distT = ly - bounds.minY; const distB = bounds.maxY - ly; + // Calculate Phantom Box + const box = getCursorBox(lx, ly, parts); + + const distL = lx - box.minX; const distR = box.maxX - lx; + const distT = ly - box.minY; const distB = box.maxY - ly; const minX = Math.min(distL, distR); const minY = Math.min(distT, distB); - const axis = minX < minY ? 'y' : 'x'; - const width = bounds.maxX - bounds.minX; - const height = bounds.maxY - bounds.minY; + const axis = minX < minY ? 'y' : 'x'; // Split shortest distance + const width = box.maxX - box.minX; + const height = box.maxY - box.minY; if ((axis === 'y' && height > 0.1) || (axis === 'x' && width > 0.1)) { const offset = axis === 'x' ? lx : ly; - const min = axis === 'x' ? bounds.minY : bounds.minX; - const max = axis === 'x' ? bounds.maxY : bounds.maxX; + const min = axis === 'x' ? box.minY : box.minX; + const max = axis === 'x' ? box.maxY : box.maxX; setPhantomPartition({ axis, offset, min, max }); } } @@ -284,6 +307,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { } }; + // --- RENDER --- const renderCellsAndPartitions = () => { const elements = []; for (let i = 0; i < sortedX.length - 1; i++) { @@ -319,74 +343,46 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { elements.push( {isHovered && } + {isAnySelected && mode === 'cells' && } {parts.map(p => { - // ИСПОЛЬЗУЕМ ДИНАМИЧЕСКИЙ РАСЧЕТ ГРАНИЦ ДЛЯ ОТРИСОВКИ - const { min: pMin, max: pMax } = calculateDynamicLimits(p, parts); + // Используем ту же логику Limits, что и для мыши, чтобы отрисовка совпадала с поведением + const { min, max } = calculateWallLimits(p, parts); let lx1, ly1, lx2, ly2; let dist1 = 0, dist2 = 0; let midX, midY; - const isVertical = p.axis === 'x'; + // Для расчета размеров нам нужны границы "коробки", в которой находится эта стенка + // Это по сути то же самое, что и getCursorBox, но для точки на стенке. + // Чтобы не дублировать код, используем пределы самой стенки и пределы перпендикулярного пространства + if (isVertical) { const px = cellX + (cellW * p.offset); lx1 = px; lx2 = px; - ly1 = cellY + (cellH * pMin); ly2 = cellY + (cellH * pMax); + ly1 = cellY + (cellH * min); ly2 = cellY + (cellH * max); - // Для X-стенки, p.offset - это X координата. - // pMin/pMax - это границы по Y. - // Чтобы найти расстояние по бокам, нам нужны границы по X. - // Мы ищем ВЕРТИКАЛЬНЫХ соседей в диапазоне Y [pMin, pMax] - // calculateDynamicLimits дает границы ВДОЛЬ самой стенки. Это нам дало высоту. + // Чтобы найти расстояние до левой/правой стенки, берем центр этой стенки + const cy = (min + max) / 2; + const box = getCursorBox(p.offset, cy, parts); // Используем Box-логику для поиска соседей - // Теперь найдем ширину (слева/справа). - // Мы берем точку в центре стенки и ищем ближайших вертикальных соседей - const { min: leftLim, max: rightLim } = calculateDynamicLimits({ axis: 'y', offset: (pMin + pMax)/2, min: 0, max: 1 }, parts.filter(pp => pp.axis === 'x')); - // Это хак. Правильнее: - let left = 0, right = 1; - const cy = (pMin + pMax)/2; - parts.forEach(n => { - if (n.axis === 'x') { - // Соседка перекрывает нас по высоте? - // Нужно найти её реальные границы - const { min: nMin, max: nMax } = calculateDynamicLimits(n, parts); - if (cy > nMin && cy < nMax) { - if (n.offset < p.offset) left = Math.max(left, n.offset); - if (n.offset > p.offset) right = Math.min(right, n.offset); - } - } - }); - - dist1 = (p.offset - left) * realW - wallThick; - dist2 = (right - p.offset) * realW - wallThick; + dist1 = Math.abs((p.offset - box.minX) * realW) - wallThick; + dist2 = Math.abs((box.maxX - p.offset) * realW) - wallThick; - midX = px; - midY = (ly1 + ly2) / 2; - + midX = px; midY = (ly1 + ly2) / 2; } else { const py = cellY + (cellH * p.offset); ly1 = py; ly2 = py; - lx1 = cellX + (cellW * pMin); lx2 = cellX + (cellW * pMax); + lx1 = cellX + (cellW * min); lx2 = cellX + (cellW * max); - let top = 0, bot = 1; - const cx = (pMin + pMax)/2; - parts.forEach(n => { - if (n.axis === 'y') { - const { min: nMin, max: nMax } = calculateDynamicLimits(n, parts); - if (cx > nMin && cx < nMax) { - if (n.offset < p.offset) top = Math.max(top, n.offset); - if (n.offset > p.offset) bot = Math.min(bot, n.offset); - } - } - }); + const cx = (min + max) / 2; + const box = getCursorBox(cx, p.offset, parts); - dist1 = (p.offset - top) * realD - wallThick; - dist2 = (bot - p.offset) * realD - wallThick; + dist1 = Math.abs((p.offset - box.minY) * realD) - wallThick; + dist2 = Math.abs((box.maxY - p.offset) * realD) - wallThick; - midX = (lx1 + lx2) / 2; - midY = py; + midX = (lx1 + lx2) / 2; midY = py; } const isSel = selectedPartitionId === p.id; @@ -399,7 +395,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { - {isVertical ? ( <> @@ -420,14 +415,14 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { {isHovered && phantomPartition && !hoveredPartition && !dragging && ( {(() => { - const { min: pMin, max: pMax } = phantomPartition; + const { min, max } = phantomPartition; let fx1, fy1, fx2, fy2; if (phantomPartition.axis === 'x') { const px = cellX + (cellW * phantomPartition.offset); - fx1 = px; fx2 = px; fy1 = cellY + (cellH * pMin); fy2 = cellY + (cellH * pMax); + fx1 = px; fx2 = px; fy1 = cellY + (cellH * min); fy2 = cellY + (cellH * max); } else { const py = cellY + (cellH * phantomPartition.offset); - fy1 = py; fy2 = py; fx1 = cellX + (cellW * pMin); fx2 = cellX + (cellW * pMax); + fy1 = py; fy2 = py; fx1 = cellX + (cellW * min); fx2 = cellX + (cellW * max); } return ; })()} From eb8c5c48c787db3ba783097531c5e6e6c5605d87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sun, 11 Jan 2026 14:12:17 +0300 Subject: [PATCH 07/15] 5 --- src/components/LayoutStep.tsx | 104 ++++++++++++-------------- src/services/geometryGenerator.ts | 119 ++++++++++++++++++------------ 2 files changed, 118 insertions(+), 105 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index 35ecd49..a7eeeb0 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -10,6 +10,8 @@ interface Props { type EditMode = 'lines' | 'cells'; type Axis = 'x' | 'y'; +type Limits = { min: number; max: number }; +type LimitMap = Record; type DragTarget = | { type: 'main'; axis: Axis; index: number } @@ -24,11 +26,9 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const [dragging, setDragging] = useState(null); const [isButtonHovered, setIsButtonHovered] = useState(false); - // Main Grid Hover const [phantomMainAxis, setPhantomMainAxis] = useState(null); const [hoveredMainSplit, setHoveredMainSplit] = useState<{ axis: Axis; index: number } | null>(null); - // Partition Hover const [hoveredCell, setHoveredCell] = useState<{ i: number; j: number } | null>(null); const [hoveredPartition, setHoveredPartition] = useState<{ id: string; cellKey: string } | null>(null); const [phantomPartition, setPhantomPartition] = useState<{ axis: Axis; offset: number; min: number; max: number } | null>(null); @@ -61,71 +61,62 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; const selectedData = getSelectedPartition(); - // 1. Рассчитываем реальные (динамические) границы стенки, основываясь на её соседях. - // Это нужно, чтобы отрисовать стенку "обрезанной" по соседним стенкам. - const calculateWallLimits = (target: Partition, allParts: Partition[]) => { + // --- CORE LOGIC: Two-Pass Limit Calculation (Sync with 3D) --- + const calculateLimits = (target: { axis: Axis, offset: number }, allParts: Partition[], limitMap: LimitMap | null) => { let min = 0; let max = 1; - - // Середина стенки (используем сохраненные данные как подсказку центра) - const center = ((target.min ?? 0) + (target.max ?? 1)) / 2; + const mid = target.offset; allParts.forEach(p => { - // Ищем только перпендикулярные стенки if (p.axis === target.axis) return; - // Проверяем, пересекает ли соседка нашу линию движения. - // Соседка P (перпендикулярная) имеет offset по своей оси (которая совпадает с нашей осью движения) - // И занимает диапазон [p.min, p.max] по нашей перпендикулярной оси. - - const pMin = p.min ?? 0; - const pMax = p.max ?? 1; + let pMin = p.min ?? 0; + let pMax = p.max ?? 1; + if (limitMap && limitMap[p.id]) { + pMin = limitMap[p.id].min; + pMax = limitMap[p.id].max; + } - // target.offset - это наша позиция. Попадает ли она в диапазон длины соседки? if (target.offset > pMin && target.offset < pMax) { - // Да, соседка стоит на нашем пути. - // Где она? Сзади (уменьшает min) или спереди (уменьшает max)? - if (p.offset < center) { - min = Math.max(min, p.offset); - } else if (p.offset > center) { - max = Math.min(max, p.offset); - } + if (p.offset < mid) min = Math.max(min, p.offset); + else if (p.offset > mid) max = Math.min(max, p.offset); } }); return { min, max }; }; - // 2. Рассчитываем "коробку" под курсором мыши для создания НОВОЙ стенки. - // Используем Raycasting: ищем ближайшие стенки во всех 4 направлениях. - const getCursorBox = (lx: number, ly: number, parts: Partition[]) => { + // Helper to get final limits for a list of parts + const getFinalLimitsMap = (parts: Partition[]): LimitMap => { + const map: LimitMap = {}; + // Pass 1 + parts.forEach(p => { map[p.id] = calculateLimits(p, parts, null); }); + // Pass 2 + parts.forEach(p => { map[p.id] = calculateLimits(p, parts, map); }); + return map; + }; + + // Calculate phantom box under cursor using Raycasting + const getCursorBox = (lx: number, ly: number, parts: Partition[], limitMap: LimitMap) => { let minX = 0, maxX = 1; let minY = 0, maxY = 1; - // Сначала рассчитываем актуальные границы для всех существующих стенок, - // чтобы знать их реальную длину. - const processedParts = parts.map(p => ({ - ...p, - ...calculateWallLimits(p, parts) // Добавляем min/max calculated - })); + parts.forEach(p => { + const { min: pMin, max: pMax } = limitMap[p.id]; + // Ignore collapsed walls + if (pMax - pMin < 0.001) return; - processedParts.forEach(p => { if (p.axis === 'x') { - // Вертикальная стенка (препятствие по X) - // Проверяем, перекрывает ли она наш Y (курсор) - if (ly > p.min && ly < p.max) { + if (ly > pMin && ly < pMax) { if (p.offset < lx) minX = Math.max(minX, p.offset); if (p.offset > lx) maxX = Math.min(maxX, p.offset); } } else { - // Горизонтальная стенка (препятствие по Y) - // Проверяем, перекрывает ли она наш X (курсор) - if (lx > p.min && lx < p.max) { + if (lx > pMin && lx < pMax) { if (p.offset < ly) minY = Math.max(minY, p.offset); if (p.offset > ly) maxY = Math.min(maxY, p.offset); } } }); - return { minX, maxX, minY, maxY }; }; @@ -226,6 +217,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setHoveredCell(cellIdx); const key = `${cellIdx.i}-${cellIdx.j}`; const parts = safePartitions[key] || []; + const limitMap = getFinalLimitsMap(parts); // Calculate limits once per move const cx1 = sortedX[cellIdx.i]; const cx2 = sortedX[cellIdx.i+1]; const cy1 = sortedY[cellIdx.j]; const cy2 = sortedY[cellIdx.j+1]; @@ -235,9 +227,9 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { let found = null; const SNAP = 0.05; - // Check hover over existing (using dynamic limits for precision) for (const p of parts) { - const { min, max } = calculateWallLimits(p, parts); + const { min, max } = limitMap[p.id]; + if (max - min < 0.001) continue; // Skip collapsed if (p.axis === 'x') { if (ly >= min && ly <= max && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p; } else { @@ -248,19 +240,18 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (found) { setHoveredPartition({ id: found.id, cellKey: key }); } else { - // Calculate Phantom Box - const box = getCursorBox(lx, ly, parts); + const box = getCursorBox(lx, ly, parts, limitMap); const distL = lx - box.minX; const distR = box.maxX - lx; const distT = ly - box.minY; const distB = box.maxY - ly; const minX = Math.min(distL, distR); const minY = Math.min(distT, distB); - const axis = minX < minY ? 'y' : 'x'; // Split shortest distance + const axis = minX < minY ? 'y' : 'x'; const width = box.maxX - box.minX; const height = box.maxY - box.minY; - if ((axis === 'y' && height > 0.1) || (axis === 'x' && width > 0.1)) { + 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; @@ -326,6 +317,9 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const realW = (x2 - x1) * drawerW; const realD = (y2 - y1) * drawerD; + // Calculate limits for rendering + const limitMap = getFinalLimitsMap(parts); + if (parts.length === 0) { const labelX = cellX + cellW / 2; const labelY = cellY + cellH / 2; @@ -346,30 +340,25 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { {isAnySelected && mode === 'cells' && } {parts.map(p => { - // Используем ту же логику Limits, что и для мыши, чтобы отрисовка совпадала с поведением - const { min, max } = calculateWallLimits(p, parts); - + const { min, max } = limitMap[p.id]; + if (max - min < 0.001) return null; // Don't render collapsed + let lx1, ly1, lx2, ly2; let dist1 = 0, dist2 = 0; let midX, midY; const isVertical = p.axis === 'x'; - - // Для расчета размеров нам нужны границы "коробки", в которой находится эта стенка - // Это по сути то же самое, что и getCursorBox, но для точки на стенке. - // Чтобы не дублировать код, используем пределы самой стенки и пределы перпендикулярного пространства if (isVertical) { const px = cellX + (cellW * p.offset); lx1 = px; lx2 = px; ly1 = cellY + (cellH * min); ly2 = cellY + (cellH * max); - // Чтобы найти расстояние до левой/правой стенки, берем центр этой стенки const cy = (min + max) / 2; - const box = getCursorBox(p.offset, cy, parts); // Используем Box-логику для поиска соседей + // Use already calculated limits for neighbors + const box = getCursorBox(p.offset, cy, parts, limitMap); dist1 = Math.abs((p.offset - box.minX) * realW) - wallThick; dist2 = Math.abs((box.maxX - p.offset) * realW) - wallThick; - midX = px; midY = (ly1 + ly2) / 2; } else { const py = cellY + (cellH * p.offset); @@ -377,11 +366,10 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { lx1 = cellX + (cellW * min); lx2 = cellX + (cellW * max); const cx = (min + max) / 2; - const box = getCursorBox(cx, p.offset, parts); + const box = getCursorBox(cx, p.offset, parts, limitMap); dist1 = Math.abs((p.offset - box.minY) * realD) - wallThick; dist2 = Math.abs((box.maxY - p.offset) * realD) - wallThick; - midX = (lx1 + lx2) / 2; midY = py; } diff --git a/src/services/geometryGenerator.ts b/src/services/geometryGenerator.ts index 96daedc..8d7b71f 100644 --- a/src/services/geometryGenerator.ts +++ b/src/services/geometryGenerator.ts @@ -2,6 +2,10 @@ import * as THREE from 'three'; import { STLExporter, mergeBufferGeometries } from 'three-stdlib'; import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types'; +// --- ТИПЫ ДЛЯ РАСЧЕТА --- +type Limits = { min: number; max: number }; +type LimitMap = Record; + export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => { const parts: GeneratedPart[] = []; const safeX = Array.isArray(splits?.x) ? splits.x : []; @@ -15,11 +19,15 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat for (let i = 0; i < xPoints.length - 1; i++) { for (let j = 0; j < yPoints.length - 1; j++) { - const rawX = xPoints[i] * config.drawer.width; - const rawY = yPoints[j] * config.drawer.depth; const rawW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width; const rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth; + // Пропускаем слишком маленькие ячейки + if (rawW < 10 || rawD < 10) continue; + + const rawX = xPoints[i] * config.drawer.width; + const rawY = yPoints[j] * config.drawer.depth; + const internalPartitions = safeParts[`${i}-${j}`] || []; const realWidth = rawW - config.printerTolerance; @@ -52,7 +60,8 @@ const createRoundedRectShape = (width: number, height: number, radius: number): const shape = new THREE.Shape(); const x = -width / 2; const y = -height / 2; - const r = Math.min(radius, width / 2, height / 2); + // Ограничиваем радиус, чтобы не сломать геометрию при маленьких размерах + const r = Math.min(radius, width / 2 - 0.1, height / 2 - 0.1); if (r <= 0.1) { shape.moveTo(x, y); @@ -74,47 +83,40 @@ const createRoundedRectShape = (width: number, height: number, radius: number): return shape; }; +// Форма галтели (вогнутый угол) const createFilletShape = (radius: number): THREE.Shape => { const shape = new THREE.Shape(); shape.moveTo(0, 0); shape.lineTo(radius, 0); + // Рисуем вогнутую дугу в квадранте (+X, +Y) shape.absarc(radius, radius, radius, 1.5 * Math.PI, Math.PI, true); shape.lineTo(0, 0); return shape; }; -// --- УМНЫЙ РАСЧЕТ ГРАНИЦ (Fix overlapping walls) --- -const calculateDynamicLimits = (target: Partition, allParts: Partition[]) => { +// --- УМНЫЙ РАСЧЕТ ГРАНИЦ (ДВУХПРОХОДНЫЙ) --- +const calculateLimits = (target: Partition, allParts: Partition[], limitMap: LimitMap | null) => { let min = 0; let max = 1; - - // Центр текущей стенки (чтобы понять, в каком мы сегменте) - const mid = ((target.min ?? 0) + (target.max ?? 1)) / 2; + const mid = target.offset; // Используем offset как центр для определения стороны allParts.forEach(p => { - // Нас интересуют только ПЕРПЕНДИКУЛЯРНЫЕ стенки - if (p.axis === target.axis) return; + if (p.axis === target.axis) return; // Игнорируем параллельные - // Определяем, пересекает ли соседка путь нашей стенки - // Для этого соседка должна "покрывать" нашу координату offset - const pMin = p.min ?? 0; - const pMax = p.max ?? 1; - - // p.offset - это позиция соседки по нашей оси движения - // target.offset - это наша позиция по оси соседки - + // Получаем границы соседки. Если это второй проход, берем уже рассчитанные. + let pMin = p.min ?? 0; + let pMax = p.max ?? 1; + if (limitMap && limitMap[p.id]) { + pMin = limitMap[p.id].min; + pMax = limitMap[p.id].max; + } + + // Проверяем пересечение if (target.offset > pMin && target.offset < pMax) { - // Соседка стоит на пути. Где она? Сверху или снизу (слева или справа)? - if (p.offset < mid) { - // Соседка "перед" нами, это новая нижняя граница - min = Math.max(min, p.offset); - } else if (p.offset > mid) { - // Соседка "после" нас, это новая верхняя граница - max = Math.min(max, p.offset); - } + if (p.offset < mid) min = Math.max(min, p.offset); + else if (p.offset > mid) max = Math.min(max, p.offset); } }); - return { min, max }; }; @@ -123,30 +125,42 @@ export const createBinGeometry = ( ): THREE.BufferGeometry => { const geometries: THREE.BufferGeometry[] = []; + // ДНО const floorShape = createRoundedRectShape(width, depth, radius); - const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false, curveSegments: 12 }); + const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false, curveSegments: 16 }); floorGeo.rotateX(-Math.PI / 2); geometries.push(floorGeo); + // ВНЕШНИЕ СТЕНКИ const outerShape = createRoundedRectShape(width, depth, radius); - const innerRadius = Math.max(0, radius - thickness); + const innerRadius = Math.max(0.1, radius - thickness); const innerWidth = width - (2 * thickness); const innerDepth = depth - (2 * thickness); - if (innerWidth > 0 && innerDepth > 0) { + if (innerWidth > 0.1 && innerDepth > 0.1) { const innerHole = createRoundedRectShape(innerWidth, innerDepth, innerRadius); outerShape.holes.push(innerHole); } const wallHeight = height - thickness; - const wallGeo = new THREE.ExtrudeGeometry(outerShape, { depth: wallHeight, bevelEnabled: false, curveSegments: 12 }); + const wallGeo = new THREE.ExtrudeGeometry(outerShape, { depth: wallHeight, bevelEnabled: false, curveSegments: 16 }); wallGeo.rotateX(-Math.PI / 2); wallGeo.translate(0, thickness, 0); geometries.push(wallGeo); + // --- РАСЧЕТ ГРАНИЦ ПЕРЕГОРОДОК (2 ПРОХОДА) --- + const limitMap: LimitMap = {}; + // Проход 1: Считаем черновые границы + partitions.forEach(p => { limitMap[p.id] = calculateLimits(p, partitions, null); }); + // Проход 2: Уточняем границы, используя результаты первого прохода + partitions.forEach(p => { limitMap[p.id] = calculateLimits(p, partitions, limitMap); }); + + // --- ГЕНЕРАЦИЯ ПЕРЕГОРОДОК --- partitions.forEach(p => { - // ИСПОЛЬЗУЕМ ДИНАМИЧЕСКИЙ РАСЧЕТ ВМЕСТО p.min/p.max - const { min: pMin, max: pMax } = calculateDynamicLimits(p, partitions); + const { min: pMin, max: pMax } = limitMap[p.id]; + + // Если стенка схлопнулась в ноль или стала отрицательной - пропускаем + if (pMax - pMin < 0.01) return; const lengthRatio = pMax - pMin; const midRatio = pMin + (lengthRatio / 2); @@ -165,16 +179,20 @@ export const createBinGeometry = ( pY = (-innerDepth / 2) + (innerDepth * p.offset); } - const partShape = createRoundedRectShape(pWidth, pDepth, 0.1); - const partGeo = new THREE.ExtrudeGeometry(partShape, { depth: p.height, bevelEnabled: false, curveSegments: 2 }); + // Сама стенка (чуть скругленная для красоты) + const partShape = createRoundedRectShape(pWidth, pDepth, 0.2); + const partGeo = new THREE.ExtrudeGeometry(partShape, { depth: p.height, bevelEnabled: false, curveSegments: 4 }); partGeo.rotateX(-Math.PI / 2); partGeo.translate(pX, thickness, pY); geometries.push(partGeo); - if (p.rounded && radius > 0.5) { - const filletR = Math.min(radius, 6); + // --- ГАЛТЕЛИ (СКРУГЛЕНИЯ) --- + if (p.rounded && radius > 1) { + const filletR = Math.min(radius, 6, thickness * 2); + if (filletR < 0.5) return; + const filletShape = createFilletShape(filletR); - const filletExtrudeSettings = { depth: p.height, bevelEnabled: false, curveSegments: 8 }; + const filletExtrudeSettings = { depth: p.height, bevelEnabled: false, curveSegments: 12 }; const addFillet = (x: number, y: number, rotation: number) => { const geo = new THREE.ExtrudeGeometry(filletShape, filletExtrudeSettings); @@ -187,26 +205,33 @@ export const createBinGeometry = ( const halfThick = thickness / 2; if (p.axis === 'x') { + // ВЕРТИКАЛЬНАЯ СТЕНКА - Углы были правильные const startY = (-innerDepth / 2) + (innerDepth * pMin); const endY = (-innerDepth / 2) + (innerDepth * pMax); - addFillet(pX - halfThick, startY, 0); - addFillet(pX + halfThick, startY, -Math.PI/2); - addFillet(pX - halfThick, endY, Math.PI/2); - addFillet(pX + halfThick, endY, Math.PI); + addFillet(pX - halfThick, startY, 0); // Top-Left + addFillet(pX + halfThick, startY, -Math.PI/2); // Top-Right + addFillet(pX - halfThick, endY, Math.PI/2); // Bottom-Left + addFillet(pX + halfThick, endY, Math.PI); // Bottom-Right } else { + // ГОРИЗОНТАЛЬНАЯ СТЕНКА - ИСПРАВЛЕНЫ УГЛЫ const startX = (-innerWidth / 2) + (innerWidth * pMin); const endX = (-innerWidth / 2) + (innerWidth * pMax); - addFillet(startX, pY + halfThick, -Math.PI/2); - addFillet(startX, pY - halfThick, 0); - addFillet(endX, pY + halfThick, Math.PI); - addFillet(endX, pY - halfThick, Math.PI/2); + + // Left End + addFillet(startX, pY + halfThick, 0); // Top-Left + addFillet(startX, pY - halfThick, Math.PI/2); // Bottom-Left + + // Right End + addFillet(endX, pY + halfThick, -Math.PI/2); // Top-Right + addFillet(endX, pY - halfThick, Math.PI); // Bottom-Right } } }); const merged = mergeBufferGeometries(geometries); if (merged) merged.computeVertexNormals(); - return merged || new THREE.BoxGeometry(1, 1, 1); + // Возвращаем пустой бокс если ничего не сгенерировалось, чтобы не крашить + return merged || new THREE.BoxGeometry(0.1, 0.1, 0.1); }; export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => { From 94eb2f00b2b85bcc4b6e485cd6ccb2a178f4d68b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sun, 11 Jan 2026 14:26:00 +0300 Subject: [PATCH 08/15] 6 --- src/components/LayoutStep.tsx | 96 ++++++++-------- src/services/geometryGenerator.ts | 175 ++++++++++++++++-------------- 2 files changed, 139 insertions(+), 132 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index a7eeeb0..45aa85c 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -61,48 +61,43 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; const selectedData = getSelectedPartition(); - // --- CORE LOGIC: Two-Pass Limit Calculation (Sync with 3D) --- - const calculateLimits = (target: { axis: Axis, offset: number }, allParts: Partition[], limitMap: LimitMap | null) => { - let min = 0; - let max = 1; - const mid = target.offset; + // --- SOLVER (Копия из geometryGenerator для синхронизации) --- + const solveWallLimits = (parts: Partition[]): LimitMap => { + const limits: LimitMap = {}; + parts.forEach(p => { limits[p.id] = { min: 0, max: 1 }; }); - allParts.forEach(p => { - if (p.axis === target.axis) return; + for (let pass = 0; pass < 3; pass++) { + parts.forEach(target => { + let newMin = 0; + let newMax = 1; + const center = target.offset; - let pMin = p.min ?? 0; - let pMax = p.max ?? 1; - if (limitMap && limitMap[p.id]) { - pMin = limitMap[p.id].min; - pMax = limitMap[p.id].max; - } + parts.forEach(obstacle => { + if (target.id === obstacle.id) return; + if (target.axis === obstacle.axis) return; - if (target.offset > pMin && target.offset < pMax) { - if (p.offset < mid) min = Math.max(min, p.offset); - else if (p.offset > mid) max = Math.min(max, p.offset); - } - }); - return { min, max }; + const obsMin = limits[obstacle.id].min; + const obsMax = limits[obstacle.id].max; + + if (target.offset > obsMin && target.offset < obsMax) { + 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; }; - // Helper to get final limits for a list of parts - const getFinalLimitsMap = (parts: Partition[]): LimitMap => { - const map: LimitMap = {}; - // Pass 1 - parts.forEach(p => { map[p.id] = calculateLimits(p, parts, null); }); - // Pass 2 - parts.forEach(p => { map[p.id] = calculateLimits(p, parts, map); }); - return map; - }; - - // Calculate phantom box under cursor using Raycasting + // Расчет границ для НОВОЙ стенки (используем уже решенные границы существующих) const getCursorBox = (lx: number, ly: number, parts: Partition[], limitMap: LimitMap) => { let minX = 0, maxX = 1; let minY = 0, maxY = 1; parts.forEach(p => { + // Берем актуальные границы const { min: pMin, max: pMax } = limitMap[p.id]; - // Ignore collapsed walls if (pMax - pMin < 0.001) return; if (p.axis === 'x') { @@ -127,8 +122,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const newPart: Partition = { id: Math.random().toString(36).substr(2, 9), axis, offset, min, max, - height: config.drawer.height || 80, - rounded: false + height: config.drawer.height || 80, rounded: false }; onChange({ ...splits, partitions: { ...safePartitions, [key]: [...current, newPart] } }); setSelectedPartitionId(newPart.id); @@ -155,7 +149,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setDragging(null); }; - // -- MOUSE HANDLERS -- + // -- MOUSE -- const handleMouseMove = (e: React.MouseEvent) => { if (!svgRef.current) return; const rect = svgRef.current.getBoundingClientRect(); @@ -217,7 +211,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setHoveredCell(cellIdx); const key = `${cellIdx.i}-${cellIdx.j}`; const parts = safePartitions[key] || []; - const limitMap = getFinalLimitsMap(parts); // Calculate limits once per move + 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]; @@ -229,7 +223,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const SNAP = 0.05; for (const p of parts) { const { min, max } = limitMap[p.id]; - if (max - min < 0.001) continue; // Skip collapsed if (p.axis === 'x') { if (ly >= min && ly <= max && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p; } else { @@ -242,20 +235,25 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { } else { const box = getCursorBox(lx, ly, parts, limitMap); + const axis = (lx - box.minX < box.maxX - lx) && (lx - box.minX < Math.min(ly - box.minY, box.maxY - ly)) ? 'x' : + (box.maxX - lx < lx - box.minX) && (box.maxX - lx < Math.min(ly - box.minY, box.maxY - ly)) ? 'x' : + Math.min(lx - box.minX, box.maxX - lx) < Math.min(ly - box.minY, box.maxY - ly) ? 'x' : 'y'; + + // Лучше: перпендикулярно ближайшей стороне const distL = lx - box.minX; const distR = box.maxX - lx; const distT = ly - box.minY; const distB = box.maxY - ly; - const minX = Math.min(distL, distR); - const minY = Math.min(distT, distB); + const minD = Math.min(distL, distR, distT, distB); - const axis = minX < minY ? 'y' : 'x'; + const newAxis = (minD === distL || minD === distR) ? 'x' : 'y'; + const width = box.maxX - box.minX; const height = box.maxY - box.minY; - 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 }); + if ((newAxis === 'y' && height > 0.05) || (newAxis === 'x' && width > 0.05)) { + 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 }); } } } @@ -317,8 +315,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const realW = (x2 - x1) * drawerW; const realD = (y2 - y1) * drawerD; - // Calculate limits for rendering - const limitMap = getFinalLimitsMap(parts); + const limitMap = solveWallLimits(parts); // SOLVER для отрисовки if (parts.length === 0) { const labelX = cellX + cellW / 2; @@ -341,7 +338,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { {parts.map(p => { const { min, max } = limitMap[p.id]; - if (max - min < 0.001) return null; // Don't render collapsed + if (max - min < 0.001) return null; let lx1, ly1, lx2, ly2; let dist1 = 0, dist2 = 0; @@ -354,9 +351,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { ly1 = cellY + (cellH * min); ly2 = cellY + (cellH * max); const cy = (min + max) / 2; - // Use already calculated limits for neighbors const box = getCursorBox(p.offset, cy, parts, limitMap); - dist1 = Math.abs((p.offset - box.minX) * realW) - wallThick; dist2 = Math.abs((box.maxX - p.offset) * realW) - wallThick; midX = px; midY = (ly1 + ly2) / 2; @@ -367,7 +362,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const cx = (min + max) / 2; const box = getCursorBox(cx, p.offset, parts, limitMap); - dist1 = Math.abs((p.offset - box.minY) * realD) - wallThick; dist2 = Math.abs((box.maxY - p.offset) * realD) - wallThick; midX = (lx1 + lx2) / 2; midY = py; @@ -375,7 +369,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const isSel = selectedPartitionId === p.id; const isHov = hoveredPartition?.id === p.id; - const textOffset = 10; + const textOffset = 12; return ( diff --git a/src/services/geometryGenerator.ts b/src/services/geometryGenerator.ts index 8d7b71f..35ed368 100644 --- a/src/services/geometryGenerator.ts +++ b/src/services/geometryGenerator.ts @@ -2,10 +2,52 @@ import * as THREE from 'three'; import { STLExporter, mergeBufferGeometries } from 'three-stdlib'; import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types'; -// --- ТИПЫ ДЛЯ РАСЧЕТА --- +// Типы для внутреннего решателя type Limits = { min: number; max: number }; type LimitMap = Record; +// --- SOLVER: Итеративный расчет границ --- +// Эта функция гарантирует, что стенки не будут торчать друг из друга +const solveWallLimits = (partitions: Partition[]): LimitMap => { + const limits: LimitMap = {}; + + // 1. Инициализация: считаем, что все стенки идут от 0 до 1 + partitions.forEach(p => { limits[p.id] = { min: 0, max: 1 }; }); + + // 2. Итеративное решение (3 прохода достаточно для любой вложенности) + for (let pass = 0; pass < 3; pass++) { + partitions.forEach(target => { + let newMin = 0; + let newMax = 1; + const center = target.offset; // Положение стенки + + partitions.forEach(obstacle => { + if (target.id === obstacle.id) return; + if (target.axis === obstacle.axis) return; // Параллельные не мешают + + // Берем АКТУАЛЬНЫЕ границы препятствия с прошлого шага + const obsMin = limits[obstacle.id].min; + const obsMax = limits[obstacle.id].max; + + // Пересекает ли препятствие путь нашей стенки? + // obstacle.offset - это позиция препятствия на нашем пути. + // target.offset - это наша позиция. Она должна быть ВНУТРИ длины препятствия. + if (target.offset > obsMin && target.offset < obsMax) { + // Препятствие на пути. Где оно? + 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; +}; + export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => { const parts: GeneratedPart[] = []; const safeX = Array.isArray(splits?.x) ? splits.x : []; @@ -21,9 +63,9 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat for (let j = 0; j < yPoints.length - 1; j++) { const rawW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width; const rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth; - - // Пропускаем слишком маленькие ячейки - if (rawW < 10 || rawD < 10) continue; + + // Игнорируем микро-ячейки + if (rawW < 5 || rawD < 5) continue; const rawX = xPoints[i] * config.drawer.width; const rawY = yPoints[j] * config.drawer.depth; @@ -35,8 +77,6 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat const realX = rawX + (config.printerTolerance / 2); const realY = rawY + (config.printerTolerance / 2); - if (realWidth < 5 || realDepth < 5) continue; - parts.push({ id: `part-${partCounter}`, name: `Ячейка ${i+1}-${j+1}`, @@ -60,7 +100,6 @@ const createRoundedRectShape = (width: number, height: number, radius: number): const shape = new THREE.Shape(); const x = -width / 2; const y = -height / 2; - // Ограничиваем радиус, чтобы не сломать геометрию при маленьких размерах const r = Math.min(radius, width / 2 - 0.1, height / 2 - 0.1); if (r <= 0.1) { @@ -83,55 +122,29 @@ const createRoundedRectShape = (width: number, height: number, radius: number): return shape; }; -// Форма галтели (вогнутый угол) +// Форма галтели (вогнутый уголок) const createFilletShape = (radius: number): THREE.Shape => { const shape = new THREE.Shape(); + // Рисуем в 1-м квадранте shape.moveTo(0, 0); shape.lineTo(radius, 0); - // Рисуем вогнутую дугу в квадранте (+X, +Y) shape.absarc(radius, radius, radius, 1.5 * Math.PI, Math.PI, true); shape.lineTo(0, 0); return shape; }; -// --- УМНЫЙ РАСЧЕТ ГРАНИЦ (ДВУХПРОХОДНЫЙ) --- -const calculateLimits = (target: Partition, allParts: Partition[], limitMap: LimitMap | null) => { - let min = 0; - let max = 1; - const mid = target.offset; // Используем offset как центр для определения стороны - - allParts.forEach(p => { - if (p.axis === target.axis) return; // Игнорируем параллельные - - // Получаем границы соседки. Если это второй проход, берем уже рассчитанные. - let pMin = p.min ?? 0; - let pMax = p.max ?? 1; - if (limitMap && limitMap[p.id]) { - pMin = limitMap[p.id].min; - pMax = limitMap[p.id].max; - } - - // Проверяем пересечение - if (target.offset > pMin && target.offset < pMax) { - if (p.offset < mid) min = Math.max(min, p.offset); - else if (p.offset > mid) max = Math.min(max, p.offset); - } - }); - return { min, max }; -}; - export const createBinGeometry = ( width: number, depth: number, height: number, thickness: number, radius: number = 0, partitions: Partition[] = [] ): THREE.BufferGeometry => { const geometries: THREE.BufferGeometry[] = []; - // ДНО + // 1. ДНО const floorShape = createRoundedRectShape(width, depth, radius); - const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false, curveSegments: 16 }); + const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false }); floorGeo.rotateX(-Math.PI / 2); geometries.push(floorGeo); - // ВНЕШНИЕ СТЕНКИ + // 2. ВНЕШНИЕ СТЕНКИ const outerShape = createRoundedRectShape(width, depth, radius); const innerRadius = Math.max(0.1, radius - thickness); const innerWidth = width - (2 * thickness); @@ -143,95 +156,95 @@ export const createBinGeometry = ( } const wallHeight = height - thickness; - const wallGeo = new THREE.ExtrudeGeometry(outerShape, { depth: wallHeight, bevelEnabled: false, curveSegments: 16 }); + const wallGeo = new THREE.ExtrudeGeometry(outerShape, { depth: wallHeight, bevelEnabled: false }); wallGeo.rotateX(-Math.PI / 2); wallGeo.translate(0, thickness, 0); geometries.push(wallGeo); - // --- РАСЧЕТ ГРАНИЦ ПЕРЕГОРОДОК (2 ПРОХОДА) --- - const limitMap: LimitMap = {}; - // Проход 1: Считаем черновые границы - partitions.forEach(p => { limitMap[p.id] = calculateLimits(p, partitions, null); }); - // Проход 2: Уточняем границы, используя результаты первого прохода - partitions.forEach(p => { limitMap[p.id] = calculateLimits(p, partitions, limitMap); }); + // 3. ВНУТРЕННИЕ ПЕРЕГОРОДКИ (С SOLVER'ом) + const limitMap = solveWallLimits(partitions); - // --- ГЕНЕРАЦИЯ ПЕРЕГОРОДОК --- partitions.forEach(p => { const { min: pMin, max: pMax } = limitMap[p.id]; + if (pMax - pMin < 0.01) return; // Слишком короткая - // Если стенка схлопнулась в ноль или стала отрицательной - пропускаем - if (pMax - pMin < 0.01) return; - const lengthRatio = pMax - pMin; const midRatio = pMin + (lengthRatio / 2); let pWidth = 0, pDepth = 0, pX = 0, pY = 0; if (p.axis === 'x') { + // Вертикальная pWidth = thickness; pDepth = lengthRatio * innerDepth; pX = (-innerWidth / 2) + (innerWidth * p.offset); pY = (-innerDepth / 2) + (innerDepth * midRatio); } else { + // Горизонтальная pWidth = lengthRatio * innerWidth; pDepth = thickness; pX = (-innerWidth / 2) + (innerWidth * midRatio); pY = (-innerDepth / 2) + (innerDepth * p.offset); } - // Сама стенка (чуть скругленная для красоты) - const partShape = createRoundedRectShape(pWidth, pDepth, 0.2); - const partGeo = new THREE.ExtrudeGeometry(partShape, { depth: p.height, bevelEnabled: false, curveSegments: 4 }); + // Геометрия стенки + const partShape = createRoundedRectShape(pWidth, pDepth, 0.2); + const partGeo = new THREE.ExtrudeGeometry(partShape, { depth: p.height, bevelEnabled: false }); partGeo.rotateX(-Math.PI / 2); partGeo.translate(pX, thickness, pY); geometries.push(partGeo); - // --- ГАЛТЕЛИ (СКРУГЛЕНИЯ) --- + // --- ДОБАВЛЕНИЕ СКРУГЛЕНИЙ (FILLETS) --- if (p.rounded && radius > 1) { - const filletR = Math.min(radius, 6, thickness * 2); - if (filletR < 0.5) return; - + const filletR = Math.min(radius, 5); const filletShape = createFilletShape(filletR); - const filletExtrudeSettings = { depth: p.height, bevelEnabled: false, curveSegments: 12 }; + const filletExtrude = { depth: p.height, bevelEnabled: false }; - const addFillet = (x: number, y: number, rotation: number) => { - const geo = new THREE.ExtrudeGeometry(filletShape, filletExtrudeSettings); + const addFillet = (x: number, y: number, rotY: number) => { + const geo = new THREE.ExtrudeGeometry(filletShape, filletExtrude); geo.rotateX(-Math.PI / 2); - geo.rotateY(rotation); + geo.rotateY(rotY); geo.translate(x, thickness, y); geometries.push(geo); }; - const halfThick = thickness / 2; + const h = thickness / 2; // half thickness if (p.axis === 'x') { - // ВЕРТИКАЛЬНАЯ СТЕНКА - Углы были правильные - const startY = (-innerDepth / 2) + (innerDepth * pMin); - const endY = (-innerDepth / 2) + (innerDepth * pMax); - addFillet(pX - halfThick, startY, 0); // Top-Left - addFillet(pX + halfThick, startY, -Math.PI/2); // Top-Right - addFillet(pX - halfThick, endY, Math.PI/2); // Bottom-Left - addFillet(pX + halfThick, endY, Math.PI); // Bottom-Right - } else { - // ГОРИЗОНТАЛЬНАЯ СТЕНКА - ИСПРАВЛЕНЫ УГЛЫ - const startX = (-innerWidth / 2) + (innerWidth * pMin); - const endX = (-innerWidth / 2) + (innerWidth * pMax); - - // Left End - addFillet(startX, pY + halfThick, 0); // Top-Left - addFillet(startX, pY - halfThick, Math.PI/2); // Bottom-Left + // Вертикальная (идет вдоль Z в 3D) + const startY = (-innerDepth / 2) + (innerDepth * pMin); // "Верхний" конец (Back) + const endY = (-innerDepth / 2) + (innerDepth * pMax); // "Нижний" конец (Front) - // Right End - addFillet(endX, pY + halfThick, -Math.PI/2); // Top-Right - addFillet(endX, pY - halfThick, Math.PI); // Bottom-Right + // Проверяем, упирается ли она в края или другие стенки? (всегда рисуем, так как solver обрезал) + // Скругляем 4 угла стыка + + // Top End (pMin) + addFillet(pX - h, startY, 0); // Слева, смотрит вверх + addFillet(pX + h, startY, -Math.PI/2); // Справа, смотрит вверх + + // Bottom End (pMax) + addFillet(pX - h, endY, Math.PI/2); // Слева, смотрит вниз + addFillet(pX + h, endY, Math.PI); // Справа, смотрит вниз + + } else { + // Горизонтальная (идет вдоль X в 3D) + const startX = (-innerWidth / 2) + (innerWidth * pMin); // Левый конец + const endX = (-innerWidth / 2) + (innerWidth * pMax); // Правый конец + + // Left End (pMin) + addFillet(startX, pY + h, Math.PI); // Сверху, смотрит влево (FIXED ANGLE) + addFillet(startX, pY - h, Math.PI/2); // Снизу, смотрит влево (FIXED ANGLE) + + // Right End (pMax) + addFillet(endX, pY + h, -Math.PI/2); // Сверху, смотрит вправо (FIXED ANGLE) + addFillet(endX, pY - h, 0); // Снизу, смотрит вправо (FIXED ANGLE) } } }); const merged = mergeBufferGeometries(geometries); if (merged) merged.computeVertexNormals(); - // Возвращаем пустой бокс если ничего не сгенерировалось, чтобы не крашить - return merged || new THREE.BoxGeometry(0.1, 0.1, 0.1); + return merged || new THREE.BoxGeometry(1, 1, 1); }; export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => { From 8c39e18de4fc48bd6d7555145f5035cb742296f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sun, 11 Jan 2026 14:36:56 +0300 Subject: [PATCH 09/15] 7 --- src/components/LayoutStep.tsx | 65 ++++++++++------ src/services/geometryGenerator.ts | 121 +++++++++++++++--------------- 2 files changed, 102 insertions(+), 84 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index 45aa85c..d58feaa 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -19,6 +19,7 @@ type DragTarget = export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const svgRef = useRef(null); + const containerRef = useRef(null); // -- STATE -- const [mode, setMode] = useState('lines'); @@ -50,7 +51,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]); const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]); - // -- HELPERS -- + // -- HELPER: Get Selected -- const getSelectedPartition = () => { if (!selectedPartitionId) return null; for (const key in safePartitions) { @@ -61,7 +62,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; const selectedData = getSelectedPartition(); - // --- SOLVER (Копия из geometryGenerator для синхронизации) --- + // --- SOLVER (Синхронизирован с 3D) --- const solveWallLimits = (parts: Partition[]): LimitMap => { const limits: LimitMap = {}; parts.forEach(p => { limits[p.id] = { min: 0, max: 1 }; }); @@ -73,8 +74,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const center = target.offset; parts.forEach(obstacle => { - if (target.id === obstacle.id) return; - if (target.axis === obstacle.axis) return; + if (target.id === obstacle.id || target.axis === obstacle.axis) return; const obsMin = limits[obstacle.id].min; const obsMax = limits[obstacle.id].max; @@ -90,22 +90,42 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return limits; }; - // Расчет границ для НОВОЙ стенки (используем уже решенные границы существующих) + // Поиск ближайших соседей для текста размеров + const getNeighborOffsets = (currentOffset: number, crossPos: number, axis: Axis, parts: Partition[]) => { + let minLimit = 0; + let maxLimit = 1; + const limitMap = solveWallLimits(parts); // Используем решенные границы для соседей + + parts.forEach(p => { + if (p.axis === axis) { // Параллельные + const { min: pMin, max: pMax } = limitMap[p.id]; + // Пересекаются ли проекции? + if (crossPos > pMin && crossPos < pMax) { + if (p.offset < currentOffset) minLimit = Math.max(minLimit, p.offset); + if (p.offset > currentOffset) maxLimit = Math.min(maxLimit, p.offset); + } + } + }); + return { min: minLimit, max: maxLimit }; + }; + + // Границы для курсора (Raycasting) const getCursorBox = (lx: number, ly: number, parts: Partition[], limitMap: LimitMap) => { 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; if (p.axis === 'x') { + // Вертикальная преграда if (ly > pMin && ly < pMax) { if (p.offset < lx) minX = Math.max(minX, p.offset); if (p.offset > lx) maxX = Math.min(maxX, p.offset); } } else { + // Горизонтальная преграда if (lx > pMin && lx < pMax) { if (p.offset < ly) minY = Math.max(minY, p.offset); if (p.offset > ly) maxY = Math.min(maxY, p.offset); @@ -196,6 +216,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setPhantomPartition(null); setHoveredCell(null); + // 1. Находим ячейку let cellIdx = null; for (let i = 0; i < sortedX.length - 1; i++) { if (nx >= sortedX[i] && nx <= sortedX[i+1]) { @@ -211,7 +232,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setHoveredCell(cellIdx); const key = `${cellIdx.i}-${cellIdx.j}`; const parts = safePartitions[key] || []; - const limitMap = solveWallLimits(parts); // Вызываем солвер + 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]; @@ -233,17 +254,14 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (found) { setHoveredPartition({ id: found.id, cellKey: key }); } else { + // Вычисляем бокс под курсором const box = getCursorBox(lx, ly, parts, limitMap); - const axis = (lx - box.minX < box.maxX - lx) && (lx - box.minX < Math.min(ly - box.minY, box.maxY - ly)) ? 'x' : - (box.maxX - lx < lx - box.minX) && (box.maxX - lx < Math.min(ly - box.minY, box.maxY - ly)) ? 'x' : - Math.min(lx - box.minX, box.maxX - lx) < Math.min(ly - box.minY, box.maxY - ly) ? 'x' : 'y'; - - // Лучше: перпендикулярно ближайшей стороне const distL = lx - box.minX; const distR = box.maxX - lx; const distT = ly - box.minY; const distB = box.maxY - ly; - const minD = Math.min(distL, distR, distT, distB); + // Выбираем ось перпендикулярно ближайшей границе + const minD = Math.min(distL, distR, distT, distB); const newAxis = (minD === distL || minD === distR) ? 'x' : 'y'; const width = box.maxX - box.minX; @@ -296,7 +314,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { } }; - // --- RENDER --- const renderCellsAndPartitions = () => { const elements = []; for (let i = 0; i < sortedX.length - 1; i++) { @@ -315,7 +332,8 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const realW = (x2 - x1) * drawerW; const realD = (y2 - y1) * drawerD; - const limitMap = solveWallLimits(parts); // SOLVER для отрисовки + // ВАЖНО: Вычисляем границы для отображения + const limitMap = solveWallLimits(parts); if (parts.length === 0) { const labelX = cellX + cellW / 2; @@ -350,20 +368,21 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { lx1 = px; lx2 = px; ly1 = cellY + (cellH * min); ly2 = cellY + (cellH * max); - const cy = (min + max) / 2; - const box = getCursorBox(p.offset, cy, parts, limitMap); - dist1 = Math.abs((p.offset - box.minX) * realW) - wallThick; - dist2 = Math.abs((box.maxX - p.offset) * realW) - wallThick; + // Ищем соседей относительно текущей длины + const neighbors = getNeighborOffsets(p.offset, (min + max)/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); - const cx = (min + max) / 2; - const box = getCursorBox(cx, p.offset, parts, limitMap); - dist1 = Math.abs((p.offset - box.minY) * realD) - wallThick; - dist2 = Math.abs((box.maxY - p.offset) * realD) - wallThick; + const neighbors = getNeighborOffsets(p.offset, (min + max)/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; } diff --git a/src/services/geometryGenerator.ts b/src/services/geometryGenerator.ts index 35ed368..9365a35 100644 --- a/src/services/geometryGenerator.ts +++ b/src/services/geometryGenerator.ts @@ -2,46 +2,32 @@ import * as THREE from 'three'; import { STLExporter, mergeBufferGeometries } from 'three-stdlib'; import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types'; -// Типы для внутреннего решателя type Limits = { min: number; max: number }; type LimitMap = Record; -// --- SOLVER: Итеративный расчет границ --- -// Эта функция гарантирует, что стенки не будут торчать друг из друга +// --- SOLVER (Устраняет пересечения стенок) --- const solveWallLimits = (partitions: Partition[]): LimitMap => { const limits: LimitMap = {}; - - // 1. Инициализация: считаем, что все стенки идут от 0 до 1 partitions.forEach(p => { limits[p.id] = { min: 0, max: 1 }; }); - // 2. Итеративное решение (3 прохода достаточно для любой вложенности) + // 3 прохода для надежности вложенных структур for (let pass = 0; pass < 3; pass++) { partitions.forEach(target => { let newMin = 0; let newMax = 1; - const center = target.offset; // Положение стенки + const center = target.offset; partitions.forEach(obstacle => { - if (target.id === obstacle.id) return; - if (target.axis === obstacle.axis) return; // Параллельные не мешают + if (target.id === obstacle.id || target.axis === obstacle.axis) return; - // Берем АКТУАЛЬНЫЕ границы препятствия с прошлого шага const obsMin = limits[obstacle.id].min; const obsMax = limits[obstacle.id].max; - // Пересекает ли препятствие путь нашей стенки? - // obstacle.offset - это позиция препятствия на нашем пути. - // target.offset - это наша позиция. Она должна быть ВНУТРИ длины препятствия. if (target.offset > obsMin && target.offset < obsMax) { - // Препятствие на пути. Где оно? - if (obstacle.offset < center) { - newMin = Math.max(newMin, obstacle.offset); - } else if (obstacle.offset > center) { - newMax = Math.min(newMax, obstacle.offset); - } + 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 }; }); } @@ -64,12 +50,10 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat const rawW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width; const rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth; - // Игнорируем микро-ячейки if (rawW < 5 || rawD < 5) continue; const rawX = xPoints[i] * config.drawer.width; const rawY = yPoints[j] * config.drawer.depth; - const internalPartitions = safeParts[`${i}-${j}`] || []; const realWidth = rawW - config.printerTolerance; @@ -122,13 +106,14 @@ const createRoundedRectShape = (width: number, height: number, radius: number): return shape; }; -// Форма галтели (вогнутый уголок) -const createFilletShape = (radius: number): THREE.Shape => { +// Правильная форма "обратного" скругления (вогнутая) +const createConcaveFilletShape = (radius: number): THREE.Shape => { const shape = new THREE.Shape(); - // Рисуем в 1-м квадранте + // Рисуем квадрат (0,0) -> (r,r), но вырезаем из него круг shape.moveTo(0, 0); shape.lineTo(radius, 0); - shape.absarc(radius, radius, radius, 1.5 * Math.PI, Math.PI, true); + // Дуга: центр (r,r), радиус r, от 270 (-PI/2) до 180 (-PI) градусов + shape.absarc(radius, radius, radius, -Math.PI / 2, -Math.PI, true); shape.lineTo(0, 0); return shape; }; @@ -138,13 +123,12 @@ export const createBinGeometry = ( ): THREE.BufferGeometry => { const geometries: THREE.BufferGeometry[] = []; - // 1. ДНО + // ДНО И ВНЕШНИЕ СТЕНКИ const floorShape = createRoundedRectShape(width, depth, radius); const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false }); floorGeo.rotateX(-Math.PI / 2); geometries.push(floorGeo); - // 2. ВНЕШНИЕ СТЕНКИ const outerShape = createRoundedRectShape(width, depth, radius); const innerRadius = Math.max(0.1, radius - thickness); const innerWidth = width - (2 * thickness); @@ -161,12 +145,12 @@ export const createBinGeometry = ( wallGeo.translate(0, thickness, 0); geometries.push(wallGeo); - // 3. ВНУТРЕННИЕ ПЕРЕГОРОДКИ (С SOLVER'ом) + // ВНУТРЕННИЕ ПЕРЕГОРОДКИ const limitMap = solveWallLimits(partitions); partitions.forEach(p => { const { min: pMin, max: pMax } = limitMap[p.id]; - if (pMax - pMin < 0.01) return; // Слишком короткая + if (pMax - pMin < 0.01) return; const lengthRatio = pMax - pMin; const midRatio = pMin + (lengthRatio / 2); @@ -174,70 +158,85 @@ export const createBinGeometry = ( let pWidth = 0, pDepth = 0, pX = 0, pY = 0; if (p.axis === 'x') { - // Вертикальная pWidth = thickness; pDepth = lengthRatio * innerDepth; pX = (-innerWidth / 2) + (innerWidth * p.offset); pY = (-innerDepth / 2) + (innerDepth * midRatio); } else { - // Горизонтальная pWidth = lengthRatio * innerWidth; pDepth = thickness; pX = (-innerWidth / 2) + (innerWidth * midRatio); pY = (-innerDepth / 2) + (innerDepth * p.offset); } - // Геометрия стенки - const partShape = createRoundedRectShape(pWidth, pDepth, 0.2); + const partShape = createRoundedRectShape(pWidth, pDepth, 0.1); const partGeo = new THREE.ExtrudeGeometry(partShape, { depth: p.height, bevelEnabled: false }); partGeo.rotateX(-Math.PI / 2); partGeo.translate(pX, thickness, pY); geometries.push(partGeo); - // --- ДОБАВЛЕНИЕ СКРУГЛЕНИЙ (FILLETS) --- + // --- ДОБАВЛЕНИЕ ГАЛТЕЛЕЙ (FILLETS) --- if (p.rounded && radius > 1) { const filletR = Math.min(radius, 5); - const filletShape = createFilletShape(filletR); + const filletShape = createConcaveFilletShape(filletR); const filletExtrude = { depth: p.height, bevelEnabled: false }; - const addFillet = (x: number, y: number, rotY: number) => { + const addFillet = (x: number, y: number, rotationY: number) => { const geo = new THREE.ExtrudeGeometry(filletShape, filletExtrude); + // Сначала кладем на пол (-PI/2 по X) + // Потом вращаем вокруг оси Y (которая теперь смотрит вверх) geo.rotateX(-Math.PI / 2); - geo.rotateY(rotY); + + // ВАЖНО: Вращение геометрии происходит вокруг (0,0,0). + // Наша форма галтели имеет угол в (0,0). Это идеально. + geo.rotateY(rotationY); + geo.translate(x, thickness, y); geometries.push(geo); }; - const h = thickness / 2; // half thickness + const h = thickness / 2; if (p.axis === 'x') { - // Вертикальная (идет вдоль Z в 3D) - const startY = (-innerDepth / 2) + (innerDepth * pMin); // "Верхний" конец (Back) - const endY = (-innerDepth / 2) + (innerDepth * pMax); // "Нижний" конец (Front) - - // Проверяем, упирается ли она в края или другие стенки? (всегда рисуем, так как solver обрезал) - // Скругляем 4 угла стыка + // Вертикальная стенка (вдоль Z) + // Top (Min Y) + const topY = (-innerDepth / 2) + (innerDepth * pMin); + // Углы: Слева (-X) и Справа (+X) - // Top End (pMin) - addFillet(pX - h, startY, 0); // Слева, смотрит вверх - addFillet(pX + h, startY, -Math.PI/2); // Справа, смотрит вверх + // Left-Top: смотрит в (-X, +Z). Угол PI (180) + addFillet(pX - h, topY, Math.PI); + + // Right-Top: смотрит в (+X, +Z). Угол -PI/2 (-90) + addFillet(pX + h, topY, -Math.PI / 2); - // Bottom End (pMax) - addFillet(pX - h, endY, Math.PI/2); // Слева, смотрит вниз - addFillet(pX + h, endY, Math.PI); // Справа, смотрит вниз + // Bottom (Max Y) + const botY = (-innerDepth / 2) + (innerDepth * pMax); + + // Left-Bottom: смотрит в (-X, -Z). Угол PI/2 (90) + addFillet(pX - h, botY, Math.PI / 2); + + // Right-Bottom: смотрит в (+X, -Z). Угол 0 + addFillet(pX + h, botY, 0); } else { - // Горизонтальная (идет вдоль X в 3D) - const startX = (-innerWidth / 2) + (innerWidth * pMin); // Левый конец - const endX = (-innerWidth / 2) + (innerWidth * pMax); // Правый конец + // Горизонтальная стенка (вдоль X) + // Left (Min X) + const leftX = (-innerWidth / 2) + (innerWidth * pMin); + + // Top-Left: смотрит в (+X, -Z). Угол 0 + addFillet(leftX, pY - h, 0); + + // Bottom-Left: смотрит в (+X, +Z). Угол -PI/2 (-90) + addFillet(leftX, pY + h, -Math.PI / 2); - // Left End (pMin) - addFillet(startX, pY + h, Math.PI); // Сверху, смотрит влево (FIXED ANGLE) - addFillet(startX, pY - h, Math.PI/2); // Снизу, смотрит влево (FIXED ANGLE) - - // Right End (pMax) - addFillet(endX, pY + h, -Math.PI/2); // Сверху, смотрит вправо (FIXED ANGLE) - addFillet(endX, pY - h, 0); // Снизу, смотрит вправо (FIXED ANGLE) + // Right (Max X) + const rightX = (-innerWidth / 2) + (innerWidth * pMax); + + // Top-Right: смотрит в (-X, -Z). Угол PI/2 (90) + addFillet(rightX, pY - h, Math.PI / 2); + + // Bottom-Right: смотрит в (-X, +Z). Угол PI (180) + addFillet(rightX, pY + h, Math.PI); } } }); From 1e9a1d288a3e46c6391e3ba3d61cd762078b8835 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sun, 11 Jan 2026 15:01:42 +0300 Subject: [PATCH 10/15] 8 --- src/components/LayoutStep.tsx | 127 +++++++++++++++++++--------------- 1 file changed, 73 insertions(+), 54 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index d58feaa..80a3ef8 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -19,7 +19,6 @@ type DragTarget = export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const svgRef = useRef(null); - const containerRef = useRef(null); // -- STATE -- const [mode, setMode] = useState('lines'); @@ -51,7 +50,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]); const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]); - // -- HELPER: Get Selected -- + // -- HELPERS -- const getSelectedPartition = () => { if (!selectedPartitionId) return null; for (const key in safePartitions) { @@ -62,12 +61,14 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; const selectedData = getSelectedPartition(); - // --- SOLVER (Синхронизирован с 3D) --- + // --- SOLVER (Пересчет границ для корректного 3D и UI) --- const solveWallLimits = (parts: Partition[]): LimitMap => { const limits: LimitMap = {}; + // Изначально считаем, что все стенки от края до края (0-1) parts.forEach(p => { limits[p.id] = { min: 0, max: 1 }; }); - for (let pass = 0; pass < 3; pass++) { + // Несколько проходов для решения вложенных зависимостей + for (let pass = 0; pass < 4; pass++) { parts.forEach(target => { let newMin = 0; let newMax = 1; @@ -76,9 +77,11 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { 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; + // Если препятствие пересекает наш путь if (target.offset > obsMin && target.offset < obsMax) { if (obstacle.offset < center) newMin = Math.max(newMin, obstacle.offset); else if (obstacle.offset > center) newMax = Math.min(newMax, obstacle.offset); @@ -90,51 +93,67 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return limits; }; - // Поиск ближайших соседей для текста размеров - const getNeighborOffsets = (currentOffset: number, crossPos: number, axis: Axis, parts: Partition[]) => { - let minLimit = 0; - let maxLimit = 1; - const limitMap = solveWallLimits(parts); // Используем решенные границы для соседей - - parts.forEach(p => { - if (p.axis === axis) { // Параллельные - const { min: pMin, max: pMax } = limitMap[p.id]; - // Пересекаются ли проекции? - if (crossPos > pMin && crossPos < pMax) { - if (p.offset < currentOffset) minLimit = Math.max(minLimit, p.offset); - if (p.offset > currentOffset) maxLimit = Math.min(maxLimit, p.offset); - } - } - }); - return { min: minLimit, max: maxLimit }; - }; - - // Границы для курсора (Raycasting) + // --- RAYCASTING: Поиск свободного места под курсором --- + // Это исправляет проблему, когда линия рисуется сквозь стенки const getCursorBox = (lx: number, ly: number, parts: Partition[], limitMap: LimitMap) => { + // Начинаем с границ всей ячейки 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; if (p.axis === 'x') { - // Вертикальная преграда - if (ly > pMin && ly < pMax) { - if (p.offset < lx) minX = Math.max(minX, p.offset); - if (p.offset > lx) maxX = Math.min(maxX, p.offset); + // Вертикальная стенка. Это препятствие по оси X. + // Проверяем, находится ли наш курсор (ly) в диапазоне высоты этой стенки? + if (ly >= pMin && ly <= pMax) { + // Стенка на нашем уровне по Y. Она слева или справа? + if (p.offset < lx) { + minX = Math.max(minX, p.offset); // Ближайшая стенка слева + } else { + maxX = Math.min(maxX, p.offset); // Ближайшая стенка справа + } } } else { - // Горизонтальная преграда - if (lx > pMin && lx < pMax) { - if (p.offset < ly) minY = Math.max(minY, p.offset); - if (p.offset > ly) maxY = Math.min(maxY, p.offset); + // Горизонтальная стенка. Препятствие по оси Y. + // Проверяем, находится ли наш курсор (lx) в диапазоне ширины этой стенки? + if (lx >= pMin && lx <= pMax) { + // Стенка на нашем уровне по X. Она сверху или снизу? + if (p.offset < ly) { + minY = Math.max(minY, p.offset); // Ближайшая стенка сверху + } else { + maxY = Math.min(maxY, p.offset); // Ближайшая стенка снизу + } } } }); + return { minX, maxX, minY, maxY }; }; + // Поиск соседей для отображения размеров (аналогичная логика) + const getNeighborOffsets = (offset: number, crossCenter: number, axis: Axis, parts: Partition[], limitMap: LimitMap) => { + let min = 0; + let max = 1; + + parts.forEach(p => { + if (p.axis === axis) { // Ищем параллельные стенки + const { min: pMin, max: pMax } = limitMap[p.id]; + // Если проекции пересекаются + if (crossCenter > pMin && crossCenter < pMax) { + if (p.offset < offset) min = Math.max(min, p.offset); + if (p.offset > offset) max = Math.min(max, p.offset); + } + } + }); + return { min, max }; + }; + // -- ACTIONS -- const createPartition = (i: number, j: number, axis: Axis, offset: number, min: number, max: number) => { const key = `${i}-${j}`; @@ -169,7 +188,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setDragging(null); }; - // -- MOUSE -- + // -- MOUSE HANDLERS -- const handleMouseMove = (e: React.MouseEvent) => { if (!svgRef.current) return; const rect = svgRef.current.getBoundingClientRect(); @@ -216,7 +235,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setPhantomPartition(null); setHoveredCell(null); - // 1. Находим ячейку let cellIdx = null; for (let i = 0; i < sortedX.length - 1; i++) { if (nx >= sortedX[i] && nx <= sortedX[i+1]) { @@ -232,7 +250,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setHoveredCell(cellIdx); const key = `${cellIdx.i}-${cellIdx.j}`; const parts = safePartitions[key] || []; - const limitMap = solveWallLimits(parts); + 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]; @@ -242,6 +260,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { let found = null; const SNAP = 0.05; + // Проверяем наведение на существующие стенки for (const p of parts) { const { min, max } = limitMap[p.id]; if (p.axis === 'x') { @@ -254,24 +273,25 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (found) { setHoveredPartition({ id: found.id, cellKey: key }); } else { - // Вычисляем бокс под курсором + // --- КЛЮЧЕВОЙ МОМЕНТ: Raycasting для фантома --- const box = getCursorBox(lx, ly, parts, limitMap); - const distL = lx - box.minX; const distR = box.maxX - lx; - const distT = ly - box.minY; const distB = box.maxY - ly; - - // Выбираем ось перпендикулярно ближайшей границе - const minD = Math.min(distL, distR, distT, distB); - const newAxis = (minD === distL || minD === distR) ? 'x' : 'y'; - const width = box.maxX - box.minX; const height = box.maxY - box.minY; - if ((newAxis === 'y' && height > 0.05) || (newAxis === 'x' && width > 0.05)) { - 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 }); + // Логика авто-выбора оси: делим более длинную сторону "комнаты" + // Если комната широкая -> ставим вертикальную (X) + // Если комната высокая -> ставим горизонтальную (Y) + const axis = width > height ? 'x' : 'y'; + + // Разрешаем рисовать, если есть хоть немного места (>5%) + if ((axis === 'x' && width > 0.05) || (axis === 'y' && height > 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 }); } } } @@ -314,6 +334,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { } }; + // --- RENDER --- const renderCellsAndPartitions = () => { const elements = []; for (let i = 0; i < sortedX.length - 1; i++) { @@ -332,9 +353,9 @@ export const LayoutStep: React.FC = ({ 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; @@ -368,9 +389,8 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { lx1 = px; lx2 = px; ly1 = cellY + (cellH * min); ly2 = cellY + (cellH * max); - // Ищем соседей относительно текущей длины - const neighbors = getNeighborOffsets(p.offset, (min + max)/2, p.axis, parts); - + // Для размеров ищем границы относительно центра отрисованной линии + const neighbors = getNeighborOffsets(p.offset, (min + max)/2, p.axis, parts, limitMap); dist1 = Math.abs((p.offset - neighbors.min) * realW) - wallThick; dist2 = Math.abs((neighbors.max - p.offset) * realW) - wallThick; midX = px; midY = (ly1 + ly2) / 2; @@ -379,8 +399,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { ly1 = py; ly2 = py; lx1 = cellX + (cellW * min); lx2 = cellX + (cellW * max); - const neighbors = getNeighborOffsets(p.offset, (min + max)/2, p.axis, parts); - + const neighbors = getNeighborOffsets(p.offset, (min + max)/2, p.axis, parts, limitMap); dist1 = Math.abs((p.offset - neighbors.min) * realD) - wallThick; dist2 = Math.abs((neighbors.max - p.offset) * realD) - wallThick; midX = (lx1 + lx2) / 2; midY = py; From 454e6cf822c80022c72be66bcfcb293e99483c47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sun, 11 Jan 2026 15:14:29 +0300 Subject: [PATCH 11/15] 9 --- src/components/LayoutStep.tsx | 107 +++++++++++++----------------- src/services/geometryGenerator.ts | 65 ++++++------------ 2 files changed, 66 insertions(+), 106 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index 80a3ef8..ffd94b8 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -50,7 +50,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]); const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]); - // -- HELPERS -- + // -- HELPER: Get Selected -- const getSelectedPartition = () => { if (!selectedPartitionId) return null; for (const key in safePartitions) { @@ -61,13 +61,11 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; const selectedData = getSelectedPartition(); - // --- SOLVER (Пересчет границ для корректного 3D и UI) --- + // --- SOLVER (Копия из geometryGenerator) --- const solveWallLimits = (parts: Partition[]): LimitMap => { const limits: LimitMap = {}; - // Изначально считаем, что все стенки от края до края (0-1) parts.forEach(p => { limits[p.id] = { min: 0, max: 1 }; }); - // Несколько проходов для решения вложенных зависимостей for (let pass = 0; pass < 4; pass++) { parts.forEach(target => { let newMin = 0; @@ -77,12 +75,11 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { 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; - // Если препятствие пересекает наш путь - if (target.offset > obsMin && target.offset < obsMax) { + // Используем >= и <= для надежности + if (target.offset >= obsMin - 0.001 && target.offset <= obsMax + 0.001) { if (obstacle.offset < center) newMin = Math.max(newMin, obstacle.offset); else if (obstacle.offset > center) newMax = Math.min(newMax, obstacle.offset); } @@ -93,59 +90,47 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return limits; }; - // --- RAYCASTING: Поиск свободного места под курсором --- - // Это исправляет проблему, когда линия рисуется сквозь стенки + // --- RAYCASTING (Исправленный поиск свободного места) --- const getCursorBox = (lx: number, ly: number, parts: Partition[], limitMap: LimitMap) => { - // Начинаем с границ всей ячейки 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; + // Используем те же допуски, что и в Solver + const EPSILON = 0.001; + if (p.axis === 'x') { - // Вертикальная стенка. Это препятствие по оси X. - // Проверяем, находится ли наш курсор (ly) в диапазоне высоты этой стенки? - if (ly >= pMin && ly <= pMax) { - // Стенка на нашем уровне по Y. Она слева или справа? - if (p.offset < lx) { - minX = Math.max(minX, p.offset); // Ближайшая стенка слева - } else { - maxX = Math.min(maxX, p.offset); // Ближайшая стенка справа - } + // Вертикальная преграда (X) + // Проверяем, перекрывает ли она Y курсора + if (ly >= pMin - EPSILON && ly <= pMax + EPSILON) { + if (p.offset < lx) minX = Math.max(minX, p.offset); + if (p.offset > lx) maxX = Math.min(maxX, p.offset); } } else { - // Горизонтальная стенка. Препятствие по оси Y. - // Проверяем, находится ли наш курсор (lx) в диапазоне ширины этой стенки? - if (lx >= pMin && lx <= pMax) { - // Стенка на нашем уровне по X. Она сверху или снизу? - if (p.offset < ly) { - minY = Math.max(minY, p.offset); // Ближайшая стенка сверху - } else { - maxY = Math.min(maxY, p.offset); // Ближайшая стенка снизу - } + // Горизонтальная преграда (Y) + // Проверяем, перекрывает ли она X курсора + if (lx >= pMin - EPSILON && lx <= pMax + EPSILON) { + if (p.offset < ly) minY = Math.max(minY, p.offset); + if (p.offset > ly) maxY = Math.min(maxY, p.offset); } } }); - return { minX, maxX, minY, maxY }; }; - // Поиск соседей для отображения размеров (аналогичная логика) - const getNeighborOffsets = (offset: number, crossCenter: number, axis: Axis, parts: Partition[], limitMap: LimitMap) => { + // Поиск соседей для отображения размеров + const getNeighborOffsets = (offset: number, crossPos: number, axis: Axis, parts: Partition[], limitMap: LimitMap) => { let min = 0; let max = 1; + const EPSILON = 0.001; parts.forEach(p => { - if (p.axis === axis) { // Ищем параллельные стенки + if (p.axis === axis) { const { min: pMin, max: pMax } = limitMap[p.id]; - // Если проекции пересекаются - if (crossCenter > pMin && crossCenter < pMax) { + if (crossPos >= pMin - EPSILON && crossPos <= pMax + EPSILON) { if (p.offset < offset) min = Math.max(min, p.offset); if (p.offset > offset) max = Math.min(max, p.offset); } @@ -250,7 +235,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setHoveredCell(cellIdx); const key = `${cellIdx.i}-${cellIdx.j}`; const parts = safePartitions[key] || []; - const limitMap = solveWallLimits(parts); // Сначала решаем геометрию + 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]; @@ -260,7 +245,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { let found = null; const SNAP = 0.05; - // Проверяем наведение на существующие стенки for (const p of parts) { const { min, max } = limitMap[p.id]; if (p.axis === 'x') { @@ -273,25 +257,24 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (found) { setHoveredPartition({ id: found.id, cellKey: key }); } else { - // --- КЛЮЧЕВОЙ МОМЕНТ: Raycasting для фантома --- + // --- ВАЖНО: Получаем корректные границы с учетом Solver --- const box = getCursorBox(lx, ly, parts, limitMap); + const distL = lx - box.minX; const distR = box.maxX - lx; + const distT = ly - box.minY; const distB = box.maxY - ly; + + // Выбираем ось перпендикулярно ближайшей стороне + const minD = Math.min(distL, distR, distT, distB); + const newAxis = (minD === distL || minD === distR) ? 'x' : 'y'; + const width = box.maxX - box.minX; const height = box.maxY - box.minY; - // Логика авто-выбора оси: делим более длинную сторону "комнаты" - // Если комната широкая -> ставим вертикальную (X) - // Если комната высокая -> ставим горизонтальную (Y) - const axis = width > height ? 'x' : 'y'; - - // Разрешаем рисовать, если есть хоть немного места (>5%) - if ((axis === 'x' && width > 0.05) || (axis === 'y' && height > 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 }); + if ((newAxis === 'y' && height > 0.05) || (newAxis === 'x' && width > 0.05)) { + 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 }); } } } @@ -353,6 +336,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const realW = (x2 - x1) * drawerW; const realD = (y2 - y1) * drawerD; + // ВАЖНО: Используем solver для отрисовки const limitMap = solveWallLimits(parts); // Label @@ -389,19 +373,20 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { lx1 = px; lx2 = px; ly1 = cellY + (cellH * min); ly2 = cellY + (cellH * max); - // Для размеров ищем границы относительно центра отрисованной линии - const neighbors = getNeighborOffsets(p.offset, (min + max)/2, p.axis, parts, limitMap); - dist1 = Math.abs((p.offset - neighbors.min) * realW) - wallThick; - dist2 = Math.abs((neighbors.max - p.offset) * realW) - wallThick; + const cy = (min + max) / 2; + const box = getCursorBox(p.offset, cy, parts, limitMap); + dist1 = Math.abs((p.offset - box.minX) * realW) - wallThick; + dist2 = Math.abs((box.maxX - 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); - const neighbors = getNeighborOffsets(p.offset, (min + max)/2, p.axis, parts, limitMap); - dist1 = Math.abs((p.offset - neighbors.min) * realD) - wallThick; - dist2 = Math.abs((neighbors.max - p.offset) * realD) - wallThick; + const cx = (min + max) / 2; + const box = getCursorBox(cx, p.offset, parts, limitMap); + dist1 = Math.abs((p.offset - box.minY) * realD) - wallThick; + dist2 = Math.abs((box.maxY - p.offset) * realD) - wallThick; midX = (lx1 + lx2) / 2; midY = py; } diff --git a/src/services/geometryGenerator.ts b/src/services/geometryGenerator.ts index 9365a35..affa06a 100644 --- a/src/services/geometryGenerator.ts +++ b/src/services/geometryGenerator.ts @@ -5,29 +5,39 @@ import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types'; type Limits = { min: number; max: number }; type LimitMap = Record; -// --- SOLVER (Устраняет пересечения стенок) --- +// --- SOLVER: Итеративный расчет границ (Улучшенный) --- const solveWallLimits = (partitions: Partition[]): LimitMap => { const limits: LimitMap = {}; + // 1. Инициализация partitions.forEach(p => { limits[p.id] = { min: 0, max: 1 }; }); - // 3 прохода для надежности вложенных структур - for (let pass = 0; pass < 3; pass++) { + // 2. Итерации (4 прохода для стабилизации сложных вложений) + for (let pass = 0; pass < 4; pass++) { partitions.forEach(target => { let newMin = 0; let newMax = 1; const center = target.offset; partitions.forEach(obstacle => { - if (target.id === obstacle.id || target.axis === obstacle.axis) return; + if (target.id === obstacle.id) return; + if (target.axis === obstacle.axis) return; // Параллельные не влияют + // Берем границы препятствия с предыдущего шага const obsMin = limits[obstacle.id].min; const obsMax = limits[obstacle.id].max; - if (target.offset > obsMin && target.offset < obsMax) { - if (obstacle.offset < center) newMin = Math.max(newMin, obstacle.offset); - else if (obstacle.offset > center) newMax = Math.min(newMax, obstacle.offset); + // Важно: используем >= и <= с небольшим запасом для надежности + // Пересекает ли препятствие линию нашей стенки? + if (target.offset >= obsMin - 0.001 && target.offset <= obsMax + 0.001) { + // Препятствие на пути. Где оно относительно центра нашей стенки? + 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 }; }); } @@ -106,13 +116,10 @@ const createRoundedRectShape = (width: number, height: number, radius: number): return shape; }; -// Правильная форма "обратного" скругления (вогнутая) const createConcaveFilletShape = (radius: number): THREE.Shape => { const shape = new THREE.Shape(); - // Рисуем квадрат (0,0) -> (r,r), но вырезаем из него круг shape.moveTo(0, 0); shape.lineTo(radius, 0); - // Дуга: центр (r,r), радиус r, от 270 (-PI/2) до 180 (-PI) градусов shape.absarc(radius, radius, radius, -Math.PI / 2, -Math.PI, true); shape.lineTo(0, 0); return shape; @@ -123,7 +130,6 @@ export const createBinGeometry = ( ): THREE.BufferGeometry => { const geometries: THREE.BufferGeometry[] = []; - // ДНО И ВНЕШНИЕ СТЕНКИ const floorShape = createRoundedRectShape(width, depth, radius); const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false }); floorGeo.rotateX(-Math.PI / 2); @@ -145,7 +151,7 @@ export const createBinGeometry = ( wallGeo.translate(0, thickness, 0); geometries.push(wallGeo); - // ВНУТРЕННИЕ ПЕРЕГОРОДКИ + // Используем солвер для расчета реальных границ const limitMap = solveWallLimits(partitions); partitions.forEach(p => { @@ -175,22 +181,15 @@ export const createBinGeometry = ( partGeo.translate(pX, thickness, pY); geometries.push(partGeo); - // --- ДОБАВЛЕНИЕ ГАЛТЕЛЕЙ (FILLETS) --- if (p.rounded && radius > 1) { const filletR = Math.min(radius, 5); const filletShape = createConcaveFilletShape(filletR); const filletExtrude = { depth: p.height, bevelEnabled: false }; - const addFillet = (x: number, y: number, rotationY: number) => { + const addFillet = (x: number, y: number, rotY: number) => { const geo = new THREE.ExtrudeGeometry(filletShape, filletExtrude); - // Сначала кладем на пол (-PI/2 по X) - // Потом вращаем вокруг оси Y (которая теперь смотрит вверх) geo.rotateX(-Math.PI / 2); - - // ВАЖНО: Вращение геометрии происходит вокруг (0,0,0). - // Наша форма галтели имеет угол в (0,0). Это идеально. - geo.rotateY(rotationY); - + geo.rotateY(rotY); geo.translate(x, thickness, y); geometries.push(geo); }; @@ -198,44 +197,20 @@ export const createBinGeometry = ( const h = thickness / 2; if (p.axis === 'x') { - // Вертикальная стенка (вдоль Z) - // Top (Min Y) const topY = (-innerDepth / 2) + (innerDepth * pMin); - // Углы: Слева (-X) и Справа (+X) - - // Left-Top: смотрит в (-X, +Z). Угол PI (180) addFillet(pX - h, topY, Math.PI); - - // Right-Top: смотрит в (+X, +Z). Угол -PI/2 (-90) addFillet(pX + h, topY, -Math.PI / 2); - // Bottom (Max Y) const botY = (-innerDepth / 2) + (innerDepth * pMax); - - // Left-Bottom: смотрит в (-X, -Z). Угол PI/2 (90) addFillet(pX - h, botY, Math.PI / 2); - - // Right-Bottom: смотрит в (+X, -Z). Угол 0 addFillet(pX + h, botY, 0); - } else { - // Горизонтальная стенка (вдоль X) - // Left (Min X) const leftX = (-innerWidth / 2) + (innerWidth * pMin); - - // Top-Left: смотрит в (+X, -Z). Угол 0 addFillet(leftX, pY - h, 0); - - // Bottom-Left: смотрит в (+X, +Z). Угол -PI/2 (-90) addFillet(leftX, pY + h, -Math.PI / 2); - // Right (Max X) const rightX = (-innerWidth / 2) + (innerWidth * pMax); - - // Top-Right: смотрит в (-X, -Z). Угол PI/2 (90) addFillet(rightX, pY - h, Math.PI / 2); - - // Bottom-Right: смотрит в (-X, +Z). Угол PI (180) addFillet(rightX, pY + h, Math.PI); } } From 272b2b6f774a548adc254f8f5ff161db4b7f79ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sun, 11 Jan 2026 15:27:12 +0300 Subject: [PATCH 12/15] 10 --- src/components/LayoutStep.tsx | 69 ++++++++++++++++++++++------------- 1 file changed, 44 insertions(+), 25 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index ffd94b8..32d9295 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -50,7 +50,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]); const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]); - // -- HELPER: Get Selected -- + // -- HELPERS -- const getSelectedPartition = () => { if (!selectedPartitionId) return null; for (const key in safePartitions) { @@ -61,11 +61,12 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; const selectedData = getSelectedPartition(); - // --- SOLVER (Копия из geometryGenerator) --- + // --- SOLVER (Пересчет границ) --- const solveWallLimits = (parts: Partition[]): LimitMap => { const limits: LimitMap = {}; parts.forEach(p => { limits[p.id] = { min: 0, max: 1 }; }); + // 4 прохода для сложных вложений for (let pass = 0; pass < 4; pass++) { parts.forEach(target => { let newMin = 0; @@ -78,8 +79,9 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const obsMin = limits[obstacle.id].min; const obsMax = limits[obstacle.id].max; - // Используем >= и <= для надежности - if (target.offset >= obsMin - 0.001 && target.offset <= obsMax + 0.001) { + // Допуск (epsilon) чуть больше, чтобы надежнее ловить пересечения + const EPS = 0.005; + 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); } @@ -90,7 +92,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return limits; }; - // --- RAYCASTING (Исправленный поиск свободного места) --- + // --- RAYCASTING (Поиск коробки под курсором) --- const getCursorBox = (lx: number, ly: number, parts: Partition[], limitMap: LimitMap) => { let minX = 0, maxX = 1; let minY = 0, maxY = 1; @@ -99,20 +101,18 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const { min: pMin, max: pMax } = limitMap[p.id]; if (pMax - pMin < 0.001) return; - // Используем те же допуски, что и в Solver - const EPSILON = 0.001; + // Используем небольшой допуск, чтобы мышь точно "видела" стенку + const EPS = 0.002; if (p.axis === 'x') { - // Вертикальная преграда (X) - // Проверяем, перекрывает ли она Y курсора - if (ly >= pMin - EPSILON && ly <= pMax + EPSILON) { + // Вертикальная преграда + 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 { - // Горизонтальная преграда (Y) - // Проверяем, перекрывает ли она X курсора - if (lx >= pMin - EPSILON && lx <= pMax + EPSILON) { + // Горизонтальная преграда + 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); } @@ -121,16 +121,16 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return { minX, maxX, minY, maxY }; }; - // Поиск соседей для отображения размеров + // Поиск соседей для размеров const getNeighborOffsets = (offset: number, crossPos: number, axis: Axis, parts: Partition[], limitMap: LimitMap) => { let min = 0; let max = 1; - const EPSILON = 0.001; + const EPS = 0.001; parts.forEach(p => { if (p.axis === axis) { const { min: pMin, max: pMax } = limitMap[p.id]; - if (crossPos >= pMin - EPSILON && crossPos <= pMax + EPSILON) { + 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); } @@ -220,6 +220,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setPhantomPartition(null); setHoveredCell(null); + // 1. Находим ячейку let cellIdx = null; for (let i = 0; i < sortedX.length - 1; i++) { if (nx >= sortedX[i] && nx <= sortedX[i+1]) { @@ -243,6 +244,10 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const lx = (nx - cx1) / cw; const ly = (ny - cy1) / ch; + // Реальные размеры ячейки в мм (для корректного расчета дистанции мыши) + const realCellW = cw * drawerW; + const realCellH = ch * drawerD; + let found = null; const SNAP = 0.05; for (const p of parts) { @@ -257,20 +262,34 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (found) { setHoveredPartition({ id: found.id, cellKey: key }); } else { - // --- ВАЖНО: Получаем корректные границы с учетом Solver --- + // Вычисляем бокс под курсором const box = getCursorBox(lx, ly, parts, limitMap); - const distL = lx - box.minX; const distR = box.maxX - lx; - const distT = ly - box.minY; const distB = box.maxY - ly; + // --- ВАЖНО: Расчет дистанции с учетом РЕАЛЬНОГО размера ячейки (мм) --- + // Ранее считалось в относительных 0-1, что ломало логику в узких/широких ячейках + const distL = (lx - box.minX) * realCellW; + const distR = (box.maxX - lx) * realCellW; + const distT = (ly - box.minY) * realCellH; + const distB = (box.maxY - ly) * realCellH; - // Выбираем ось перпендикулярно ближайшей стороне + // Выбираем ось, к которой мы БЛИЖЕ ВИЗУАЛЬНО const minD = Math.min(distL, distR, distT, distB); - const newAxis = (minD === distL || minD === distR) ? 'x' : 'y'; - - const width = box.maxX - box.minX; - const height = box.maxY - box.minY; - if ((newAxis === 'y' && height > 0.05) || (newAxis === 'x' && width > 0.05)) { + // Если мы близко к бокам -> ставим вертикальную (x) + // Если близко к верху/низу -> ставим горизонтальную (y) + let newAxis: Axis = (minD === distL || minD === distR) ? 'x' : 'y'; + + // Но если мы в центре, выбираем ось, которая делит длинную сторону + const boxW = (box.maxX - box.minX) * realCellW; + const boxH = (box.maxY - box.minY) * realCellH; + + // Если мы не "прилипли" к краю (находимся далеко от всего > 20мм), то делим длинную сторону + if (minD > 20) { + newAxis = boxW > boxH ? 'x' : 'y'; + } + + // Финальная проверка, есть ли место для стенки (минимум 10% от размера коробки) + if ((newAxis === 'y' && (box.maxY - box.minY) > 0.1) || (newAxis === 'x' && (box.maxX - box.minX) > 0.1)) { const offset = newAxis === 'x' ? lx : ly; const min = newAxis === 'x' ? box.minY : box.minX; const max = newAxis === 'x' ? box.maxY : box.maxX; From 56183b3adaca43bccafafd78178970b0cafec8b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sun, 11 Jan 2026 15:40:07 +0300 Subject: [PATCH 13/15] 11 --- src/components/LayoutStep.tsx | 131 +++++++++++++++++----------------- 1 file changed, 65 insertions(+), 66 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index 32d9295..eb3a280 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -50,7 +50,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]); const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]); - // -- HELPERS -- + // -- HELPER: Get Selected -- const getSelectedPartition = () => { if (!selectedPartitionId) return null; for (const key in safePartitions) { @@ -61,12 +61,11 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; const selectedData = getSelectedPartition(); - // --- SOLVER (Пересчет границ) --- + // --- SOLVER --- const solveWallLimits = (parts: Partition[]): LimitMap => { const limits: LimitMap = {}; parts.forEach(p => { limits[p.id] = { min: 0, max: 1 }; }); - // 4 прохода для сложных вложений for (let pass = 0; pass < 4; pass++) { parts.forEach(target => { let newMin = 0; @@ -79,9 +78,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const obsMin = limits[obstacle.id].min; const obsMax = limits[obstacle.id].max; - // Допуск (epsilon) чуть больше, чтобы надежнее ловить пересечения - const EPS = 0.005; - if (target.offset >= obsMin - EPS && target.offset <= obsMax + EPS) { + if (target.offset >= obsMin - 0.001 && target.offset <= obsMax + 0.001) { if (obstacle.offset < center) newMin = Math.max(newMin, obstacle.offset); else if (obstacle.offset > center) newMax = Math.min(newMax, obstacle.offset); } @@ -92,7 +89,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return limits; }; - // --- RAYCASTING (Поиск коробки под курсором) --- + // --- RAYCASTING --- const getCursorBox = (lx: number, ly: number, parts: Partition[], limitMap: LimitMap) => { let minX = 0, maxX = 1; let minY = 0, maxY = 1; @@ -101,17 +98,14 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const { min: pMin, max: pMax } = limitMap[p.id]; if (pMax - pMin < 0.001) return; - // Используем небольшой допуск, чтобы мышь точно "видела" стенку const EPS = 0.002; if (p.axis === 'x') { - // Вертикальная преграда 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 { - // Горизонтальная преграда 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); @@ -220,7 +214,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setPhantomPartition(null); setHoveredCell(null); - // 1. Находим ячейку + // 1. Find Cell let cellIdx = null; for (let i = 0; i < sortedX.length - 1; i++) { if (nx >= sortedX[i] && nx <= sortedX[i+1]) { @@ -244,7 +238,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const lx = (nx - cx1) / cw; const ly = (ny - cy1) / ch; - // Реальные размеры ячейки в мм (для корректного расчета дистанции мыши) + // Реальные размеры в мм (для интуитивности) const realCellW = cw * drawerW; const realCellH = ch * drawerD; @@ -262,34 +256,38 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (found) { setHoveredPartition({ id: found.id, cellKey: key }); } else { - // Вычисляем бокс под курсором + // --- ЛОГИКА ФАНТОМА --- const box = getCursorBox(lx, ly, parts, limitMap); - // --- ВАЖНО: Расчет дистанции с учетом РЕАЛЬНОГО размера ячейки (мм) --- - // Ранее считалось в относительных 0-1, что ломало логику в узких/широких ячейках - const distL = (lx - box.minX) * realCellW; - const distR = (box.maxX - lx) * realCellW; - const distT = (ly - box.minY) * realCellH; - const distB = (box.maxY - ly) * realCellH; + const distL = lx - box.minX; const distR = box.maxX - lx; + const distT = ly - box.minY; const distB = box.maxY - ly; - // Выбираем ось, к которой мы БЛИЖЕ ВИЗУАЛЬНО - const minD = Math.min(distL, distR, distT, distB); - - // Если мы близко к бокам -> ставим вертикальную (x) - // Если близко к верху/низу -> ставим горизонтальную (y) - let newAxis: Axis = (minD === distL || minD === distR) ? 'x' : 'y'; - - // Но если мы в центре, выбираем ось, которая делит длинную сторону + // Размеры "комнаты" под курсором const boxW = (box.maxX - box.minX) * realCellW; const boxH = (box.maxY - box.minY) * realCellH; - - // Если мы не "прилипли" к краю (находимся далеко от всего > 20мм), то делим длинную сторону - if (minD > 20) { - newAxis = boxW > boxH ? 'x' : 'y'; + + // 1. По умолчанию делим длинную сторону (чтобы ячейки стремились к квадрату) + let newAxis: Axis = boxW > boxH ? 'x' : 'y'; + + // 2. Но если мы близко к краю (менее 15% ширины/высоты), + // значит пользователь хочет отрезать узкую полоску параллельно этому краю. + const edgeThreshold = 0.15; // 15% + const relL = lx - box.minX; + const relT = ly - box.minY; + const relW = box.maxX - box.minX; + const relH = box.maxY - box.minY; + + // Если близко к бокам -> ставим вертикальную (X) + if (relL / relW < edgeThreshold || (relW - relL) / relW < edgeThreshold) { + newAxis = 'x'; + } + // Если близко к верху/низу -> ставим горизонтальную (Y) + else if (relT / relH < edgeThreshold || (relH - relT) / relH < edgeThreshold) { + newAxis = 'y'; } - // Финальная проверка, есть ли место для стенки (минимум 10% от размера коробки) - if ((newAxis === 'y' && (box.maxY - box.minY) > 0.1) || (newAxis === 'x' && (box.maxX - box.minX) > 0.1)) { + // Проверяем, есть ли место (>10% размера) + if ((newAxis === 'y' && relH > 0.1) || (newAxis === 'x' && relW > 0.1)) { const offset = newAxis === 'x' ? lx : ly; const min = newAxis === 'x' ? box.minY : box.minX; const max = newAxis === 'x' ? box.maxY : box.maxX; @@ -355,10 +353,8 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const realW = (x2 - x1) * drawerW; const realD = (y2 - y1) * drawerD; - // ВАЖНО: Используем solver для отрисовки const limitMap = solveWallLimits(parts); - // Label if (parts.length === 0) { const labelX = cellX + cellW / 2; const labelY = cellY + cellH / 2; @@ -460,27 +456,22 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; return ( -
-
-

2. Редактор макета

-
- - -
- -
+
+ + {/* LEFT: WORKSPACE */} +
+ {/* TOOLBAR */} +
+

Редактор

+
+ + +
+ +
-
- - {mode === 'lines' ? ( -
ЛКМ: ЛинияПКМ: Удалить
- ) : ( -
ЛКМ в ячейке: СтенкаДраг: Двигать2xЛКМ: Удалить
- )} -
- -
-
+ {/* CANVAS */} +
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') }}> setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()}> @@ -503,19 +494,27 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { )}
-
+
+
- {mode === 'cells' && selectedData && ( -
-

Настройки стенки

-
-
Высота {selectedData.part.height} мм
updatePartition(selectedData.key, selectedData.part.id, { height: parseFloat(e.target.value) })} className="w-full h-1 bg-slate-600 rounded-lg appearance-none cursor-pointer accent-purple-500"/>
-
updatePartition(selectedData.key, selectedData.part.id, { rounded: e.target.checked })} className="w-4 h-4 rounded bg-slate-700 border-slate-600 text-purple-500 focus:ring-0 cursor-pointer"/>
- -
-
- )} + {/* RIGHT: SIDEBAR */} + {mode === 'cells' && selectedData ? ( +
+

Настройки

+
+
Высота {selectedData.part.height} мм
updatePartition(selectedData.key, selectedData.part.id, { height: parseFloat(e.target.value) })} className="w-full h-1 bg-slate-600 rounded-lg appearance-none cursor-pointer accent-purple-500"/>
+
updatePartition(selectedData.key, selectedData.part.id, { rounded: e.target.checked })} className="w-4 h-4 rounded bg-slate-700 border-slate-600 text-purple-500 focus:ring-0 cursor-pointer"/>
+ +
+
Выделите стенку для настройки.
Двойной клик удаляет её.
+ ) : ( +
+ +

Выберите стенку для настройки

+

Кликните по любой перегородке внутри ячейки

+
+ )}
); }; \ No newline at end of file From 803c7213d5121769a7f6a2eb21f4165d1a83fd9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sun, 11 Jan 2026 15:48:49 +0300 Subject: [PATCH 14/15] 12 --- src/components/LayoutStep.tsx | 78 ++++++++++++++++++----------------- 1 file changed, 41 insertions(+), 37 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index eb3a280..2d2b749 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -1,4 +1,4 @@ -import React, { useRef, useState, useMemo } from 'react'; +import React, { useRef, useState, useMemo, useEffect } from 'react'; import { AppConfig, LayoutSplits, Partition } from '../types'; import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings2 } from 'lucide-react'; @@ -61,11 +61,12 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; const selectedData = getSelectedPartition(); - // --- SOLVER --- + // --- SOLVER (Robust) --- const solveWallLimits = (parts: Partition[]): LimitMap => { const limits: LimitMap = {}; parts.forEach(p => { limits[p.id] = { min: 0, max: 1 }; }); + // 4 прохода для надежности for (let pass = 0; pass < 4; pass++) { parts.forEach(target => { let newMin = 0; @@ -78,7 +79,9 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const obsMin = limits[obstacle.id].min; const obsMax = limits[obstacle.id].max; - if (target.offset >= obsMin - 0.001 && target.offset <= obsMax + 0.001) { + // Epsilon для надежного пересечения + const EPS = 0.001; + 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); } @@ -89,23 +92,26 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return limits; }; - // --- RAYCASTING --- + // --- RAYCASTING (Find empty box) --- const getCursorBox = (lx: number, ly: number, parts: Partition[], limitMap: LimitMap) => { 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.002; + const EPS = 0.005; // Чуть больше допуск для мыши if (p.axis === 'x') { + // Вертикальная стенка 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 { + // Горизонтальная стенка 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); @@ -115,7 +121,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return { minX, maxX, minY, maxY }; }; - // Поиск соседей для размеров + // --- NEIGHBORS (For dimensions) --- const getNeighborOffsets = (offset: number, crossPos: number, axis: Axis, parts: Partition[], limitMap: LimitMap) => { let min = 0; let max = 1; @@ -214,7 +220,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setPhantomPartition(null); setHoveredCell(null); - // 1. Find Cell + // 1. Find Global Cell let cellIdx = null; for (let i = 0; i < sortedX.length - 1; i++) { if (nx >= sortedX[i] && nx <= sortedX[i+1]) { @@ -238,10 +244,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const lx = (nx - cx1) / cw; const ly = (ny - cy1) / ch; - // Реальные размеры в мм (для интуитивности) - const realCellW = cw * drawerW; - const realCellH = ch * drawerD; - + // Check hover over existing walls let found = null; const SNAP = 0.05; for (const p of parts) { @@ -256,38 +259,41 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (found) { setHoveredPartition({ id: found.id, cellKey: key }); } else { - // --- ЛОГИКА ФАНТОМА --- + // --- PHANTOM LOGIC --- const box = getCursorBox(lx, ly, parts, limitMap); - const distL = lx - box.minX; const distR = box.maxX - lx; - const distT = ly - box.minY; const distB = box.maxY - ly; + // Локальные координаты относительно "коробки" (0..1) + const localBoxW = box.maxX - box.minX; + const localBoxH = box.maxY - box.minY; - // Размеры "комнаты" под курсором - const boxW = (box.maxX - box.minX) * realCellW; - const boxH = (box.maxY - box.minY) * realCellH; + const relX = (lx - box.minX) / localBoxW; + const relY = (ly - box.minY) / localBoxH; - // 1. По умолчанию делим длинную сторону (чтобы ячейки стремились к квадрату) - let newAxis: Axis = boxW > boxH ? 'x' : 'y'; + // Определяем ось на основе позиции мыши в "коробке" + // Если мы близко к краям - хотим отрезать кусок (перпендикуляр) + // Если в центре - делим длинную сторону + + const edgeThreshold = 0.2; // 20% от края + let newAxis: Axis; - // 2. Но если мы близко к краю (менее 15% ширины/высоты), - // значит пользователь хочет отрезать узкую полоску параллельно этому краю. - const edgeThreshold = 0.15; // 15% - const relL = lx - box.minX; - const relT = ly - box.minY; - const relW = box.maxX - box.minX; - const relH = box.maxY - box.minY; + const nearLeftRight = relX < edgeThreshold || relX > (1 - edgeThreshold); + const nearTopBottom = relY < edgeThreshold || relY > (1 - edgeThreshold); - // Если близко к бокам -> ставим вертикальную (X) - if (relL / relW < edgeThreshold || (relW - relL) / relW < edgeThreshold) { - newAxis = 'x'; - } - // Если близко к верху/низу -> ставим горизонтальную (Y) - else if (relT / relH < edgeThreshold || (relH - relT) / relH < edgeThreshold) { - newAxis = 'y'; + if (nearLeftRight && !nearTopBottom) { + newAxis = 'x'; // Рядом с боковой стенкой -> Вертикальная + } else if (nearTopBottom && !nearLeftRight) { + newAxis = 'y'; // Рядом с верхней/нижней -> Горизонтальная + } else { + // В центре или в углу -> делим длинную сторону (учитывая реальные мм) + const realBoxW = localBoxW * (cw * drawerW); + const realBoxH = localBoxH * (ch * drawerD); + newAxis = realBoxW > realBoxH ? 'x' : 'y'; } - // Проверяем, есть ли место (>10% размера) - if ((newAxis === 'y' && relH > 0.1) || (newAxis === 'x' && relW > 0.1)) { + // Финальная проверка: есть ли место? + const valid = (newAxis === 'x' && localBoxW > 0.05) || (newAxis === 'y' && localBoxH > 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; @@ -460,7 +466,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { {/* LEFT: WORKSPACE */}
- {/* TOOLBAR */}

Редактор

@@ -470,7 +475,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => {
- {/* CANVAS */}
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') }}> setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()}> From 33a5b8d44df14c6b71a0a122d1b08196a65540c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sun, 11 Jan 2026 15:54:50 +0300 Subject: [PATCH 15/15] 13 --- src/components/LayoutStep.tsx | 150 ++++++++++-------------------- src/services/geometryGenerator.ts | 53 ++--------- 2 files changed, 58 insertions(+), 145 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index 2d2b749..bde04f1 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -1,4 +1,4 @@ -import React, { useRef, useState, useMemo, useEffect } from 'react'; +import React, { useRef, useState, useMemo } from 'react'; import { AppConfig, LayoutSplits, Partition } from '../types'; import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings2 } from 'lucide-react'; @@ -10,8 +10,6 @@ interface Props { type EditMode = 'lines' | 'cells'; type Axis = 'x' | 'y'; -type Limits = { min: number; max: number }; -type LimitMap = Record; type DragTarget = | { type: 'main'; axis: Axis; index: number } @@ -61,58 +59,29 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; const selectedData = getSelectedPartition(); - // --- SOLVER (Robust) --- - const solveWallLimits = (parts: Partition[]): LimitMap => { - const limits: LimitMap = {}; - parts.forEach(p => { limits[p.id] = { min: 0, max: 1 }; }); - - // 4 прохода для надежности - 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.001; - 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 (Find empty box) --- - 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); } @@ -121,15 +90,16 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return { minX, maxX, minY, maxY }; }; - // --- NEIGHBORS (For dimensions) --- - 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); @@ -220,7 +190,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setPhantomPartition(null); setHoveredCell(null); - // 1. Find Global Cell + // Find Cell let cellIdx = null; for (let i = 0; i < sortedX.length - 1; i++) { if (nx >= sortedX[i] && nx <= sortedX[i+1]) { @@ -236,7 +206,6 @@ export const LayoutStep: React.FC = ({ 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]; @@ -244,54 +213,43 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const lx = (nx - cx1) / cw; const ly = (ny - cy1) / ch; - // Check hover over existing walls + // 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 { - // --- PHANTOM LOGIC --- - const box = getCursorBox(lx, ly, parts, limitMap); + // --- FIND BOX --- + const box = getCursorBox(lx, ly, parts); - // Локальные координаты относительно "коробки" (0..1) - const localBoxW = box.maxX - box.minX; - const localBoxH = box.maxY - box.minY; - - const relX = (lx - box.minX) / localBoxW; - const relY = (ly - box.minY) / localBoxH; + const boxW = (box.maxX - box.minX) * realCellW; + const boxH = (box.maxY - box.minY) * realCellH; - // Определяем ось на основе позиции мыши в "коробке" - // Если мы близко к краям - хотим отрезать кусок (перпендикуляр) - // Если в центре - делим длинную сторону - - const edgeThreshold = 0.2; // 20% от края - let newAxis: Axis; + // Default axis based on longest side + let newAxis: Axis = boxW > boxH ? 'x' : 'y'; - const nearLeftRight = relX < edgeThreshold || relX > (1 - edgeThreshold); - const nearTopBottom = relY < edgeThreshold || relY > (1 - edgeThreshold); + // 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 (nearLeftRight && !nearTopBottom) { - newAxis = 'x'; // Рядом с боковой стенкой -> Вертикальная - } else if (nearTopBottom && !nearLeftRight) { - newAxis = 'y'; // Рядом с верхней/нижней -> Горизонтальная - } else { - // В центре или в углу -> делим длинную сторону (учитывая реальные мм) - const realBoxW = localBoxW * (cw * drawerW); - const realBoxH = localBoxH * (ch * drawerD); - newAxis = realBoxW > realBoxH ? 'x' : 'y'; - } + 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' && localBoxW > 0.05) || (newAxis === 'y' && localBoxH > 0.05); + 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; @@ -359,8 +317,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const realW = (x2 - x1) * drawerW; const realD = (y2 - y1) * drawerD; - const limitMap = solveWallLimits(parts); - if (parts.length === 0) { const labelX = cellX + cellW / 2; const labelY = cellY + cellH / 2; @@ -381,8 +337,9 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { {isAnySelected && mode === 'cells' && } {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; @@ -392,22 +349,20 @@ export const LayoutStep: React.FC = ({ 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 cy = (min + max) / 2; - const box = getCursorBox(p.offset, cy, parts, limitMap); - dist1 = Math.abs((p.offset - box.minX) * realW) - wallThick; - dist2 = Math.abs((box.maxX - p.offset) * realW) - wallThick; + 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 cx = (min + max) / 2; - const box = getCursorBox(cx, p.offset, parts, limitMap); - dist1 = Math.abs((p.offset - box.minY) * realD) - wallThick; - dist2 = Math.abs((box.maxY - p.offset) * realD) - wallThick; + 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; } @@ -463,14 +418,12 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return (
- - {/* LEFT: WORKSPACE */}

Редактор

- +
@@ -501,7 +454,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => {
- {/* RIGHT: SIDEBAR */} {mode === 'cells' && selectedData ? (

Настройки

diff --git a/src/services/geometryGenerator.ts b/src/services/geometryGenerator.ts index affa06a..58d7263 100644 --- a/src/services/geometryGenerator.ts +++ b/src/services/geometryGenerator.ts @@ -2,48 +2,6 @@ import * as THREE from 'three'; import { STLExporter, mergeBufferGeometries } from 'three-stdlib'; import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types'; -type Limits = { min: number; max: number }; -type LimitMap = Record; - -// --- SOLVER: Итеративный расчет границ (Улучшенный) --- -const solveWallLimits = (partitions: Partition[]): LimitMap => { - const limits: LimitMap = {}; - // 1. Инициализация - partitions.forEach(p => { limits[p.id] = { min: 0, max: 1 }; }); - - // 2. Итерации (4 прохода для стабилизации сложных вложений) - for (let pass = 0; pass < 4; pass++) { - partitions.forEach(target => { - let newMin = 0; - let newMax = 1; - const center = target.offset; - - partitions.forEach(obstacle => { - if (target.id === obstacle.id) return; - if (target.axis === obstacle.axis) return; // Параллельные не влияют - - // Берем границы препятствия с предыдущего шага - const obsMin = limits[obstacle.id].min; - const obsMax = limits[obstacle.id].max; - - // Важно: используем >= и <= с небольшим запасом для надежности - // Пересекает ли препятствие линию нашей стенки? - if (target.offset >= obsMin - 0.001 && target.offset <= obsMax + 0.001) { - // Препятствие на пути. Где оно относительно центра нашей стенки? - 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; -}; - export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => { const parts: GeneratedPart[] = []; const safeX = Array.isArray(splits?.x) ? splits.x : []; @@ -130,6 +88,7 @@ export const createBinGeometry = ( ): THREE.BufferGeometry => { const geometries: THREE.BufferGeometry[] = []; + // ДНО И ВНЕШНИЕ СТЕНКИ const floorShape = createRoundedRectShape(width, depth, radius); const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false }); floorGeo.rotateX(-Math.PI / 2); @@ -151,11 +110,12 @@ export const createBinGeometry = ( wallGeo.translate(0, thickness, 0); geometries.push(wallGeo); - // Используем солвер для расчета реальных границ - const limitMap = solveWallLimits(partitions); - + // ВНУТРЕННИЕ ПЕРЕГОРОДКИ + // Мы просто верим сохраненным данным (p.min/p.max). Они должны быть корректны при создании. partitions.forEach(p => { - const { min: pMin, max: pMax } = limitMap[p.id]; + const pMin = p.min ?? 0; + const pMax = p.max ?? 1; + if (pMax - pMin < 0.01) return; const lengthRatio = pMax - pMin; @@ -181,6 +141,7 @@ export const createBinGeometry = ( partGeo.translate(pX, thickness, pY); geometries.push(partGeo); + // СКРУГЛЕНИЯ if (p.rounded && radius > 1) { const filletR = Math.min(radius, 5); const filletShape = createConcaveFilletShape(filletR);