Compare commits

..
22 Commits
Author SHA1 Message Date
Халимов Рустам 3e1471061a Merge remote-tracking branch 'origin/test' into test 2026-01-12 15:19:18 +03:00
Халимов Рустам 3d774880b6 12 2026-01-12 15:07:57 +03:00
Халимов Рустам f588da1820 11 2026-01-12 14:59:08 +03:00
Халимов Рустам 1240612876 10 2026-01-12 14:05:51 +03:00
Халимов Рустам 58cfc0f8e4 9 2026-01-12 03:09:51 +03:00
Халимов Рустам 5235fa888f 8 2026-01-12 02:58:41 +03:00
Халимов Рустам d8d34371a9 7 2026-01-12 02:53:45 +03:00
Халимов Рустам 6d40bc851d 6 2026-01-12 02:52:53 +03:00
Халимов Рустам 5c06da8450 5 2026-01-12 02:36:42 +03:00
Халимов Рустам 03a787a459 4 2026-01-12 02:27:57 +03:00
Халимов Рустам 7d258ff575 3 2026-01-12 02:21:17 +03:00
Халимов Рустам 1f70a7652c 2 2026-01-12 02:12:16 +03:00
Халимов Рустам fa2f02bd18 1 2026-01-12 01:57:09 +03:00
Халимов Рустам 7af156fea0 Try fix used three-bvh-csg 2026-01-12 01:44:19 +03:00
Халимов Рустам e90348ab32 Use three-bvh-csg 2026-01-12 01:35:02 +03:00
Халимов Рустам 0521c23246 5 2026-01-12 01:19:20 +03:00
Халимов Рустам 3d79abf4d4 4 2026-01-12 01:07:55 +03:00
Халимов Рустам 2fee39afce 3 2026-01-12 00:59:56 +03:00
Халимов Рустам d3170e79ab 2 2026-01-12 00:47:52 +03:00
Халимов Рустам 9e4c88e424 1 2026-01-12 00:36:02 +03:00
Халимов Рустам 58a2e0468f Fix config view 2026-01-12 00:13:32 +03:00
Халимов Рустам e7d153ce6b Try add perforation 2026-01-12 00:03:24 +03:00
8 changed files with 738 additions and 1456 deletions
-19
View File
@@ -1,19 +0,0 @@
# Build stage
FROM node:20-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
+13 -73
View File
@@ -1,80 +1,20 @@
# PrintFit - Генератор Органайзеров для 3D Печати <div align="center">
<img width="1200" height="475" alt="GHBanner" src="https://github.com/user-attachments/assets/0aa67016-6eaf-458a-adb2-6e31a0763ed6" />
</div>
PrintFit — это мощный веб-инструмент для создания параметрических органайзеров, разделителей и ящиков, оптимизированных для 3D-печати. Приложение позволяет легко проектировать системы хранения под любые размеры с возможностью детальной настройки перегородок и перфорации. # Run and deploy your AI Studio app
![PrintFit Preview](https://via.placeholder.com/1200x600?text=PrintFit+3D+Preview) This contains everything you need to run your app locally.
## ✨ Основные Возможности View your app in AI Studio: https://ai.studio/apps/drive/1gUfO_tgl_CPfAGf1eXuSFyC0K7nUZFgu
### 🛠 Параметрическое Моделирование ## Run Locally
- **Полный контроль размеров**: Настраивайте ширину, глубину и высоту ящика с точностью до миллиметра.
- **Толщина стенок и допуски**: Установка толщины внешних стенок и внутренних перегородок, а также компенсация усадки пластика (tolerance) для идеальной совместимости.
- **Скругление углов**: Настройка радиуса углов для эстетики и совместимости с различными стандартами (например, Gridfinity).
### 📐 Гибкая Система Перегородок **Prerequisites:** Node.js
- **Визуальный редактор макета**: Интуитивно понятный интерфейс для добавления вертикальных и горизонтальных разделителей.
- **Вложенность**: Создание сложных сеток и ячеек разных размеров внутри одного органайзера.
- **Умное отображение размеров**: Автоматический расчет и отображение внутренних габаритов каждого отсека прямо на 3D-модели.
### 💨 Продвинутая Перфорация
- **Экономия материала и времени**: Возможность создания перфорированных стенок.
- **Различные узоры**: Выбор формы отверстий (соты/гексагоны, круги, треугольники и др.).
- **Умные исключения**: Алгоритм автоматически убирает перфорацию в местах стыков перегородок и углов, обеспечивая прочность конструкции (Solid Zones).
- **Настройка плотности**: Регулировка размера отверстий и отступов между ними.
### 🖥 Интерактивный 3D Предпросмотр 1. Install dependencies:
- **Real-time рендеринг**: Мгновенное отображение изменений в браузере с помощью Three.js. `npm install`
- **Управление камерой**: Вращение, масштабирование и панорамирование для детального осмотра модели со всех сторон. 2. Set the `GEMINI_API_KEY` in [.env.local](.env.local) to your Gemini API key
- **Индикация размеров**: Внутренние размеры отсеков отображаются прямо внутри ячеек. 3. Run the app:
`npm run dev`
### 💾 Экспорт и Шеринг
- **STL Экспорт**: Генерация готовых к печати STL файлов. Можно скачать отдельные детали или весь проект архивом (ZIP).
- **Сохранение проектов**: Возможность поделиться ссылкой на конфигурацию (все параметры кодируются в URL).
## 🚀 Запуск Локально
Для работы требуется установленный **Node.js**.
1. Клонируйте репозиторий:
```bash
git clone https://github.com/your-username/printfit-box-generator.git
cd printfit-box-generator
```
2. Установите зависимости:
```bash
npm install
```
3. Запустите локальный сервер разработки:
```bash
npm run dev
```
4. Откройте приложение в браузере (обычно http://localhost:5173).
## 🐳 Запуск в Docker
Приложение можно легко развернуть в контейнере Docker (используется Nginx для раздачи статики).
1. Соберите образ:
```bash
docker build -t printfit-app .
```
2. Запустите контейнер:
```bash
docker run -p 8080:80 printfit-app
```
3. Откройте http://localhost:8080
## 🛠 Технологический Стек
- **React**: UI и управление состоянием.
- **Three.js (@react-three/fiber)**: 3D рендеринг и геометрия.
- **Tailwind CSS**: Стилизация интерфейса.
- **Vite**: Сборщик проекта.
- **Lucide React**: Иконки.
## 📝 Лицензия
Этот проект распространяется под лицензией MIT. Вы можете свободно использовать, изменять и распространять его.
+5 -5
View File
@@ -13,20 +13,20 @@
"start": "vite preview --port 3000 --host" "start": "vite preview --port 3000 --host"
}, },
"dependencies": { "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": "^19.2.3",
"react-dom": "^19.2.3", "react-dom": "^19.2.3",
"three": "^0.182.0", "three": "^0.182.0",
"three-stdlib": "^2.36.1", "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" "uuid": "^9.0.1"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^22.14.0",
"@types/react": "^19.0.0", "@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0", "@types/react-dom": "^19.0.0",
"@types/node": "^22.14.0",
"@types/uuid": "^9.0.8", "@types/uuid": "^9.0.8",
"@vitejs/plugin-react": "^5.0.0", "@vitejs/plugin-react": "^5.0.0",
"typescript": "~5.8.2", "typescript": "~5.8.2",
+5 -11
View File
@@ -29,16 +29,10 @@ const App = () => {
const [step, setStep] = useState(1); const [step, setStep] = useState(1);
const [config, setConfig] = useState<AppConfig>({ const [config, setConfig] = useState<AppConfig>({
drawer: { width: 100, depth: 100, height: 100 }, drawer: { width: 300, depth: 400, height: 80 },
wallThickness: 0.8, wallThickness: 1.2,
printerTolerance: 0.5, printerTolerance: 0.5,
cornerRadius: 4, cornerRadius: 4,
perforation: {
enabled: true,
shape: 'honeycomb',
size: 8,
gap: 2
}
}); });
const [splits, setSplits] = useState<LayoutSplits>({ const [splits, setSplits] = useState<LayoutSplits>({
@@ -75,7 +69,7 @@ const App = () => {
return ( return (
<div className="h-screen flex flex-col font-sans text-gray-100 bg-slate-950 overflow-hidden"> <div className="h-screen flex flex-col font-sans text-gray-100 bg-slate-950 overflow-hidden">
{/* Шапка */} {/* Header */}
<header className="bg-slate-900 border-b border-slate-800 p-4 shadow-md shrink-0 z-50"> <header className="bg-slate-900 border-b border-slate-800 p-4 shadow-md shrink-0 z-50">
<div className="max-w-7xl mx-auto flex items-center justify-between"> <div className="max-w-7xl mx-auto flex items-center justify-between">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
@@ -93,7 +87,7 @@ const App = () => {
</div> </div>
</header> </header>
{/* Основной контент */} {/* Main Content */}
<main className="flex-1 w-full max-w-7xl mx-auto p-4 overflow-hidden flex flex-col min-h-0"> <main className="flex-1 w-full max-w-7xl mx-auto p-4 overflow-hidden flex flex-col min-h-0">
{step === 1 && ( {step === 1 && (
<div className="h-full overflow-y-auto animate-fade-in custom-scrollbar"> <div className="h-full overflow-y-auto animate-fade-in custom-scrollbar">
@@ -116,7 +110,7 @@ const App = () => {
)} )}
</main> </main>
{/* Подвал */} {/* Footer */}
<footer className="bg-slate-900 border-t border-slate-800 p-4 shrink-0 z-50"> <footer className="bg-slate-900 border-t border-slate-800 p-4 shrink-0 z-50">
<div className="max-w-7xl mx-auto flex justify-between items-center"> <div className="max-w-7xl mx-auto flex justify-between items-center">
<button disabled={step === 1} onClick={() => setStep(s => Math.max(1, s - 1))} className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold bg-slate-800 text-white disabled:opacity-50 disabled:cursor-not-allowed hover:bg-slate-700 transition-colors"><ChevronLeft size={18} /> Назад</button> <button disabled={step === 1} onClick={() => setStep(s => Math.max(1, s - 1))} className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold bg-slate-800 text-white disabled:opacity-50 disabled:cursor-not-allowed hover:bg-slate-700 transition-colors"><ChevronLeft size={18} /> Назад</button>
+215 -251
View File
@@ -1,320 +1,284 @@
import React from 'react'; import React, { useEffect } from 'react';
import { AppConfig, PerforationShape } from '../types'; import { AppConfig, PerforationPattern } from '../types';
import { Ruler, Box, Layers, Minimize2, CircleDashed, Grid, Circle, Hexagon, Triangle } from 'lucide-react'; import { Settings2, Box, Ruler, LayoutGrid, Circle, Hexagon, Triangle, Scan } from 'lucide-react';
interface Props { interface Props {
config: AppConfig; 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>
);
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 }) => { 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 updatePerforation = (key: keyof AppConfig['perforation'], val: any) => { const updateDrawer = (key: keyof typeof config.drawer, value: number) => {
onChange({ ...config, perforation: { ...config.perforation, [key]: val } }) 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 ( return (
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 animate-fade-in space-y-8"> <svg viewBox={`0 0 ${W} ${H}`} className="w-full h-full bg-slate-950/50 border border-slate-700/50 rounded">
{elements}
</svg>
);
};
{/* SECTION 1: Dimensions & Settings */} return (
<div> <div className="max-w-5xl mx-auto space-y-6 pb-24">
<h2 className="text-xl font-bold mb-6 flex items-center gap-2 text-primary">
<Box size={24} /> 1. Размеры {/* ВЕРХНИЙ БЛОК: Размеры и Параметры печати */}
<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> </h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-8"> <div className="space-y-5">
{/* Drawer Dimensions */} <div className="bg-slate-950/50 p-4 rounded-lg border border-slate-800/50">
<div className="bg-slate-800/50 p-4 rounded-lg border border-slate-700"> <h3 className="text-xs font-bold text-gray-400 uppercase mb-3 flex items-center gap-2"><Ruler size={14}/> Внутренние размеры ящика</h3>
<h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-gray-200"> <div className="space-y-4">
<Ruler className="text-accent" size={18} /> Внутренние размеры ящика <div>
</h3> <label className="text-xs text-gray-500 mb-1.5 block ml-1">Ширина (X)</label>
<InputGroup label="Ширина (X)"> <div className="relative">
<NumberInput label="Ш" value={config.drawer.width} onChange={(v) => updateDrawer('width', v)} /> <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"/>
</InputGroup> <span className="absolute right-4 top-1/2 -translate-y-1/2 text-xs text-gray-500 font-bold">MM</span>
<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> </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>
{/* Settings */} {/* 2. ПАРАМЕТРЫ ПЕЧАТИ */}
<div className="bg-slate-800/50 p-4 rounded-lg border border-slate-700 flex flex-col justify-center"> <section className="bg-slate-900 p-6 rounded-xl border border-slate-800 shadow-xl">
<h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-gray-200"> <h2 className="text-lg font-bold mb-6 flex items-center gap-2 text-yellow-500">
<Layers className="text-accent" size={18} /> Параметры печати <Settings2 size={20}/> Параметры печати
</h3> </h2>
<div className="bg-slate-950/50 p-4 rounded-lg border border-slate-800/50 space-y-6">
{/* Wall Thickness */} {/* Wall Thickness */}
<div className="mb-6"> <div>
<div className="flex justify-between items-center mb-2"> <div className="flex justify-between text-xs font-medium text-gray-400 mb-2">
<label className="text-sm font-medium text-gray-300">Толщина стенок</label> <span>Толщина стенок</span>
<span className="text-primary font-bold bg-primary/10 px-2 py-1 rounded text-sm border border-primary/20"> <span className="text-blue-400 bg-blue-400/10 px-2 py-0.5 rounded">{config.wallThickness} мм</span>
{config.wallThickness.toFixed(1)} мм
</span>
</div> </div>
<div className="flex items-center gap-4"> <input type="range" min="0.8" max="4.0" step="0.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} 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" className="w-full h-1.5 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-blue-500"
/> />
<span className="text-xs text-gray-500 font-mono">3.2</span> <div className="flex justify-between text-[10px] text-gray-600 mt-1 px-1">
<span>0.8</span><span>4.0</span>
</div> </div>
</div> </div>
{/* Corner Radius */} {/* Corner Radius */}
<div className="mb-6"> <div>
<div className="flex justify-between items-center mb-2"> <div className="flex justify-between text-xs font-medium text-gray-400 mb-2">
<label className="text-sm font-medium text-gray-300 flex items-center gap-1"> <span>Радиус скругления</span>
<CircleDashed size={14} className="text-gray-400" /> Радиус скругления <span className="text-purple-400 bg-purple-400/10 px-2 py-0.5 rounded">{config.cornerRadius} мм</span>
</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>
<div className="flex items-center gap-4"> <input type="range" min="0" max="20" step="1"
<span className="text-xs text-gray-500 font-mono">0</span> value={config.cornerRadius}
<input
type="range"
min="0"
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" className="w-full h-1.5 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-purple-500"
/> />
<span className="text-xs text-gray-500 font-mono">20</span> <div className="flex justify-between text-[10px] text-gray-600 mt-1 px-1">
<span>0</span><span>20</span>
</div> </div>
</div> </div>
{/* Printer Tolerance */} {/* Tolerance */}
<div className="mb-4"> <div>
<div className="flex justify-between items-center mb-2"> <div className="flex justify-between text-xs font-medium text-gray-400 mb-2">
<label className="text-sm font-medium text-gray-300 flex items-center gap-1"> <span>Зазор (Tolerance)</span>
<Minimize2 size={14} className="text-gray-400" /> Зазор (Tolerance) <span className="text-yellow-400 bg-yellow-400/10 px-2 py-0.5 rounded">{config.printerTolerance} мм</span>
</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>
<div className="flex items-center gap-4"> <input type="range" min="0" max="1.0" step="0.05"
<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} 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" className="w-full h-1.5 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-yellow-500"
/> />
<span className="text-xs text-gray-500 font-mono">2.0</span> <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>
</div> </div>
</div> </section>
</div> </div>
{/* SECTION 2: Perforation */} {/* НИЖНИЙ БЛОК: ПЕРФОРАЦИЯ */}
<div className="bg-slate-800/30 p-6 rounded-lg border border-slate-700/50"> <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 items-center justify-between mb-6"> <div className="flex justify-between items-center mb-6">
<h3 className="text-lg font-semibold flex items-center gap-2 text-blue-400"> <h2 className={`text-lg font-bold flex items-center gap-2 ${perf.enabled ? 'text-blue-400' : 'text-gray-500'}`}>
<Grid size={20} /> 2. Перфорация (узоры) <LayoutGrid size={20}/> 2. Перфорация (узоры)
</h3> </h2>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<span className="text-sm font-medium text-gray-400 uppercase tracking-wider">Включено</span> <span className="text-xs font-bold text-gray-500 uppercase tracking-wider">{perf.enabled ? 'Включено' : 'Выключено'}</span>
<button <button
onClick={() => updatePerforation('enabled', !config.perforation.enabled)} onClick={() => updatePerf({ enabled: !perf.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'}`} 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'}`}
> >
<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'}`} /> <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> </button>
</div> </div>
</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 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> {/* Настройки */}
<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 className="space-y-6">
{/* Тип узора */}
<div> <div>
<div className="flex justify-between items-center mb-2"> <label className="text-xs font-bold text-gray-400 uppercase mb-3 block">Тип узора</label>
<label className="text-sm font-medium text-gray-300">Диаметр отверстий</label> <div className="grid grid-cols-3 gap-3">
<span className="text-sm font-bold text-blue-400">{config.perforation.size} мм</span> <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'}`}>
</div> <Circle size={20}/> <span className="text-xs font-medium">Круг</span>
<div className="flex items-center gap-4"> </button>
<span className="text-xs text-gray-500">2 мм</span> <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'}`}>
<input <Hexagon size={20}/> <span className="text-xs font-medium">Соты</span>
type="range" min="2" max="25" step="1" </button>
value={config.perforation.size} <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'}`}>
onChange={(e) => updatePerforation('size', parseFloat(e.target.value))} <Triangle size={20}/> <span className="text-xs font-medium">Треуг.</span>
className="flex-1 h-1.5 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-blue-500" </button>
/>
<span className="text-xs text-gray-500">25 мм</span>
</div> </div>
</div> </div>
{/* Ползунки параметров */}
<div className="bg-slate-950/50 p-4 rounded-lg border border-slate-800/50 space-y-6">
{/* Diameter */}
<div> <div>
<div className="flex justify-between items-center mb-2"> <div className="flex justify-between text-xs font-medium text-gray-400 mb-2">
<label className="text-sm font-medium text-gray-300">Зазор (между отверстиями)</label> <span>Диаметр отверстий</span>
<span className="text-sm font-bold text-blue-400">{config.perforation.gap} мм</span> <span className="text-blue-400 bg-blue-400/10 px-2 py-0.5 rounded font-mono">{perf.diameter} мм</span>
</div> </div>
<div className="flex items-center gap-4"> <input type="range" min="2" max="12" step="0.5"
<span className="text-xs text-gray-500">1 мм</span> value={perf.diameter}
<input onChange={(e) => updatePerf({ diameter: parseFloat(e.target.value) })}
type="range" min="1" max="10" step="0.5" className="w-full h-1.5 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-blue-500"
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 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>
</div> </div>
</div> </div>
{/* Preview */} {/* Preview */}
<div> <div className="flex flex-col">
<label className="text-xs font-bold text-gray-500 uppercase mb-3 block">Предпросмотр</label> <div className="flex justify-between items-end mb-2">
<PerforationPreview config={config.perforation} /> <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>
</div> </div>
</div> </div>
</section>
</div>
); );
}; };
+79 -288
View File
@@ -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 { Canvas } from '@react-three/fiber';
import { OrbitControls, Center, Environment, Text } from '@react-three/drei'; import { OrbitControls, Center, Environment } from '@react-three/drei';
import * as THREE from 'three'; import * as THREE from 'three';
import JSZip from 'jszip'; import JSZip from 'jszip';
import { AppConfig, GeneratedPart, LayoutSplits, PerforationConfig } from '../types'; import { AppConfig, GeneratedPart } from '../types';
import { createBinGeometry, generateSTL, exportSTL } from '../services/geometryGenerator'; import { createBinGeometry, exportSTL, generateSTL } from '../services/geometryGenerator';
import { Download, Package, Info, Loader2, Share2, Check, Ruler } from 'lucide-react'; import { Download, Package, Info, Loader2 } from 'lucide-react';
import { generateShareUrl } from '../utils/share';
// --- 3D Helper Components ---
// --- DrawerFrame (Каркас ящика) ---
const DrawerFrame = ({ config }: { config: AppConfig }) => { const DrawerFrame = ({ config }: { config: AppConfig }) => {
const { width, depth, height } = config.drawer; const { width, depth, height } = config.drawer;
const offset = 0.5; const offset = 0.5;
return ( return (
<group position={[width / 2, height / 2, depth / 2]}> <group position={[width / 2, height / 2, depth / 2]}>
<lineSegments> <lineSegments>
@@ -22,171 +23,43 @@ const DrawerFrame = ({ config }: { config: AppConfig }) => {
) )
} }
// --- BinMesh (Ячейка) --- // --- Bin Component ---
interface BinMeshProps { interface BinMeshProps {
part: GeneratedPart; part: GeneratedPart;
thickness: number; config: AppConfig;
cornerRadius: number;
perforation: PerforationConfig;
isSelected: boolean; isSelected: boolean;
onClick: () => void; onClick: () => void;
} }
const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, perforation, isSelected, onClick }) => { const BinMesh: React.FC<BinMeshProps> = ({ part, config, isSelected, onClick }) => {
// 1. Создаем геометрию, учитывая ВНУТРЕННИЕ ПЕРЕГОРОДКИ // Мемоизация геометрии для производительности
const geometry = useMemo(() => { const geometry = useMemo(() => {
return createBinGeometry( return createBinGeometry(
part.width, part.width,
part.depth, part.depth,
part.height, part.height,
thickness, config.wallThickness,
cornerRadius, config.perforation // Передаем конфиг перфорации!
part.internalPartitions, // <--- ВАЖНО: передаем перегородки в генератор
perforation
); );
}, [part, thickness, cornerRadius, perforation]); }, [part, config.wallThickness, config.perforation]);
// 2. Создаем контур выделения (EdgesGeometry)
// Threshold 20 градусов скрывает линии на плавных скруглениях
const edgesGeometry = useMemo(() => {
return new THREE.EdgesGeometry(geometry, 20);
}, [geometry]);
// 3. Вычисляем размеры и позиции для каждой под-ячейки
// 3. Вычисляем размеры и позиции для реальных отсеков (с учетом мерджинга)
const dimLabels = useMemo(() => {
const xOffsets = new Set<number>([0, 1]);
const zOffsets = new Set<number>([0, 1]);
part.internalPartitions.forEach(p => {
if (p.axis === 'x') xOffsets.add(p.offset);
if (p.axis === 'y') zOffsets.add(p.offset);
});
const xSplits = Array.from(xOffsets).sort((a, b) => a - b);
const zSplits = Array.from(zOffsets).sort((a, b) => a - b);
const numCols = xSplits.length - 1;
const numRows = zSplits.length - 1;
if (numCols === 0 || numRows === 0) return [];
// Union-Find для объединения ячеек, не разделенных стеной
const parent = new Int32Array(numCols * numRows).map((_, i) => i);
const find = (i: number): number => {
if (parent[i] === i) return i;
parent[i] = find(parent[i]);
return parent[i];
}
const union = (i: number, j: number) => {
const rootI = find(i);
const rootJ = find(j);
if (rootI !== rootJ) parent[rootJ] = rootI;
}
const getIdx = (c: number, r: number) => r * numCols + c;
// Вертикальные границы (X)
for (let i = 0; i < numCols - 1; i++) {
const boundaryX = xSplits[i + 1];
for (let j = 0; j < numRows; j++) {
const zMid = (zSplits[j] + zSplits[j + 1]) / 2;
// Проверяем наличие перегородки axis='x'
const isBlocked = part.internalPartitions.some(p =>
p.axis === 'x' &&
Math.abs(p.offset - boundaryX) < 0.001 &&
(p.min ?? 0) <= zMid && (p.max ?? 1) >= zMid
);
if (!isBlocked) union(getIdx(i, j), getIdx(i + 1, j));
}
}
// Горизонтальные границы (Z/Y)
for (let j = 0; j < numRows - 1; j++) {
const boundaryZ = zSplits[j + 1];
for (let i = 0; i < numCols; i++) {
const xMid = (xSplits[i] + xSplits[i + 1]) / 2;
// Проверяем наличие перегородки axis='y'
const isBlocked = part.internalPartitions.some(p =>
p.axis === 'y' &&
Math.abs(p.offset - boundaryZ) < 0.001 &&
(p.min ?? 0) <= xMid && (p.max ?? 1) >= xMid
);
if (!isBlocked) union(getIdx(i, j), getIdx(i, j + 1));
}
}
// Агрегируем регионы
const regions: Record<number, { minC: number, maxC: number, minR: number, maxR: number }> = {};
for (let j = 0; j < numRows; j++) {
for (let i = 0; i < numCols; i++) {
const root = find(getIdx(i, j));
if (!regions[root]) regions[root] = { minC: i, maxC: i, minR: j, maxR: j };
else {
const r = regions[root];
r.minC = Math.min(r.minC, i);
r.maxC = Math.max(r.maxC, i);
r.minR = Math.min(r.minR, j);
r.maxR = Math.max(r.maxR, j);
}
}
}
return Object.values(regions).map((r, idx) => {
const fXStart = xSplits[r.minC];
const fXEnd = xSplits[r.maxC + 1];
const fZStart = zSplits[r.minR];
const fZEnd = zSplits[r.maxR + 1];
const fracW = fXEnd - fXStart;
const fracD = fZEnd - fZStart;
const dimX = Math.max(0, fracW * (part.width - thickness) - thickness);
const dimZ = Math.max(0, fracD * (part.depth - thickness) - thickness);
const cx = -part.width / 2 + (fXStart + fXEnd) / 2 * part.width;
const cz = -part.depth / 2 + (fZStart + fZEnd) / 2 * part.depth;
return {
key: `region-${idx}`,
pos: [cx, thickness + 0.2, cz] as [number, number, number],
text: `${dimX.toFixed(0)} x ${dimZ.toFixed(0)}`
};
});
}, [part, thickness]);
return ( return (
<group <group position={[part.x + part.width/2, 0, part.y + part.depth/2]}>
position={[part.x + part.width / 2, 0, part.y + part.depth / 2]} <mesh
geometry={geometry}
onClick={(e) => { e.stopPropagation(); onClick(); }} onClick={(e) => { e.stopPropagation(); onClick(); }}
> >
{/* Сама модель */}
<mesh geometry={geometry}>
<meshStandardMaterial <meshStandardMaterial
color={isSelected ? '#f59e0b' : part.color} color={isSelected ? '#f59e0b' : part.color}
roughness={0.5} roughness={0.5}
metalness={0.1} metalness={0.1}
side={THREE.DoubleSide}
/> />
</mesh> </mesh>
{/* Текстовые метки размеров внутри каждой ячейки */}
{dimLabels.map(label => (
<Text
key={label.key}
position={label.pos}
rotation={[-Math.PI / 2, 0, 0]}
fontSize={Math.min(part.width, part.depth) * 0.035}
color="#1e293b"
anchorX="center"
anchorY="middle"
characters="0123456789x "
>
{label.text}
</Text>
))}
{/* Белая подсветка при выборе */}
{isSelected && ( {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} /> <lineBasicMaterial color="white" linewidth={2} />
</lineSegments> </lineSegments>
)} )}
@@ -194,151 +67,70 @@ const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, perfor
); );
}; };
// --- PreviewStep (Основной компонент) ---
interface Props { interface Props {
parts: GeneratedPart[]; parts: GeneratedPart[];
config: AppConfig; 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 [selectedId, setSelectedId] = useState<string | null>(null);
const [isZipping, setIsZipping] = useState(false); const [isZipping, setIsZipping] = useState(false);
const [shareUrlCopied, setShareUrlCopied] = useState(false);
const itemRefs = useRef<{ [key: string]: HTMLDivElement | null }>({}); const itemRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});
// Скролл к выбранной детали в списке
useEffect(() => { useEffect(() => {
if (selectedId && itemRefs.current[selectedId]) { if (selectedId && itemRefs.current[selectedId]) {
itemRefs.current[selectedId]?.scrollIntoView({ behavior: 'smooth', block: 'center' }); itemRefs.current[selectedId]?.scrollIntoView({
behavior: 'smooth',
block: 'center'
});
} }
}, [selectedId]); }, [selectedId]);
// Скачивание одной детали
const handleDownload = (part: GeneratedPart) => { const handleDownload = (part: GeneratedPart) => {
const geometry = createBinGeometry( const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness, config.perforation);
part.width,
part.depth,
part.height,
config.wallThickness,
config.cornerRadius,
part.internalPartitions, // <--- ВАЖНО для STL
config.perforation
);
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial()); const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
exportSTL(mesh, `${part.name.replace(/\s+/g, '_')}.stl`); exportSTL(mesh, `${part.name.replace(/\s+/g, '_')}.stl`);
}; };
// Скачивание всего архивом
const handleDownloadAll = async () => { const handleDownloadAll = async () => {
if (isZipping) return; if (isZipping) return;
setIsZipping(true); setIsZipping(true);
try { try {
console.log("Starting ZIP generation...");
if (typeof JSZip === 'undefined' && !JSZip) {
throw new Error("Библиотека JSZip не загружена.");
}
const zip = new JSZip(); const zip = new JSZip();
parts.forEach(part => { parts.forEach(part => {
const geometry = createBinGeometry( const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness, config.perforation);
part.width,
part.depth,
part.height,
config.wallThickness,
config.cornerRadius,
part.internalPartitions, // <--- ВАЖНО для STL
config.perforation
);
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial()); const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
const stlData = generateSTL(mesh); const stlData = generateSTL(mesh);
zip.file(`${part.name.replace(/\s+/g, '_')}.stl`, stlData); zip.file(`${part.name.replace(/\s+/g, '_')}.stl`, stlData);
}); });
const content = await zip.generateAsync({ type: "blob" }); const content = await zip.generateAsync({ type: "blob" });
const link = document.createElement('a'); const link = document.createElement('a');
link.href = URL.createObjectURL(content); link.href = URL.createObjectURL(content);
link.download = "PrintFit_Project.zip"; link.download = "PrintFit_Project.zip";
document.body.appendChild(link); document.body.appendChild(link);
link.click(); link.click();
document.body.removeChild(link); document.body.removeChild(link);
} catch (e: any) { } catch (e: any) {
alert(`Ошибка архивации: ${e.message}`); console.error("Failed to create zip archive", e);
alert(`Ошибка при создании архива: ${e.message || 'Неизвестная ошибка'}`);
} finally { } finally {
setIsZipping(false); 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 ( return (
<div className="flex flex-col h-full"> <div className="flex flex-col lg:flex-row h-full gap-6">
{/* Верхняя панель: Размеры + Поделиться */} {/* 3D Viewer */}
<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 Просмотр */}
<div className="flex-1 bg-slate-900 rounded-xl overflow-hidden shadow-2xl border border-slate-800 relative min-h-[400px]"> <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="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"> <div className="flex items-center gap-2 mb-1 text-primary font-bold">
@@ -348,6 +140,7 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
<li> ЛКМ: Вращение</li> <li> ЛКМ: Вращение</li>
<li> ПКМ: Перемещение</li> <li> ПКМ: Перемещение</li>
<li> Скролл: Масштаб</li> <li> Скролл: Масштаб</li>
<li className="text-accent mt-2 font-semibold"> Клик по детали для выбора</li>
</ul> </ul>
</div> </div>
@@ -363,9 +156,12 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
> >
<Suspense fallback={null}> <Suspense fallback={null}>
<color attach="background" args={['#0f172a']} /> <color attach="background" args={['#0f172a']} />
<ambientLight intensity={0.7} /> <ambientLight intensity={0.7} />
<directionalLight position={[100, 200, 50]} intensity={1.2} /> <directionalLight position={[100, 200, 50]} intensity={1.2} />
<directionalLight position={[-100, 100, -50]} intensity={0.5} />
<Environment preset="city" /> <Environment preset="city" />
<Center> <Center>
<group> <group>
<DrawerFrame config={config} /> <DrawerFrame config={config} />
@@ -373,21 +169,20 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
<BinMesh <BinMesh
key={part.id} key={part.id}
part={part} part={part}
thickness={config.wallThickness} config={config}
cornerRadius={config.cornerRadius || 0}
perforation={config.perforation}
isSelected={selectedId === part.id} isSelected={selectedId === part.id}
onClick={() => setSelectedId(part.id)} onClick={() => setSelectedId(part.id)}
/> />
))} ))}
</group> </group>
</Center> </Center>
<OrbitControls makeDefault minDistance={10} maxDistance={10000} /> <OrbitControls makeDefault minDistance={10} maxDistance={10000} />
</Suspense> </Suspense>
</Canvas> </Canvas>
</div> </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="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"> <div className="flex justify-between items-center mb-6 shrink-0">
<h2 className="text-xl font-bold flex items-center gap-2 text-primary"> <h2 className="text-xl font-bold flex items-center gap-2 text-primary">
@@ -396,63 +191,59 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
<button <button
onClick={handleDownloadAll} onClick={handleDownloadAll}
disabled={isZipping || parts.length === 0} 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" 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" /> : <Download size={16} />} {isZipping ? (
Архив <>
<Loader2 size={16} className="animate-spin" /> ZIP...
</>
) : (
<>
<Download size={16} /> Скачать все
</>
)}
</button> </button>
</div> </div>
<div className="flex-1 overflow-y-auto pr-1 custom-scrollbar"> <div className="flex-1 overflow-y-auto pr-2 space-y-3 custom-scrollbar">
<div className="grid grid-cols-2 gap-3 pb-4">
{parts.map(part => ( {parts.map(part => (
<div <div
key={part.id} key={part.id}
ref={(el) => { itemRefs.current[part.id] = el }} ref={(el) => { itemRefs.current[part.id] = el }}
className={` 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'}`}
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)} 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 <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" className="w-3 h-3 rounded-full border border-white/10"
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 }} style={{ backgroundColor: part.color }}
/> />
</div> </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">
<div className="text-[10px] text-gray-400 font-mono z-10"> <span className="block text-gray-500 uppercase text-[9px] mb-0.5">Ширина</span>
{part.width.toFixed(0)} × {part.depth.toFixed(0)} × {part.height.toFixed(0)} {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> </div>
{/* Кнопка скачивания */}
<button <button
onClick={(e) => { e.stopPropagation(); handleDownload(part); }} 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" 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={12} /> STL <Download size={14} /> Скачать STL
</button> </button>
</div> </div>
))} ))}
</div> </div>
</div> </div>
</div> </div>
</div>
</div>
); );
}; };
+142 -530
View File
@@ -1,33 +1,40 @@
import * as THREE from 'three'; import * as THREE from 'three';
import { STLExporter, mergeBufferGeometries } from 'three-stdlib'; import { STLExporter, mergeBufferGeometries } from 'three-stdlib';
import { AppConfig, LayoutSplits, GeneratedPart, Partition, PerforationConfig } 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 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; let partCounter = 1;
for (let i = 0; i < xPoints.length - 1; i++) { for (let i = 0; i < xPoints.length - 1; i++) {
for (let j = 0; j < yPoints.length - 1; j++) { 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; // Применяем Tolerance (зазор)
const rawY = yPoints[j] * config.drawer.depth; const realWidth = segmentW - config.printerTolerance;
const internalPartitions = safeParts[`${i}-${j}`] || []; 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; if (realWidth < 1 || realDepth < 1) {
const realX = rawX + (config.printerTolerance / 2); continue;
const realY = rawY + (config.printerTolerance / 2); }
parts.push({ parts.push({
id: `part-${partCounter}`, id: `part-${partCounter}`,
@@ -37,584 +44,189 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
height: config.drawer.height, height: config.drawer.height,
x: realX, x: realX,
y: realY, y: realY,
color: `hsl(${Math.random() * 360}, 70%, 50%)`, color: `hsl(${(partCounter * 137.5) % 360}, 70%, 50%)`
internalPartitions: internalPartitions
}); });
partCounter++; partCounter++;
} }
} }
return parts; return parts;
}; };
// --- ГЕОМЕТРИЯ --- /**
* 2. Создание формы стены с отверстиями (алгоритм из архива)
const createRoundedRectShape = (width: number, height: number, radius: number): THREE.Shape => { */
const shape = new THREE.Shape(); const createPerforatedWallShape = (
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 => {
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(0, 0);
return shape;
};
// Вспомогательная функция: Создание перфорированной пластины (Вертикальная стенка)
const createPerforatedPlate = (
width: number, width: number,
height: number, height: number,
thickness: number, perf: PerforationConfig
perf: PerforationConfig, ): THREE.Shape => {
marginLeft: number = 0,
marginRight: number = 0,
exclusions: { start: number, end: number, yMax?: number }[] = []
): THREE.BufferGeometry => {
const shape = new THREE.Shape(); const shape = new THREE.Shape();
// Основной контур
shape.moveTo(0, 0); shape.moveTo(0, 0);
shape.lineTo(width, 0); shape.lineTo(width, 0);
shape.lineTo(width, height); shape.lineTo(width, height);
shape.lineTo(0, height); shape.lineTo(0, height);
shape.lineTo(0, 0); shape.lineTo(0, 0);
// Генерация отверстий if (!perf.enabled) return shape;
if (perf && perf.enabled && width > perf.size && height > perf.size) {
const { shape: shapeType, size, gap } = perf;
const step = size + gap;
// Отступы: предотвращаем попадание отверстий на сплошные края
const startX = Math.max(gap, marginLeft + gap);
const startY = gap;
const endX = width - Math.max(gap, marginRight + gap);
const endY = height - gap;
// Строки const { size, spacing, shape: type, border } = perf;
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 startX = border;
const r = size / 2; 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 (x - r < marginLeft || x + r > width - marginRight || y - r < 0 || y + r > height) continue; if (cx - size/2 < startX || cx + size/2 > endX || cy - size/2 < startY || cy + size/2 > endY) return;
// Проверка зон исключения const holePath = new THREE.Path();
// Зона активна, если X отверстия входит в [start, end] И Y отверстия ниже yMax (если указан).
// Если y > yMax, исключение не применяется (отверстие выше пересекающей стенки).
// Примечание: y измеряется от низа (0) до верха (height).
// yMax - высота пересекающей перегородки.
const inExclusion = exclusions.some(zone => { if (type === 'circle') {
if (x + r <= zone.start || x - r >= zone.end) return false; // Проверка по оси X holePath.absarc(cx, cy, size / 2, 0, Math.PI * 2, true);
if (zone.yMax !== undefined && y - r > zone.yMax) return false; // Проверка по оси Y (отверстие выше стенки) } else if (type === 'hexagon') {
return true; 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();
if (inExclusion) continue;
if (shapeType === 'circle') {
hole.absarc(x, y, r, 0, Math.PI * 2, true);
} else if (shapeType === 'honeycomb') {
// Шестиугольник (Соты)
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') { shape.holes.push(holePath);
// Треугольник };
const ang1 = -90 * Math.PI / 180;
const ang2 = 30 * Math.PI / 180; // Генерация сетки
const ang3 = 150 * Math.PI / 180; if (type === 'hexagon') {
hole.moveTo(x + r * Math.cos(ang1), y + r * Math.sin(ang1)); const hexHeight = size;
hole.lineTo(x + r * Math.cos(ang2), y + r * Math.sin(ang2)); const hexWidth = size * 0.866;
hole.lineTo(x + r * Math.cos(ang3), y + r * Math.sin(ang3)); const colDist = hexWidth + spacing;
hole.closePath(); const rowDist = (hexHeight * 0.75) + spacing;
}
shape.holes.push(hole); 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++; 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);
}
}
} }
const geo = new THREE.ExtrudeGeometry(shape, { depth: thickness, bevelEnabled: false }); return shape;
// Выдавливание по Z. Стенка плоская в XY.
// Мы хотим, чтобы "thickness" была глубиной по Z.
return geo;
};
// Вспомогательная функция: Создание профиля угла (Выдавленный вертикально)
const createCornerProfile = (radius: number, thickness: number, height: number): THREE.BufferGeometry => {
if (radius <= 0) return new THREE.BufferGeometry();
const shape = new THREE.Shape();
// Создаем сегмент кольца (Полый угол) как единый контур.
// Центр в (0,0).
const innerRadius = Math.max(0.01, radius - thickness); // Гарантируем чуть > 0 для целостности формы
// 1. Начало внешней дуги
shape.moveTo(radius, 0);
// 2. Внешняя дуга (против часовой стрелки) -> К (0, radius)
shape.absarc(0, 0, radius, 0, Math.PI / 2, false);
// 3. Линия к внутреннему концу (0, innerRadius)
shape.lineTo(0, innerRadius);
// 4. Внутренняя дуга (по часовой стрелке) -> К (innerRadius, 0)
shape.absarc(0, 0, innerRadius, Math.PI / 2, 0, true);
// 5. Замыкаем контур
shape.lineTo(radius, 0);
// Выдавливание
// curveSegments 32 для гладкости
const geo = new THREE.ExtrudeGeometry(shape, { depth: height, bevelEnabled: false, curveSegments: 32 });
return geo;
}; };
/**
* 3. Генерация 3D геометрии одного ящика
*/
export const createBinGeometry = ( export const createBinGeometry = (
width: number, width: number,
depth: number, depth: number,
height: number, height: number,
thickness: number, thickness: number,
radius: number = 0,
partitions: Partition[] = [],
perforation?: PerforationConfig perforation?: PerforationConfig
): THREE.BufferGeometry => { ): THREE.BufferGeometry => {
const geometries: THREE.BufferGeometry[] = []; const geometries: THREE.BufferGeometry[] = [];
const perfConfig = perforation || { enabled: false, shape: 'circle', size: 0, spacing: 0, border: 0 };
// ДНО (Floor) - Always same // 1. Пол - Всегда сплошной
const floorShape = createRoundedRectShape(width, depth, radius); // ВАЖНО: .toNonIndexed() нужен для корректного слияния с ExtrudeGeometry
const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false }); const floorGeo = new THREE.BoxGeometry(width, thickness, depth).toNonIndexed();
floorGeo.rotateX(-Math.PI / 2); // Lay flat floorGeo.translate(0, thickness / 2, 0);
geometries.push(floorGeo); geometries.push(floorGeo);
// СТЕНКИ
if (!perforation || !perforation.enabled) {
// --- ЛОГИКА ДЛЯ СПЛОШНЫХ СТЕН (Без перфорации) ---
const outerShape = createRoundedRectShape(width, depth, radius);
const innerRadius = Math.max(0.1, radius - thickness);
const innerWidth = width - (2 * thickness);
const innerDepth = depth - (2 * thickness);
if (innerWidth > 0.1 && innerDepth > 0.1) {
const innerHole = createRoundedRectShape(innerWidth, innerDepth, innerRadius);
outerShape.holes.push(innerHole);
}
const wallHeight = height - thickness; 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);
} else {
// --- ЛОГИКА ДЛЯ ПЕРФОРИРОВАННЫХ СТЕН (Раздельные части) ---
const wallHeight = height - thickness;
// Ограничиваем радиус минимум толщиной стенки для корректных углов
const effRadius = Math.max(radius, thickness);
const straightW = width - 2 * effRadius; if (wallHeight > 0) {
const straightD = depth - 2 * effRadius; const extrudeSettings = {
depth: thickness,
// 1. Углы (4 шт) bevelEnabled: false,
if (effRadius > 0) {
const cornerGeoBase = createCornerProfile(effRadius, thickness, wallHeight);
// 1. Поднимаем: Выдавливание Z -> Y. Форма перемещается в X(+)/Z(+).
cornerGeoBase.rotateX(-Math.PI / 2);
// Базовая форма угла (после rotateX) это Q4 (+X, -Z).
// Логика вращения: -90 градусов на квадрант (Стандартный Y-Rot в Three.js).
// Q4 (0) -> Q1 (-90) -> Q2 (-180/180) -> Q3 (-270/+90).
const positions = [
// Задний Правый (+X, +Z). Q1.
// Поворот -90 (-PI/2).
{ x: width / 2 - effRadius, z: depth / 2 - effRadius, rot: -Math.PI / 2 },
// Задний Левый (-X, +Z). Q2.
// Поворот 180 (PI).
{ x: -(width / 2 - effRadius), z: depth / 2 - effRadius, rot: Math.PI },
// Передний Левый (-X, -Z). Q3.
// Поворот 90 (PI/2). (Эквивалентно -270).
{ x: -(width / 2 - effRadius), z: -(depth / 2 - effRadius), rot: Math.PI / 2 },
// Передний Правый (+X, -Z). Q4.
// Поворот 0.
{ x: width / 2 - effRadius, z: -(depth / 2 - effRadius), rot: 0 }
];
positions.forEach(pos => {
const corner = cornerGeoBase.clone();
corner.rotateY(pos.rot);
corner.translate(pos.x, 0, pos.z); // Старт на Y=0
corner.translate(0, thickness, 0); // Сдвиг на толщину дна
geometries.push(corner);
});
}
// 2. Прямые стены (4 шт) - Центрированы по краям
// ЛОГИКА СБОРА ИСКЛЮЧЕНИЙ ДЛЯ СТЕН
const exclusionsBack: { start: number, end: number, yMax: number }[] = [];
const exclusionsFront: { start: number, end: number, yMax: number }[] = [];
const exclusionsLeft: { start: number, end: number, yMax: number }[] = [];
const exclusionsRight: { start: number, end: number, yMax: number }[] = [];
// Внутренние размеры
const effectiveInnerW = width - 2 * thickness;
const effectiveInnerD = depth - 2 * thickness;
partitions.forEach(p => {
const hEff = Math.max(0.1, p.height - thickness); // Исключаем только до высоты перегородки
// Гарантируем сплошную полосу вокруг перегородки добавлением отступа к зоне исключения
const padding = (perforation?.gap ?? 2) + 1;
if (p.axis === 'x') {
// Идет по глубине (Ось Y в макете).
// Пересекает Переднюю и Заднюю стенки.
const partGlobalX = (-effectiveInnerW / 2) + (effectiveInnerW * p.offset);
const sW = width - 2 * effRadius;
const localXOnWall = partGlobalX + sW / 2;
// Проверка пересечения с активной зоной стены + отступ
if (localXOnWall + thickness / 2 + padding > 0 && localXOnWall - thickness / 2 - padding < sW) {
const zone = {
start: localXOnWall - thickness / 2 - padding,
end: localXOnWall + thickness / 2 + padding,
yMax: hEff
}; };
if ((p.max ?? 1) > 0.99) exclusionsFront.push(zone); // Ближняя // 2. Левая и Правая стенки (Полная глубина)
if ((p.min ?? 0) < 0.01) exclusionsBack.push(zone); // Дальняя // Рисуем профиль шириной = глубине ящика
} const lrShape = createPerforatedWallShape(depth, wallHeight, perfConfig);
// ВАЖНО: .toNonIndexed()
const lrGeo = new THREE.ExtrudeGeometry(lrShape, extrudeSettings).toNonIndexed();
} else { // p.axis === 'y' // Left Wall
// Идет по ширине (Ось X в макете). const leftWall = lrGeo.clone();
// Пересекает Левую и Правую стенки. leftWall.rotateY(-Math.PI / 2);
leftWall.translate(-(width/2) + thickness, thickness, -(depth/2));
geometries.push(leftWall);
const partGlobalZ = (-effectiveInnerD / 2) + (effectiveInnerD * p.offset); // Right Wall
const sD = depth - 2 * effRadius; const rightWall = lrGeo.clone();
const localXOnWall = partGlobalZ + sD / 2; rightWall.rotateY(-Math.PI / 2);
rightWall.translate((width/2), thickness, -(depth/2));
geometries.push(rightWall);
if (localXOnWall + thickness / 2 + padding > 0 && localXOnWall - thickness / 2 - padding < sD) { // 3. Передняя и Задняя стенки (Вставляются между боковыми)
const zone = { // Ширина уменьшена на 2 толщины
start: localXOnWall - thickness / 2 - padding, const wallFBWidth = Math.max(0, width - (2 * thickness));
end: localXOnWall + thickness / 2 + padding, if (wallFBWidth > 0) {
yMax: hEff const fbShape = createPerforatedWallShape(wallFBWidth, wallHeight, perfConfig);
}; const fbGeo = new THREE.ExtrudeGeometry(fbShape, extrudeSettings).toNonIndexed();
if ((p.min ?? 0) < 0.01) { // Front Wall
exclusionsLeft.push(zone); const frontWall = fbGeo.clone();
} frontWall.translate(-(wallFBWidth/2), thickness, (depth/2) - thickness);
if ((p.max ?? 1) > 0.99) { geometries.push(frontWall);
exclusionsRight.push(zone);
}
}
}
});
// Передняя/Задняя // Back Wall
if (straightW > 0.1) { const backWall = fbGeo.clone();
// Стенка 1 (+Z). Это "Передняя" (Ближняя). Контактирует с p.max. backWall.translate(-(wallFBWidth/2), thickness, -(depth/2));
// Использует exclusionsFront. geometries.push(backWall);
const wGeoFront = createPerforatedPlate(straightW, wallHeight, thickness, perforation, 0, 0, exclusionsFront);
wGeoFront.translate(-straightW / 2, 0, 0);
const w1 = wGeoFront.clone();
w1.translate(0, thickness, depth / 2 - thickness);
geometries.push(w1);
// Стенка 2 (-Z). Это "Задняя" (Дальняя). Контактирует с p.min.
// Использует exclusionsBack.
// Нужна проверка маппинга (Поворот 180).
// p.offset увеличивает X. Стенка повернута на 180, значит X инвертирован.
// Маппим exclusionsBack.
const exclusionsBackMapped = exclusionsBack.map(e => ({
start: straightW - e.end,
end: straightW - e.start,
yMax: e.yMax
}));
const wGeoBack = createPerforatedPlate(straightW, wallHeight, thickness, perforation, 0, 0, exclusionsBackMapped);
wGeoBack.translate(-straightW / 2, 0, 0);
const w2 = wGeoBack.clone();
w2.rotateY(Math.PI);
w2.translate(0, thickness, -(depth / 2 - thickness));
geometries.push(w2);
}
// Левая/Правая
if (straightD > 0.1) {
// Стенка 3 (Правая +X).
// Пластина 0..straightD по X, 0..wallHeight по Y. Толщина по Z.
// Хотим разместить на X = width/2.
// Нужно повернуть -PI/2 вокруг Y чтобы выровнять ось X пластины с мировой осью Z.
const wGeoRight = createPerforatedPlate(straightD, wallHeight, thickness, perforation, 0, 0, exclusionsRight);
wGeoRight.translate(-straightD / 2, 0, 0); // Центр X пластины
const w3 = wGeoRight.clone();
w3.rotateY(-Math.PI / 2); // Поворот
w3.translate(width / 2, thickness, 0); // Позиция на X=width/2
geometries.push(w3);
// Стенка 4 (Левая -X).
// Также повернута на PI/2.
// Толщина по Z станем Мировой X (направо).
// Хотим на X=-width/2.
const exclusionsLeftMapped = exclusionsLeft.map(e => ({
start: straightD - e.end,
end: straightD - e.start,
yMax: e.yMax
}));
const wGeoLeft = createPerforatedPlate(straightD, wallHeight, thickness, perforation, 0, 0, exclusionsLeftMapped);
wGeoLeft.translate(-straightD / 2, 0, 0); // Центр X пластины
const w4 = wGeoLeft.clone();
w4.rotateY(Math.PI / 2);
w4.translate(-width / 2, thickness, 0); // Позиция на X=-width/2
geometries.push(w4);
} }
} }
// Слияние в один меш
// ВНУТРЕННИЕ ПЕРЕГОРОДКИ
const innerWidth = width - (2 * thickness);
const innerDepth = depth - (2 * thickness); // Приблизительное полезное пространство
partitions.forEach(p => {
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);
// ИСПРАВЛЕНИЕ: Вычитаем толщину, так как перегородки стоят НА дне
const effectiveHeight = Math.max(0.1, p.height - thickness);
// --- ЛОГИКА ДЛЯ ПЕРФОРИРОВАННЫХ ПЕРЕГОРОДОК ---
// Если включено, используем Пластину. Иначе - сплошное Выдавливание.
const usePerf = perforation && perforation.enabled;
let pX = 0, pY = 0; // Объявляем здесь для видимости в Скруглениях
if (usePerf) {
// Вычисляем точную геометрию
let pLen = 0;
if (p.axis === 'x') {
// Ось X -> Разделитель идет вдоль Y (Глубина)
pLen = lengthRatio * innerDepth;
pX = (-innerWidth / 2) + (innerWidth * p.offset);
pY = (-innerDepth / 2) + (innerDepth * midRatio); // Центр перегородки
// Вычисляем исключения для внутренней перегородки
const partExclusions: { start: number, end: number, yMax?: number }[] = [];
// Эта перегородка 'p' (Ось X, идет по Глубине).
// Пересекается перегородками 'n' (Ось Y, идут по Ширине).
partitions.forEach(n => {
if (n.axis !== 'y') return; // Пересекаются только ортогональные перегородки
// Проверяем, пересекает ли n перегородку p
// Y-координата пересечения:
const nY = (-innerDepth / 2) + (innerDepth * n.offset);
const pStartGlobal = pY - pLen / 2;
const pEndGlobal = pY + pLen / 2;
// И проверяем, покрывает ли n позицию X перегородки p.
// n идет по X от nMin до nMax.
const nXStart = (-innerWidth / 2) + (innerWidth * (n.min ?? 0));
const nXEnd = (-innerWidth / 2) + (innerWidth * (n.max ?? 1));
const pXLoc = pX;
if (nY >= pStartGlobal && nY <= pEndGlobal && pXLoc >= nXStart && pXLoc <= nXEnd) {
// Пересечение подтверждено.
// Вычисляем локальные координаты на пластине p.
// p идет по Y. Локальный X пластины мапится на глобальный Y.
const nHeight = Math.max(0.1, n.height - thickness);
const localX = nY - pY + pLen / 2;
partExclusions.push({ start: localX - thickness / 2, end: localX + thickness / 2, yMax: nHeight });
}
});
// Добавляем отступы (сплошные концы)
const margin = thickness;
const plate = createPerforatedPlate(pLen, effectiveHeight, thickness, perforation!, margin, margin, partExclusions);
plate.translate(-pLen / 2, 0, 0); // Центр X
// Поворачиваем для выравнивания по Глубине (вдоль Z)
// Пластина X -> Z
plate.rotateY(-Math.PI / 2);
// Позиционирование
// Пластина теперь вертикально по Z. Толщина по X.
plate.translate(pX + thickness / 2, thickness, pY);
geometries.push(plate);
} else {
// Ось Y -> Разделитель идет вдоль X (Ширина)
pLen = lengthRatio * innerWidth;
pX = (-innerWidth / 2) + (innerWidth * midRatio);
pY = (-innerDepth / 2) + (innerDepth * p.offset);
// Вычисление исключений
const partExclusions: { start: number, end: number, yMax?: number }[] = [];
// Эта перегородка 'p' (Ось Y, идет по Ширине).
// Пересекается перегородками 'n' (Ось X, идут по Глубине).
partitions.forEach(n => {
if (n.axis !== 'x') return;
const nX = (-innerWidth / 2) + (innerWidth * n.offset);
const pStartGlobal = pX - pLen / 2; // Диапазон X для p
const pEndGlobal = pX + pLen / 2;
const nYStart = (-innerDepth / 2) + (innerDepth * (n.min ?? 0));
const nYEnd = (-innerDepth / 2) + (innerDepth * (n.max ?? 1));
const pYLoc = pY;
if (nX >= pStartGlobal && nX <= pEndGlobal && pYLoc >= nYStart && pYLoc <= nYEnd) {
// Пересечение подтверждено
const nHeight = Math.max(0.1, n.height - thickness); // ВЫСОТА ПЕРЕСЕКАЮЩЕЙ ПЕРЕГОРОДКИ
const localX = nX - pX + pLen / 2;
partExclusions.push({ start: localX - thickness / 2, end: localX + thickness / 2, yMax: nHeight });
}
});
const margin = thickness;
const plate = createPerforatedPlate(pLen, effectiveHeight, thickness, perforation!, margin, margin, partExclusions);
plate.translate(-pLen / 2, 0, 0); // Центр X
// Уже выровнено по X. Толщина по Z.
// Диапазон Z [0, th]. Мы хотим [-th/2, th/2] относительно pY.
plate.translate(0, 0, -thickness / 2);
// Перемещение на позицию
plate.translate(pX, thickness, pY);
geometries.push(plate);
}
} else {
// --- ЛОГИКА ДЛЯ СПЛОШНЫХ ПЕРЕГОРОДОК ---
let pWidth = 0, pDepth = 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: effectiveHeight, bevelEnabled: false });
partGeo.rotateX(-Math.PI / 2);
partGeo.translate(pX, thickness, pY);
geometries.push(partGeo);
}
// Логика скруглений для перегородок (Оставляем сплошными для прочности/эстетики)
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) => {
const hEff = Math.max(0.1, h - thickness);
if (hEff <= 1) return;
const geo = new THREE.ExtrudeGeometry(filletShape, { depth: hEff, 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); const merged = mergeBufferGeometries(geometries);
if (merged) merged.computeVertexNormals(); return merged || new THREE.BoxGeometry(1, 1, 1).toNonIndexed();
return merged || new THREE.BoxGeometry(1, 1, 1);
}; };
export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => { export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {
const exporter = new STLExporter(); const exporter = new STLExporter();
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;
}; };
export const exportSTL = (mesh: THREE.Object3D, filename: string) => { export const exportSTL = (mesh: THREE.Object3D, filename: string) => {
const result = generateSTL(mesh); const result = generateSTL(mesh);
const blob = new Blob([result as any], { type: 'application/octet-stream' }); const blob = new Blob([result], { type: 'application/octet-stream' });
const link = document.createElement('a'); const link = document.createElement('a');
link.href = URL.createObjectURL(blob); link.href = URL.createObjectURL(blob);
link.download = filename; link.download = filename;
+13 -13
View File
@@ -4,29 +4,29 @@ export interface DrawerDimensions {
height: number; height: number;
} }
export type PerforationPattern = 'circle' | 'hexagon' | 'triangle';
export interface PerforationConfig {
enabled: boolean;
pattern: PerforationPattern;
diameter: number; // Размер отверстия
spacing: number; // Расстояние между центрами (шаг)
}
export interface AppConfig { export interface AppConfig {
drawer: DrawerDimensions; drawer: DrawerDimensions;
wallThickness: number; wallThickness: number;
printerTolerance: number; printerTolerance: number;
cornerRadius: number; cornerRadius: number;
perforation: PerforationConfig; perforation: PerforationConfig; // Новая секция
}
export type PerforationShape = 'circle' | 'honeycomb' | 'triangle' | 'diamond';
export interface PerforationConfig {
enabled: boolean;
shape: PerforationShape;
size: number;
gap: number;
} }
export interface Partition { export interface Partition {
id: string; id: string;
axis: 'x' | 'y'; axis: 'x' | 'y';
offset: number; // Позиция (0.0 - 1.0) offset: number;
min: number; // Начало стенки (0.0 - 1.0) min: number;
max: number; // Конец стенки (0.0 - 1.0) max: number;
height: number; height: number;
rounded: boolean; rounded: boolean;
} }