This commit is contained in:
Халимов Рустам
2026-01-12 01:07:55 +03:00
parent 2fee39afce
commit 3d79abf4d4
+133 -129
View File
@@ -2,28 +2,37 @@ 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';
// --- ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ --- // --- CLEANUP UTILS ---
// Очистка дубликатов и сортировка точек (убирает фантомные ячейки) // Удаляет дублирующиеся перегородки (фантомы)
const cleanPoints = (points: number[]) => { const deduplicatePartitions = (partitions: Partition[]): Partition[] => {
const sorted = [...points].sort((a, b) => a - b); const unique: Partition[] = [];
const unique = [sorted[0]]; const seen = new Set<string>();
for (let i = 1; i < sorted.length; i++) {
if (sorted[i] - unique[unique.length - 1] > 0.005) { // Игнорируем точки ближе 0.5% partitions.forEach(p => {
unique.push(sorted[i]); // Округляем координаты для создания уникального ключа
const k = `${p.axis}-${p.offset.toFixed(3)}-${p.min?.toFixed(3)}-${p.max?.toFixed(3)}`;
if (!seen.has(k)) {
seen.add(k);
unique.push(p);
} }
} });
return unique; return unique;
}; };
// Очистка точек для генерации цветных объемов
const cleanPoints = (points: number[]) => {
return Array.from(new Set(points.map(p => parseFloat(p.toFixed(3))))).sort((a, b) => a - b);
};
// --- CALCULATE VOLUMES (ЦВЕТНЫЕ КУБИКИ) ---
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 rawX = Array.isArray(splits?.x) ? splits.x : []; const safeY = Array.isArray(splits?.y) ? splits.y : [];
const rawY = Array.isArray(splits?.y) ? splits.y : [];
const uniqueX = cleanPoints([0, ...rawX, 1]); const uniqueX = cleanPoints([0, ...safeX, 1]);
const uniqueY = cleanPoints([0, ...rawY, 1]); const uniqueY = cleanPoints([0, ...safeY, 1]);
let partCounter = 1; let partCounter = 1;
@@ -37,22 +46,21 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
const w = (x2 - x1) * config.drawer.width; const w = (x2 - x1) * config.drawer.width;
const d = (y2 - y1) * config.drawer.depth; const d = (y2 - y1) * config.drawer.depth;
// Пропускаем слишком маленькие или некорректные объемы
if (w < 2 || d < 2) continue; if (w < 2 || d < 2) continue;
// Визуальный отступ, чтобы кубики не слипались со стенками // Отступ для визуализации (gap)
const gap = config.wallThickness / 2 + 0.5; const gap = config.wallThickness / 2 + 0.2;
parts.push({ parts.push({
id: `part-${partCounter}`, id: `part-${partCounter}`,
name: `Ячейка ${partCounter}`, name: `Ячейка ${partCounter}`,
width: Math.max(1, w - gap * 2), width: Math.max(1, w - gap * 2),
depth: Math.max(1, d - gap * 2), depth: Math.max(1, d - gap * 2),
height: config.drawer.height, height: config.drawer.height - config.wallThickness,
x: (x1 * config.drawer.width) + gap, x: (x1 * config.drawer.width) + gap,
y: (y1 * config.drawer.depth) + gap, y: (y1 * config.drawer.depth) + gap,
color: `hsl(${(partCounter * 137.5) % 360}, 70%, 50%)`, color: `hsl(${(partCounter * 137.5) % 360}, 70%, 50%)`,
internalPartitions: [] // Внутренние перегородки обрабатываются отдельно в createBinGeometry internalPartitions: []
}); });
partCounter++; partCounter++;
} }
@@ -60,25 +68,24 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
return parts; return parts;
}; };
// --- ГЕОМЕТРИЯ СТЕН И ОТВЕРСТИЙ --- // --- SHAPE GENERATION (PERFORATION) ---
const createPerforatedWallShape = (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) -> (len,0) -> (len,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 < 15 || height < 15) return shape; if (!config.perforation?.enabled || length < 10 || height < 10) 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;
@@ -92,8 +99,6 @@ const createPerforatedWallShape = (length: number, height: number, config: AppCo
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;
const holes: THREE.Path[] = [];
for (let j = 0; j < rows; j++) { for (let j = 0; j < rows; j++) {
const isOdd = j % 2 !== 0; const isOdd = j % 2 !== 0;
const cy = startY + j * rowH; const cy = startY + j * rowH;
@@ -102,24 +107,20 @@ const createPerforatedWallShape = (length: number, height: number, config: AppCo
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 (По часовой) - Это критично для Three.js!
// Это критически важно для корректного отображения и экспорта!
if (pattern === 'circle') { if (pattern === 'circle') {
// aClockwise = true (CW)
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') {
// Рисуем 6 точек по часовой стрелке
for (let k = 0; k < 6; k++) { for (let k = 0; k < 6; k++) {
// -k (отрицательный шаг) обеспечивает CW порядок // -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);
@@ -129,7 +130,6 @@ const createPerforatedWallShape = (length: number, height: number, config: AppCo
} }
else if (pattern === 'triangle') { else if (pattern === 'triangle') {
const rot = isOdd ? 180 : 0; const rot = isOdd ? 180 : 0;
// Рисуем 3 точки по часовой стрелке
for (let k = 0; k < 3; k++) { for (let k = 0; k < 3; k++) {
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);
@@ -138,21 +138,19 @@ const createPerforatedWallShape = (length: number, height: number, config: AppCo
} }
hole.closePath(); hole.closePath();
} }
holes.push(hole); shape.holes.push(hole);
} }
} }
shape.holes = holes;
return shape; return shape;
}; };
// Пол (всегда сплошной) // Floor Shape (Solid)
const createFloorShape = (width: number, depth: number, radius: number): THREE.Shape => { const createFloorShape = (width: number, depth: number, radius: number): THREE.Shape => {
const shape = new THREE.Shape(); const shape = new THREE.Shape();
const x = -width / 2; const x = -width / 2;
const y = -depth / 2; const y = -depth / 2;
const r = Math.min(radius, width / 2 - 0.1, depth / 2 - 0.1); const r = Math.min(radius, width / 2 - 0.1, depth / 2 - 0.1);
// CCW Order
if (r <= 0.1) { if (r <= 0.1) {
shape.moveTo(x, y); shape.moveTo(x, y);
shape.lineTo(x + width, y); shape.lineTo(x + width, y);
@@ -173,18 +171,16 @@ const createFloorShape = (width: number, depth: number, radius: number): THREE.S
return shape; return shape;
}; };
// Галтель (вогнутая)
const createFilletShape = (radius: number): THREE.Shape => { const createFilletShape = (radius: number): THREE.Shape => {
const shape = new THREE.Shape(); const shape = new THREE.Shape();
shape.moveTo(0, 0); shape.moveTo(0, 0);
shape.lineTo(radius, 0); shape.lineTo(radius, 0);
// Дуга CW для выреза, но так как это тело вращения/экструзии, тут важна форма профиля
shape.absarc(radius, radius, radius, -Math.PI / 2, -Math.PI, true); shape.absarc(radius, radius, radius, -Math.PI / 2, -Math.PI, true);
shape.lineTo(0, 0); shape.lineTo(0, 0);
return shape; return shape;
}; };
// --- СБОРКА МОДЕЛИ --- // --- BUILDER ---
export const createBinGeometry = ( export const createBinGeometry = (
width: number, depth: number, height: number, thickness: number, radius: number = 0, partitions: Partition[] = [], config?: AppConfig width: number, depth: number, height: number, thickness: number, radius: number = 0, partitions: Partition[] = [], config?: AppConfig
@@ -192,10 +188,10 @@ export const createBinGeometry = (
const geometries: THREE.BufferGeometry[] = []; const geometries: THREE.BufferGeometry[] = [];
const safeConfig = config || { perforation: { enabled: false } } as AppConfig; const safeConfig = config || { perforation: { enabled: false } } as AppConfig;
// 1. ПОЛ // 1. FLOOR
const floorShape = createFloorShape(width, depth, radius); const floorShape = createFloorShape(width, depth, radius);
const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false }); const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false });
floorGeo.rotateX(-Math.PI / 2); // Лежит в плоскости XZ floorGeo.rotateX(-Math.PI / 2);
geometries.push(floorGeo); geometries.push(floorGeo);
// Размеры внутреннего пространства // Размеры внутреннего пространства
@@ -203,129 +199,137 @@ export const createBinGeometry = (
const innerD = depth - 2 * thickness; const innerD = depth - 2 * thickness;
const wallH = height - thickness; const wallH = height - thickness;
// 2. ВНЕШНИЕ СТЕНКИ // Helper для установки стенки
// Мы создаем их вертикально. Базовая форма рисуется в XY (Width x Height), потом вращается. const placeWall = (length: number, isVertical: boolean, centerX: number, centerZ: number) => {
// Генерируем 2D форму с дырками
const shape = createPerforatedShape(length, wallH, safeConfig);
const geo = new THREE.ExtrudeGeometry(shape, { depth: thickness, bevelEnabled: false });
// -- Передняя и Задняя (Вдоль X) -- if (isVertical) {
const shapeFB = createPerforatedWallShape(innerW, wallH, safeConfig); // Вертикальная (идет вдоль Z)
// Shape рисуется в XY. Extrude в Z.
// Поворачиваем вокруг Y на 90.
// X -> Z, Y -> Y, Z -> X.
// Теперь длина (бывший X) идет вдоль Z. Толщина (бывший Z) идет вдоль X.
geo.rotateY(Math.PI / 2);
// Front // Центр по X: centerX. Начало по Z: centerZ - length/2.
const geoF = new THREE.ExtrudeGeometry(shapeFB, { depth: thickness, bevelEnabled: false }); // После поворота: начало в (0,0,0) перешло в (0,0,0).
geoF.translate(-innerW/2, thickness, depth/2 - thickness); // Центр X, на полу, край Z // Длина ушла в -Z (или +Z в зависимости от правил).
geometries.push(geoF); // Проще: ставим центр геометрии в центр позиции.
geo.center(); // Центрируем геометрию локально
geo.translate(centerX, thickness + wallH/2, centerZ); // Ставим на место
} else {
// Горизонтальная (идет вдоль X)
// Shape в XY. Extrude в Z.
// Длина вдоль X. Толщина вдоль Z.
geo.center();
geo.translate(centerX, thickness + wallH/2, centerZ);
}
geometries.push(geo);
};
// Back // 2. EXTERNAL WALLS
const geoB = new THREE.ExtrudeGeometry(shapeFB, { depth: thickness, bevelEnabled: false }); // Front (вдоль X)
geoB.translate(-innerW/2, thickness, -depth/2); // Центр X, на полу, задний край Z placeWall(innerW, false, -width/2 + innerW/2 + thickness, depth/2 - thickness/2); // Исправленные координаты
geometries.push(geoB); // Проще: Front стоит на Z = depth/2 - thick/2. X центр = 0 (если floor от -W/2 до W/2).
// Floor shape: -W/2..W/2.
// -- Левая и Правая (Вдоль Z) -- // Давайте пересчитаем позиции точно относительно центра (0,0)
// Они идут по всей глубине (depth), перекрывая торцы передней/задней // Front: CenterX=0, CenterZ = (depth - thickness)/2
const shapeLR = createPerforatedWallShape(depth, wallH, safeConfig); placeWall(innerW, false, 0, (depth - thickness)/2);
// Left // Back: CenterX=0, CenterZ = -(depth - thickness)/2
const geoL = new THREE.ExtrudeGeometry(shapeLR, { depth: thickness, bevelEnabled: false }); placeWall(innerW, false, 0, -(depth - thickness)/2);
geoL.rotateY(Math.PI / 2); // Поворот +90 (теперь идет вдоль Z)
// При повороте +90 вокруг (0,0,0): X+ -> Z-. Начало (0,0) остается (0,0).
// Нам нужно сместить начало в (X=-width/2, Z=-depth/2)
geoL.translate(-width/2, thickness, -depth/2);
geometries.push(geoL);
// Right // Left: CenterX=-(width - thickness)/2, CenterZ=0. Length = depth.
const geoR = new THREE.ExtrudeGeometry(shapeLR, { depth: thickness, bevelEnabled: false }); placeWall(depth, true, -(width - thickness)/2, 0);
geoR.rotateY(Math.PI / 2);
geoR.translate(width/2 - thickness, thickness, -depth/2); // Right: CenterX=(width - thickness)/2, CenterZ=0. Length = depth.
geometries.push(geoR); placeWall(depth, true, (width - thickness)/2, 0);
// 3. ВНУТРЕННИЕ ПЕРЕГОРОДКИ // 3. INTERNAL PARTITIONS
partitions.forEach(p => { // Используем дедупликацию, чтобы убрать двойные стенки
const uniquePartitions = deduplicatePartitions(partitions);
uniquePartitions.forEach(p => {
const pMin = p.min ?? 0; const pMin = p.min ?? 0;
const pMax = p.max ?? 1; const pMax = p.max ?? 1;
// Игнорируем некорректные
if (pMax - pMin < 0.01) return; if (pMax - pMin < 0.01) return;
let length = 0; let length = 0;
let posX = 0; let cX = 0;
let posZ = 0; let cZ = 0;
let isVert = false; let isVertical = false;
if (p.axis === 'x') { if (p.axis === 'x') {
// Вертикальная на 2D-схеме (идет вдоль Z в 3D) // Вертикальная на экране 2D (вдоль Z в 3D)
isVert = true; isVertical = true;
length = (pMax - pMin) * innerD; length = (pMax - pMin) * innerD;
// Центр по X
posX = (-innerW/2) + (p.offset * innerW); // X: offset * innerW. Но innerW начинается от -innerW/2.
// Начало по Z cX = (-innerW/2) + (p.offset * innerW);
posZ = (-innerD/2) + (pMin * innerD);
// Z центр: Середина между pMin и pMax
const midRatio = (pMin + pMax) / 2;
cZ = (-innerD/2) + (midRatio * innerD);
} else { } else {
// Горизонтальная на 2D-схеме (идет вдоль X в 3D) // Горизонтальная на экране 2D (вдоль X в 3D)
isVert = false; isVertical = false;
length = (pMax - pMin) * innerW; length = (pMax - pMin) * innerW;
// Начало по X
posX = (-innerW/2) + (pMin * innerW); // X центр
// Центр по Z const midRatio = (pMin + pMax) / 2;
posZ = (-innerD/2) + (p.offset * innerD); cX = (-innerW/2) + (midRatio * innerW);
// Z: offset * innerD
cZ = (-innerD/2) + (p.offset * innerD);
} }
// Генерируем форму с дырками placeWall(length, isVertical, cX, cZ);
const partShape = createPerforatedWallShape(length, wallH, safeConfig);
const partGeo = new THREE.ExtrudeGeometry(partShape, { depth: thickness, bevelEnabled: false });
if (isVert) { // --- FILLETS ---
// Поворачиваем вдоль Z
partGeo.rotateY(Math.PI / 2);
// Смещаем. Учитываем толщину, чтобы центрировать по линии реза.
partGeo.translate(posX - thickness/2, thickness, posZ);
} else {
// Вдоль X. Поворот не нужен.
// Смещаем.
partGeo.translate(posX, thickness, posZ - thickness/2);
}
geometries.push(partGeo);
// --- ГАЛТЕЛИ (FILLETS) ---
if (p.rounded && radius > 1) { if (p.rounded && radius > 1) {
const fR = Math.min(radius, 5); const fR = Math.min(radius, 5);
const fShape = createFilletShape(fR); const fShape = createFilletShape(fR);
const h = p.height; const h = p.height;
const addFillet = (fx: number, fz: number, rot: number) => { const addFillet = (x: number, z: number, rot: number) => {
const geo = new THREE.ExtrudeGeometry(fShape, { depth: h, bevelEnabled: false }); const geo = new THREE.ExtrudeGeometry(fShape, { depth: h, bevelEnabled: false });
geo.rotateX(-Math.PI / 2); // Кладем плашмя geo.rotateX(-Math.PI / 2);
geo.rotateY(rot); // Крутим geo.rotateY(rot);
geo.translate(fx, thickness, fz); geo.translate(x, thickness, z);
geometries.push(geo); geometries.push(geo);
}; };
const t = thickness / 2; const t = thickness / 2;
if (isVert) { // Вычисляем концы стенки для скруглений
const zStart = posZ; if (isVertical) {
const zEnd = posZ + length; const zStart = cZ - length/2;
// Top junction const zEnd = cZ + length/2;
addFillet(posX - t, zStart, Math.PI);
addFillet(posX + t, zStart, -Math.PI/2); // Верхний стык (дальний по Z, если смотреть в 2D) -> Min
// Bottom junction addFillet(cX - t, zStart, Math.PI);
addFillet(posX - t, zEnd, Math.PI/2); addFillet(cX + t, zStart, -Math.PI/2);
addFillet(posX + t, zEnd, 0); // Нижний стык -> Max
addFillet(cX - t, zEnd, Math.PI/2);
addFillet(cX + t, zEnd, 0);
} else { } else {
const xStart = posX; const xStart = cX - length/2;
const xEnd = posX + length; const xEnd = cX + length/2;
// Left junction
addFillet(xStart, posZ - t, 0); addFillet(xStart, cZ - t, 0);
addFillet(xStart, posZ + t, -Math.PI/2); addFillet(xStart, cZ + t, -Math.PI/2);
// Right junction addFillet(xEnd, cZ - t, Math.PI/2);
addFillet(xEnd, posZ - t, Math.PI/2); addFillet(xEnd, cZ + t, Math.PI);
addFillet(xEnd, posZ + t, Math.PI);
} }
} }
}); });
const merged = mergeBufferGeometries(geometries); const merged = mergeBufferGeometries(geometries);
// Пересчет нормалей критичен для правильного освещения (убирает "прозрачность")
if (merged) { if (merged) {
merged.computeVertexNormals(); merged.computeVertexNormals();
return merged; return merged;