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] 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);