Merge remote-tracking branch 'origin/test' into test
This commit is contained in:
12
package.json
12
package.json
@@ -13,23 +13,23 @@
|
||||
"start": "vite preview --port 3000 --host"
|
||||
},
|
||||
"dependencies": {
|
||||
"@react-three/drei": "^10.7.7",
|
||||
"@react-three/fiber": "^9.4.2",
|
||||
"jszip": "3.10.1",
|
||||
"lucide-react": "^0.562.0",
|
||||
"react": "^19.2.3",
|
||||
"react-dom": "^19.2.3",
|
||||
"three": "^0.182.0",
|
||||
"three-stdlib": "^2.36.1",
|
||||
"lucide-react": "^0.562.0",
|
||||
"@react-three/drei": "^10.7.7",
|
||||
"@react-three/fiber": "^9.4.2",
|
||||
"jszip": "3.10.1",
|
||||
"uuid": "^9.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.14.0",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@types/node": "^22.14.0",
|
||||
"@types/uuid": "^9.0.8",
|
||||
"@vitejs/plugin-react": "^5.0.0",
|
||||
"typescript": "~5.8.2",
|
||||
"vite": "^6.2.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,153 +1,284 @@
|
||||
import React from 'react';
|
||||
import { AppConfig } from '../types';
|
||||
import { Ruler, Box, Layers, Minimize2, CircleDashed } from 'lucide-react';
|
||||
import React, { useEffect } from 'react';
|
||||
import { AppConfig, PerforationPattern } from '../types';
|
||||
import { Settings2, Box, Ruler, LayoutGrid, Circle, Hexagon, Triangle, Scan } from 'lucide-react';
|
||||
|
||||
interface Props {
|
||||
config: AppConfig;
|
||||
onChange: (newConfig: AppConfig) => void;
|
||||
onChange: (config: AppConfig) => void;
|
||||
}
|
||||
|
||||
const InputGroup: React.FC<{ label: string; children: React.ReactNode }> = ({ label, children }) => (
|
||||
<div className="flex flex-col gap-2 mb-4">
|
||||
<label className="text-sm font-medium text-gray-300">{label}</label>
|
||||
<div className="flex gap-4">{children}</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const NumberInput = ({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
max
|
||||
}: {
|
||||
label: string;
|
||||
value: number;
|
||||
onChange: (val: number) => void;
|
||||
max?: number
|
||||
}) => (
|
||||
<div className="flex-1 relative">
|
||||
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 text-xs">{label}</span>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
max={max}
|
||||
value={value}
|
||||
onChange={(e) => onChange(parseFloat(e.target.value) || 0)}
|
||||
className="w-full bg-slate-800 border border-slate-700 rounded p-2 pl-8 text-white focus:ring-2 focus:ring-primary outline-none"
|
||||
/>
|
||||
<span className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 text-xs">мм</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
export const ConfigStep: React.FC<Props> = ({ config, onChange }) => {
|
||||
const updateDrawer = (key: keyof AppConfig['drawer'], val: number) => {
|
||||
onChange({ ...config, drawer: { ...config.drawer, [key]: val } });
|
||||
|
||||
// Инициализация дефолтных значений перфорации
|
||||
useEffect(() => {
|
||||
if (!config.perforation) {
|
||||
onChange({
|
||||
...config,
|
||||
perforation: { enabled: false, pattern: 'hexagon', diameter: 8, spacing: 2 }
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
const perf = config.perforation || { enabled: false, pattern: 'hexagon', diameter: 8, spacing: 2 };
|
||||
|
||||
const updatePerf = (updates: Partial<typeof perf>) => {
|
||||
onChange({ ...config, perforation: { ...perf, ...updates } });
|
||||
};
|
||||
|
||||
const updateDrawer = (key: keyof typeof config.drawer, value: number) => {
|
||||
onChange({ ...config, drawer: { ...config.drawer, [key]: value } });
|
||||
};
|
||||
|
||||
// --- RENDER PREVIEW ---
|
||||
const renderPreview = () => {
|
||||
if (!perf.enabled) return <div className="text-gray-500 text-xs flex items-center justify-center h-full">Перфорация выключена</div>;
|
||||
|
||||
const size = perf.diameter;
|
||||
const gap = Math.max(2, perf.spacing);
|
||||
const step = size + gap;
|
||||
const W = 200;
|
||||
const H = 120;
|
||||
|
||||
const elements = [];
|
||||
// Приблизительный расчет для превью
|
||||
const rows = Math.floor(H / (step * 0.866));
|
||||
const cols = Math.floor(W / step);
|
||||
|
||||
const startX = (W - (cols * step)) / 2;
|
||||
const startY = (H - (rows * step * 0.866)) / 2;
|
||||
|
||||
for(let j=0; j<rows; j++) {
|
||||
const isOdd = j % 2 !== 0;
|
||||
const y = startY + j * (perf.pattern === 'circle' ? step : step * 0.866);
|
||||
|
||||
for(let i=0; i<cols; i++) {
|
||||
let x = startX + i * step;
|
||||
if ((perf.pattern === 'hexagon' || perf.pattern === 'triangle') && isOdd) x += step / 2;
|
||||
|
||||
if (x > W - size || y > H - size) continue;
|
||||
|
||||
const color = "#3b82f6";
|
||||
|
||||
if (perf.pattern === 'circle') {
|
||||
elements.push(<circle key={`${i}-${j}`} cx={x} cy={y} r={size/2} fill={color} />);
|
||||
} else if (perf.pattern === 'hexagon') {
|
||||
const r = size / 2;
|
||||
const points = [];
|
||||
for (let k = 0; k < 6; k++) {
|
||||
const angle = (k * 60 + 30) * Math.PI / 180;
|
||||
points.push(`${x + r * Math.cos(angle)},${y + r * Math.sin(angle)}`);
|
||||
}
|
||||
elements.push(<polygon key={`${i}-${j}`} points={points.join(' ')} fill={color} />);
|
||||
} else if (perf.pattern === 'triangle') {
|
||||
const r = size / 2;
|
||||
const angleOffset = isOdd ? 180 : 0;
|
||||
const points = [];
|
||||
for (let k = 0; k < 3; k++) {
|
||||
const angle = (k * 120 - 90 + angleOffset) * Math.PI / 180;
|
||||
points.push(`${x + r * Math.cos(angle)},${y + r * Math.sin(angle)}`);
|
||||
}
|
||||
elements.push(<polygon key={`${i}-${j}`} points={points.join(' ')} fill={color} />);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<svg viewBox={`0 0 ${W} ${H}`} className="w-full h-full bg-slate-950/50 border border-slate-700/50 rounded">
|
||||
{elements}
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 animate-fade-in">
|
||||
<h2 className="text-xl font-bold mb-6 flex items-center gap-2 text-primary">
|
||||
<Box size={24} /> 1. Размеры
|
||||
</h2>
|
||||
<div className="max-w-5xl mx-auto space-y-6 pb-24">
|
||||
|
||||
{/* ВЕРХНИЙ БЛОК: Размеры и Параметры печати */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
|
||||
{/* 1. РАЗМЕРЫ */}
|
||||
<section className="bg-slate-900 p-6 rounded-xl border border-slate-800 shadow-xl">
|
||||
<h2 className="text-lg font-bold mb-6 flex items-center gap-2 text-blue-400">
|
||||
<Box size={20}/> 1. Размеры
|
||||
</h2>
|
||||
|
||||
<div className="space-y-5">
|
||||
<div className="bg-slate-950/50 p-4 rounded-lg border border-slate-800/50">
|
||||
<h3 className="text-xs font-bold text-gray-400 uppercase mb-3 flex items-center gap-2"><Ruler size={14}/> Внутренние размеры ящика</h3>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="text-xs text-gray-500 mb-1.5 block ml-1">Ширина (X)</label>
|
||||
<div className="relative">
|
||||
<input type="number" value={config.drawer.width} onChange={(e) => updateDrawer('width', parseFloat(e.target.value))} className="w-full bg-slate-800 border border-slate-700 rounded-lg pl-4 pr-12 py-2.5 text-white focus:ring-2 focus:ring-blue-500/50 outline-none transition-all font-mono"/>
|
||||
<span className="absolute right-4 top-1/2 -translate-y-1/2 text-xs text-gray-500 font-bold">MM</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-gray-500 mb-1.5 block ml-1">Глубина (Y)</label>
|
||||
<div className="relative">
|
||||
<input type="number" value={config.drawer.depth} onChange={(e) => updateDrawer('depth', parseFloat(e.target.value))} className="w-full bg-slate-800 border border-slate-700 rounded-lg pl-4 pr-12 py-2.5 text-white focus:ring-2 focus:ring-blue-500/50 outline-none transition-all font-mono"/>
|
||||
<span className="absolute right-4 top-1/2 -translate-y-1/2 text-xs text-gray-500 font-bold">MM</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-gray-500 mb-1.5 block ml-1">Высота (Z)</label>
|
||||
<div className="relative">
|
||||
<input type="number" value={config.drawer.height} onChange={(e) => updateDrawer('height', parseFloat(e.target.value))} className="w-full bg-slate-800 border border-slate-700 rounded-lg pl-4 pr-12 py-2.5 text-white focus:ring-2 focus:ring-blue-500/50 outline-none transition-all font-mono"/>
|
||||
<span className="absolute right-4 top-1/2 -translate-y-1/2 text-xs text-gray-500 font-bold">MM</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
{/* Drawer Dimensions */}
|
||||
<div className="bg-slate-800/50 p-4 rounded-lg border border-slate-700">
|
||||
<h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-gray-200">
|
||||
<Ruler className="text-accent" size={18} /> Внутренние размеры ящика
|
||||
</h3>
|
||||
<InputGroup label="Ширина (X)">
|
||||
<NumberInput label="Ш" value={config.drawer.width} onChange={(v) => updateDrawer('width', v)} />
|
||||
</InputGroup>
|
||||
<InputGroup label="Глубина (Y)">
|
||||
<NumberInput label="Г" value={config.drawer.depth} onChange={(v) => updateDrawer('depth', v)} />
|
||||
</InputGroup>
|
||||
<InputGroup label="Высота (Z)">
|
||||
<NumberInput label="В" value={config.drawer.height} onChange={(v) => updateDrawer('height', v)} />
|
||||
</InputGroup>
|
||||
</div>
|
||||
{/* 2. ПАРАМЕТРЫ ПЕЧАТИ */}
|
||||
<section className="bg-slate-900 p-6 rounded-xl border border-slate-800 shadow-xl">
|
||||
<h2 className="text-lg font-bold mb-6 flex items-center gap-2 text-yellow-500">
|
||||
<Settings2 size={20}/> Параметры печати
|
||||
</h2>
|
||||
|
||||
{/* Settings */}
|
||||
<div className="bg-slate-800/50 p-4 rounded-lg border border-slate-700 flex flex-col justify-center">
|
||||
<h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-gray-200">
|
||||
<Layers className="text-accent" size={18} /> Параметры печати
|
||||
</h3>
|
||||
|
||||
{/* Wall Thickness */}
|
||||
<div className="mb-6">
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<label className="text-sm font-medium text-gray-300">Толщина стенок</label>
|
||||
<span className="text-primary font-bold bg-primary/10 px-2 py-1 rounded text-sm border border-primary/20">
|
||||
{config.wallThickness.toFixed(1)} мм
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="text-xs text-gray-500 font-mono">0.4</span>
|
||||
<input
|
||||
type="range"
|
||||
min="0.4"
|
||||
max="3.2"
|
||||
step="0.1"
|
||||
value={config.wallThickness}
|
||||
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>
|
||||
<div className="bg-slate-950/50 p-4 rounded-lg border border-slate-800/50 space-y-6">
|
||||
|
||||
{/* Wall Thickness */}
|
||||
<div>
|
||||
<div className="flex justify-between text-xs font-medium text-gray-400 mb-2">
|
||||
<span>Толщина стенок</span>
|
||||
<span className="text-blue-400 bg-blue-400/10 px-2 py-0.5 rounded">{config.wallThickness} мм</span>
|
||||
</div>
|
||||
<input type="range" min="0.8" max="4.0" step="0.4"
|
||||
value={config.wallThickness}
|
||||
onChange={(e) => onChange({...config, wallThickness: parseFloat(e.target.value)})}
|
||||
className="w-full h-1.5 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-blue-500"
|
||||
/>
|
||||
<div className="flex justify-between text-[10px] text-gray-600 mt-1 px-1">
|
||||
<span>0.8</span><span>4.0</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Corner Radius (NEW) */}
|
||||
<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"/> Радиус скругления
|
||||
</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} мм
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="text-xs text-gray-500 font-mono">0</span>
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="20"
|
||||
step="1"
|
||||
value={config.cornerRadius || 0}
|
||||
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>
|
||||
</div>
|
||||
</div>
|
||||
{/* Corner Radius */}
|
||||
<div>
|
||||
<div className="flex justify-between text-xs font-medium text-gray-400 mb-2">
|
||||
<span>Радиус скругления</span>
|
||||
<span className="text-purple-400 bg-purple-400/10 px-2 py-0.5 rounded">{config.cornerRadius} мм</span>
|
||||
</div>
|
||||
<input type="range" min="0" max="20" step="1"
|
||||
value={config.cornerRadius}
|
||||
onChange={(e) => onChange({...config, cornerRadius: parseFloat(e.target.value)})}
|
||||
className="w-full h-1.5 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-purple-500"
|
||||
/>
|
||||
<div className="flex justify-between text-[10px] text-gray-600 mt-1 px-1">
|
||||
<span>0</span><span>20</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Printer Tolerance */}
|
||||
<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)
|
||||
</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)} мм
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="text-xs text-gray-500 font-mono">0.0</span>
|
||||
<input
|
||||
type="range"
|
||||
min="0.0"
|
||||
max="2.0"
|
||||
step="0.1"
|
||||
value={config.printerTolerance}
|
||||
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>
|
||||
</div>
|
||||
</div>
|
||||
{/* Tolerance */}
|
||||
<div>
|
||||
<div className="flex justify-between text-xs font-medium text-gray-400 mb-2">
|
||||
<span>Зазор (Tolerance)</span>
|
||||
<span className="text-yellow-400 bg-yellow-400/10 px-2 py-0.5 rounded">{config.printerTolerance} мм</span>
|
||||
</div>
|
||||
<input type="range" min="0" max="1.0" step="0.05"
|
||||
value={config.printerTolerance}
|
||||
onChange={(e) => onChange({...config, printerTolerance: parseFloat(e.target.value)})}
|
||||
className="w-full h-1.5 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-yellow-500"
|
||||
/>
|
||||
<div className="flex justify-between text-[10px] text-gray-600 mt-1 px-1">
|
||||
<span>0.0</span><span>1.0</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
{/* НИЖНИЙ БЛОК: ПЕРФОРАЦИЯ */}
|
||||
<section className={`bg-slate-900 p-6 rounded-xl border border-slate-800 shadow-xl transition-all ${perf.enabled ? 'border-blue-500/30' : ''}`}>
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h2 className={`text-lg font-bold flex items-center gap-2 ${perf.enabled ? 'text-blue-400' : 'text-gray-500'}`}>
|
||||
<LayoutGrid size={20}/> 2. Перфорация (узоры)
|
||||
</h2>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-xs font-bold text-gray-500 uppercase tracking-wider">{perf.enabled ? 'Включено' : 'Выключено'}</span>
|
||||
<button
|
||||
onClick={() => updatePerf({ enabled: !perf.enabled })}
|
||||
className={`w-14 h-7 rounded-full p-1 transition-all duration-300 ${perf.enabled ? 'bg-blue-600 shadow-lg shadow-blue-900/50' : 'bg-slate-700'}`}
|
||||
>
|
||||
<div className={`w-5 h-5 bg-white rounded-full shadow-sm transform transition-transform duration-300 ${perf.enabled ? 'translate-x-7' : 'translate-x-0'}`}/>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={`grid grid-cols-1 md:grid-cols-2 gap-8 transition-all duration-500 ${perf.enabled ? 'opacity-100 max-h-[500px]' : 'opacity-40 pointer-events-none grayscale max-h-[100px] overflow-hidden'}`}>
|
||||
{/* Настройки */}
|
||||
<div className="space-y-6">
|
||||
|
||||
{/* Тип узора */}
|
||||
<div>
|
||||
<label className="text-xs font-bold text-gray-400 uppercase mb-3 block">Тип узора</label>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<button onClick={() => updatePerf({ pattern: 'circle' })} className={`py-3 rounded-lg border flex flex-col items-center justify-center gap-2 transition-all ${perf.pattern === 'circle' ? 'bg-blue-500/10 border-blue-500 text-blue-400 shadow-lg shadow-blue-900/20' : 'bg-slate-800 border-slate-700 text-gray-500 hover:bg-slate-700 hover:text-gray-300'}`}>
|
||||
<Circle size={20}/> <span className="text-xs font-medium">Круг</span>
|
||||
</button>
|
||||
<button onClick={() => updatePerf({ pattern: 'hexagon' })} className={`py-3 rounded-lg border flex flex-col items-center justify-center gap-2 transition-all ${perf.pattern === 'hexagon' ? 'bg-blue-500/10 border-blue-500 text-blue-400 shadow-lg shadow-blue-900/20' : 'bg-slate-800 border-slate-700 text-gray-500 hover:bg-slate-700 hover:text-gray-300'}`}>
|
||||
<Hexagon size={20}/> <span className="text-xs font-medium">Соты</span>
|
||||
</button>
|
||||
<button onClick={() => updatePerf({ pattern: 'triangle' })} className={`py-3 rounded-lg border flex flex-col items-center justify-center gap-2 transition-all ${perf.pattern === 'triangle' ? 'bg-blue-500/10 border-blue-500 text-blue-400 shadow-lg shadow-blue-900/20' : 'bg-slate-800 border-slate-700 text-gray-500 hover:bg-slate-700 hover:text-gray-300'}`}>
|
||||
<Triangle size={20}/> <span className="text-xs font-medium">Треуг.</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Ползунки параметров */}
|
||||
<div className="bg-slate-950/50 p-4 rounded-lg border border-slate-800/50 space-y-6">
|
||||
{/* Diameter */}
|
||||
<div>
|
||||
<div className="flex justify-between text-xs font-medium text-gray-400 mb-2">
|
||||
<span>Диаметр отверстий</span>
|
||||
<span className="text-blue-400 bg-blue-400/10 px-2 py-0.5 rounded font-mono">{perf.diameter} мм</span>
|
||||
</div>
|
||||
<input type="range" min="2" max="12" step="0.5"
|
||||
value={perf.diameter}
|
||||
onChange={(e) => updatePerf({ diameter: parseFloat(e.target.value) })}
|
||||
className="w-full h-1.5 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-blue-500"
|
||||
/>
|
||||
<div className="flex justify-between text-[10px] text-gray-600 mt-1 px-1">
|
||||
<span>2 мм</span><span>12 мм</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Spacing */}
|
||||
<div>
|
||||
<div className="flex justify-between text-xs font-medium text-gray-400 mb-2">
|
||||
<span>Зазор (между отверстиями)</span>
|
||||
<span className="text-blue-400 bg-blue-400/10 px-2 py-0.5 rounded font-mono">{perf.spacing} мм</span>
|
||||
</div>
|
||||
<input type="range" min="2" max="10" step="0.5"
|
||||
value={perf.spacing}
|
||||
onChange={(e) => updatePerf({ spacing: parseFloat(e.target.value) })}
|
||||
className="w-full h-1.5 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-blue-500"
|
||||
/>
|
||||
<div className="flex justify-between text-[10px] text-gray-600 mt-1 px-1">
|
||||
<span>2 мм</span><span>10 мм</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Preview */}
|
||||
<div className="flex flex-col">
|
||||
<div className="flex justify-between items-end mb-2">
|
||||
<label className="text-xs font-bold text-gray-400 uppercase">Предпросмотр</label>
|
||||
<span className="text-[10px] text-gray-600 flex items-center gap-1"><Scan size={10}/> Масштаб условен</span>
|
||||
</div>
|
||||
<div className="flex-1 min-h-[200px] bg-slate-950 rounded-lg border border-slate-800 relative overflow-hidden flex items-center justify-center p-4">
|
||||
<div className="w-full h-full max-w-[300px] max-h-[180px] shadow-2xl">
|
||||
{renderPreview()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,17 +1,18 @@
|
||||
import React, { Suspense, useEffect, useRef, useState, useMemo } from 'react';
|
||||
import React, { useMemo, Suspense, useEffect, useRef, useState } from 'react';
|
||||
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 { createBinGeometry, generateSTL, exportSTL } from '../services/geometryGenerator';
|
||||
import { Download, Package, Info, Loader2, Share2, Check, Ruler } from 'lucide-react';
|
||||
import { generateShareUrl } from '../utils/share';
|
||||
import { AppConfig, GeneratedPart } from '../types';
|
||||
import { createBinGeometry, exportSTL, generateSTL } from '../services/geometryGenerator';
|
||||
import { Download, Package, Info, Loader2 } from 'lucide-react';
|
||||
|
||||
// --- 3D Helper Components ---
|
||||
|
||||
// --- DrawerFrame (Каркас ящика) ---
|
||||
const DrawerFrame = ({ config }: { config: AppConfig }) => {
|
||||
const { width, depth, height } = config.drawer;
|
||||
const offset = 0.5;
|
||||
|
||||
return (
|
||||
<group position={[width / 2, height / 2, depth / 2]}>
|
||||
<lineSegments>
|
||||
@@ -22,49 +23,43 @@ const DrawerFrame = ({ config }: { config: AppConfig }) => {
|
||||
)
|
||||
}
|
||||
|
||||
// --- BinMesh (Ячейка) ---
|
||||
// --- Bin Component ---
|
||||
|
||||
interface BinMeshProps {
|
||||
part: GeneratedPart;
|
||||
thickness: number;
|
||||
cornerRadius: number;
|
||||
config: AppConfig;
|
||||
isSelected: boolean;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSelected, onClick }) => {
|
||||
// 1. Создаем геометрию, учитывая ВНУТРЕННИЕ ПЕРЕГОРОДКИ
|
||||
const BinMesh: React.FC<BinMeshProps> = ({ part, config, isSelected, onClick }) => {
|
||||
// Мемоизация геометрии для производительности
|
||||
const geometry = useMemo(() => {
|
||||
return createBinGeometry(
|
||||
part.width,
|
||||
part.depth,
|
||||
part.height,
|
||||
thickness,
|
||||
cornerRadius,
|
||||
part.internalPartitions // <--- ВАЖНО: передаем перегородки в генератор
|
||||
config.wallThickness,
|
||||
config.perforation // Передаем конфиг перфорации!
|
||||
);
|
||||
}, [part, thickness, cornerRadius]);
|
||||
|
||||
// 2. Создаем контур выделения (EdgesGeometry)
|
||||
// Threshold 20 градусов скрывает линии на плавных скруглениях
|
||||
const edgesGeometry = useMemo(() => {
|
||||
return new THREE.EdgesGeometry(geometry, 20);
|
||||
}, [geometry]);
|
||||
}, [part, config.wallThickness, config.perforation]);
|
||||
|
||||
return (
|
||||
<group position={[part.x + part.width/2, 0, part.y + part.depth/2]}>
|
||||
{/* Сама модель */}
|
||||
<mesh geometry={geometry} onClick={(e) => { e.stopPropagation(); onClick(); }}>
|
||||
<mesh
|
||||
geometry={geometry}
|
||||
onClick={(e) => { e.stopPropagation(); onClick(); }}
|
||||
>
|
||||
<meshStandardMaterial
|
||||
color={isSelected ? '#f59e0b' : part.color}
|
||||
roughness={0.5}
|
||||
roughness={0.5}
|
||||
metalness={0.1}
|
||||
side={THREE.DoubleSide} // Рисуем обе стороны стенок
|
||||
/>
|
||||
</mesh>
|
||||
|
||||
{/* Белая подсветка при выборе */}
|
||||
{isSelected && (
|
||||
<lineSegments geometry={edgesGeometry}>
|
||||
<lineSegments position={[0, part.height/2, 0]}>
|
||||
<edgesGeometry args={[new THREE.BoxGeometry(part.width, part.height, part.depth)]} />
|
||||
<lineBasicMaterial color="white" linewidth={2} />
|
||||
</lineSegments>
|
||||
)}
|
||||
@@ -72,260 +67,181 @@ const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSele
|
||||
);
|
||||
};
|
||||
|
||||
// --- PreviewStep (Основной компонент) ---
|
||||
interface Props {
|
||||
parts: GeneratedPart[];
|
||||
config: AppConfig;
|
||||
splits: LayoutSplits;
|
||||
}
|
||||
|
||||
export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
|
||||
export const PreviewStep: React.FC<Props> = ({ parts, config }) => {
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [isZipping, setIsZipping] = useState(false);
|
||||
const [shareUrlCopied, setShareUrlCopied] = useState(false);
|
||||
const itemRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});
|
||||
|
||||
// Скролл к выбранной детали в списке
|
||||
useEffect(() => {
|
||||
if (selectedId && itemRefs.current[selectedId]) {
|
||||
itemRefs.current[selectedId]?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
itemRefs.current[selectedId]?.scrollIntoView({
|
||||
behavior: 'smooth',
|
||||
block: 'center'
|
||||
});
|
||||
}
|
||||
}, [selectedId]);
|
||||
|
||||
// Скачивание одной детали
|
||||
const handleDownload = (part: GeneratedPart) => {
|
||||
const geometry = createBinGeometry(
|
||||
part.width,
|
||||
part.depth,
|
||||
part.height,
|
||||
config.wallThickness,
|
||||
config.cornerRadius,
|
||||
part.internalPartitions // <--- ВАЖНО для STL
|
||||
);
|
||||
const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness, config.perforation);
|
||||
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
|
||||
exportSTL(mesh, `${part.name.replace(/\s+/g, '_')}.stl`);
|
||||
};
|
||||
|
||||
// Скачивание всего архивом
|
||||
const handleDownloadAll = async () => {
|
||||
if (isZipping) return;
|
||||
setIsZipping(true);
|
||||
|
||||
try {
|
||||
console.log("Starting ZIP generation...");
|
||||
if (typeof JSZip === 'undefined' && !JSZip) {
|
||||
throw new Error("Библиотека JSZip не загружена.");
|
||||
}
|
||||
|
||||
const zip = new JSZip();
|
||||
|
||||
parts.forEach(part => {
|
||||
const geometry = createBinGeometry(
|
||||
part.width,
|
||||
part.depth,
|
||||
part.height,
|
||||
config.wallThickness,
|
||||
config.cornerRadius,
|
||||
part.internalPartitions // <--- ВАЖНО для STL
|
||||
);
|
||||
const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness, config.perforation);
|
||||
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
|
||||
const stlData = generateSTL(mesh);
|
||||
zip.file(`${part.name.replace(/\s+/g, '_')}.stl`, stlData);
|
||||
});
|
||||
|
||||
const content = await zip.generateAsync({ type: "blob" });
|
||||
|
||||
const link = document.createElement('a');
|
||||
link.href = URL.createObjectURL(content);
|
||||
link.download = "PrintFit_Project.zip";
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
|
||||
} catch (e: any) {
|
||||
alert(`Ошибка архивации: ${e.message}`);
|
||||
console.error("Failed to create zip archive", e);
|
||||
alert(`Ошибка при создании архива: ${e.message || 'Неизвестная ошибка'}`);
|
||||
} finally {
|
||||
setIsZipping(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Поделиться ссылкой
|
||||
const handleShare = async () => {
|
||||
const url = generateShareUrl(config, splits);
|
||||
let success = false;
|
||||
try {
|
||||
if (navigator.clipboard && navigator.clipboard.writeText) {
|
||||
await navigator.clipboard.writeText(url);
|
||||
success = true;
|
||||
} else { throw new Error('Clipboard API unavailable'); }
|
||||
} catch (err) {
|
||||
try {
|
||||
const textArea = document.createElement("textarea");
|
||||
textArea.value = url;
|
||||
textArea.style.position = "fixed";
|
||||
textArea.style.left = "-9999px";
|
||||
textArea.style.top = "0";
|
||||
document.body.appendChild(textArea);
|
||||
textArea.focus();
|
||||
textArea.select();
|
||||
const result = document.execCommand('copy');
|
||||
document.body.removeChild(textArea);
|
||||
if (result) success = true;
|
||||
} catch (e) { console.error("Copy failed", e); }
|
||||
}
|
||||
if (success) {
|
||||
setShareUrlCopied(true);
|
||||
setTimeout(() => setShareUrlCopied(false), 3000);
|
||||
} else {
|
||||
prompt("Скопируйте ссылку вручную:", url);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
{/* Верхняя панель: Размеры + Поделиться */}
|
||||
<div className="flex flex-col xl:flex-row justify-between items-center bg-slate-800/80 p-4 rounded-xl border border-slate-700 mb-4 gap-4 backdrop-blur-sm shadow-lg">
|
||||
|
||||
<div className="flex flex-wrap items-center gap-6 justify-center md:justify-start">
|
||||
<div className="hidden md:flex items-center gap-2 text-gray-300 mr-2">
|
||||
<Ruler className="text-primary" size={20} />
|
||||
<span className="font-medium text-sm uppercase tracking-wide opacity-70">Размеры ящика:</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-6 font-mono text-white items-baseline">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-slate-500 text-sm font-bold uppercase tracking-wider">Ширина:</span>
|
||||
<span className="text-2xl font-bold text-white drop-shadow-sm">{config.drawer.width}</span>
|
||||
</div>
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-slate-500 text-sm font-bold uppercase tracking-wider">Глубина:</span>
|
||||
<span className="text-2xl font-bold text-white drop-shadow-sm">{config.drawer.depth}</span>
|
||||
</div>
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-slate-500 text-sm font-bold uppercase tracking-wider">Высота:</span>
|
||||
<span className="text-2xl font-bold text-white drop-shadow-sm">{config.drawer.height}</span>
|
||||
</div>
|
||||
<span className="text-sm text-slate-500 font-bold self-baseline">мм</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleShare}
|
||||
className={`
|
||||
flex items-center gap-2 px-6 py-3 rounded-lg text-sm font-bold transition-all border shadow-md active:scale-95 shrink-0
|
||||
${shareUrlCopied
|
||||
? 'bg-green-600 border-green-500 text-white shadow-green-900/20'
|
||||
: 'bg-blue-600 hover:bg-blue-500 border-blue-500 text-white shadow-blue-900/20'
|
||||
}
|
||||
`}
|
||||
>
|
||||
{shareUrlCopied ? <Check size={18} /> : <Share2 size={18} />}
|
||||
{shareUrlCopied ? 'СКОПИРОВАНО!' : 'Поделиться'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col lg:flex-row h-full gap-6 relative flex-1 min-h-0">
|
||||
{/* 3D Viewer */}
|
||||
<div className="flex-1 bg-slate-900 rounded-xl overflow-hidden shadow-2xl border border-slate-800 relative min-h-[400px]">
|
||||
<div className="absolute top-4 right-4 z-10 bg-black/60 p-3 rounded-lg text-xs text-gray-300 backdrop-blur pointer-events-none border border-slate-700">
|
||||
<div className="flex items-center gap-2 mb-1 text-primary font-bold">
|
||||
<Info size={14} /> Управление
|
||||
</div>
|
||||
<ul className="space-y-1">
|
||||
<li>• ЛКМ: Вращение</li>
|
||||
<li>• ПКМ: Перемещение</li>
|
||||
<li>• Скролл: Масштаб</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<Canvas
|
||||
<div className="flex flex-col lg:flex-row h-full gap-6">
|
||||
{/* 3D Viewer */}
|
||||
<div className="flex-1 bg-slate-900 rounded-xl overflow-hidden shadow-2xl border border-slate-800 relative min-h-[400px]">
|
||||
<div className="absolute top-4 right-4 z-10 bg-black/60 p-3 rounded-lg text-xs text-gray-300 backdrop-blur pointer-events-none border border-slate-700">
|
||||
<div className="flex items-center gap-2 mb-1 text-primary font-bold">
|
||||
<Info size={14} /> Управление
|
||||
</div>
|
||||
<ul className="space-y-1">
|
||||
<li>• ЛКМ: Вращение</li>
|
||||
<li>• ПКМ: Перемещение</li>
|
||||
<li>• Скролл: Масштаб</li>
|
||||
<li className="text-accent mt-2 font-semibold">• Клик по детали для выбора</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<Canvas
|
||||
shadows
|
||||
dpr={[1, 2]}
|
||||
camera={{
|
||||
position: [config.drawer.width * 1.5, config.drawer.height * 3, config.drawer.depth * 1.5],
|
||||
fov: 45,
|
||||
near: 1,
|
||||
far: 20000
|
||||
near: 1,
|
||||
far: 20000
|
||||
}}
|
||||
>
|
||||
<Suspense fallback={null}>
|
||||
<color attach="background" args={['#0f172a']} />
|
||||
<ambientLight intensity={0.7} />
|
||||
<directionalLight position={[100, 200, 50]} intensity={1.2} />
|
||||
<Environment preset="city" />
|
||||
<Center>
|
||||
<group>
|
||||
<DrawerFrame config={config} />
|
||||
{parts.map(part => (
|
||||
<BinMesh
|
||||
key={part.id}
|
||||
part={part}
|
||||
thickness={config.wallThickness}
|
||||
cornerRadius={config.cornerRadius || 0}
|
||||
isSelected={selectedId === part.id}
|
||||
onClick={() => setSelectedId(part.id)}
|
||||
/>
|
||||
))}
|
||||
</group>
|
||||
</Center>
|
||||
<OrbitControls makeDefault minDistance={10} maxDistance={10000} />
|
||||
</Suspense>
|
||||
</Canvas>
|
||||
>
|
||||
<Suspense fallback={null}>
|
||||
<color attach="background" args={['#0f172a']} />
|
||||
|
||||
<ambientLight intensity={0.7} />
|
||||
<directionalLight position={[100, 200, 50]} intensity={1.2} />
|
||||
<directionalLight position={[-100, 100, -50]} intensity={0.5} />
|
||||
<Environment preset="city" />
|
||||
|
||||
<Center>
|
||||
<group>
|
||||
<DrawerFrame config={config} />
|
||||
{parts.map(part => (
|
||||
<BinMesh
|
||||
key={part.id}
|
||||
part={part}
|
||||
config={config}
|
||||
isSelected={selectedId === part.id}
|
||||
onClick={() => setSelectedId(part.id)}
|
||||
/>
|
||||
))}
|
||||
</group>
|
||||
</Center>
|
||||
|
||||
<OrbitControls makeDefault minDistance={10} maxDistance={10000} />
|
||||
</Suspense>
|
||||
</Canvas>
|
||||
</div>
|
||||
|
||||
{/* Sidebar List */}
|
||||
<div className="w-full lg:w-96 bg-slate-900 p-6 rounded-xl border border-slate-800 flex flex-col h-full shadow-xl">
|
||||
<div className="flex justify-between items-center mb-6 shrink-0">
|
||||
<h2 className="text-xl font-bold flex items-center gap-2 text-primary">
|
||||
<Package size={24} /> Детали ({parts.length})
|
||||
</h2>
|
||||
<button
|
||||
onClick={handleDownloadAll}
|
||||
disabled={isZipping || parts.length === 0}
|
||||
className={`bg-green-600 hover:bg-green-700 text-white px-3 py-1.5 rounded-md text-sm font-medium flex items-center gap-1 transition-all active:scale-95 disabled:opacity-50 disabled:scale-100 disabled:cursor-not-allowed`}
|
||||
>
|
||||
{isZipping ? (
|
||||
<>
|
||||
<Loader2 size={16} className="animate-spin" /> ZIP...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Download size={16} /> Скачать все
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Sidebar List (Grid Layout) */}
|
||||
<div className="w-full lg:w-96 bg-slate-900 p-6 rounded-xl border border-slate-800 flex flex-col h-full shadow-xl">
|
||||
<div className="flex justify-between items-center mb-6 shrink-0">
|
||||
<h2 className="text-xl font-bold flex items-center gap-2 text-primary">
|
||||
<Package size={24} /> Детали ({parts.length})
|
||||
</h2>
|
||||
<button
|
||||
onClick={handleDownloadAll}
|
||||
disabled={isZipping || parts.length === 0}
|
||||
className="bg-slate-700 hover:bg-slate-600 text-white px-3 py-1.5 rounded-md text-sm font-medium flex items-center gap-1 transition-all"
|
||||
>
|
||||
{isZipping ? <Loader2 size={16} className="animate-spin" /> : <Download size={16} />}
|
||||
Архив
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto pr-1 custom-scrollbar">
|
||||
<div className="grid grid-cols-2 gap-3 pb-4">
|
||||
{parts.map(part => (
|
||||
<div
|
||||
key={part.id}
|
||||
ref={(el) => { itemRefs.current[part.id] = el }}
|
||||
className={`
|
||||
p-3 rounded-lg border transition-all cursor-pointer group flex flex-col gap-2 relative overflow-hidden
|
||||
${selectedId === part.id
|
||||
? 'bg-slate-800 border-accent shadow-md shadow-accent/10 ring-1 ring-accent'
|
||||
: 'bg-slate-800/50 border-slate-700 hover:border-slate-500 hover:bg-slate-800'
|
||||
}
|
||||
`}
|
||||
onClick={() => setSelectedId(part.id)}
|
||||
>
|
||||
{/* Индикатор цвета */}
|
||||
<div
|
||||
className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-white/5 to-transparent rounded-bl-3xl pointer-events-none"
|
||||
style={{ backgroundColor: part.color, opacity: 0.1 }}
|
||||
/>
|
||||
|
||||
{/* Заголовок */}
|
||||
<div className="flex items-center justify-between z-10">
|
||||
<span className="font-bold text-gray-200 text-xs truncate" title={part.name}>
|
||||
{part.name}
|
||||
</span>
|
||||
<div
|
||||
className="w-2.5 h-2.5 rounded-full border border-white/20 shadow-sm"
|
||||
style={{ backgroundColor: part.color }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Размеры */}
|
||||
<div className="text-[10px] text-gray-400 font-mono z-10">
|
||||
{part.width.toFixed(0)} × {part.depth.toFixed(0)} × {part.height.toFixed(0)}
|
||||
</div>
|
||||
|
||||
{/* Кнопка скачивания */}
|
||||
<button
|
||||
onClick={(e) => { e.stopPropagation(); handleDownload(part); }}
|
||||
className="w-full py-1.5 bg-slate-700 hover:bg-primary hover:text-white text-gray-300 rounded text-xs flex items-center justify-center gap-1.5 transition-colors font-medium border border-slate-600 hover:border-primary z-10 mt-1"
|
||||
>
|
||||
<Download size={12} /> STL
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto pr-2 space-y-3 custom-scrollbar">
|
||||
{parts.map(part => (
|
||||
<div
|
||||
key={part.id}
|
||||
ref={(el) => { itemRefs.current[part.id] = el }}
|
||||
className={`p-4 rounded-lg border transition-all cursor-pointer group ${selectedId === part.id ? 'bg-slate-800 border-accent shadow-md shadow-accent/10 ring-1 ring-accent' : 'bg-slate-800/50 border-slate-700 hover:border-slate-500 hover:bg-slate-800'}`}
|
||||
onClick={() => setSelectedId(part.id)}
|
||||
>
|
||||
<div className="flex justify-between items-start mb-2">
|
||||
<span className="font-semibold text-gray-200 group-hover:text-white transition-colors">{part.name}</span>
|
||||
<div
|
||||
className="w-3 h-3 rounded-full border border-white/10"
|
||||
style={{ backgroundColor: part.color }}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2 text-xs text-gray-400 mb-3">
|
||||
<div className="bg-slate-900/50 p-1.5 rounded">
|
||||
<span className="block text-gray-500 uppercase text-[9px] mb-0.5">Ширина</span>
|
||||
{part.width.toFixed(1)}
|
||||
</div>
|
||||
<div className="bg-slate-900/50 p-1.5 rounded">
|
||||
<span className="block text-gray-500 uppercase text-[9px] mb-0.5">Глубина</span>
|
||||
{part.depth.toFixed(1)}
|
||||
</div>
|
||||
<div className="bg-slate-900/50 p-1.5 rounded">
|
||||
<span className="block text-gray-500 uppercase text-[9px] mb-0.5">Высота</span>
|
||||
{part.height.toFixed(1)}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={(e) => { e.stopPropagation(); handleDownload(part); }}
|
||||
className="w-full py-2 bg-slate-700 hover:bg-primary hover:text-white text-gray-300 rounded text-xs flex items-center justify-center gap-2 transition-colors font-medium"
|
||||
>
|
||||
<Download size={14} /> Скачать STL
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,33 +1,40 @@
|
||||
import * as THREE from 'three';
|
||||
import { STLExporter, mergeBufferGeometries } from 'three-stdlib';
|
||||
import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types';
|
||||
import { AppConfig, LayoutSplits, GeneratedPart, PerforationConfig } from '../types';
|
||||
|
||||
export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => {
|
||||
/**
|
||||
* 1. Расчет списка ящиков на основе сетки
|
||||
*/
|
||||
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 xPoints = [0, ...[...safeX].sort((a, b) => a - b), 1];
|
||||
const yPoints = [0, ...[...safeY].sort((a, b) => a - b), 1];
|
||||
|
||||
// Сортируем линии реза
|
||||
const xPoints = [0, ...[...splits.x].sort((a, b) => a - b), 1];
|
||||
const yPoints = [0, ...[...splits.y].sort((a, b) => a - b), 1];
|
||||
|
||||
let partCounter = 1;
|
||||
|
||||
for (let i = 0; i < xPoints.length - 1; i++) {
|
||||
for (let j = 0; j < yPoints.length - 1; j++) {
|
||||
const rawW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width;
|
||||
const rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
|
||||
|
||||
if (rawW < 5 || rawD < 5) continue;
|
||||
const segmentX = xPoints[i] * config.drawer.width;
|
||||
const segmentY = yPoints[j] * config.drawer.depth;
|
||||
const segmentW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width;
|
||||
const segmentD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
|
||||
|
||||
const rawX = xPoints[i] * config.drawer.width;
|
||||
const rawY = yPoints[j] * config.drawer.depth;
|
||||
const internalPartitions = safeParts[`${i}-${j}`] || [];
|
||||
// Применяем Tolerance (зазор)
|
||||
const realWidth = segmentW - config.printerTolerance;
|
||||
const realDepth = segmentD - config.printerTolerance;
|
||||
const realX = segmentX + (config.printerTolerance / 2);
|
||||
const realY = segmentY + (config.printerTolerance / 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 < 1 || realDepth < 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
parts.push({
|
||||
id: `part-${partCounter}`,
|
||||
@@ -37,174 +44,183 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
|
||||
height: config.drawer.height,
|
||||
x: realX,
|
||||
y: realY,
|
||||
color: `hsl(${Math.random() * 360}, 70%, 50%)`,
|
||||
internalPartitions: internalPartitions
|
||||
color: `hsl(${(partCounter * 137.5) % 360}, 70%, 50%)`
|
||||
});
|
||||
partCounter++;
|
||||
}
|
||||
}
|
||||
|
||||
return parts;
|
||||
};
|
||||
|
||||
// --- ГЕОМЕТРИЯ ---
|
||||
|
||||
const createRoundedRectShape = (width: number, height: number, radius: number): THREE.Shape => {
|
||||
const shape = new THREE.Shape();
|
||||
const x = -width / 2;
|
||||
const y = -height / 2;
|
||||
const r = Math.min(radius, width / 2 - 0.1, height / 2 - 0.1);
|
||||
|
||||
if (r <= 0.1) {
|
||||
shape.moveTo(x, y);
|
||||
shape.lineTo(x + width, y);
|
||||
shape.lineTo(x + width, y + height);
|
||||
shape.lineTo(x, y + height);
|
||||
shape.lineTo(x, y);
|
||||
} else {
|
||||
shape.moveTo(x, y + r);
|
||||
shape.lineTo(x, y + height - r);
|
||||
shape.quadraticCurveTo(x, y + height, x + r, y + height);
|
||||
shape.lineTo(x + width - r, y + height);
|
||||
shape.quadraticCurveTo(x + width, y + height, x + width, y + height - r);
|
||||
shape.lineTo(x + width, y + r);
|
||||
shape.quadraticCurveTo(x + width, y, x + width - r, y);
|
||||
shape.lineTo(x + r, y);
|
||||
shape.quadraticCurveTo(x, y, x, y + r);
|
||||
}
|
||||
return shape;
|
||||
};
|
||||
|
||||
const createConcaveFilletShape = (radius: number): THREE.Shape => {
|
||||
/**
|
||||
* 2. Создание формы стены с отверстиями (алгоритм из архива)
|
||||
*/
|
||||
const createPerforatedWallShape = (
|
||||
width: number,
|
||||
height: number,
|
||||
perf: PerforationConfig
|
||||
): THREE.Shape => {
|
||||
const shape = new THREE.Shape();
|
||||
// Основной контур
|
||||
shape.moveTo(0, 0);
|
||||
shape.lineTo(radius, 0);
|
||||
shape.absarc(radius, radius, radius, -Math.PI / 2, -Math.PI, true);
|
||||
shape.lineTo(width, 0);
|
||||
shape.lineTo(width, height);
|
||||
shape.lineTo(0, height);
|
||||
shape.lineTo(0, 0);
|
||||
|
||||
if (!perf.enabled) return shape;
|
||||
|
||||
const { size, spacing, shape: type, border } = perf;
|
||||
|
||||
// Эффективная зона
|
||||
const startX = border;
|
||||
const endX = width - border;
|
||||
const startY = border;
|
||||
const endY = height - border;
|
||||
|
||||
if (startX >= endX || startY >= endY) return shape;
|
||||
|
||||
const cellSize = size + spacing;
|
||||
|
||||
// Хелпер добавления отверстия
|
||||
const addHole = (cx: number, cy: number) => {
|
||||
// Проверка границ
|
||||
if (cx - size/2 < startX || cx + size/2 > endX || cy - size/2 < startY || cy + size/2 > endY) return;
|
||||
|
||||
const holePath = new THREE.Path();
|
||||
|
||||
if (type === 'circle') {
|
||||
holePath.absarc(cx, cy, size / 2, 0, Math.PI * 2, true);
|
||||
} else if (type === 'hexagon') {
|
||||
const r = size / 2;
|
||||
for (let k = 0; k < 6; k++) {
|
||||
const angle = (k * 60 + 30) * (Math.PI / 180);
|
||||
const px = cx + r * Math.cos(angle);
|
||||
const py = cy + r * Math.sin(angle);
|
||||
if (k === 0) holePath.moveTo(px, py);
|
||||
else holePath.lineTo(px, py);
|
||||
}
|
||||
holePath.closePath();
|
||||
} else if (type === 'triangle') {
|
||||
const r = size / 2;
|
||||
const angles = [90, 210, 330];
|
||||
angles.forEach((deg, idx) => {
|
||||
const rad = deg * (Math.PI / 180);
|
||||
const px = cx + r * Math.cos(rad);
|
||||
const py = cy + r * Math.sin(rad);
|
||||
if (idx === 0) holePath.moveTo(px, py);
|
||||
else holePath.lineTo(px, py);
|
||||
});
|
||||
holePath.closePath();
|
||||
}
|
||||
|
||||
shape.holes.push(holePath);
|
||||
};
|
||||
|
||||
// Генерация сетки
|
||||
if (type === 'hexagon') {
|
||||
const hexHeight = size;
|
||||
const hexWidth = size * 0.866;
|
||||
const colDist = hexWidth + spacing;
|
||||
const rowDist = (hexHeight * 0.75) + spacing;
|
||||
|
||||
let row = 0;
|
||||
for (let y = startY + size/2; y < endY; y += rowDist) {
|
||||
const offset = (row % 2) === 1 ? colDist / 2 : 0;
|
||||
for (let x = startX + size/2 + offset; x < endX; x += colDist) {
|
||||
addHole(x, y);
|
||||
}
|
||||
row++;
|
||||
}
|
||||
} else {
|
||||
// Обычная сетка
|
||||
for (let x = startX + size/2; x < endX; x += cellSize) {
|
||||
for (let y = startY + size/2; y < endY; y += cellSize) {
|
||||
addHole(x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return shape;
|
||||
};
|
||||
|
||||
/**
|
||||
* 3. Генерация 3D геометрии одного ящика
|
||||
*/
|
||||
export const createBinGeometry = (
|
||||
width: number, depth: number, height: number, thickness: number, radius: number = 0, partitions: Partition[] = []
|
||||
width: number,
|
||||
depth: number,
|
||||
height: number,
|
||||
thickness: number,
|
||||
perforation?: PerforationConfig
|
||||
): THREE.BufferGeometry => {
|
||||
const geometries: THREE.BufferGeometry[] = [];
|
||||
|
||||
// ДНО И ВНЕШНИЕ СТЕНКИ
|
||||
const floorShape = createRoundedRectShape(width, depth, radius);
|
||||
const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false });
|
||||
floorGeo.rotateX(-Math.PI / 2);
|
||||
const perfConfig = perforation || { enabled: false, shape: 'circle', size: 0, spacing: 0, border: 0 };
|
||||
|
||||
// 1. Пол - Всегда сплошной
|
||||
// ВАЖНО: .toNonIndexed() нужен для корректного слияния с ExtrudeGeometry
|
||||
const floorGeo = new THREE.BoxGeometry(width, thickness, depth).toNonIndexed();
|
||||
floorGeo.translate(0, thickness / 2, 0);
|
||||
geometries.push(floorGeo);
|
||||
|
||||
const outerShape = createRoundedRectShape(width, depth, radius);
|
||||
const innerRadius = Math.max(0.1, radius - thickness);
|
||||
const innerWidth = width - (2 * thickness);
|
||||
const innerDepth = depth - (2 * thickness);
|
||||
const wallHeight = height - thickness;
|
||||
|
||||
if (innerWidth > 0.1 && innerDepth > 0.1) {
|
||||
const innerHole = createRoundedRectShape(innerWidth, innerDepth, innerRadius);
|
||||
outerShape.holes.push(innerHole);
|
||||
if (wallHeight > 0) {
|
||||
const extrudeSettings = {
|
||||
depth: thickness,
|
||||
bevelEnabled: false,
|
||||
};
|
||||
|
||||
// 2. Левая и Правая стенки (Полная глубина)
|
||||
// Рисуем профиль шириной = глубине ящика
|
||||
const lrShape = createPerforatedWallShape(depth, wallHeight, perfConfig);
|
||||
// ВАЖНО: .toNonIndexed()
|
||||
const lrGeo = new THREE.ExtrudeGeometry(lrShape, extrudeSettings).toNonIndexed();
|
||||
|
||||
// Left Wall
|
||||
const leftWall = lrGeo.clone();
|
||||
leftWall.rotateY(-Math.PI / 2);
|
||||
leftWall.translate(-(width/2) + thickness, thickness, -(depth/2));
|
||||
geometries.push(leftWall);
|
||||
|
||||
// Right Wall
|
||||
const rightWall = lrGeo.clone();
|
||||
rightWall.rotateY(-Math.PI / 2);
|
||||
rightWall.translate((width/2), thickness, -(depth/2));
|
||||
geometries.push(rightWall);
|
||||
|
||||
// 3. Передняя и Задняя стенки (Вставляются между боковыми)
|
||||
// Ширина уменьшена на 2 толщины
|
||||
const wallFBWidth = Math.max(0, width - (2 * thickness));
|
||||
if (wallFBWidth > 0) {
|
||||
const fbShape = createPerforatedWallShape(wallFBWidth, wallHeight, perfConfig);
|
||||
const fbGeo = new THREE.ExtrudeGeometry(fbShape, extrudeSettings).toNonIndexed();
|
||||
|
||||
// Front Wall
|
||||
const frontWall = fbGeo.clone();
|
||||
frontWall.translate(-(wallFBWidth/2), thickness, (depth/2) - thickness);
|
||||
geometries.push(frontWall);
|
||||
|
||||
// Back Wall
|
||||
const backWall = fbGeo.clone();
|
||||
backWall.translate(-(wallFBWidth/2), thickness, -(depth/2));
|
||||
geometries.push(backWall);
|
||||
}
|
||||
}
|
||||
|
||||
const wallHeight = height - thickness;
|
||||
const wallGeo = new THREE.ExtrudeGeometry(outerShape, { depth: wallHeight, bevelEnabled: false });
|
||||
wallGeo.rotateX(-Math.PI / 2);
|
||||
wallGeo.translate(0, thickness, 0);
|
||||
geometries.push(wallGeo);
|
||||
|
||||
// ВНУТРЕННИЕ ПЕРЕГОРОДКИ (СТРОГО ПО ДАННЫМ, БЕЗ SOLVER)
|
||||
partitions.forEach(p => {
|
||||
// Берем данные напрямую. Если в 2D нарисовано от 0.2 до 0.8, тут будет 0.2 до 0.8.
|
||||
const pMin = p.min ?? 0;
|
||||
const pMax = p.max ?? 1;
|
||||
|
||||
if (pMax - pMin < 0.01) return;
|
||||
|
||||
const lengthRatio = pMax - pMin;
|
||||
const midRatio = pMin + (lengthRatio / 2);
|
||||
|
||||
let pWidth = 0, pDepth = 0, pX = 0, pY = 0;
|
||||
|
||||
if (p.axis === 'x') {
|
||||
pWidth = thickness;
|
||||
pDepth = lengthRatio * innerDepth;
|
||||
pX = (-innerWidth / 2) + (innerWidth * p.offset);
|
||||
pY = (-innerDepth / 2) + (innerDepth * midRatio);
|
||||
} else {
|
||||
pWidth = lengthRatio * innerWidth;
|
||||
pDepth = thickness;
|
||||
pX = (-innerWidth / 2) + (innerWidth * midRatio);
|
||||
pY = (-innerDepth / 2) + (innerDepth * p.offset);
|
||||
}
|
||||
|
||||
const partShape = createRoundedRectShape(pWidth, pDepth, 0.1);
|
||||
const partGeo = new THREE.ExtrudeGeometry(partShape, { depth: p.height, bevelEnabled: false });
|
||||
partGeo.rotateX(-Math.PI / 2);
|
||||
partGeo.translate(pX, thickness, pY);
|
||||
geometries.push(partGeo);
|
||||
|
||||
// СКРУГЛЕНИЯ (Fillets)
|
||||
if (p.rounded && radius > 1) {
|
||||
const filletR = Math.min(radius, 5);
|
||||
const filletShape = createConcaveFilletShape(filletR);
|
||||
|
||||
// Функция проверки высоты соседа (простая проверка на пересечение)
|
||||
const getNeighborHeight = (pos: number) => {
|
||||
if (pos < 0.001 || pos > 0.999) return height; // Край ящика
|
||||
|
||||
const neighbor = partitions.find(n => {
|
||||
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;
|
||||
};
|
||||
|
||||
const hStart = Math.min(p.height, getNeighborHeight(pMin));
|
||||
const hEnd = Math.min(p.height, getNeighborHeight(pMax));
|
||||
|
||||
const addFillet = (x: number, y: number, rotY: number, h: number) => {
|
||||
if (h <= 1) return;
|
||||
const geo = new THREE.ExtrudeGeometry(filletShape, { depth: h, bevelEnabled: false });
|
||||
geo.rotateX(-Math.PI / 2);
|
||||
geo.rotateY(rotY);
|
||||
geo.translate(x, thickness, y);
|
||||
geometries.push(geo);
|
||||
};
|
||||
|
||||
const t = thickness / 2;
|
||||
|
||||
if (p.axis === 'x') {
|
||||
const topY = (-innerDepth / 2) + (innerDepth * pMin);
|
||||
const botY = (-innerDepth / 2) + (innerDepth * pMax);
|
||||
|
||||
addFillet(pX - t, topY, Math.PI, hStart);
|
||||
addFillet(pX + t, topY, -Math.PI / 2, hStart);
|
||||
addFillet(pX - t, botY, Math.PI / 2, hEnd);
|
||||
addFillet(pX + t, botY, 0, hEnd);
|
||||
} else {
|
||||
const leftX = (-innerWidth / 2) + (innerWidth * pMin);
|
||||
const rightX = (-innerWidth / 2) + (innerWidth * pMax);
|
||||
|
||||
addFillet(leftX, pY - t, 0, hStart);
|
||||
addFillet(leftX, pY + t, -Math.PI / 2, hStart);
|
||||
addFillet(rightX, pY - t, Math.PI / 2, hEnd);
|
||||
addFillet(rightX, pY + t, Math.PI, hEnd);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Слияние в один меш
|
||||
const merged = mergeBufferGeometries(geometries);
|
||||
if (merged) merged.computeVertexNormals();
|
||||
return merged || new THREE.BoxGeometry(1, 1, 1);
|
||||
return merged || new THREE.BoxGeometry(1, 1, 1).toNonIndexed();
|
||||
};
|
||||
|
||||
export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {
|
||||
const exporter = new STLExporter();
|
||||
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;
|
||||
};
|
||||
|
||||
|
||||
16
src/types.ts
16
src/types.ts
@@ -4,19 +4,29 @@ export interface DrawerDimensions {
|
||||
height: number;
|
||||
}
|
||||
|
||||
export type PerforationPattern = 'circle' | 'hexagon' | 'triangle';
|
||||
|
||||
export interface PerforationConfig {
|
||||
enabled: boolean;
|
||||
pattern: PerforationPattern;
|
||||
diameter: number; // Размер отверстия
|
||||
spacing: number; // Расстояние между центрами (шаг)
|
||||
}
|
||||
|
||||
export interface AppConfig {
|
||||
drawer: DrawerDimensions;
|
||||
wallThickness: number;
|
||||
printerTolerance: number;
|
||||
cornerRadius: number;
|
||||
perforation: PerforationConfig; // Новая секция
|
||||
}
|
||||
|
||||
export interface Partition {
|
||||
id: string;
|
||||
axis: 'x' | 'y';
|
||||
offset: number; // Позиция (0.0 - 1.0)
|
||||
min: number; // Начало стенки (0.0 - 1.0)
|
||||
max: number; // Конец стенки (0.0 - 1.0)
|
||||
offset: number;
|
||||
min: number;
|
||||
max: number;
|
||||
height: number;
|
||||
rounded: boolean;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user