Try fix used three-bvh-csg
This commit is contained in:
Generated
+2675
File diff suppressed because it is too large
Load Diff
@@ -1,30 +1,26 @@
|
|||||||
import * as THREE from 'three';
|
import * as THREE from 'three';
|
||||||
import { STLExporter } from 'three-stdlib';
|
import { STLExporter } from 'three-stdlib';
|
||||||
import { SUBTRACTION, UNION, Brush, Evaluator } from 'three-bvh-csg';
|
import { SUBTRACTION, ADDITION, Brush, Evaluator } from 'three-bvh-csg'; // ИСПРАВЛЕНО: ADDITION вместо UNION
|
||||||
import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types';
|
import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types';
|
||||||
|
|
||||||
// --- ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ ---
|
// --- ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ ---
|
||||||
|
|
||||||
// Функция для очистки дубликатов точек (убирает фантомные микро-ячейки)
|
|
||||||
const cleanPoints = (points: number[]) => {
|
const cleanPoints = (points: number[]) => {
|
||||||
// Округляем до 3 знака и сортируем
|
|
||||||
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();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Функция для визуализации "кубиков" ячеек (цветной предпросмотр)
|
||||||
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 : [];
|
||||||
const safeY = Array.isArray(splits?.y) ? splits.y : [];
|
const safeY = Array.isArray(splits?.y) ? splits.y : [];
|
||||||
|
|
||||||
// Очищаем координаты резов от мусора
|
|
||||||
const uniqueX = cleanPoints([0, ...safeX, 1]);
|
const uniqueX = cleanPoints([0, ...safeX, 1]);
|
||||||
const uniqueY = cleanPoints([0, ...safeY, 1]);
|
const uniqueY = cleanPoints([0, ...safeY, 1]);
|
||||||
|
|
||||||
@@ -37,16 +33,13 @@ 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];
|
||||||
|
|
||||||
|
if (x2 - x1 < 0.001 || y2 - y1 < 0.001) continue;
|
||||||
|
|
||||||
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;
|
|
||||||
|
|
||||||
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.1;
|
||||||
|
|
||||||
parts.push({
|
parts.push({
|
||||||
@@ -66,7 +59,7 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
|
|||||||
return parts;
|
return parts;
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- CSG ГЕОМЕТРИЯ ---
|
// --- ГЕНЕРАЦИЯ ГЕОМЕТРИИ ЧЕРЕЗ CSG (ВЫЧИТАНИЕ) ---
|
||||||
|
|
||||||
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,
|
||||||
@@ -77,39 +70,33 @@ export const createBinGeometry = (
|
|||||||
const safeConfig = config || { perforation: { enabled: false } } as AppConfig;
|
const safeConfig = config || { perforation: { enabled: false } } as AppConfig;
|
||||||
const evaluator = new Evaluator();
|
const evaluator = new Evaluator();
|
||||||
|
|
||||||
// 1. БАЗОВАЯ ГЕОМЕТРИЯ (ПОЛ)
|
// 1. БАЗА (ПОЛ)
|
||||||
// Brush - это специальный объект для CSG операций
|
|
||||||
const floorGeo = new THREE.BoxGeometry(width, thickness, depth);
|
const floorGeo = new THREE.BoxGeometry(width, thickness, depth);
|
||||||
floorGeo.translate(0, thickness / 2, 0); // Поднимаем на уровень пола
|
floorGeo.translate(0, thickness / 2, 0);
|
||||||
let resultBrush = new Brush(floorGeo);
|
let resultBrush = new Brush(floorGeo);
|
||||||
|
|
||||||
// Материал для CSG (нужен для вычислений, но не влияет на экспорт)
|
|
||||||
resultBrush.updateMatrixWorld();
|
resultBrush.updateMatrixWorld();
|
||||||
|
|
||||||
// 2. СТЕНКИ (ВНЕШНИЕ)
|
// 2. СТЕНКИ
|
||||||
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;
|
||||||
|
|
||||||
// Функция создания блока стены
|
// Функция добавления блока стены (ADDITION)
|
||||||
const addWallBlock = (w: number, h: number, d: number, x: number, y: number, z: number) => {
|
const addWallBlock = (w: number, h: number, d: number, x: number, y: number, z: number) => {
|
||||||
const geo = new THREE.BoxGeometry(w, h, d);
|
const geo = new THREE.BoxGeometry(w, h, d);
|
||||||
geo.translate(x, y, z);
|
geo.translate(x, y, z);
|
||||||
const wallBrush = new Brush(geo);
|
const wallBrush = new Brush(geo);
|
||||||
wallBrush.updateMatrixWorld();
|
wallBrush.updateMatrixWorld();
|
||||||
// Объединяем (UNION) стену с полом
|
resultBrush = evaluator.evaluate(resultBrush, wallBrush, ADDITION); // ИСПРАВЛЕНО ЗДЕСЬ
|
||||||
resultBrush = evaluator.evaluate(resultBrush, wallBrush, UNION);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Передняя и Задняя (Вдоль X)
|
// Внешние стенки
|
||||||
addWallBlock(innerW, wallH, thickness, 0, thickness + wallH/2, depth/2 - thickness/2); // Front
|
addWallBlock(innerW, wallH, thickness, 0, thickness + wallH/2, depth/2 - thickness/2); // Front
|
||||||
addWallBlock(innerW, wallH, thickness, 0, thickness + wallH/2, -depth/2 + thickness/2); // Back
|
addWallBlock(innerW, wallH, thickness, 0, thickness + wallH/2, -depth/2 + thickness/2); // Back
|
||||||
|
|
||||||
// Левая и Правая (Вдоль Z) - Полная глубина, перекрывают углы
|
|
||||||
addWallBlock(thickness, wallH, depth, -width/2 + thickness/2, thickness + wallH/2, 0); // Left
|
addWallBlock(thickness, wallH, depth, -width/2 + thickness/2, thickness + wallH/2, 0); // Left
|
||||||
addWallBlock(thickness, wallH, depth, width/2 - thickness/2, thickness + wallH/2, 0); // Right
|
addWallBlock(thickness, wallH, depth, width/2 - thickness/2, thickness + wallH/2, 0); // Right
|
||||||
|
|
||||||
// 3. ВНУТРЕННИЕ ПЕРЕГОРОДКИ
|
// Внутренние перегородки
|
||||||
let partitions: Partition[] = [];
|
let partitions: Partition[] = [];
|
||||||
if (Array.isArray(splits)) {
|
if (Array.isArray(splits)) {
|
||||||
partitions = splits;
|
partitions = splits;
|
||||||
@@ -120,44 +107,37 @@ 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 (pMax - pMin < 0.001) return;
|
if (pMax - pMin < 0.001) return;
|
||||||
|
|
||||||
let w=0, h=p.height, d=0, x=0, z=0;
|
let w=0, h=p.height, d=0, x=0, z=0;
|
||||||
|
|
||||||
if (p.axis === 'x') {
|
if (p.axis === 'x') { // Вертикальная (вдоль Z)
|
||||||
// Вертикальная на 2D (Вдоль Z в 3D)
|
|
||||||
w = thickness;
|
w = thickness;
|
||||||
d = (pMax - pMin) * innerD;
|
d = (pMax - pMin) * innerD;
|
||||||
x = (-innerW/2) + (p.offset * innerW);
|
x = (-innerW/2) + (p.offset * innerW);
|
||||||
z = (-innerD/2) + (pMin * innerD) + (d / 2);
|
z = (-innerD/2) + (pMin * innerD) + (d / 2);
|
||||||
} else {
|
} else { // Горизонтальная (вдоль X)
|
||||||
// Горизонтальная на 2D (Вдоль X в 3D)
|
|
||||||
w = (pMax - pMin) * innerW;
|
w = (pMax - pMin) * innerW;
|
||||||
d = thickness;
|
d = thickness;
|
||||||
x = (-innerW/2) + (pMin * innerW) + (w / 2);
|
x = (-innerW/2) + (pMin * innerW) + (w / 2);
|
||||||
z = (-innerD/2) + (p.offset * innerD);
|
z = (-innerD/2) + (p.offset * innerD);
|
||||||
}
|
}
|
||||||
|
|
||||||
addWallBlock(w, h, d, x, thickness + h/2, z);
|
addWallBlock(w, h, d, x, thickness + h/2, z);
|
||||||
});
|
});
|
||||||
|
|
||||||
// 4. ПЕРФОРАЦИЯ (ВЫЧИТАНИЕ)
|
// 3. ПЕРФОРАЦИЯ (ВЫЧИТАНИЕ)
|
||||||
// Чтобы не тормозить, мы создаем ОДИН сложный объект из всех "сверл" и вычитаем его один раз
|
|
||||||
if (safeConfig.perforation?.enabled) {
|
if (safeConfig.perforation?.enabled) {
|
||||||
const { pattern, diameter, spacing } = safeConfig.perforation;
|
const { pattern, diameter, spacing } = safeConfig.perforation;
|
||||||
|
// Цилиндр для вырезания (длинный, чтобы прошел насквозь)
|
||||||
const holeGeo = new THREE.CylinderGeometry(diameter/2, diameter/2, thickness * 4, 16);
|
const holeGeo = new THREE.CylinderGeometry(diameter/2, diameter/2, thickness * 4, 16);
|
||||||
|
holeGeo.rotateZ(Math.PI / 2); // По умолчанию вдоль X (для боковых стен)
|
||||||
// Поворачиваем цилиндр, чтобы он "сверлил" вдоль оси X (для боковых стенок)
|
|
||||||
holeGeo.rotateZ(Math.PI / 2);
|
|
||||||
|
|
||||||
const step = diameter + Math.max(2, spacing);
|
const step = diameter + Math.max(2, spacing);
|
||||||
const margin = 4;
|
const margin = 4;
|
||||||
|
|
||||||
// Массив геометрий для слияния (это быстрее, чем 1000 раз вызывать CSG)
|
// Собираем все "сверла" в одну геометрию для скорости
|
||||||
const cutters: THREE.BufferGeometry[] = [];
|
const cutters: THREE.BufferGeometry[] = [];
|
||||||
|
|
||||||
// Функция генерации "сверл" для плоскости
|
|
||||||
const generateCutters = (W: number, H: number, startX: number, startY: number, startZ: number, rotateY: boolean) => {
|
const generateCutters = (W: number, H: number, startX: number, startY: number, startZ: number, rotateY: boolean) => {
|
||||||
const cols = Math.floor((W - margin*2) / step);
|
const cols = Math.floor((W - margin*2) / step);
|
||||||
const rowH = pattern === 'circle' ? step : step * 0.866;
|
const rowH = pattern === 'circle' ? step : step * 0.866;
|
||||||
@@ -179,17 +159,11 @@ export const createBinGeometry = (
|
|||||||
const cutter = holeGeo.clone();
|
const cutter = holeGeo.clone();
|
||||||
|
|
||||||
if (rotateY) {
|
if (rotateY) {
|
||||||
// Для стенок, идущих вдоль X (Передняя/Задняя)
|
// Для передней/задней стенки (сверлим вдоль Z)
|
||||||
// Изначально цилиндр вдоль X. Поворачиваем на 90 -> Вдоль Z.
|
|
||||||
cutter.rotateY(Math.PI / 2);
|
cutter.rotateY(Math.PI / 2);
|
||||||
// Позиционируем
|
|
||||||
// В локальной системе стенки: X=Длина, Y=Высота.
|
|
||||||
// Глобально: X=startX+hx, Y=startY+hy, Z=startZ
|
|
||||||
cutter.translate(startX + hx, startY + hy, startZ);
|
cutter.translate(startX + hx, startY + hy, startZ);
|
||||||
} else {
|
} else {
|
||||||
// Для стенок, идущих вдоль Z (Левая/Правая)
|
// Для боковых стенок (сверлим вдоль X)
|
||||||
// Цилиндр вдоль X (по умолчанию).
|
|
||||||
// Глобально: X=startX, Y=startY+hy, Z=startZ+hx
|
|
||||||
cutter.translate(startX, startY + hy, startZ + hx);
|
cutter.translate(startX, startY + hy, startZ + hx);
|
||||||
}
|
}
|
||||||
cutters.push(cutter);
|
cutters.push(cutter);
|
||||||
@@ -197,40 +171,31 @@ export const createBinGeometry = (
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Генерируем сверла для всех 4 сторон
|
// Генерируем отверстия для внешних стен
|
||||||
// Front/Back (Сверлим вдоль Z)
|
generateCutters(innerW, wallH, -innerW/2, thickness, depth/2, true); // Front
|
||||||
generateCutters(innerW, wallH, -innerW/2, thickness, depth/2, true); // Front plane
|
generateCutters(innerW, wallH, -innerW/2, thickness, -depth/2, true); // Back
|
||||||
generateCutters(innerW, wallH, -innerW/2, thickness, -depth/2, true); // Back plane
|
generateCutters(depth, wallH, -width/2, thickness, -depth/2, false); // Left
|
||||||
|
generateCutters(depth, wallH, width/2, thickness, -depth/2, false); // Right
|
||||||
// Left/Right (Сверлим вдоль X)
|
|
||||||
// Для боковых стенок (Left/Right) W = depth.
|
|
||||||
generateCutters(depth, wallH, -width/2, thickness, -depth/2, false); // Left plane
|
|
||||||
generateCutters(depth, wallH, width/2, thickness, -depth/2, false); // Right plane
|
|
||||||
|
|
||||||
// Если есть внутренние стенки, их тоже надо бы сверлить, но это сложнее рассчитать.
|
|
||||||
// Пока сверлим только внешний периметр, как в Gridfinity.
|
|
||||||
// (Можно добавить логику для внутренних, перебирая partitions, если нужно)
|
|
||||||
|
|
||||||
|
// Применяем вычитание (SUBTRACTION)
|
||||||
if (cutters.length > 0) {
|
if (cutters.length > 0) {
|
||||||
// Объединяем все сверла в один Mesh
|
// Используем функцию слияния из three-stdlib (так как в core three её может не быть в старых версиях)
|
||||||
// Используем mergeBufferGeometries из three-stdlib, так как в чистом three его вынесли
|
// Если mergeBufferGeometries не импортирован, убедитесь что он есть в импортах
|
||||||
const mergedCutters = mergeBufferGeometries(cutters);
|
const mergedCutters = mergeBufferGeometries(cutters);
|
||||||
if (mergedCutters) {
|
if (mergedCutters) {
|
||||||
const cutterBrush = new Brush(mergedCutters);
|
const cutterBrush = new Brush(mergedCutters);
|
||||||
cutterBrush.updateMatrixWorld();
|
cutterBrush.updateMatrixWorld();
|
||||||
// ВЫЧИТАНИЕ (SUBTRACTION)
|
|
||||||
resultBrush = evaluator.evaluate(resultBrush, cutterBrush, SUBTRACTION);
|
resultBrush = evaluator.evaluate(resultBrush, cutterBrush, SUBTRACTION);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Возвращаем чистую геометрию
|
// Возвращаем результат
|
||||||
return resultBrush.geometry;
|
return resultBrush.geometry;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {
|
export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {
|
||||||
const exporter = new STLExporter();
|
const exporter = new STLExporter();
|
||||||
// Для CSG геометрии иногда нужно убедиться, что она корректно интерпретируется
|
|
||||||
const result = exporter.parse(mesh, { binary: true });
|
const result = exporter.parse(mesh, { binary: true });
|
||||||
if (result instanceof DataView) return new Uint8Array(result.buffer, result.byteOffset, result.byteLength);
|
if (result instanceof DataView) return new Uint8Array(result.buffer, result.byteOffset, result.byteLength);
|
||||||
return result as string;
|
return result as string;
|
||||||
|
|||||||
Reference in New Issue
Block a user