This commit is contained in:
Халимов Рустам
2026-01-12 00:59:56 +03:00
parent d3170e79ab
commit 2fee39afce

View File

@@ -4,15 +4,26 @@ import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types';
// --- ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ ---
// Очистка дубликатов и сортировка точек (убирает фантомные ячейки)
const cleanPoints = (points: number[]) => {
const sorted = [...points].sort((a, b) => a - b);
const unique = [sorted[0]];
for (let i = 1; i < sorted.length; i++) {
if (sorted[i] - unique[unique.length - 1] > 0.005) { // Игнорируем точки ближе 0.5%
unique.push(sorted[i]);
}
}
return unique;
};
export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => {
const parts: GeneratedPart[] = [];
const safeX = Array.isArray(splits?.x) ? splits.x : [];
const safeY = Array.isArray(splits?.y) ? splits.y : [];
const safeParts = splits?.partitions || {};
// Очистка и сортировка точек реза с удалением дубликатов (защита от лишних ячеек)
const uniqueX = Array.from(new Set([0, ...safeX, 1])).sort((a, b) => a - b);
const uniqueY = Array.from(new Set([0, ...safeY, 1])).sort((a, b) => a - b);
// Используем защищенные массивы
const rawX = Array.isArray(splits?.x) ? splits.x : [];
const rawY = Array.isArray(splits?.y) ? splits.y : [];
const uniqueX = cleanPoints([0, ...rawX, 1]);
const uniqueY = cleanPoints([0, ...rawY, 1]);
let partCounter = 1;
@@ -23,39 +34,25 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
const y1 = uniqueY[j];
const y2 = uniqueY[j+1];
// Пропускаем микро-сдвиги (меньше 1мм)
if (Math.abs(x2 - x1) < 0.001 || Math.abs(y2 - y1) < 0.001) continue;
const w = (x2 - x1) * config.drawer.width;
const d = (y2 - y1) * config.drawer.depth;
const rawW = (x2 - x1) * config.drawer.width;
const rawD = (y2 - y1) * config.drawer.depth;
const rawX = x1 * config.drawer.width;
const rawY = y1 * config.drawer.depth;
// Ключ для поиска перегородок берем из оригинальных индексов (тут упрощение, предполагаем соответствие)
// Для точности лучше искать по координатам, но пока оставим ключ
const internalPartitions = safeParts[`${i}-${j}`] || [];
// Пропускаем слишком маленькие или некорректные объемы
if (w < 2 || d < 2) continue;
// Отступ для визуализации "кубиков" (gap), чтобы они не слипались в превью
const gap = config.wallThickness / 2;
const realWidth = rawW - config.printerTolerance;
const realDepth = rawD - config.printerTolerance;
const realX = rawX + (config.printerTolerance / 2);
const realY = rawY + (config.printerTolerance / 2);
if (realWidth < 2 || realDepth < 2) continue;
// Визуальный отступ, чтобы кубики не слипались со стенками
const gap = config.wallThickness / 2 + 0.5;
parts.push({
id: `part-${partCounter}`,
name: `Ячейка ${partCounter}`,
width: realWidth,
depth: realDepth,
width: Math.max(1, w - gap * 2),
depth: Math.max(1, d - gap * 2),
height: config.drawer.height,
x: realX,
y: realY,
color: `hsl(${(partCounter * 137.5) % 360}, 70%, 50%)`, // Золотое сечение для цветов
internalPartitions: internalPartitions
x: (x1 * config.drawer.width) + gap,
y: (y1 * config.drawer.depth) + gap,
color: `hsl(${(partCounter * 137.5) % 360}, 70%, 50%)`,
internalPartitions: [] // Внутренние перегородки обрабатываются отдельно в createBinGeometry
});
partCounter++;
}
@@ -63,28 +60,30 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
return parts;
};
// --- ГЕОМЕТРИЯ ---
// --- ГЕОМЕТРИЯ СТЕН И ОТВЕРСТИЙ ---
// Прямоугольник с отверстиями (для стен)
const createPerforatedShape = (width: number, height: number, config: AppConfig): THREE.Shape => {
const createPerforatedWallShape = (length: number, height: number, config: AppConfig): THREE.Shape => {
const shape = new THREE.Shape();
// Внешний контур (Counter-Clockwise)
// 1. Внешний контур: Против часовой стрелки (CCW)
// (0,0) -> (len,0) -> (len,h) -> (0,h) -> (0,0)
shape.moveTo(0, 0);
shape.lineTo(width, 0);
shape.lineTo(width, height);
shape.lineTo(length, 0);
shape.lineTo(length, height);
shape.lineTo(0, height);
shape.lineTo(0, 0);
if (!config.perforation?.enabled || width < 15 || height < 15) return shape;
// Если перфорация выключена или стена слишком мала, возвращаем целую
if (!config.perforation?.enabled || length < 15 || height < 15) return shape;
const { pattern, diameter, spacing } = config.perforation;
const step = diameter + Math.max(2, spacing);
const margin = 4; // Отступ от краев стенки
const margin = 4; // Отступ от края стенки
const effW = width - margin * 2;
const effW = length - margin * 2;
const effH = height - margin * 2;
if (effW <= 0 || effH <= 0) return shape;
if (effW <= diameter || effH <= diameter) return shape;
const rowH = pattern === 'circle' ? step : step * 0.866;
const cols = Math.floor(effW / step);
@@ -93,61 +92,67 @@ const createPerforatedShape = (width: number, height: number, config: AppConfig)
const startX = margin + (effW - (cols - 1) * step) / 2;
const startY = margin + (effH - (rows - 1) * rowH) / 2;
const holes: THREE.Path[] = [];
for (let j = 0; j < rows; j++) {
const isOdd = j % 2 !== 0;
const y = startY + j * rowH;
const cy = startY + j * rowH;
for (let i = 0; i < cols; i++) {
let x = startX + i * step;
if ((pattern === 'hexagon' || pattern === 'triangle') && isOdd) x += step / 2;
let cx = startX + i * step;
if ((pattern === 'hexagon' || pattern === 'triangle') && isOdd) cx += step / 2;
// Проверка границ
if (x - diameter/2 < margin || x + diameter/2 > width - margin ||
y - diameter/2 < margin || y + diameter/2 > height - margin) continue;
// Проверка выхода за границы
if (cx - diameter/2 < margin || cx + diameter/2 > length - margin ||
cy - diameter/2 < margin || cy + diameter/2 > height - margin) continue;
const hole = new THREE.Path();
const r = diameter / 2;
// ВАЖНО: Отверстия должны рисоваться по ЧАСОВОЙ стрелке (Clockwise),
// иначе Three.js не вырежет их, а зальет.
// 2. Отверстия: Строго по часовой стрелке (CW)
// Это критически важно для корректного отображения и экспорта!
if (pattern === 'circle') {
// aClockwise = false
hole.absarc(x, y, r, 0, Math.PI * 2, false);
} else if (pattern === 'hexagon') {
// aClockwise = true (CW)
hole.absarc(cx, cy, r, 0, Math.PI * 2, true);
}
else if (pattern === 'hexagon') {
// Рисуем 6 точек по часовой стрелке
for (let k = 0; k < 6; k++) {
const angle = (k * 60 + 30) * Math.PI / 180;
const px = x + r * Math.cos(angle);
const py = y + r * Math.sin(angle);
// -k (отрицательный шаг) обеспечивает CW порядок
const angle = (-k * 60 + 90) * Math.PI / 180;
const px = cx + r * Math.cos(angle);
const py = cy + r * Math.sin(angle);
if (k === 0) hole.moveTo(px, py); else hole.lineTo(px, py);
}
// Для многоугольников порядок зависит от порядка точек.
// Создаем их в нужном порядке или используем reverse() если не вырезается.
// Текущий порядок CCW, нужно CW? Проверим на практике. Обычно Path AutoClose работает.
// Если возникнут проблемы, поменяем порядок k (5..0).
} else if (pattern === 'triangle') {
hole.closePath();
}
else if (pattern === 'triangle') {
const rot = isOdd ? 180 : 0;
// Рисуем 3 точки по часовой стрелке
for (let k = 0; k < 3; k++) {
const angle = (k * 120 - 90 + rot) * Math.PI / 180;
const px = x + r * Math.cos(angle);
const py = y + r * Math.sin(angle);
const angle = (-k * 120 + 90 + rot) * Math.PI / 180;
const px = cx + r * Math.cos(angle);
const py = cy + r * Math.sin(angle);
if (k === 0) hole.moveTo(px, py); else hole.lineTo(px, py);
}
hole.closePath();
}
hole.closePath();
shape.holes.push(hole);
holes.push(hole);
}
}
shape.holes = holes;
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);
// CCW Order
if (r <= 0.1) {
shape.moveTo(x, y);
shape.lineTo(x + width, y);
@@ -168,16 +173,18 @@ const createFloorShape = (width: number, depth: number, radius: number): THREE.S
return shape;
};
const createConcaveFilletShape = (radius: number): THREE.Shape => {
// Галтель (вогнутая)
const createFilletShape = (radius: number): THREE.Shape => {
const shape = new THREE.Shape();
shape.moveTo(0, 0);
shape.lineTo(radius, 0);
// Дуга CW для выреза, но так как это тело вращения/экструзии, тут важна форма профиля
shape.absarc(radius, radius, radius, -Math.PI / 2, -Math.PI, true);
shape.lineTo(0, 0);
return shape;
};
// --- СБОРКА БИНА ---
// --- СБОРКА МОДЕЛИ ---
export const createBinGeometry = (
width: number, depth: number, height: number, thickness: number, radius: number = 0, partitions: Partition[] = [], config?: AppConfig
@@ -188,124 +195,92 @@ export const createBinGeometry = (
// 1. ПОЛ
const floorShape = createFloorShape(width, depth, radius);
const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false });
floorGeo.rotateX(-Math.PI / 2); // XZ plane
floorGeo.rotateX(-Math.PI / 2); // Лежит в плоскости XZ
geometries.push(floorGeo);
// 2. СТЕНКИ (Внешние)
const wallH = height - thickness;
// Размеры внутреннего пространства
const innerW = width - 2 * thickness;
const innerD = depth - 2 * thickness;
const wallH = height - thickness;
// Формы стен с перфорацией (2D профиль)
const shapeFrontBack = createPerforatedShape(innerW, wallH, safeConfig);
const shapeLeftRight = createPerforatedShape(depth, wallH, safeConfig); // Полная глубина для боковин
// Helper для установки стены
const addWall = (shape: THREE.Shape, x: number, z: number, rotationY: number, offsetZ: number = 0) => {
const geo = new THREE.ExtrudeGeometry(shape, { depth: thickness, bevelEnabled: false });
// По умолчанию Shape 0..W, 0..H. Extrude 0..Thick (Z).
// Центрируем по высоте (ставим на пол)
if (rotationY !== 0) geo.rotateY(rotationY);
// Позиционирование
geo.translate(x, thickness, z);
geometries.push(geo);
};
// Front (Спереди, вдоль X)
const geoF = new THREE.ExtrudeGeometry(shapeFrontBack, { depth: thickness, bevelEnabled: false });
// Центрируем по X (-innerW/2)
geoF.translate(-innerW/2, thickness, depth/2 - thickness);
// 2. ВНЕШНИЕ СТЕНКИ
// Мы создаем их вертикально. Базовая форма рисуется в XY (Width x Height), потом вращается.
// -- Передняя и Задняя (Вдоль X) --
const shapeFB = createPerforatedWallShape(innerW, wallH, safeConfig);
// Front
const geoF = new THREE.ExtrudeGeometry(shapeFB, { depth: thickness, bevelEnabled: false });
geoF.translate(-innerW/2, thickness, depth/2 - thickness); // Центр X, на полу, край Z
geometries.push(geoF);
// Back (Сзади, вдоль X)
const geoB = new THREE.ExtrudeGeometry(shapeFrontBack, { depth: thickness, bevelEnabled: false });
// Сдвигаем depth mesh'а назад
geoB.translate(0, 0, -thickness);
geoB.translate(-innerW/2, thickness, -depth/2 + thickness);
// Back
const geoB = new THREE.ExtrudeGeometry(shapeFB, { depth: thickness, bevelEnabled: false });
geoB.translate(-innerW/2, thickness, -depth/2); // Центр X, на полу, задний край Z
geometries.push(geoB);
// Left (Слева, вдоль Z)
const geoL = new THREE.ExtrudeGeometry(shapeLeftRight, { depth: thickness, bevelEnabled: false });
geoL.rotateY(Math.PI / 2); // Поворот +90. X->Z. (Len, 0, 0) -> (0, 0, -Len) ? Нет, (0,0,-Len)
// Коррекция позиции
// -- Левая и Правая (Вдоль Z) --
// Они идут по всей глубине (depth), перекрывая торцы передней/задней
const shapeLR = createPerforatedWallShape(depth, wallH, safeConfig);
// Left
const geoL = new THREE.ExtrudeGeometry(shapeLR, { depth: thickness, bevelEnabled: false });
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 (Справа, вдоль Z)
const geoR = new THREE.ExtrudeGeometry(shapeLeftRight, { depth: thickness, bevelEnabled: false });
// Right
const geoR = new THREE.ExtrudeGeometry(shapeLR, { depth: thickness, bevelEnabled: false });
geoR.rotateY(Math.PI / 2);
geoR.translate(width/2 - thickness, thickness, -depth/2);
geometries.push(geoR);
// 3. ВНУТРЕННИЕ ПЕРЕГОРОДКИ
// Используем жесткие координаты min/max, без попыток угадать (Solver удален для соответствия 2D)
partitions.forEach(p => {
const pMin = p.min ?? 0;
const pMax = p.max ?? 1;
// Игнорируем некорректные
if (pMax - pMin < 0.01) return;
const lengthRatio = pMax - pMin;
let partLen = 0;
let length = 0;
let posX = 0;
let posZ = 0;
let isVertical = false; // Vertical on 2D screen = Along Z axis in 3D
let isVert = false;
if (p.axis === 'x') {
// Вертикальная на экране -> Вдоль Z
isVertical = true;
partLen = lengthRatio * innerD;
// Вертикальная на 2D-схеме (идет вдоль Z в 3D)
isVert = true;
length = (pMax - pMin) * innerD;
// Центр по X
posX = (-innerW/2) + (p.offset * innerW);
// Начало по Z
posZ = (-innerD/2) + (pMin * innerD);
} else {
// Горизонтальная на экране -> Вдоль X
isVertical = false;
partLen = lengthRatio * innerW;
// Горизонтальная на 2D-схеме (идет вдоль X в 3D)
isVert = false;
length = (pMax - pMin) * innerW;
// Начало по X
posX = (-innerW/2) + (pMin * innerW);
// Центр по Z
posZ = (-innerD/2) + (p.offset * innerD);
}
// Создаем профиль с дырками
const partShape = createPerforatedShape(partLen, wallH, safeConfig);
// Генерируем форму с дырками
const partShape = createPerforatedWallShape(length, wallH, safeConfig);
const partGeo = new THREE.ExtrudeGeometry(partShape, { depth: thickness, bevelEnabled: false });
if (isVertical) {
// Поворот чтобы шла вдоль Z
if (isVert) {
// Поворачиваем вдоль Z
partGeo.rotateY(Math.PI / 2);
// При повороте +90 вокруг (0,0,0), положительный X уходит в отрицательный Z (или положительный, зависит от системы)
// ThreeJS: Right handed. Y up.
// Shape 0..Len по X. Rotate Y 90 -> 0..-Len по Z.
// Нам нужно поставить начало (0,0) в (posX, floor, posZ).
// Но из-за поворота "длина" ушла в -Z. Значит posZ - это "верхняя" точка?
// Нет, в 2D Y идет вниз. min - это верх. max - это низ.
// В 3D Z идет "на нас" (обычно). minZ - зад, maxZ - перед.
// Если min=0 (верх в 2D) -> -depth/2 (зад в 3D).
// Стенка идет от зада к переду. Значит Z растет.
// Нам нужен поворот -90 (-PI/2), чтобы X перешел в +Z.
partGeo.rotateY(-Math.PI / 2);
// Центрируем толщину по X
partGeo.translate(posX + thickness/2, thickness, posZ);
// Сдвиг на thickness/2 может зависеть от того, как экструдилось (0..thick или -thick/2..thick/2)
// Extrude создает 0..depth. После поворота это становится X? Нет.
// Extrude по Z локальному. Rotate Y крутит оси X и Z.
// Изначально: Shape в XY. Extrude в Z.
// Rotate Y -90:
// X -> Z. Y -> Y. Z -> -X.
// Толщина ушла в -X. Длина ушла в +Z.
// Позиция: StartX, StartY, StartZ.
// Смещаем. Учитываем толщину, чтобы центрировать по линии реза.
partGeo.translate(posX - thickness/2, thickness, posZ);
} else {
// Вдоль X. Поворот не нужен.
// Толщина уходит в +Z.
// Нам нужно центрировать толщину вокруг posZ.
// Смещаем.
partGeo.translate(posX, thickness, posZ - thickness/2);
}
@@ -313,42 +288,50 @@ export const createBinGeometry = (
// --- ГАЛТЕЛИ (FILLETS) ---
if (p.rounded && radius > 1) {
const filletR = Math.min(radius, 5);
const filletShape = createConcaveFilletShape(filletR);
const h = p.height; // Упрощаем высоту до полной, чтобы избежать глюков
const fR = Math.min(radius, 5);
const fShape = createFilletShape(fR);
const h = p.height;
const addFillet = (x: number, z: number, rot: number) => {
const geo = new THREE.ExtrudeGeometry(filletShape, { depth: h, bevelEnabled: false });
geo.rotateX(-Math.PI / 2);
geo.rotateY(rot);
geo.translate(x, thickness, z);
const addFillet = (fx: number, fz: number, rot: number) => {
const geo = new THREE.ExtrudeGeometry(fShape, { depth: h, bevelEnabled: false });
geo.rotateX(-Math.PI / 2); // Кладем плашмя
geo.rotateY(rot); // Крутим
geo.translate(fx, thickness, fz);
geometries.push(geo);
};
const t = thickness / 2;
if (isVertical) {
const startZ = posZ;
const endZ = posZ + partLen;
// Стыки
addFillet(posX - t, startZ, Math.PI);
addFillet(posX + t, startZ, -Math.PI/2);
addFillet(posX - t, endZ, Math.PI/2);
addFillet(posX + t, endZ, 0);
if (isVert) {
const zStart = posZ;
const zEnd = posZ + length;
// Top junction
addFillet(posX - t, zStart, Math.PI);
addFillet(posX + t, zStart, -Math.PI/2);
// Bottom junction
addFillet(posX - t, zEnd, Math.PI/2);
addFillet(posX + t, zEnd, 0);
} else {
const startX = posX;
const endX = posX + partLen;
addFillet(startX, posZ - t, 0);
addFillet(startX, posZ + t, -Math.PI/2);
addFillet(endX, posZ - t, Math.PI/2);
addFillet(endX, posZ + t, Math.PI);
const xStart = posX;
const xEnd = posX + length;
// Left junction
addFillet(xStart, posZ - t, 0);
addFillet(xStart, posZ + t, -Math.PI/2);
// Right junction
addFillet(xEnd, posZ - t, Math.PI/2);
addFillet(xEnd, posZ + t, Math.PI);
}
}
});
const merged = mergeBufferGeometries(geometries);
if (merged) merged.computeVertexNormals();
return merged || new THREE.BoxGeometry(1, 1, 1);
// Пересчет нормалей критичен для правильного освещения (убирает "прозрачность")
if (merged) {
merged.computeVertexNormals();
return merged;
}
return new THREE.BoxGeometry(1, 1, 1);
};
export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {