This commit is contained in:
Халимов Рустам
2026-01-12 02:58:41 +03:00
parent d8d34371a9
commit 5235fa888f
+109 -39
View File
@@ -2,19 +2,21 @@ import * as THREE from 'three';
import { STLExporter, mergeBufferGeometries } from 'three-stdlib'; import { STLExporter, mergeBufferGeometries } from 'three-stdlib';
import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types'; import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types';
// --- УТИЛИТЫ --- // --- ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ ---
// Очистка координат (убирает фантомные ячейки и дрожание)
const cleanPoints = (points: number[]) => { const cleanPoints = (points: number[]) => {
const rounded = points.map(p => Math.round(p * 1000) / 1000).sort((a, b) => a - b); const rounded = points.map(p => Math.round(p * 1000) / 1000).sort((a, b) => a - b);
return [...new Set(rounded)]; return [...new Set(rounded)];
}; };
// Сбор всех перегородок в плоский список
const getAllPartitions = (splits: LayoutSplits): Partition[] => { const getAllPartitions = (splits: LayoutSplits): Partition[] => {
if (!splits || !splits.partitions) return []; if (!splits || !splits.partitions) return [];
return Object.values(splits.partitions).flat(); return Object.values(splits.partitions).flat();
}; };
// Функция для визуализации (шаг 3) // --- ВИЗУАЛИЗАЦИЯ (Цветные кубики для шага 3) ---
export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => { export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => {
const parts: GeneratedPart[] = []; const parts: GeneratedPart[] = [];
const safeX = Array.isArray(splits?.x) ? splits.x : []; const safeX = Array.isArray(splits?.x) ? splits.x : [];
@@ -35,18 +37,21 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
const rawW = (x2 - x1) * config.drawer.width; const rawW = (x2 - x1) * config.drawer.width;
const rawD = (y2 - y1) * config.drawer.depth; const rawD = (y2 - y1) * config.drawer.depth;
// Фильтр слишком мелких ячеек
if (rawW < 2 || rawD < 2) continue; if (rawW < 2 || rawD < 2) continue;
const rawX = x1 * config.drawer.width; const rawX = x1 * config.drawer.width;
const rawY = y1 * config.drawer.depth; const rawY = y1 * config.drawer.depth;
const gap = config.wallThickness / 2 + 0.1;
// Зазор для визуализации (чтобы блоки не слипались)
const gap = config.wallThickness / 2 + 0.15;
parts.push({ parts.push({
id: `part-${partCounter}`, id: `part-${partCounter}`,
name: `Ячейка ${partCounter}`, name: `Ячейка ${partCounter}`,
width: Math.max(1, rawW - gap * 2), width: Math.max(1, rawW - gap * 2),
depth: Math.max(1, rawD - gap * 2), depth: Math.max(1, rawD - gap * 2),
height: config.drawer.height, height: config.drawer.height - config.wallThickness, // Высота без пола
x: rawX + gap, x: rawX + gap,
y: rawY + gap, y: rawY + gap,
color: `hsl(${(partCounter * 137.5) % 360}, 70%, 50%)`, color: `hsl(${(partCounter * 137.5) % 360}, 70%, 50%)`,
@@ -58,35 +63,39 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
return parts; return parts;
}; };
// --- ГЕНЕРАЦИЯ ГЕОМЕТРИИ (НАТИВНЫЙ THREE.JS) --- // --- ГЕНЕРАЦИЯ ГЕОМЕТРИИ (NATIVE THREE.JS) ---
// Создает 2D форму стены с отверстиями // Функция создания 2D формы с дырками
const createPerforatedShape = (length: number, height: number, config: AppConfig): THREE.Shape => { const createPerforatedShape = (length: number, height: number, config: AppConfig): THREE.Shape => {
const shape = new THREE.Shape(); const shape = new THREE.Shape();
// 1. Внешний контур (CCW - Против часовой стрелки) // 1. Внешний контур: ПРОТИВ ЧАСОВОЙ (CCW)
// (0,0) -> (L,0) -> (L,H) -> (0,H) -> (0,0)
shape.moveTo(0, 0); shape.moveTo(0, 0);
shape.lineTo(length, 0); shape.lineTo(length, 0);
shape.lineTo(length, height); shape.lineTo(length, height);
shape.lineTo(0, height); shape.lineTo(0, height);
shape.lineTo(0, 0); shape.lineTo(0, 0);
// Если перфорация выключена // Если перфорация выключена или стенка слишком маленькая для дырок
if (!config.perforation?.enabled || length < 10 || height < 10) return shape; if (!config.perforation?.enabled || length < 15 || height < 15) return shape;
const { pattern, diameter, spacing } = config.perforation; const { pattern, diameter, spacing } = config.perforation;
const step = diameter + Math.max(2, spacing); const step = diameter + Math.max(2, spacing);
const margin = 4; const margin = 4; // Отступ от краев стенки
// Эффективная зона для отверстий
const effW = length - margin * 2; const effW = length - margin * 2;
const effH = height - margin * 2; const effH = height - margin * 2;
if (effW <= diameter || effH <= diameter) return shape; if (effW <= diameter || effH <= diameter) return shape;
// Расчет сетки
const rowH = pattern === 'circle' ? step : step * 0.866; const rowH = pattern === 'circle' ? step : step * 0.866;
const cols = Math.floor(effW / step); const cols = Math.floor(effW / step);
const rows = Math.floor(effH / rowH); const rows = Math.floor(effH / rowH);
// Центрирование сетки
const startX = margin + (effW - (cols - 1) * step) / 2; const startX = margin + (effW - (cols - 1) * step) / 2;
const startY = margin + (effH - (rows - 1) * rowH) / 2; const startY = margin + (effH - (rows - 1) * rowH) / 2;
@@ -96,21 +105,25 @@ const createPerforatedShape = (length: number, height: number, config: AppConfig
for (let i = 0; i < cols; i++) { for (let i = 0; i < cols; i++) {
let cx = startX + i * step; let cx = startX + i * step;
// Смещение для сот/треугольников
if ((pattern === 'hexagon' || pattern === 'triangle') && isOdd) cx += step / 2; if ((pattern === 'hexagon' || pattern === 'triangle') && isOdd) cx += step / 2;
// Проверка, что отверстие не вылезает за пределы
if (cx - diameter/2 < margin || cx + diameter/2 > length - margin || if (cx - diameter/2 < margin || cx + diameter/2 > length - margin ||
cy - diameter/2 < margin || cy + diameter/2 > height - margin) continue; cy - diameter/2 < margin || cy + diameter/2 > height - margin) continue;
const hole = new THREE.Path(); const hole = new THREE.Path();
const r = diameter / 2; const r = diameter / 2;
// 2. Отверстия (CW - По часовой стрелке). // 2. ВНУТРЕННИЕ ОТВЕРСТИЯ: ПО ЧАСОВОЙ (CW)
// aClockwise = true. Это критично для корректного вырезания. // Параметр aClockwise = true в absarc. Это критично!
if (pattern === 'circle') { if (pattern === 'circle') {
hole.absarc(cx, cy, r, 0, Math.PI * 2, true); hole.absarc(cx, cy, r, 0, Math.PI * 2, true);
} }
else if (pattern === 'hexagon') { else if (pattern === 'hexagon') {
for (let k = 0; k < 6; k++) { for (let k = 0; k < 6; k++) {
// Угол идет в минус -> CW направление
const angle = (-k * 60 + 90) * Math.PI / 180; const angle = (-k * 60 + 90) * Math.PI / 180;
const px = cx + r * Math.cos(angle); const px = cx + r * Math.cos(angle);
const py = cy + r * Math.sin(angle); const py = cy + r * Math.sin(angle);
@@ -121,6 +134,7 @@ const createPerforatedShape = (length: number, height: number, config: AppConfig
else if (pattern === 'triangle') { else if (pattern === 'triangle') {
const rot = isOdd ? 180 : 0; const rot = isOdd ? 180 : 0;
for (let k = 0; k < 3; k++) { for (let k = 0; k < 3; k++) {
// Угол идет в минус -> CW направление
const angle = (-k * 120 + 90 + rot) * Math.PI / 180; const angle = (-k * 120 + 90 + rot) * Math.PI / 180;
const px = cx + r * Math.cos(angle); const px = cx + r * Math.cos(angle);
const py = cy + r * Math.sin(angle); const py = cy + r * Math.sin(angle);
@@ -134,6 +148,46 @@ const createPerforatedShape = (length: number, height: number, config: AppConfig
return shape; return shape;
}; };
// Форма пола (без дырок)
const createFloorShape = (width: number, depth: number, radius: number): THREE.Shape => {
const shape = new THREE.Shape();
const x = -width / 2;
const y = -depth / 2;
const r = Math.min(radius, width / 2 - 0.1, depth / 2 - 0.1);
if (r <= 0.1) {
shape.moveTo(x, y);
shape.lineTo(x + width, y);
shape.lineTo(x + width, y + depth);
shape.lineTo(x, y + depth);
shape.lineTo(x, y);
} else {
shape.moveTo(x, y + r);
shape.lineTo(x, y + depth - r);
shape.quadraticCurveTo(x, y + depth, x + r, y + depth);
shape.lineTo(x + width - r, y + depth);
shape.quadraticCurveTo(x + width, y + depth, x + width, y + depth - r);
shape.lineTo(x + width, y + r);
shape.quadraticCurveTo(x + width, y, x + width - r, y);
shape.lineTo(x + r, y);
shape.quadraticCurveTo(x, y, x, y + r);
}
return shape;
};
// Форма скругления (Cylinder sector)
const createFilletShape = (radius: number): THREE.Shape => {
const shape = new THREE.Shape();
shape.moveTo(0, 0);
shape.lineTo(radius, 0);
// Дуга
shape.absarc(radius, radius, radius, -Math.PI / 2, -Math.PI, true);
shape.lineTo(0, 0);
return shape;
};
// --- СБОРКА ВСЕЙ ГЕОМЕТРИИ ---
export const createBinGeometry = ( export const createBinGeometry = (
width: number, depth: number, height: number, thickness: number, radius: number = 0, width: number, depth: number, height: number, thickness: number, radius: number = 0,
splits: LayoutSplits | Partition[] = [], splits: LayoutSplits | Partition[] = [],
@@ -144,42 +198,47 @@ export const createBinGeometry = (
const safeConfig = config || { perforation: { enabled: false } } as AppConfig; const safeConfig = config || { perforation: { enabled: false } } as AppConfig;
// 1. ПОЛ // 1. ПОЛ
const floorGeo = new THREE.BoxGeometry(width, thickness, depth); const floorShape = createFloorShape(width, depth, radius);
floorGeo.translate(0, thickness / 2, 0); const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false });
floorGeo.rotateX(-Math.PI / 2); // Кладем на землю
geometries.push(floorGeo); geometries.push(floorGeo);
const wallH = height - thickness; const wallH = height - thickness;
const innerW = width - 2 * thickness; const innerW = width - 2 * thickness;
const innerD = depth - 2 * thickness; const innerD = depth - 2 * thickness;
// Хелпер: создает стену, экструдит, вращает и ставит на место // Функция для создания, экструзии и установки стены
const addWall = (len: number, h: number, x: number, z: number, isVert: boolean) => { const addWall = (length: number, h: number, x: number, z: number, isVertical: boolean) => {
// 1. 2D форма // 1. Создаем 2D чертеж с дырками
const shape = createPerforatedShape(len, h, safeConfig); const shape = createPerforatedShape(length, h, safeConfig);
// 2. Экструзия (Толщина)
// 2. Выдавливаем (получаем толщину)
const geo = new THREE.ExtrudeGeometry(shape, { depth: thickness, bevelEnabled: false }); const geo = new THREE.ExtrudeGeometry(shape, { depth: thickness, bevelEnabled: false });
// 3. Центрирование геометрии (чтобы вращать вокруг центра) // 3. Центрируем геометрию в локальных осях (чтобы вращать вокруг центра)
geo.center(); geo.center();
// Теперь координаты стены от -Len/2 до +Len/2
// 4. Поворот и Позиционирование // 4. Поворачиваем если нужно
if (isVert) { if (isVertical) {
geo.rotateY(Math.PI / 2); geo.rotateY(Math.PI / 2);
} }
// Поднимаем на пол (thickness + h/2)
// 5. Ставим на место
// Y: поднимаем на пол (thickness) + половина высоты (так как мы центрировали по Y)
geo.translate(x, thickness + h/2, z); geo.translate(x, thickness + h/2, z);
geometries.push(geo); geometries.push(geo);
}; };
// 2. ВНЕШНИЕ СТЕНЫ // 2. ВНЕШНИЕ СТЕНЫ
// Front (вдоль X) // Front (Вдоль X)
addWall(innerW, wallH, 0, depth/2 - thickness/2, false); addWall(innerW, wallH, 0, depth/2 - thickness/2, false);
// Back (вдоль X) // Back (Вдоль X)
addWall(innerW, wallH, 0, -depth/2 + thickness/2, false); addWall(innerW, wallH, 0, -depth/2 + thickness/2, false);
// Left (вдоль Z) // Left (Вдоль Z, полная глубина)
addWall(depth, wallH, -width/2 + thickness/2, 0, true); addWall(depth, wallH, -width/2 + thickness/2, 0, true);
// Right (вдоль Z) // Right (Вдоль Z, полная глубина)
addWall(depth, wallH, width/2 - thickness/2, 0, true); addWall(depth, wallH, width/2 - thickness/2, 0, true);
// 3. ВНУТРЕННИЕ ПЕРЕГОРОДКИ // 3. ВНУТРЕННИЕ ПЕРЕГОРОДКИ
@@ -190,6 +249,8 @@ export const createBinGeometry = (
partitions.forEach(p => { partitions.forEach(p => {
const pMin = p.min ?? 0; const pMin = p.min ?? 0;
const pMax = p.max ?? 1; const pMax = p.max ?? 1;
// Защита от мусорных данных
if (Math.abs(pMax - pMin) < 0.001) return; if (Math.abs(pMax - pMin) < 0.001) return;
let len = 0; let len = 0;
@@ -197,55 +258,64 @@ export const createBinGeometry = (
let zPos = 0; let zPos = 0;
let isVert = false; let isVert = false;
if (p.axis === 'x') { // Vert (Z-axis) // Рассчитываем позицию центра перегородки
if (p.axis === 'x') { // Vert (Вдоль Z)
isVert = true; isVert = true;
len = (pMax - pMin) * innerD; len = (pMax - pMin) * innerD;
// X позиция: от левого края innerW
xPos = (-innerW/2) + (p.offset * innerW); xPos = (-innerW/2) + (p.offset * innerW);
// Z центр: середина отрезка
const midZ = (pMin + pMax) / 2; const midZ = (pMin + pMax) / 2;
zPos = (-innerD/2) + (midZ * innerD); zPos = (-innerD/2) + (midZ * innerD);
} else { // Horiz (X-axis) } else { // Horiz (Вдоль X)
isVert = false; isVert = false;
len = (pMax - pMin) * innerW; len = (pMax - pMin) * innerW;
// X центр: середина отрезка
const midX = (pMin + pMax) / 2; const midX = (pMin + pMax) / 2;
xPos = (-innerW/2) + (midX * innerW); xPos = (-innerW/2) + (midX * innerW);
// Z позиция: от заднего края innerD
zPos = (-innerD/2) + (p.offset * innerD); zPos = (-innerD/2) + (p.offset * innerD);
} }
// Создаем стенку
addWall(len, p.height, xPos, zPos, isVert); addWall(len, p.height, xPos, zPos, isVert);
// --- СКРУГЛЕНИЯ (СТОЛБИКИ) --- // --- СКРУГЛЕНИЯ (СТОЛБИКИ) ---
// Добавляем цилиндры в торцы перегородок, если включено
if (p.rounded && radius > 0) { if (p.rounded && radius > 0) {
const r = Math.min(radius, 5); const r = Math.min(radius, 5);
const cylGeo = new THREE.CylinderGeometry(r, r, p.height, 12); const cylGeo = new THREE.CylinderGeometry(r, r, p.height, 16);
// Поднимаем пивот в центр (так как addWall центрирует) // Центрируем по высоте, чтобы translate работал так же как для стен
// Или просто позиционируем как есть // (по умолчанию cylinder pivot в центре, так что всё ок)
const addFillet = (fx: number, fz: number) => { const addCyl = (cx: number, cz: number) => {
const c = cylGeo.clone(); const c = cylGeo.clone();
c.translate(fx, thickness + p.height/2, fz); c.translate(cx, thickness + p.height/2, cz);
geometries.push(c); geometries.push(c);
}; };
if (isVert) { if (isVert) {
const zStart = zPos - len/2; const zStart = zPos - len/2;
const zEnd = zPos + len/2; const zEnd = zPos + len/2;
addFillet(xPos, zStart); addCyl(xPos, zStart);
addFillet(xPos, zEnd); addCyl(xPos, zEnd);
} else { } else {
const xStart = xPos - len/2; const xStart = xPos - len/2;
const xEnd = xPos + len/2; const xEnd = xPos + len/2;
addFillet(xStart, zPos); addCyl(xStart, zPos);
addFillet(xEnd, zPos); addCyl(xEnd, zPos);
} }
} }
}); });
// 4. СЛИЯНИЕ // 4. СЛИЯНИЕ
const merged = mergeBufferGeometries(geometries); const merged = mergeBufferGeometries(geometries);
if (merged) merged.computeVertexNormals(); if (merged) merged.computeVertexNormals(); // Исправляет тени и "прозрачность"
return merged || new THREE.BoxGeometry(1, 1, 1); return merged || new THREE.BoxGeometry(1, 1, 1);
}; };
// --- ЭКСПОРТ ---
export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => { export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {
const exporter = new STLExporter(); const exporter = new STLExporter();
const result = exporter.parse(mesh, { binary: true }); const result = exporter.parse(mesh, { binary: true });