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