Add perforation

This commit is contained in:
Халимов Рустам
2026-01-12 17:32:41 +03:00
parent 356873fb0e
commit 531b5dc0b1
5 changed files with 995 additions and 564 deletions
+9 -3
View File
@@ -8,13 +8,13 @@ import { parseShareUrl } from './utils/share';
import { ChevronRight, ChevronLeft, Box, AlertTriangle } from 'lucide-react';
// ВАЖНО: ErrorBoundary должен быть ЗДЕСЬ, снаружи компонента App
class ErrorBoundary extends React.Component<{children: React.ReactNode}, {hasError: boolean}> {
class ErrorBoundary extends React.Component<{ children: React.ReactNode }, { hasError: boolean }> {
state = { hasError: false };
static getDerivedStateFromError() { return { hasError: true }; }
render() {
if (this.state.hasError) return (
<div className="h-full flex flex-col items-center justify-center text-red-400">
<AlertTriangle size={32} className="mb-2"/>
<AlertTriangle size={32} className="mb-2" />
<p>Ошибка отрисовки интерфейса.</p>
<button onClick={() => window.location.reload()} className="mt-4 px-4 py-2 bg-slate-800 rounded hover:bg-slate-700 transition-colors">
Перезагрузить
@@ -33,6 +33,12 @@ const App = () => {
wallThickness: 1.2,
printerTolerance: 0.5,
cornerRadius: 4,
perforation: {
enabled: false,
shape: 'honeycomb',
size: 8,
gap: 2
}
});
const [splits, setSplits] = useState<LayoutSplits>({
@@ -118,7 +124,7 @@ const App = () => {
{step < 3 ? (
<button onClick={() => setStep(s => Math.min(3, s + 1))} className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold bg-primary text-white hover:bg-blue-600 shadow-lg shadow-blue-900/20 transition-all active:scale-95">Далее <ChevronRight size={18} /></button>
) : (
<button onClick={() => { setStep(1); setSplits({x: [], y: [], partitions: {}}); window.history.replaceState({}, '', window.location.pathname); }} className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold text-gray-400 hover:text-white transition-colors border border-transparent hover:border-slate-700">Новый проект</button>
<button onClick={() => { setStep(1); setSplits({ x: [], y: [], partitions: {} }); window.history.replaceState({}, '', window.location.pathname); }} className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold text-gray-400 hover:text-white transition-colors border border-transparent hover:border-slate-700">Новый проект</button>
)}
</div>
</footer>
+176 -9
View File
@@ -1,6 +1,6 @@
import React from 'react';
import { AppConfig } from '../types';
import { Ruler, Box, Layers, Minimize2, CircleDashed } from 'lucide-react';
import { AppConfig, PerforationShape } from '../types';
import { Ruler, Box, Layers, Minimize2, CircleDashed, Grid, Circle, Hexagon, Triangle } from 'lucide-react';
interface Props {
config: AppConfig;
@@ -39,13 +39,92 @@ const NumberInput = ({
</div>
);
const PerforationPreview = ({ config }: { config: AppConfig['perforation'] }) => {
if (!config.enabled) return (
<div className="w-full h-48 bg-slate-950 rounded-lg border border-slate-800 flex items-center justify-center text-gray-600">
<span className="text-sm">Перфорация отключена</span>
</div>
);
// Simple canvas-like SVG generation
const width = 200;
const height = 120;
const size = config.size * 2; // Scale up mostly for visibility
const gap = config.gap * 2;
const step = size + gap;
const elements = [];
if (config.shape === 'circle') {
for (let y = 0; y < height; y += step) {
for (let x = 0; x < width; x += step) {
elements.push(<circle key={`${x}-${y}`} cx={x + step / 2} cy={y + step / 2} r={size / 2} fill="#3b82f6" />);
}
}
} else if (config.shape === 'honeycomb') {
const hStep = size * 0.866; // height of equilateral triangle
for (let y = 0; y < height; y += (size + gap) * 0.85) {
const row = Math.floor(y / ((size + gap) * 0.85));
const xOffset = row % 2 === 0 ? 0 : (size + gap) / 2;
for (let x = xOffset - step; x < width; x += step) {
// Hexagon points
const r = size / 2;
const cx = x + step / 2;
const cy = y + step / 2;
// Points for flat-topped hexagon
const points = [];
for (let i = 0; i < 6; i++) {
const angle_deg = 60 * i + 30;
const angle_rad = Math.PI / 180 * angle_deg;
points.push(`${cx + r * Math.cos(angle_rad)},${cy + r * Math.sin(angle_rad)}`);
}
elements.push(<polygon key={`${x}-${y}`} points={points.join(" ")} fill="#3b82f6" />);
}
}
} else if (config.shape === 'triangle') {
for (let y = 0; y < height; y += step * 0.866) { // Staggered rows
const row = Math.floor(y / (step * 0.866));
const xOffset = row % 2 === 0 ? 0 : step / 2;
for (let x = -step + xOffset; x < width; x += step) {
const cx = x + step / 2;
const cy = y + step / 2;
const r = size / 2;
// Upright triangle
const points = [
`${cx},${cy - r}`,
`${cx + r * 0.866},${cy + r * 0.5}`,
`${cx - r * 0.866},${cy + r * 0.5}`
];
elements.push(<polygon key={`${x}-${y}`} points={points.join(" ")} fill="#3b82f6" />);
}
}
}
return (
<div className="w-full h-48 bg-slate-950 rounded-lg border border-slate-800 overflow-hidden relative">
<svg width="100%" height="100%" viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="xMidYMid slice">
{elements}
</svg>
<div className="absolute top-2 right-2 text-xs text-gray-500">:: Масштаб условен</div>
</div>
);
}
export const ConfigStep: React.FC<Props> = ({ config, onChange }) => {
const updateDrawer = (key: keyof AppConfig['drawer'], val: number) => {
onChange({ ...config, drawer: { ...config.drawer, [key]: val } });
};
const updatePerforation = (key: keyof AppConfig['perforation'], val: any) => {
onChange({ ...config, perforation: { ...config.perforation, [key]: val } })
}
return (
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 animate-fade-in">
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 animate-fade-in space-y-8">
{/* SECTION 1: Dimensions & Settings */}
<div>
<h2 className="text-xl font-bold mb-6 flex items-center gap-2 text-primary">
<Box size={24} /> 1. Размеры
</h2>
@@ -89,18 +168,18 @@ export const ConfigStep: React.FC<Props> = ({ config, onChange }) => {
max="3.2"
step="0.1"
value={config.wallThickness}
onChange={(e) => onChange({...config, wallThickness: parseFloat(e.target.value)})}
onChange={(e) => onChange({ ...config, wallThickness: parseFloat(e.target.value) })}
className="w-full h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-primary hover:accent-blue-400 transition-all"
/>
<span className="text-xs text-gray-500 font-mono">3.2</span>
</div>
</div>
{/* Corner Radius (NEW) */}
{/* Corner Radius */}
<div className="mb-6">
<div className="flex justify-between items-center mb-2">
<label className="text-sm font-medium text-gray-300 flex items-center gap-1">
<CircleDashed size={14} className="text-gray-400"/> Радиус скругления
<CircleDashed size={14} className="text-gray-400" /> Радиус скругления
</label>
<span className="text-purple-400 font-bold bg-purple-400/10 px-2 py-1 rounded text-sm border border-purple-400/20">
{config.cornerRadius?.toFixed(0) || 0} мм
@@ -114,7 +193,7 @@ export const ConfigStep: React.FC<Props> = ({ config, onChange }) => {
max="20"
step="1"
value={config.cornerRadius || 0}
onChange={(e) => onChange({...config, cornerRadius: parseFloat(e.target.value)})}
onChange={(e) => onChange({ ...config, cornerRadius: parseFloat(e.target.value) })}
className="w-full h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-purple-500 hover:accent-purple-400 transition-all"
/>
<span className="text-xs text-gray-500 font-mono">20</span>
@@ -125,7 +204,7 @@ export const ConfigStep: React.FC<Props> = ({ config, onChange }) => {
<div className="mb-4">
<div className="flex justify-between items-center mb-2">
<label className="text-sm font-medium text-gray-300 flex items-center gap-1">
<Minimize2 size={14} className="text-gray-400"/> Зазор (Tolerance)
<Minimize2 size={14} className="text-gray-400" /> Зазор (Tolerance)
</label>
<span className="text-accent font-bold bg-accent/10 px-2 py-1 rounded text-sm border border-accent/20">
{config.printerTolerance.toFixed(1)} мм
@@ -139,7 +218,7 @@ export const ConfigStep: React.FC<Props> = ({ config, onChange }) => {
max="2.0"
step="0.1"
value={config.printerTolerance}
onChange={(e) => onChange({...config, printerTolerance: parseFloat(e.target.value)})}
onChange={(e) => onChange({ ...config, printerTolerance: parseFloat(e.target.value) })}
className="w-full h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-accent hover:accent-amber-400 transition-all"
/>
<span className="text-xs text-gray-500 font-mono">2.0</span>
@@ -149,5 +228,93 @@ export const ConfigStep: React.FC<Props> = ({ config, onChange }) => {
</div>
</div>
</div>
{/* SECTION 2: Perforation */}
<div className="bg-slate-800/30 p-6 rounded-lg border border-slate-700/50">
<div className="flex items-center justify-between mb-6">
<h3 className="text-lg font-semibold flex items-center gap-2 text-blue-400">
<Grid size={20} /> 2. Перфорация (узоры)
</h3>
<div className="flex items-center gap-3">
<span className="text-sm font-medium text-gray-400 uppercase tracking-wider">Включено</span>
<button
onClick={() => updatePerforation('enabled', !config.perforation.enabled)}
className={`w-12 h-6 rounded-full relative transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 ${config.perforation.enabled ? 'bg-blue-600' : 'bg-slate-600'}`}
>
<span className={`block w-4 h-4 rounded-full bg-white shadow transform transition-transform duration-200 ease-in-out absolute top-1 ${config.perforation.enabled ? 'translate-x-7' : 'translate-x-1'}`} />
</button>
</div>
</div>
<div className={`grid grid-cols-1 md:grid-cols-2 gap-8 transition-all duration-300 ${config.perforation.enabled ? 'opacity-100 pointer-events-auto' : 'opacity-40 pointer-events-none filter blur-[1px]'}`}>
<div>
<label className="text-xs font-bold text-gray-500 uppercase mb-3 block">Тип узора</label>
<div className="flex gap-4 mb-8">
{[
{ id: 'circle', icon: Circle, label: 'Круг' },
{ id: 'honeycomb', icon: Hexagon, label: 'Соты' },
{ id: 'triangle', icon: Triangle, label: 'Треуг.' }
].map((item) => (
<button
key={item.id}
onClick={() => updatePerforation('shape', item.id as PerforationShape)}
className={`flex-1 flex flex-col items-center justify-center gap-2 py-4 px-2 rounded-lg border transition-all ${config.perforation.shape === item.id
? 'bg-slate-700/80 border-blue-500 text-blue-400 shadow-lg shadow-blue-500/10'
: 'bg-slate-800 border-slate-700 text-gray-400 hover:bg-slate-750 hover:border-slate-600'
}`}
>
<item.icon size={24} />
<span className="text-sm font-medium">{item.label}</span>
</button>
))}
</div>
{/* Resize Controls */}
<div className="space-y-6">
<div>
<div className="flex justify-between items-center mb-2">
<label className="text-sm font-medium text-gray-300">Диаметр отверстий</label>
<span className="text-sm font-bold text-blue-400">{config.perforation.size} мм</span>
</div>
<div className="flex items-center gap-4">
<span className="text-xs text-gray-500">2 мм</span>
<input
type="range" min="2" max="25" step="1"
value={config.perforation.size}
onChange={(e) => updatePerforation('size', parseFloat(e.target.value))}
className="flex-1 h-1.5 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-blue-500"
/>
<span className="text-xs text-gray-500">25 мм</span>
</div>
</div>
<div>
<div className="flex justify-between items-center mb-2">
<label className="text-sm font-medium text-gray-300">Зазор (между отверстиями)</label>
<span className="text-sm font-bold text-blue-400">{config.perforation.gap} мм</span>
</div>
<div className="flex items-center gap-4">
<span className="text-xs text-gray-500">1 мм</span>
<input
type="range" min="1" max="10" step="0.5"
value={config.perforation.gap}
onChange={(e) => updatePerforation('gap', parseFloat(e.target.value))}
className="flex-1 h-1.5 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-blue-500"
/>
<span className="text-xs text-gray-500">10 мм</span>
</div>
</div>
</div>
</div>
{/* Preview */}
<div>
<label className="text-xs font-bold text-gray-500 uppercase mb-3 block">Предпросмотр</label>
<PerforationPreview config={config.perforation} />
</div>
</div>
</div>
</div>
);
};
+12 -7
View File
@@ -3,7 +3,7 @@ import { Canvas } from '@react-three/fiber';
import { OrbitControls, Center, Environment } from '@react-three/drei';
import * as THREE from 'three';
import JSZip from 'jszip';
import { AppConfig, GeneratedPart, LayoutSplits } from '../types';
import { AppConfig, GeneratedPart, LayoutSplits, PerforationConfig } from '../types';
import { createBinGeometry, generateSTL, exportSTL } from '../services/geometryGenerator';
import { Download, Package, Info, Loader2, Share2, Check, Ruler } from 'lucide-react';
import { generateShareUrl } from '../utils/share';
@@ -27,11 +27,12 @@ interface BinMeshProps {
part: GeneratedPart;
thickness: number;
cornerRadius: number;
perforation: PerforationConfig;
isSelected: boolean;
onClick: () => void;
}
const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSelected, onClick }) => {
const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, perforation, isSelected, onClick }) => {
// 1. Создаем геометрию, учитывая ВНУТРЕННИЕ ПЕРЕГОРОДКИ
const geometry = useMemo(() => {
return createBinGeometry(
@@ -40,9 +41,10 @@ const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSele
part.height,
thickness,
cornerRadius,
part.internalPartitions // <--- ВАЖНО: передаем перегородки в генератор
part.internalPartitions, // <--- ВАЖНО: передаем перегородки в генератор
perforation
);
}, [part, thickness, cornerRadius]);
}, [part, thickness, cornerRadius, perforation]);
// 2. Создаем контур выделения (EdgesGeometry)
// Threshold 20 градусов скрывает линии на плавных скруглениях
@@ -51,7 +53,7 @@ const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSele
}, [geometry]);
return (
<group position={[part.x + part.width/2, 0, part.y + part.depth/2]}>
<group position={[part.x + part.width / 2, 0, part.y + part.depth / 2]}>
{/* Сама модель */}
<mesh geometry={geometry} onClick={(e) => { e.stopPropagation(); onClick(); }}>
<meshStandardMaterial
@@ -100,7 +102,8 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
part.height,
config.wallThickness,
config.cornerRadius,
part.internalPartitions // <--- ВАЖНО для STL
part.internalPartitions, // <--- ВАЖНО для STL
config.perforation
);
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
exportSTL(mesh, `${part.name.replace(/\s+/g, '_')}.stl`);
@@ -119,7 +122,8 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
part.height,
config.wallThickness,
config.cornerRadius,
part.internalPartitions // <--- ВАЖНО для STL
part.internalPartitions, // <--- ВАЖНО для STL
config.perforation
);
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
const stlData = generateSTL(mesh);
@@ -251,6 +255,7 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
part={part}
thickness={config.wallThickness}
cornerRadius={config.cornerRadius || 0}
perforation={config.perforation}
isSelected={selectedId === part.id}
onClick={() => setSelectedId(part.id)}
/>
+259 -16
View File
@@ -1,6 +1,6 @@
import * as THREE from 'three';
import { STLExporter, mergeBufferGeometries } from 'three-stdlib';
import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types';
import { AppConfig, LayoutSplits, GeneratedPart, Partition, PerforationConfig } from '../types';
export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => {
const parts: GeneratedPart[] = [];
@@ -31,7 +31,7 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
parts.push({
id: `part-${partCounter}`,
name: `Ячейка ${i+1}-${j+1}`,
name: `Ячейка ${i + 1}-${j + 1}`,
width: realWidth,
depth: realDepth,
height: config.drawer.height,
@@ -83,17 +83,115 @@ const createConcaveFilletShape = (radius: number): THREE.Shape => {
return shape;
};
// New Helper: Create Perforated Plate (Vertical Wall)
const createPerforatedPlate = (width: number, height: number, thickness: number, perf: PerforationConfig): THREE.BufferGeometry => {
const shape = new THREE.Shape();
shape.moveTo(0, 0);
shape.lineTo(width, 0);
shape.lineTo(width, height);
shape.lineTo(0, height);
shape.lineTo(0, 0);
// Hole Generation
if (perf && perf.enabled && width > perf.size && height > perf.size) {
const { shape: shapeType, size, gap } = perf;
const step = size + gap;
const startX = gap; // Margin
const startY = gap; // Margin
const endX = width - gap; // Margin
const endY = height - gap;
// Rows
let row = 0;
for (let y = startY + size / 2; y < endY; y += (shapeType === 'triangle' || shapeType === 'honeycomb' ? step * 0.866 : step)) {
const isStaggered = (row % 2 !== 0);
const xOffset = (isStaggered && (shapeType === 'honeycomb' || shapeType === 'triangle')) ? step / 2 : 0;
for (let x = startX + size / 2 + xOffset; x < endX; x += step) {
const hole = new THREE.Path();
const r = size / 2;
// Boundary check (approximate center check)
if (x - r < 0 || x + r > width || y - r < 0 || y + r > height) continue;
if (shapeType === 'circle') {
hole.absarc(x, y, r, 0, Math.PI * 2, true);
} else if (shapeType === 'honeycomb') {
// Hexagon
for (let i = 0; i < 6; i++) {
const ang = (i * 60 + 30) * Math.PI / 180;
const px = x + r * Math.cos(ang);
const py = y + r * Math.sin(ang);
if (i === 0) hole.moveTo(px, py);
else hole.lineTo(px, py);
}
hole.closePath();
} else if (shapeType === 'triangle') {
// Triangle
const ang1 = -90 * Math.PI / 180;
const ang2 = 30 * Math.PI / 180;
const ang3 = 150 * Math.PI / 180;
hole.moveTo(x + r * Math.cos(ang1), y + r * Math.sin(ang1));
hole.lineTo(x + r * Math.cos(ang2), y + r * Math.sin(ang2));
hole.lineTo(x + r * Math.cos(ang3), y + r * Math.sin(ang3));
hole.closePath();
}
shape.holes.push(hole);
}
row++;
}
}
const geo = new THREE.ExtrudeGeometry(shape, { depth: thickness, bevelEnabled: false });
// Extruded along Z. Wall is flat on XY.
// We want "thickness" to be Z depth.
return geo;
};
// New Helper: Create Corner Profile (Extruded Vertical)
const createCornerProfile = (radius: number, thickness: number, height: number): THREE.BufferGeometry => {
if (radius <= 0) return new THREE.BufferGeometry();
const shape = new THREE.Shape();
// External Arc (from X-axis to Y-axis)
shape.absarc(0, 0, radius, 0, Math.PI / 2, false);
// Line to inner
shape.lineTo(0, radius - thickness); // Assuming innerRadius = radius - thickness
// Inner Arc (backwards)
const innerRadius = Math.max(0.1, radius - thickness);
shape.absarc(0, 0, innerRadius, Math.PI / 2, 0, true);
// Close
shape.lineTo(radius, 0);
// Extrude vertically (Height is Z for now, usually Extrude goes Z)
const geo = new THREE.ExtrudeGeometry(shape, { depth: height, bevelEnabled: false, curveSegments: 16 });
// Rotate so height is along Y? No, Extrude defaults to Z depth.
// We want the Profile on XZ plane extruded up Y?
// Shape is on XY. Extrude is Z.
// If shape is on XY (top view of corner), Extrude Z creates Height.
// This matches standard logic if we rotate whole object later.
return geo;
};
export const createBinGeometry = (
width: number, depth: number, height: number, thickness: number, radius: number = 0, partitions: Partition[] = []
width: number,
depth: number,
height: number,
thickness: number,
radius: number = 0,
partitions: Partition[] = [],
perforation?: PerforationConfig
): THREE.BufferGeometry => {
const geometries: THREE.BufferGeometry[] = [];
// ДНО И ВНЕШНИЕ СТЕНКИ
// ДНО (Floor) - Always same
const floorShape = createRoundedRectShape(width, depth, radius);
const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false });
floorGeo.rotateX(-Math.PI / 2);
floorGeo.rotateX(-Math.PI / 2); // Lay flat
geometries.push(floorGeo);
// WALLS
if (!perforation || !perforation.enabled) {
// --- ORIGINAL LOGIC (Optimized for Solid Walls) ---
const outerShape = createRoundedRectShape(width, depth, radius);
const innerRadius = Math.max(0.1, radius - thickness);
const innerWidth = width - (2 * thickness);
@@ -109,10 +207,109 @@ export const createBinGeometry = (
wallGeo.rotateX(-Math.PI / 2);
wallGeo.translate(0, thickness, 0);
geometries.push(wallGeo);
} else {
// --- PERFORATED LOGIC (Split Walls) ---
const wallHeight = height - thickness;
// Clamp radius to at least thickness for valid corners in this mode
const effRadius = Math.max(radius, thickness);
const straightW = width - 2 * effRadius;
const straightD = depth - 2 * effRadius;
// 1. Corners (4 pcs)
if (effRadius > 0) {
const cornerGeoBase = createCornerProfile(effRadius, thickness, wallHeight);
// 1. Stand Up: Extrusion Z -> Y. Shape moves to X(+)/Z(+).
cornerGeoBase.rotateX(-Math.PI / 2);
const positions = [
{ x: width / 2 - effRadius, z: depth / 2 - effRadius, rot: -Math.PI / 2 }, // Front Right (X+, Z+) -> Needs (X+, Z+). Base is (X+, Z-). Rot -90 -> (Z+, X+)
{ x: -(width / 2 - effRadius), z: depth / 2 - effRadius, rot: Math.PI }, // Front Left (X-, Z+) -> Needs (X-, Z+). Rot 180 -> (X-, Z+)
{ x: -(width / 2 - effRadius), z: -(depth / 2 - effRadius), rot: Math.PI / 2 }, // Back Left (X-, Z-) -> Needs (X-, Z-). Rot 90 -> (Z-, X-) which is X-, Z-? No wait.
// Rot 90 on (X+, Z-): X->Z, Z->-X. (X+, Z-) -> (-Z, -X) = (X-, Z-). Correct.
{ x: width / 2 - effRadius, z: -(depth / 2 - effRadius), rot: 0 } // Back Right (X+, Z-) -> Matches Base.
];
positions.forEach(pos => {
const c = cornerGeoBase.clone();
c.rotateY(pos.rot);
c.translate(pos.x, thickness, pos.z);
geometries.push(c);
});
}
// 2. Straight Walls (4 pcs) - Centered on edges
// Front/Back
if (straightW > 0.1) {
const wGeo = createPerforatedPlate(straightW, wallHeight, thickness, perforation);
// Plate: 0..W in X, 0..H in Y, 0..Th in Z.
// Center Horizontally:
wGeo.translate(-straightW / 2, 0, 0);
// Wall 1 (Back / Top? +Z):
// Needs to be at Z = Depth/2.
// Plate thickness is along Z (positive).
// If we put it at Z = D/2 - thickness, it occupies [D/2 - th, D/2].
// Inner face at D/2 - th. Outer face at D/2. Correct.
const w1 = wGeo.clone();
w1.translate(0, thickness, depth / 2 - thickness);
geometries.push(w1);
// Wall 2 (Front / Bottom? -Z):
// Needs to be at Z = -Depth/2.
// Occupies [-D/2, -D/2 + th].
// RotateY(180)?
// Plate (X, Z-thick). Rot180 -> (-X, -Z-thick).
// If original in [-W/2, W/2]x[0,th].
// Rot180 -> [W/2, -W/2]x[0,-th].
// Translate to Z = -(Depth/2 - thickness). -> [-th - (D/2 - th)] = -D/2.
// Wait. [-th - D/2 + th] = -D/2. Correct?
// Let's just translate manually without rotation for robustness, assuming pattern symmetric or acceptable.
const w2 = wGeo.clone();
// Rotate to face out?
w2.rotateY(Math.PI);
// After RotY(180): Z becomes negative. Range [-th, 0].
// We want range [-D/2, -D/2 + th].
// So translate Z by -D/2 + th.
w2.translate(0, thickness, -(depth / 2 - thickness));
geometries.push(w2);
}
// Left/Right
if (straightD > 0.1) {
const dGeo = createPerforatedPlate(straightD, wallHeight, thickness, perforation);
dGeo.translate(-straightD / 2, 0, 0);
// Wall 3 (Right? +X).
// RotateY(-90). X -> Z, Z -> -X.
// Plate Z[0, th] -> X[-th, 0].
// We want X [W/2 - th, W/2].
// So Translate X by W/2.
const w3 = dGeo.clone();
w3.rotateY(-Math.PI / 2);
w3.translate(width / 2, thickness, 0);
geometries.push(w3);
// Wall 4 (Left? -X).
// RotateY(90). X -> -Z, Z -> X.
// Plate Z[0, th] -> X[0, th].
// We want X [-W/2, -W/2 + th].
// Translate X by -W/2.
const w4 = dGeo.clone();
w4.rotateY(Math.PI / 2);
w4.translate(-(width / 2), thickness, 0);
geometries.push(w4);
}
}
// ВНУТРЕННИЕ ПЕРЕГОРОДКИ
const innerWidth = width - (2 * thickness);
const innerDepth = depth - (2 * thickness); // Approximate usable space logic
// ВНУТРЕННИЕ ПЕРЕГОРОДКИ (СТРОГО ПО ДАННЫМ, БЕЗ SOLVER)
partitions.forEach(p => {
// Берем данные напрямую. Если в 2D нарисовано от 0.2 до 0.8, тут будет 0.2 до 0.8.
const pMin = p.min ?? 0;
const pMax = p.max ?? 1;
@@ -121,8 +318,56 @@ export const createBinGeometry = (
const lengthRatio = pMax - pMin;
const midRatio = pMin + (lengthRatio / 2);
let pWidth = 0, pDepth = 0, pX = 0, pY = 0;
// --- PERFORATED LOGIC FOR PARTITIONS ---
// If enabled, use Plate. Else use Extrude Solid.
const usePerf = perforation && perforation.enabled;
let pX = 0, pY = 0; // Declare here for visibility in Fillets
if (usePerf) {
// Calculate exact geometry
let pLen = 0;
if (p.axis === 'x') {
// Axis X -> Divider runs along Y (Depth)
pLen = lengthRatio * innerDepth;
pX = (-innerWidth / 2) + (innerWidth * p.offset);
pY = (-innerDepth / 2) + (innerDepth * midRatio); // Center of partition
// Create Plate (Length, Height)
const plate = createPerforatedPlate(pLen, p.height, thickness, perforation!);
plate.translate(-pLen / 2, 0, 0); // Center X
// Rotate to align with Depth (along Z)
// Plate X -> Z
plate.rotateY(-Math.PI / 2);
// Position
// Plate is now vertical Z-aligned. Thickness along X.
plate.translate(pX + thickness / 2, thickness, pY);
geometries.push(plate);
} else {
// Axis Y -> Divider runs along X (Width)
pLen = lengthRatio * innerWidth;
pX = (-innerWidth / 2) + (innerWidth * midRatio);
pY = (-innerDepth / 2) + (innerDepth * p.offset);
const plate = createPerforatedPlate(pLen, p.height, thickness, perforation!);
plate.translate(-pLen / 2, 0, 0); // Center X
// Already aligned with X. Thickness along Z.
// Z range [0, th]. We want [-th/2, th/2] relative to pY.
// Translate Z by -th/2.
plate.translate(0, 0, -thickness / 2);
// Move to position
plate.translate(pX, thickness, pY);
geometries.push(plate);
}
} else {
// --- SOLID LOGIC ---
let pWidth = 0, pDepth = 0;
if (p.axis === 'x') {
pWidth = thickness;
pDepth = lengthRatio * innerDepth;
@@ -140,23 +385,21 @@ export const createBinGeometry = (
partGeo.rotateX(-Math.PI / 2);
partGeo.translate(pX, thickness, pY);
geometries.push(partGeo);
}
// СКРУГЛЕНИЯ (Fillets)
// Fillets Logic for partitions (Keep solid for strength/aesthetics)
if (p.rounded && radius > 1) {
const filletR = Math.min(radius, 5);
const filletShape = createConcaveFilletShape(filletR);
// Функция проверки высоты соседа (простая проверка на пересечение)
// Helper to get neighbor height
const getNeighborHeight = (pos: number) => {
if (pos < 0.001 || pos > 0.999) return height; // Край ящика
if (pos < 0.001 || pos > 0.999) return height;
const neighbor = partitions.find(n => {
if (n.axis === p.axis) return false; // Перпендикуляр
if (n.axis === p.axis) return false;
const nMin = n.min ?? 0;
const nMax = n.max ?? 1;
// Совпадает ли позиция?
if (Math.abs(n.offset - pos) > 0.002) return false;
// Перекрывает ли?
return p.offset > nMin && p.offset < nMax;
});
return neighbor ? neighbor.height : 0;
@@ -210,7 +453,7 @@ export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {
export const exportSTL = (mesh: THREE.Object3D, filename: string) => {
const result = generateSTL(mesh);
const blob = new Blob([result], { type: 'application/octet-stream' });
const blob = new Blob([result as any], { type: 'application/octet-stream' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
+10
View File
@@ -9,6 +9,16 @@ export interface AppConfig {
wallThickness: number;
printerTolerance: number;
cornerRadius: number;
perforation: PerforationConfig;
}
export type PerforationShape = 'circle' | 'honeycomb' | 'triangle' | 'diamond';
export interface PerforationConfig {
enabled: boolean;
shape: PerforationShape;
size: number;
gap: number;
}
export interface Partition {