Compare commits
32
Commits
6990f18c78
...
test
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
de36479da1 | ||
|
|
5664e99554 | ||
|
|
9ff2c76912 | ||
|
|
21a41ccf05 | ||
|
|
01dbf52fc7 | ||
|
|
34543d07c5 | ||
|
|
aaff0d06df | ||
|
|
531b5dc0b1 | ||
|
|
356873fb0e | ||
|
|
96bf976b64 | ||
|
|
43a54c99a6 | ||
|
|
0f071c9587 | ||
|
|
ade10e0aaf | ||
|
|
918d9e0ea7 | ||
|
|
d9bc3bda17 | ||
|
|
fe1f5df710 | ||
|
|
6daa10746b | ||
|
|
33a5b8d44d | ||
|
|
803c7213d5 | ||
|
|
56183b3ada | ||
|
|
272b2b6f77 | ||
|
|
454e6cf822 | ||
|
|
1e9a1d288a | ||
|
|
8c39e18de4 | ||
|
|
94eb2f00b2 | ||
|
|
eb8c5c48c7 | ||
|
|
490adb8ac6 | ||
|
|
6cd7a5194d | ||
|
|
438c7b6615 | ||
|
|
d85cac8a16 | ||
|
|
621958c0d4 | ||
|
|
57a5695c2a |
+19
@@ -0,0 +1,19 @@
|
|||||||
|
# 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;"]
|
||||||
@@ -1,20 +1,80 @@
|
|||||||
<div align="center">
|
# PrintFit - Генератор Органайзеров для 3D Печати
|
||||||
<img width="1200" height="475" alt="GHBanner" src="https://github.com/user-attachments/assets/0aa67016-6eaf-458a-adb2-6e31a0763ed6" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
# Run and deploy your AI Studio app
|
PrintFit — это мощный веб-инструмент для создания параметрических органайзеров, разделителей и ящиков, оптимизированных для 3D-печати. Приложение позволяет легко проектировать системы хранения под любые размеры с возможностью детальной настройки перегородок и перфорации.
|
||||||
|
|
||||||
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).
|
||||||
|
- **Настройка плотности**: Регулировка размера отверстий и отступов между ними.
|
||||||
|
|
||||||
1. Install dependencies:
|
### 🖥 Интерактивный 3D Предпросмотр
|
||||||
`npm install`
|
- **Real-time рендеринг**: Мгновенное отображение изменений в браузере с помощью Three.js.
|
||||||
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. Вы можете свободно использовать, изменять и распространять его.
|
||||||
|
|||||||
+45
-39
@@ -8,17 +8,17 @@ import { parseShareUrl } from './utils/share';
|
|||||||
import { ChevronRight, ChevronLeft, Box, AlertTriangle } from 'lucide-react';
|
import { ChevronRight, ChevronLeft, Box, AlertTriangle } from 'lucide-react';
|
||||||
|
|
||||||
// ВАЖНО: ErrorBoundary должен быть ЗДЕСЬ, снаружи компонента App
|
// ВАЖНО: ErrorBoundary должен быть ЗДЕСЬ, снаружи компонента App
|
||||||
class ErrorBoundary extends React.Component<{children: React.ReactNode}, {hasError: boolean}> {
|
class ErrorBoundary extends React.Component<{ children: React.ReactNode }, { hasError: boolean }> {
|
||||||
state = { hasError: false };
|
state = { hasError: false };
|
||||||
static getDerivedStateFromError() { return { hasError: true }; }
|
static getDerivedStateFromError() { return { hasError: true }; }
|
||||||
render() {
|
render() {
|
||||||
if (this.state.hasError) return (
|
if (this.state.hasError) return (
|
||||||
<div className="h-full flex flex-col items-center justify-center text-red-400">
|
<div className="h-full flex flex-col items-center justify-center text-red-400">
|
||||||
<AlertTriangle size={32} className="mb-2"/>
|
<AlertTriangle size={32} className="mb-2" />
|
||||||
<p>Ошибка отрисовки интерфейса.</p>
|
<p>Ошибка отрисовки интерфейса.</p>
|
||||||
<button onClick={() => window.location.reload()} className="mt-4 px-4 py-2 bg-slate-800 rounded hover:bg-slate-700 transition-colors">
|
<button onClick={() => window.location.reload()} className="mt-4 px-4 py-2 bg-slate-800 rounded hover:bg-slate-700 transition-colors">
|
||||||
Перезагрузить
|
Перезагрузить
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
return this.props.children;
|
return this.props.children;
|
||||||
@@ -29,10 +29,16 @@ const App = () => {
|
|||||||
const [step, setStep] = useState(1);
|
const [step, setStep] = useState(1);
|
||||||
|
|
||||||
const [config, setConfig] = useState<AppConfig>({
|
const [config, setConfig] = useState<AppConfig>({
|
||||||
drawer: { width: 300, depth: 400, height: 80 },
|
drawer: { width: 100, depth: 100, height: 100 },
|
||||||
wallThickness: 1.2,
|
wallThickness: 0.8,
|
||||||
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>({
|
||||||
@@ -47,9 +53,9 @@ const App = () => {
|
|||||||
if (sharedData) {
|
if (sharedData) {
|
||||||
setConfig(sharedData.config);
|
setConfig(sharedData.config);
|
||||||
setSplits({
|
setSplits({
|
||||||
x: Array.isArray(sharedData.splits.x) ? sharedData.splits.x : [],
|
x: Array.isArray(sharedData.splits.x) ? sharedData.splits.x : [],
|
||||||
y: Array.isArray(sharedData.splits.y) ? sharedData.splits.y : [],
|
y: Array.isArray(sharedData.splits.y) ? sharedData.splits.y : [],
|
||||||
partitions: sharedData.splits.partitions || {}
|
partitions: sharedData.splits.partitions || {}
|
||||||
});
|
});
|
||||||
setStep(3);
|
setStep(3);
|
||||||
window.history.replaceState({}, '', window.location.pathname);
|
window.history.replaceState({}, '', window.location.pathname);
|
||||||
@@ -69,56 +75,56 @@ 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">
|
||||||
<div className="bg-primary p-2 rounded-lg"><Box className="text-white" size={20} /></div>
|
<div className="bg-primary p-2 rounded-lg"><Box className="text-white" size={20} /></div>
|
||||||
<div><h1 className="text-xl font-bold tracking-tight">PrintFit</h1><p className="text-xs text-gray-400">Генератор органайзеров</p></div>
|
<div><h1 className="text-xl font-bold tracking-tight">PrintFit</h1><p className="text-xs text-gray-400">Генератор органайзеров</p></div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-4 text-sm font-medium">
|
<div className="flex items-center gap-4 text-sm font-medium">
|
||||||
{[1, 2, 3].map((num) => (
|
{[1, 2, 3].map((num) => (
|
||||||
<div key={num} className={`flex items-center gap-2 ${step === num ? 'text-primary' : 'text-gray-500'}`}>
|
<div key={num} className={`flex items-center gap-2 ${step === num ? 'text-primary' : 'text-gray-500'}`}>
|
||||||
<span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs border ${step === num ? 'border-primary bg-primary/10' : 'border-gray-600'}`}>{num}</span>
|
<span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs border ${step === num ? 'border-primary bg-primary/10' : 'border-gray-600'}`}>{num}</span>
|
||||||
<span className="hidden md:inline">{num === 1 ? 'Настройки' : num === 2 ? 'Макет' : 'Экспорт'}</span>
|
<span className="hidden md:inline">{num === 1 ? 'Настройки' : num === 2 ? 'Макет' : 'Экспорт'}</span>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</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">
|
||||||
<ConfigStep config={config} onChange={setConfig} />
|
<ConfigStep config={config} onChange={setConfig} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{step === 2 && (
|
{step === 2 && (
|
||||||
<div className="h-full flex flex-col animate-fade-in min-h-0">
|
<div className="h-full flex flex-col animate-fade-in min-h-0">
|
||||||
<ErrorBoundary>
|
<ErrorBoundary>
|
||||||
<LayoutStep config={config} splits={splits} onChange={setSplits} />
|
<LayoutStep config={config} splits={splits} onChange={setSplits} />
|
||||||
</ErrorBoundary>
|
</ErrorBoundary>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{step === 3 && (
|
{step === 3 && (
|
||||||
<div className="h-full flex flex-col animate-fade-in min-h-0">
|
<div className="h-full flex flex-col animate-fade-in min-h-0">
|
||||||
<PreviewStep parts={parts} config={config} splits={splits} />
|
<PreviewStep parts={parts} config={config} splits={splits} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</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>
|
||||||
<div className="text-sm text-gray-500">{step === 2 && <span className="text-accent font-mono">Ячеек: {parts.length}</span>}</div>
|
<div className="text-sm text-gray-500">{step === 2 && <span className="text-accent font-mono">Ячеек: {parts.length}</span>}</div>
|
||||||
{step < 3 ? (
|
{step < 3 ? (
|
||||||
<button onClick={() => setStep(s => Math.min(3, s + 1))} className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold bg-primary text-white hover:bg-blue-600 shadow-lg shadow-blue-900/20 transition-all active:scale-95">Далее <ChevronRight size={18} /></button>
|
<button onClick={() => setStep(s => Math.min(3, s + 1))} className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold bg-primary text-white hover:bg-blue-600 shadow-lg shadow-blue-900/20 transition-all active:scale-95">Далее <ChevronRight size={18} /></button>
|
||||||
) : (
|
) : (
|
||||||
<button onClick={() => { setStep(1); setSplits({x: [], y: [], partitions: {}}); window.history.replaceState({}, '', window.location.pathname); }} className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold text-gray-400 hover:text-white transition-colors border border-transparent hover:border-slate-700">Новый проект</button>
|
<button onClick={() => { setStep(1); setSplits({ x: [], y: [], partitions: {} }); window.history.replaceState({}, '', window.location.pathname); }} className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold text-gray-400 hover:text-white transition-colors border border-transparent hover:border-slate-700">Новый проект</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
|
|||||||
+232
-65
@@ -1,6 +1,6 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { AppConfig } from '../types';
|
import { AppConfig, PerforationShape } from '../types';
|
||||||
import { Ruler, Box, Layers, Minimize2, CircleDashed } from 'lucide-react';
|
import { Ruler, Box, Layers, Minimize2, CircleDashed, Grid, Circle, Hexagon, Triangle } from 'lucide-react';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
config: AppConfig;
|
config: AppConfig;
|
||||||
@@ -39,113 +39,280 @@ const NumberInput = ({
|
|||||||
</div>
|
</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) => {
|
const updateDrawer = (key: keyof AppConfig['drawer'], val: number) => {
|
||||||
onChange({ ...config, drawer: { ...config.drawer, [key]: val } });
|
onChange({ ...config, drawer: { ...config.drawer, [key]: val } });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const updatePerforation = (key: keyof AppConfig['perforation'], val: any) => {
|
||||||
|
onChange({ ...config, perforation: { ...config.perforation, [key]: val } })
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 animate-fade-in">
|
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 animate-fade-in space-y-8">
|
||||||
<h2 className="text-xl font-bold mb-6 flex items-center gap-2 text-primary">
|
|
||||||
<Box size={24} /> 1. Размеры
|
|
||||||
</h2>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
{/* SECTION 1: Dimensions & Settings */}
|
||||||
{/* Drawer Dimensions */}
|
<div>
|
||||||
<div className="bg-slate-800/50 p-4 rounded-lg border border-slate-700">
|
<h2 className="text-xl font-bold mb-6 flex items-center gap-2 text-primary">
|
||||||
<h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-gray-200">
|
<Box size={24} /> 1. Размеры
|
||||||
<Ruler className="text-accent" size={18} /> Внутренние размеры ящика
|
</h2>
|
||||||
</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>
|
|
||||||
|
|
||||||
{/* Settings */}
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||||
<div className="bg-slate-800/50 p-4 rounded-lg border border-slate-700 flex flex-col justify-center">
|
{/* Drawer Dimensions */}
|
||||||
<h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-gray-200">
|
<div className="bg-slate-800/50 p-4 rounded-lg border border-slate-700">
|
||||||
<Layers className="text-accent" size={18} /> Параметры печати
|
<h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-gray-200">
|
||||||
</h3>
|
<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>
|
||||||
|
|
||||||
{/* Wall Thickness */}
|
{/* Settings */}
|
||||||
<div className="mb-6">
|
<div className="bg-slate-800/50 p-4 rounded-lg border border-slate-700 flex flex-col justify-center">
|
||||||
<div className="flex justify-between items-center mb-2">
|
<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>
|
<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">
|
<span className="text-primary font-bold bg-primary/10 px-2 py-1 rounded text-sm border border-primary/20">
|
||||||
{config.wallThickness.toFixed(1)} мм
|
{config.wallThickness.toFixed(1)} мм
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
<span className="text-xs text-gray-500 font-mono">0.4</span>
|
<span className="text-xs text-gray-500 font-mono">0.4</span>
|
||||||
<input
|
<input
|
||||||
type="range"
|
type="range"
|
||||||
min="0.4"
|
min="0.4"
|
||||||
max="3.2"
|
max="3.2"
|
||||||
step="0.1"
|
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-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>
|
<span className="text-xs text-gray-500 font-mono">3.2</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Corner Radius (NEW) */}
|
{/* Corner Radius */}
|
||||||
<div className="mb-6">
|
<div className="mb-6">
|
||||||
<div className="flex justify-between items-center mb-2">
|
<div className="flex justify-between items-center mb-2">
|
||||||
<label className="text-sm font-medium text-gray-300 flex items-center gap-1">
|
<label className="text-sm font-medium text-gray-300 flex items-center gap-1">
|
||||||
<CircleDashed size={14} className="text-gray-400"/> Радиус скругления
|
<CircleDashed size={14} className="text-gray-400" /> Радиус скругления
|
||||||
</label>
|
</label>
|
||||||
<span className="text-purple-400 font-bold bg-purple-400/10 px-2 py-1 rounded text-sm border border-purple-400/20">
|
<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} мм
|
{config.cornerRadius?.toFixed(0) || 0} мм
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
<span className="text-xs text-gray-500 font-mono">0</span>
|
<span className="text-xs text-gray-500 font-mono">0</span>
|
||||||
<input
|
<input
|
||||||
type="range"
|
type="range"
|
||||||
min="0"
|
min="0"
|
||||||
max="20"
|
max="20"
|
||||||
step="1"
|
step="1"
|
||||||
value={config.cornerRadius || 0}
|
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-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>
|
<span className="text-xs text-gray-500 font-mono">20</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Printer Tolerance */}
|
{/* Printer Tolerance */}
|
||||||
<div className="mb-4">
|
<div className="mb-4">
|
||||||
<div className="flex justify-between items-center mb-2">
|
<div className="flex justify-between items-center mb-2">
|
||||||
<label className="text-sm font-medium text-gray-300 flex items-center gap-1">
|
<label className="text-sm font-medium text-gray-300 flex items-center gap-1">
|
||||||
<Minimize2 size={14} className="text-gray-400"/> Зазор (Tolerance)
|
<Minimize2 size={14} className="text-gray-400" /> Зазор (Tolerance)
|
||||||
</label>
|
</label>
|
||||||
<span className="text-accent font-bold bg-accent/10 px-2 py-1 rounded text-sm border border-accent/20">
|
<span className="text-accent font-bold bg-accent/10 px-2 py-1 rounded text-sm border border-accent/20">
|
||||||
{config.printerTolerance.toFixed(1)} мм
|
{config.printerTolerance.toFixed(1)} мм
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
<span className="text-xs text-gray-500 font-mono">0.0</span>
|
<span className="text-xs text-gray-500 font-mono">0.0</span>
|
||||||
<input
|
<input
|
||||||
type="range"
|
type="range"
|
||||||
min="0.0"
|
min="0.0"
|
||||||
max="2.0"
|
max="2.0"
|
||||||
step="0.1"
|
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-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>
|
<span className="text-xs text-gray-500 font-mono">2.0</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* SECTION 2: Perforation */}
|
||||||
|
<div className="bg-slate-800/30 p-6 rounded-lg border border-slate-700/50">
|
||||||
|
<div className="flex items-center justify-between mb-6">
|
||||||
|
<h3 className="text-lg font-semibold flex items-center gap-2 text-blue-400">
|
||||||
|
<Grid size={20} /> 2. Перфорация (узоры)
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<span className="text-sm font-medium text-gray-400 uppercase tracking-wider">Включено</span>
|
||||||
|
<button
|
||||||
|
onClick={() => updatePerforation('enabled', !config.perforation.enabled)}
|
||||||
|
className={`w-12 h-6 rounded-full relative transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 ${config.perforation.enabled ? 'bg-blue-600' : 'bg-slate-600'}`}
|
||||||
|
>
|
||||||
|
<span className={`block w-4 h-4 rounded-full bg-white shadow transform transition-transform duration-200 ease-in-out absolute top-1 ${config.perforation.enabled ? 'translate-x-7' : 'translate-x-1'}`} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className={`grid grid-cols-1 md:grid-cols-2 gap-8 transition-all duration-300 ${config.perforation.enabled ? 'opacity-100 pointer-events-auto' : 'opacity-40 pointer-events-none filter blur-[1px]'}`}>
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-bold text-gray-500 uppercase mb-3 block">Тип узора</label>
|
||||||
|
<div className="flex gap-4 mb-8">
|
||||||
|
{[
|
||||||
|
{ id: 'circle', icon: Circle, label: 'Круг' },
|
||||||
|
{ id: 'honeycomb', icon: Hexagon, label: 'Соты' },
|
||||||
|
{ id: 'triangle', icon: Triangle, label: 'Треуг.' }
|
||||||
|
].map((item) => (
|
||||||
|
<button
|
||||||
|
key={item.id}
|
||||||
|
onClick={() => updatePerforation('shape', item.id as PerforationShape)}
|
||||||
|
className={`flex-1 flex flex-col items-center justify-center gap-2 py-4 px-2 rounded-lg border transition-all ${config.perforation.shape === item.id
|
||||||
|
? 'bg-slate-700/80 border-blue-500 text-blue-400 shadow-lg shadow-blue-500/10'
|
||||||
|
: 'bg-slate-800 border-slate-700 text-gray-400 hover:bg-slate-750 hover:border-slate-600'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<item.icon size={24} />
|
||||||
|
<span className="text-sm font-medium">{item.label}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Resize Controls */}
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<div className="flex justify-between items-center mb-2">
|
||||||
|
<label className="text-sm font-medium text-gray-300">Диаметр отверстий</label>
|
||||||
|
<span className="text-sm font-bold text-blue-400">{config.perforation.size} мм</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<span className="text-xs text-gray-500">2 мм</span>
|
||||||
|
<input
|
||||||
|
type="range" min="2" max="25" step="1"
|
||||||
|
value={config.perforation.size}
|
||||||
|
onChange={(e) => updatePerforation('size', parseFloat(e.target.value))}
|
||||||
|
className="flex-1 h-1.5 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-blue-500"
|
||||||
|
/>
|
||||||
|
<span className="text-xs text-gray-500">25 мм</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div className="flex justify-between items-center mb-2">
|
||||||
|
<label className="text-sm font-medium text-gray-300">Зазор (между отверстиями)</label>
|
||||||
|
<span className="text-sm font-bold text-blue-400">{config.perforation.gap} мм</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<span className="text-xs text-gray-500">1 мм</span>
|
||||||
|
<input
|
||||||
|
type="range" min="1" max="10" step="0.5"
|
||||||
|
value={config.perforation.gap}
|
||||||
|
onChange={(e) => updatePerforation('gap', parseFloat(e.target.value))}
|
||||||
|
className="flex-1 h-1.5 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-blue-500"
|
||||||
|
/>
|
||||||
|
<span className="text-xs text-gray-500">10 мм</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Preview */}
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-bold text-gray-500 uppercase mb-3 block">Предпросмотр</label>
|
||||||
|
<PerforationPreview config={config.perforation} />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+177
-199
@@ -1,7 +1,6 @@
|
|||||||
import React, { useRef, useState, useMemo } from 'react';
|
import React, { useRef, useState, useMemo } from 'react';
|
||||||
import { AppConfig, LayoutSplits, Partition } from '../types';
|
import { AppConfig, LayoutSplits, Partition } from '../types';
|
||||||
// Добавил Settings, Move и прочее в импорты
|
import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings2 } from 'lucide-react';
|
||||||
import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings, Plus } from 'lucide-react';
|
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
config: AppConfig;
|
config: AppConfig;
|
||||||
@@ -25,23 +24,22 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
|||||||
const [dragging, setDragging] = useState<DragTarget | null>(null);
|
const [dragging, setDragging] = useState<DragTarget | null>(null);
|
||||||
const [isButtonHovered, setIsButtonHovered] = useState(false);
|
const [isButtonHovered, setIsButtonHovered] = useState(false);
|
||||||
|
|
||||||
// Main Grid Hover
|
|
||||||
const [phantomMainAxis, setPhantomMainAxis] = useState<Axis | null>(null);
|
const [phantomMainAxis, setPhantomMainAxis] = useState<Axis | null>(null);
|
||||||
const [hoveredMainSplit, setHoveredMainSplit] = useState<{ axis: Axis; index: number } | null>(null);
|
const [hoveredMainSplit, setHoveredMainSplit] = useState<{ axis: Axis; index: number } | null>(null);
|
||||||
|
|
||||||
// Partition Hover
|
|
||||||
const [hoveredCell, setHoveredCell] = useState<{ i: number; j: number } | null>(null);
|
const [hoveredCell, setHoveredCell] = useState<{ i: number; j: number } | null>(null);
|
||||||
const [hoveredPartition, setHoveredPartition] = useState<{ id: string; cellKey: string } | null>(null);
|
const [hoveredPartition, setHoveredPartition] = useState<{ id: string; cellKey: string } | null>(null);
|
||||||
const [phantomPartition, setPhantomPartition] = useState<{ axis: Axis; offset: number; min: number; max: number } | null>(null);
|
const [phantomPartition, setPhantomPartition] = useState<{ axis: Axis; offset: number; min: number; max: number } | null>(null);
|
||||||
const [selectedPartitionId, setSelectedPartitionId] = useState<string | null>(null);
|
const [selectedPartitionId, setSelectedPartitionId] = useState<string | null>(null);
|
||||||
|
|
||||||
// -- SAFE DATA --
|
// -- DATA --
|
||||||
const safeX = Array.isArray(splits?.x) ? splits.x : [];
|
const safeX = Array.isArray(splits?.x) ? splits.x : [];
|
||||||
const safeY = Array.isArray(splits?.y) ? splits.y : [];
|
const safeY = Array.isArray(splits?.y) ? splits.y : [];
|
||||||
const safePartitions = splits?.partitions || {};
|
const safePartitions = splits?.partitions || {};
|
||||||
|
|
||||||
const drawerW = Math.max(1, config.drawer.width || 300);
|
const drawerW = Math.max(1, config.drawer.width || 300);
|
||||||
const drawerD = Math.max(1, config.drawer.depth || 400);
|
const drawerD = Math.max(1, config.drawer.depth || 400);
|
||||||
|
const wallThick = config.wallThickness || 1.2;
|
||||||
const aspectRatio = drawerD / drawerW;
|
const aspectRatio = drawerD / drawerW;
|
||||||
|
|
||||||
const viewBoxW = 1000;
|
const viewBoxW = 1000;
|
||||||
@@ -61,27 +59,29 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
|||||||
};
|
};
|
||||||
const selectedData = getSelectedPartition();
|
const selectedData = getSelectedPartition();
|
||||||
|
|
||||||
// -- LOGIC: T-Junction Limits --
|
// --- RAYCASTING (Поиск коробки для НОВОЙ стенки) ---
|
||||||
// Находит ближайшие стенки, чтобы ограничить новую перегородку
|
// Мы ищем ближайшие препятствия, чтобы определить границы новой стенки
|
||||||
const getHoveredBoundaries = (lx: number, ly: number, parts: Partition[]) => {
|
const getCursorBox = (lx: number, ly: number, parts: Partition[]) => {
|
||||||
let minX = 0, maxX = 1;
|
let minX = 0, maxX = 1;
|
||||||
let minY = 0, maxY = 1;
|
let minY = 0, maxY = 1;
|
||||||
|
|
||||||
parts.forEach(p => {
|
parts.forEach(p => {
|
||||||
|
// Используем сохраненные границы (честные)
|
||||||
const pMin = p.min ?? 0;
|
const pMin = p.min ?? 0;
|
||||||
const pMax = p.max ?? 1;
|
const pMax = p.max ?? 1;
|
||||||
|
const EPS = 0.005; // Допуск
|
||||||
|
|
||||||
if (p.axis === 'x') {
|
if (p.axis === 'x') {
|
||||||
// Вертикальная стенка (x=offset, y=min..max)
|
// Вертикальная стенка. Перекрывает ли она наш Y?
|
||||||
// Проверяем, находится ли мышь в её диапазоне по Y
|
if (ly >= pMin - EPS && ly <= pMax + EPS) {
|
||||||
if (ly >= pMin && ly <= pMax) {
|
// Стенка на нашем уровне. Слева или справа?
|
||||||
if (p.offset < lx) minX = Math.max(minX, p.offset);
|
if (p.offset < lx) minX = Math.max(minX, p.offset);
|
||||||
if (p.offset > lx) maxX = Math.min(maxX, p.offset);
|
if (p.offset > lx) maxX = Math.min(maxX, p.offset);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Горизонтальная стенка (y=offset, x=min..max)
|
// Горизонтальная стенка. Перекрывает ли она наш X?
|
||||||
// Проверяем, находится ли мышь в её диапазоне по X
|
if (lx >= pMin - EPS && lx <= pMax + EPS) {
|
||||||
if (lx >= pMin && lx <= pMax) {
|
// Стенка на нашем уровне. Сверху или снизу?
|
||||||
if (p.offset < ly) minY = Math.max(minY, p.offset);
|
if (p.offset < ly) minY = Math.max(minY, p.offset);
|
||||||
if (p.offset > ly) maxY = Math.min(maxY, p.offset);
|
if (p.offset > ly) maxY = Math.min(maxY, p.offset);
|
||||||
}
|
}
|
||||||
@@ -90,20 +90,34 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
|||||||
return { minX, maxX, minY, maxY };
|
return { minX, maxX, minY, maxY };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Поиск соседей для размеров (Используем сохраненные данные)
|
||||||
|
const getNeighborOffsets = (offset: number, crossPos: number, axis: Axis, parts: Partition[]) => {
|
||||||
|
let min = 0;
|
||||||
|
let max = 1;
|
||||||
|
const EPS = 0.005;
|
||||||
|
|
||||||
|
parts.forEach(p => {
|
||||||
|
if (p.axis === axis) {
|
||||||
|
const pMin = p.min ?? 0;
|
||||||
|
const pMax = p.max ?? 1;
|
||||||
|
if (crossPos >= pMin - EPS && crossPos <= pMax + EPS) {
|
||||||
|
if (p.offset < offset) min = Math.max(min, p.offset);
|
||||||
|
if (p.offset > offset) max = Math.min(max, p.offset);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return { min, max };
|
||||||
|
};
|
||||||
|
|
||||||
// -- ACTIONS --
|
// -- ACTIONS --
|
||||||
const createPartition = (i: number, j: number, axis: Axis, offset: number, min: number, max: number) => {
|
const createPartition = (i: number, j: number, axis: Axis, offset: number, min: number, max: number) => {
|
||||||
const key = `${i}-${j}`;
|
const key = `${i}-${j}`;
|
||||||
const current = safePartitions[key] || [];
|
const current = safePartitions[key] || [];
|
||||||
const newPart: Partition = {
|
const newPart: Partition = {
|
||||||
id: Math.random().toString(36).substr(2, 9),
|
id: Math.random().toString(36).substr(2, 9),
|
||||||
axis,
|
axis, offset, min, max,
|
||||||
offset,
|
height: config.drawer.height || 80, rounded: false
|
||||||
min,
|
|
||||||
max,
|
|
||||||
height: config.drawer.height || 80,
|
|
||||||
rounded: false
|
|
||||||
};
|
};
|
||||||
// Обновляем стейт, но НЕ сбрасываем mode, так как ErrorBoundary теперь снаружи
|
|
||||||
onChange({ ...splits, partitions: { ...safePartitions, [key]: [...current, newPart] } });
|
onChange({ ...splits, partitions: { ...safePartitions, [key]: [...current, newPart] } });
|
||||||
setSelectedPartitionId(newPart.id);
|
setSelectedPartitionId(newPart.id);
|
||||||
};
|
};
|
||||||
@@ -129,12 +143,11 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
|||||||
setDragging(null);
|
setDragging(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
// -- MOUSE HANDLER --
|
// -- MOUSE HANDLERS --
|
||||||
const handleMouseMove = (e: React.MouseEvent) => {
|
const handleMouseMove = (e: React.MouseEvent) => {
|
||||||
if (!svgRef.current) return;
|
if (!svgRef.current) return;
|
||||||
const rect = svgRef.current.getBoundingClientRect();
|
const rect = svgRef.current.getBoundingClientRect();
|
||||||
if (rect.width === 0) return;
|
if (rect.width === 0) return;
|
||||||
|
|
||||||
const nx = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
|
const nx = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
|
||||||
const ny = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height));
|
const ny = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height));
|
||||||
setMousePos({ x: nx, y: ny });
|
setMousePos({ x: nx, y: ny });
|
||||||
@@ -152,19 +165,11 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
|||||||
const cellY1 = sortedY[j]; const cellY2 = sortedY[j+1];
|
const cellY1 = sortedY[j]; const cellY2 = sortedY[j+1];
|
||||||
|
|
||||||
let newOffset = 0;
|
let newOffset = 0;
|
||||||
if (dragging.axis === 'x') {
|
if (dragging.axis === 'x') newOffset = (nx - cellX1) / (cellX2 - cellX1);
|
||||||
newOffset = (nx - cellX1) / (cellX2 - cellX1);
|
else newOffset = (ny - cellY1) / (cellY2 - cellY1);
|
||||||
} else {
|
|
||||||
newOffset = (ny - cellY1) / (cellY2 - cellY1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ограничиваем в пределах "родительской" зоны (0-1) внутри ячейки
|
|
||||||
// В идеале тут тоже надо проверять коллизии, но пока просто границы ячейки
|
|
||||||
newOffset = Math.max(0.02, Math.min(0.98, newOffset));
|
newOffset = Math.max(0.02, Math.min(0.98, newOffset));
|
||||||
|
if (!isNaN(newOffset)) updatePartition(dragging.cellKey, dragging.id, { offset: newOffset });
|
||||||
if (!isNaN(newOffset)) {
|
|
||||||
updatePartition(dragging.cellKey, dragging.id, { offset: newOffset });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -177,25 +182,21 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
|||||||
if (nx > SNAP && nx < 1 - SNAP && ny > SNAP && ny < 1 - SNAP) {
|
if (nx > SNAP && nx < 1 - SNAP && ny > SNAP && ny < 1 - SNAP) {
|
||||||
const closeToX = safeX.some(val => Math.abs(nx - val) < SNAP);
|
const closeToX = safeX.some(val => Math.abs(nx - val) < SNAP);
|
||||||
const closeToY = safeY.some(val => Math.abs(ny - val) < SNAP);
|
const closeToY = safeY.some(val => Math.abs(ny - val) < SNAP);
|
||||||
if (!closeToX && !closeToY) {
|
if (!closeToX && !closeToY) setPhantomMainAxis(Math.min(nx, 1-nx) < Math.min(ny, 1-ny) ? 'y' : 'x');
|
||||||
const distRight = 1 - nx; const distBottom = 1 - ny;
|
else setPhantomMainAxis(null);
|
||||||
setPhantomMainAxis(Math.min(nx, distRight) < Math.min(ny, distBottom) ? 'y' : 'x');
|
|
||||||
} else { setPhantomMainAxis(null); }
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Cells Mode
|
|
||||||
setHoveredPartition(null);
|
setHoveredPartition(null);
|
||||||
setPhantomPartition(null);
|
setPhantomPartition(null);
|
||||||
setHoveredCell(null);
|
setHoveredCell(null);
|
||||||
|
|
||||||
// 1. Находим ячейку
|
// Find Cell
|
||||||
let cellIdx = null;
|
let cellIdx = null;
|
||||||
for (let i = 0; i < sortedX.length - 1; i++) {
|
for (let i = 0; i < sortedX.length - 1; i++) {
|
||||||
if (nx >= sortedX[i] && nx <= sortedX[i+1]) {
|
if (nx >= sortedX[i] && nx <= sortedX[i+1]) {
|
||||||
for (let j = 0; j < sortedY.length - 1; j++) {
|
for (let j = 0; j < sortedY.length - 1; j++) {
|
||||||
if (ny >= sortedY[j] && ny <= sortedY[j+1]) {
|
if (ny >= sortedY[j] && ny <= sortedY[j+1]) {
|
||||||
cellIdx = { i, j };
|
cellIdx = { i, j }; break;
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -212,11 +213,15 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
|||||||
const lx = (nx - cx1) / cw;
|
const lx = (nx - cx1) / cw;
|
||||||
const ly = (ny - cy1) / ch;
|
const ly = (ny - cy1) / ch;
|
||||||
|
|
||||||
// 2. Проверяем наведение на существующие (для удаления/выделения)
|
// Use real mm for aspect ratio logic
|
||||||
|
const realCellW = cw * drawerW;
|
||||||
|
const realCellH = ch * drawerD;
|
||||||
|
|
||||||
let found = null;
|
let found = null;
|
||||||
const SNAP = 0.05;
|
const SNAP = 0.05;
|
||||||
for (const p of parts) {
|
for (const p of parts) {
|
||||||
const pMin = p.min ?? 0; const pMax = p.max ?? 1;
|
const pMin = p.min ?? 0;
|
||||||
|
const pMax = p.max ?? 1;
|
||||||
if (p.axis === 'x') {
|
if (p.axis === 'x') {
|
||||||
if (ly >= pMin && ly <= pMax && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p;
|
if (ly >= pMin && ly <= pMax && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p;
|
||||||
} else {
|
} else {
|
||||||
@@ -227,29 +232,31 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
|||||||
if (found) {
|
if (found) {
|
||||||
setHoveredPartition({ id: found.id, cellKey: key });
|
setHoveredPartition({ id: found.id, cellKey: key });
|
||||||
} else {
|
} else {
|
||||||
// 3. Вычисляем T-образные границы
|
// --- FIND BOX USING RAYCASTING ---
|
||||||
const bounds = getHoveredBoundaries(lx, ly, parts);
|
const box = getCursorBox(lx, ly, parts);
|
||||||
|
|
||||||
const distL = lx - bounds.minX;
|
const boxW = (box.maxX - box.minX) * realCellW;
|
||||||
const distR = bounds.maxX - lx;
|
const boxH = (box.maxY - box.minY) * realCellH;
|
||||||
const distT = ly - bounds.minY;
|
|
||||||
const distB = bounds.maxY - ly;
|
|
||||||
|
|
||||||
const minX = Math.min(distL, distR);
|
// Default axis based on longest side
|
||||||
const minY = Math.min(distT, distB);
|
let newAxis: Axis = boxW > boxH ? 'x' : 'y';
|
||||||
|
|
||||||
// Определяем ось перпендикулярно ближайшей стороне
|
// Override if near edges
|
||||||
const axis = minX < minY ? 'y' : 'x';
|
const relL = (lx - box.minX) / (box.maxX - box.minX);
|
||||||
|
const relT = (ly - box.minY) / (box.maxY - box.minY);
|
||||||
|
const THRESHOLD = 0.2; // 20% zone near edges
|
||||||
|
|
||||||
// Проверяем, есть ли место
|
if (relL < THRESHOLD || relL > 1 - THRESHOLD) newAxis = 'x';
|
||||||
const width = bounds.maxX - bounds.minX;
|
else if (relT < THRESHOLD || relT > 1 - THRESHOLD) newAxis = 'y';
|
||||||
const height = bounds.maxY - bounds.minY;
|
|
||||||
|
|
||||||
if ((axis === 'y' && height > 0.1) || (axis === 'x' && width > 0.1)) {
|
// Validate space
|
||||||
const offset = axis === 'x' ? lx : ly;
|
const valid = (newAxis === 'x' && (box.maxX - box.minX) > 0.05) || (newAxis === 'y' && (box.maxY - box.minY) > 0.05);
|
||||||
const min = axis === 'x' ? bounds.minY : bounds.minX;
|
|
||||||
const max = axis === 'x' ? bounds.maxY : bounds.maxX;
|
if (valid) {
|
||||||
setPhantomPartition({ axis, offset, min, max });
|
const offset = newAxis === 'x' ? lx : ly;
|
||||||
|
const min = newAxis === 'x' ? box.minY : box.minX;
|
||||||
|
const max = newAxis === 'x' ? box.maxY : box.maxX;
|
||||||
|
setPhantomPartition({ axis: newAxis, offset, min, max });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -258,7 +265,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
|||||||
|
|
||||||
const handleMouseDown = (e: React.MouseEvent) => {
|
const handleMouseDown = (e: React.MouseEvent) => {
|
||||||
if (isButtonHovered) return;
|
if (isButtonHovered) return;
|
||||||
|
|
||||||
if (mode === 'lines') {
|
if (mode === 'lines') {
|
||||||
if (hoveredMainSplit) {
|
if (hoveredMainSplit) {
|
||||||
if (e.button === 0) setDragging({ type: 'main', ...hoveredMainSplit });
|
if (e.button === 0) setDragging({ type: 'main', ...hoveredMainSplit });
|
||||||
@@ -285,14 +291,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
|||||||
}
|
}
|
||||||
} else if (hoveredCell && phantomPartition) {
|
} else if (hoveredCell && phantomPartition) {
|
||||||
if (e.button === 0) {
|
if (e.button === 0) {
|
||||||
createPartition(
|
createPartition(hoveredCell.i, hoveredCell.j, phantomPartition.axis, phantomPartition.offset, phantomPartition.min, phantomPartition.max);
|
||||||
hoveredCell.i,
|
|
||||||
hoveredCell.j,
|
|
||||||
phantomPartition.axis,
|
|
||||||
phantomPartition.offset,
|
|
||||||
phantomPartition.min,
|
|
||||||
phantomPartition.max
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
setSelectedPartitionId(null);
|
setSelectedPartitionId(null);
|
||||||
@@ -300,6 +299,16 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// --- HANDLER: Clear Phantom on Leave ---
|
||||||
|
const handleMouseLeave = () => {
|
||||||
|
setDragging(null);
|
||||||
|
setPhantomMainAxis(null);
|
||||||
|
setHoveredMainSplit(null);
|
||||||
|
setHoveredCell(null);
|
||||||
|
setHoveredPartition(null);
|
||||||
|
setPhantomPartition(null);
|
||||||
|
};
|
||||||
|
|
||||||
// --- RENDER ---
|
// --- RENDER ---
|
||||||
const renderCellsAndPartitions = () => {
|
const renderCellsAndPartitions = () => {
|
||||||
const elements = [];
|
const elements = [];
|
||||||
@@ -307,7 +316,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
|||||||
for (let j = 0; j < sortedY.length - 1; j++) {
|
for (let j = 0; j < sortedY.length - 1; j++) {
|
||||||
const x1 = sortedX[i]; const x2 = sortedX[i + 1];
|
const x1 = sortedX[i]; const x2 = sortedX[i + 1];
|
||||||
const y1 = sortedY[j]; const y2 = sortedY[j + 1];
|
const y1 = sortedY[j]; const y2 = sortedY[j + 1];
|
||||||
|
|
||||||
if (y2 === undefined || x2 === undefined) continue;
|
if (y2 === undefined || x2 === undefined) continue;
|
||||||
|
|
||||||
const cellX = x1 * viewBoxW; const cellY = y1 * viewBoxH;
|
const cellX = x1 * viewBoxW; const cellY = y1 * viewBoxH;
|
||||||
@@ -317,6 +325,22 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
|||||||
const isHovered = hoveredCell?.i === i && hoveredCell?.j === j && mode === 'cells';
|
const isHovered = hoveredCell?.i === i && hoveredCell?.j === j && mode === 'cells';
|
||||||
const parts = safePartitions[key] || [];
|
const parts = safePartitions[key] || [];
|
||||||
const isAnySelected = parts.some(p => p.id === selectedPartitionId);
|
const isAnySelected = parts.some(p => p.id === selectedPartitionId);
|
||||||
|
const realW = (x2 - x1) * drawerW;
|
||||||
|
const realD = (y2 - y1) * drawerD;
|
||||||
|
|
||||||
|
if (parts.length === 0) {
|
||||||
|
const labelX = cellX + cellW / 2;
|
||||||
|
const labelY = cellY + cellH / 2;
|
||||||
|
const textW = Math.max(0, realW - wallThick).toFixed(0);
|
||||||
|
const textD = Math.max(0, realD - wallThick).toFixed(0);
|
||||||
|
if (cellH > 40 && cellW > 60) {
|
||||||
|
elements.push(
|
||||||
|
<text key={`label-${key}`} x={labelX} y={labelY} textAnchor="middle" dominantBaseline="middle" className="fill-slate-300 font-mono text-[16px] font-bold pointer-events-none select-none opacity-80" style={{ textShadow: '1px 1px 2px rgba(0,0,0,0.8)' }}>
|
||||||
|
{textW} × {textD}
|
||||||
|
</text>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
elements.push(
|
elements.push(
|
||||||
<g key={key}>
|
<g key={key}>
|
||||||
@@ -324,25 +348,58 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
|||||||
{isAnySelected && mode === 'cells' && <rect x={cellX} y={cellY} width={cellW} height={cellH} fill="transparent" stroke="#a855f7" strokeWidth="2" className="pointer-events-none opacity-50"/>}
|
{isAnySelected && mode === 'cells' && <rect x={cellX} y={cellY} width={cellW} height={cellH} fill="transparent" stroke="#a855f7" strokeWidth="2" className="pointer-events-none opacity-50"/>}
|
||||||
|
|
||||||
{parts.map(p => {
|
{parts.map(p => {
|
||||||
const pMin = p.min ?? 0; const pMax = p.max ?? 1;
|
const pMin = p.min ?? 0;
|
||||||
let lx1, ly1, lx2, ly2;
|
const pMax = p.max ?? 1;
|
||||||
|
if (pMax - pMin < 0.001) return null;
|
||||||
|
|
||||||
if (p.axis === 'x') {
|
let lx1, ly1, lx2, ly2;
|
||||||
|
let dist1 = 0, dist2 = 0;
|
||||||
|
let midX, midY;
|
||||||
|
const isVertical = p.axis === 'x';
|
||||||
|
|
||||||
|
if (isVertical) {
|
||||||
const px = cellX + (cellW * p.offset);
|
const px = cellX + (cellW * p.offset);
|
||||||
lx1 = px; lx2 = px;
|
lx1 = px; lx2 = px;
|
||||||
ly1 = cellY + (cellH * pMin); ly2 = cellY + (cellH * pMax);
|
ly1 = cellY + (cellH * pMin); ly2 = cellY + (cellH * pMax);
|
||||||
|
|
||||||
|
const neighbors = getNeighborOffsets(p.offset, (pMin + pMax)/2, p.axis, parts);
|
||||||
|
dist1 = Math.abs((p.offset - neighbors.min) * realW) - wallThick;
|
||||||
|
dist2 = Math.abs((neighbors.max - p.offset) * realW) - wallThick;
|
||||||
|
midX = px; midY = (ly1 + ly2) / 2;
|
||||||
} else {
|
} else {
|
||||||
const py = cellY + (cellH * p.offset);
|
const py = cellY + (cellH * p.offset);
|
||||||
ly1 = py; ly2 = py;
|
ly1 = py; ly2 = py;
|
||||||
lx1 = cellX + (cellW * pMin); lx2 = cellX + (cellW * pMax);
|
lx1 = cellX + (cellW * pMin); lx2 = cellX + (cellW * pMax);
|
||||||
|
|
||||||
|
const neighbors = getNeighborOffsets(p.offset, (pMin + pMax)/2, p.axis, parts);
|
||||||
|
dist1 = Math.abs((p.offset - neighbors.min) * realD) - wallThick;
|
||||||
|
dist2 = Math.abs((neighbors.max - p.offset) * realD) - wallThick;
|
||||||
|
midX = (lx1 + lx2) / 2; midY = py;
|
||||||
}
|
}
|
||||||
|
|
||||||
const isSel = selectedPartitionId === p.id;
|
const isSel = selectedPartitionId === p.id;
|
||||||
const isHov = hoveredPartition?.id === p.id;
|
const isHov = hoveredPartition?.id === p.id;
|
||||||
|
const textOffset = 12;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<g key={p.id} onDoubleClick={(e) => { e.stopPropagation(); removePartition(key, p.id); }}>
|
<g key={p.id}>
|
||||||
<line x1={lx1} y1={ly1} x2={lx2} y2={ly2} stroke="transparent" strokeWidth="30" />
|
<g onDoubleClick={(e) => { e.stopPropagation(); removePartition(key, p.id); }}>
|
||||||
<line x1={lx1} y1={ly1} x2={lx2} y2={ly2} stroke={isSel ? "#a855f7" : (isHov ? "#d8b4fe" : "#7e22ce")} strokeWidth={isSel ? 6 : 4} strokeLinecap="round" />
|
<line x1={lx1} y1={ly1} x2={lx2} y2={ly2} stroke="transparent" strokeWidth="40" />
|
||||||
|
<line x1={lx1} y1={ly1} x2={lx2} y2={ly2} stroke={isSel ? "#a855f7" : (isHov ? "#d8b4fe" : "#7e22ce")} strokeWidth={isSel ? 6 : 4} strokeLinecap="round" />
|
||||||
|
</g>
|
||||||
|
<g className="pointer-events-none select-none font-mono text-[14px] font-bold fill-white" style={{ textShadow: '0px 0px 3px #000' }}>
|
||||||
|
{isVertical ? (
|
||||||
|
<>
|
||||||
|
<text x={midX - textOffset} y={midY} textAnchor="end" dominantBaseline="middle">{Math.max(0, dist1).toFixed(0)}</text>
|
||||||
|
<text x={midX + textOffset} y={midY} textAnchor="start" dominantBaseline="middle">{Math.max(0, dist2).toFixed(0)}</text>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<text x={midX} y={midY - textOffset} textAnchor="middle" dominantBaseline="auto">{Math.max(0, dist1).toFixed(0)}</text>
|
||||||
|
<text x={midX} y={midY + textOffset * 2} textAnchor="middle" dominantBaseline="auto">{Math.max(0, dist2).toFixed(0)}</text>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</g>
|
||||||
</g>
|
</g>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
@@ -350,16 +407,14 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
|||||||
{isHovered && phantomPartition && !hoveredPartition && !dragging && (
|
{isHovered && phantomPartition && !hoveredPartition && !dragging && (
|
||||||
<g className="pointer-events-none opacity-60">
|
<g className="pointer-events-none opacity-60">
|
||||||
{(() => {
|
{(() => {
|
||||||
const pMin = phantomPartition.min; const pMax = phantomPartition.max;
|
const { min, max } = phantomPartition;
|
||||||
let fx1, fy1, fx2, fy2;
|
let fx1, fy1, fx2, fy2;
|
||||||
if (phantomPartition.axis === 'x') {
|
if (phantomPartition.axis === 'x') {
|
||||||
const px = cellX + (cellW * phantomPartition.offset);
|
const px = cellX + (cellW * phantomPartition.offset);
|
||||||
fx1 = px; fx2 = px;
|
fx1 = px; fx2 = px; fy1 = cellY + (cellH * min); fy2 = cellY + (cellH * max);
|
||||||
fy1 = cellY + (cellH * pMin); fy2 = cellY + (cellH * pMax);
|
|
||||||
} else {
|
} else {
|
||||||
const py = cellY + (cellH * phantomPartition.offset);
|
const py = cellY + (cellH * phantomPartition.offset);
|
||||||
fy1 = py; fy2 = py;
|
fy1 = py; fy2 = py; fx1 = cellX + (cellW * min); fx2 = cellX + (cellW * max);
|
||||||
fx1 = cellX + (cellW * pMin); fx2 = cellX + (cellW * pMax);
|
|
||||||
}
|
}
|
||||||
return <line x1={fx1} y1={fy1} x2={fx2} y2={fy2} stroke="#34d399" strokeWidth="3" strokeDasharray="6,6"/>;
|
return <line x1={fx1} y1={fy1} x2={fx2} y2={fy2} stroke="#34d399" strokeWidth="3" strokeDasharray="6,6"/>;
|
||||||
})()}
|
})()}
|
||||||
@@ -373,143 +428,66 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="bg-slate-900 p-4 rounded-xl shadow-lg border border-slate-800 h-full flex flex-col relative overflow-hidden">
|
<div className="flex w-full h-full bg-slate-900 border border-slate-800 rounded-xl overflow-hidden shadow-2xl">
|
||||||
|
<div className="flex-1 flex flex-col relative min-w-0">
|
||||||
|
<div className="flex justify-between items-center p-3 border-b border-slate-800 bg-slate-900 z-10 shrink-0">
|
||||||
|
<h2 className="text-sm font-bold flex items-center gap-2 text-primary"><Grid size={18} /> Редактор</h2>
|
||||||
|
<div className="flex bg-slate-800 p-1 rounded-lg border border-slate-700">
|
||||||
|
<button onClick={() => { setMode('lines'); setSelectedPartitionId(null); }} className={`flex items-center gap-2 px-3 py-1.5 rounded-md text-xs font-bold transition-all ${mode === 'lines' ? 'bg-primary text-white shadow' : 'text-gray-400 hover:text-gray-200'}`}><Move size={14}/> Границы</button>
|
||||||
|
<button onClick={() => setMode('cells')} className={`flex items-center gap-2 px-3 py-1.5 rounded-md text-xs font-bold transition-all ${mode === 'cells' ? 'bg-primary text-white shadow' : 'text-gray-400 hover:text-gray-200'}`}><Grid size={14}/> Внутри ячеек</button>
|
||||||
|
</div>
|
||||||
|
<button onClick={() => onChange({ x: [], y: [], partitions: {} })} className="px-3 py-1.5 text-xs text-red-400 border border-slate-700 rounded hover:bg-slate-800 transition-colors flex items-center gap-1"><RotateCcw size={14} /> Сброс</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* TOOLBAR */}
|
<div className="flex-1 bg-slate-800/30 flex items-center justify-center p-4 overflow-hidden relative">
|
||||||
<div className="flex justify-between items-center mb-2 z-20 shrink-0">
|
<div className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden" style={{ width: aspectRatio > 1 ? 'auto' : '100%', height: aspectRatio > 1 ? '100%' : 'auto', aspectRatio: `${1/aspectRatio}`, maxHeight: '100%', maxWidth: '100%', cursor: mode === 'lines' ? (dragging ? 'grabbing' : hoveredMainSplit ? 'col-resize' : 'crosshair') : (dragging ? 'grabbing' : hoveredPartition ? 'grab' : hoveredCell ? 'crosshair' : 'default') }}>
|
||||||
<h2 className="text-lg font-bold flex items-center gap-2 text-primary">
|
|
||||||
<Grid size={20} /> 2. Редактор макета
|
|
||||||
</h2>
|
|
||||||
|
|
||||||
<div className="flex bg-slate-800 p-1 rounded-lg border border-slate-700">
|
|
||||||
<button onClick={() => { setMode('lines'); setSelectedPartitionId(null); }}
|
|
||||||
className={`flex items-center gap-2 px-3 py-1.5 rounded-md text-xs font-bold transition-all ${mode === 'lines' ? 'bg-primary text-white shadow' : 'text-gray-400 hover:text-gray-200'}`}>
|
|
||||||
<Move size={14}/> Границы
|
|
||||||
</button>
|
|
||||||
<button onClick={() => setMode('cells')}
|
|
||||||
className={`flex items-center gap-2 px-3 py-1.5 rounded-md text-xs font-bold transition-all ${mode === 'cells' ? 'bg-primary text-white shadow' : 'text-gray-400 hover:text-gray-200'}`}>
|
|
||||||
<Grid size={14}/> Внутри ячеек
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button onClick={() => onChange({ x: [], y: [], partitions: {} })} className="px-3 py-1.5 text-xs text-red-400 border border-slate-700 rounded hover:bg-slate-800 transition-colors flex items-center gap-1">
|
|
||||||
<RotateCcw size={14} /> Сброс
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* INFO BAR */}
|
|
||||||
<div className="bg-slate-800/50 rounded-lg px-3 py-2 mb-2 flex items-center gap-3 text-[11px] text-gray-300 border border-slate-700/50 shrink-0">
|
|
||||||
<MousePointer2 size={14} className="text-primary" />
|
|
||||||
{mode === 'lines' ? (
|
|
||||||
<div className="flex gap-3">
|
|
||||||
<span><b className="text-blue-400">ЛКМ:</b> Линия</span>
|
|
||||||
<span><b className="text-red-400">ПКМ:</b> Удалить</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="flex gap-3">
|
|
||||||
<span><b className="text-green-400">ЛКМ в ячейке:</b> Стенка (T-соединения)</span>
|
|
||||||
<span><b className="text-purple-400">Драг:</b> Двигать</span>
|
|
||||||
<span><b className="text-red-400">2xЛКМ:</b> Удалить</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* WORKSPACE */}
|
|
||||||
<div className="flex-1 bg-slate-800/30 rounded-lg flex flex-col items-center justify-center relative overflow-hidden border border-slate-700/50 min-h-0 w-full">
|
|
||||||
<div className="relative w-full h-full flex items-center justify-center p-4">
|
|
||||||
<div
|
|
||||||
className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden"
|
|
||||||
style={{
|
|
||||||
width: aspectRatio > 1 ? 'auto' : '100%',
|
|
||||||
height: aspectRatio > 1 ? '100%' : 'auto',
|
|
||||||
aspectRatio: `${1/aspectRatio}`,
|
|
||||||
maxHeight: '100%', maxWidth: '100%',
|
|
||||||
cursor: mode === 'lines' ? (dragging ? 'grabbing' : hoveredMainSplit ? 'col-resize' : 'crosshair')
|
|
||||||
: (dragging ? 'grabbing' : hoveredPartition ? 'grab' : hoveredCell ? 'crosshair' : 'default'),
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<svg ref={svgRef} viewBox={`0 0 ${viewBoxW} ${viewBoxH}`} className="w-full h-full touch-none block"
|
<svg ref={svgRef} viewBox={`0 0 ${viewBoxW} ${viewBoxH}`} className="w-full h-full touch-none block"
|
||||||
preserveAspectRatio="none"
|
onMouseMove={handleMouseMove}
|
||||||
onMouseMove={handleMouseMove} onMouseDown={handleMouseDown} onMouseUp={() => setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()}
|
onMouseDown={handleMouseDown}
|
||||||
|
onMouseUp={() => setDragging(null)}
|
||||||
|
onMouseLeave={handleMouseLeave} // ДОБАВЛЕНО СЮДА
|
||||||
|
onContextMenu={(e) => e.preventDefault()}
|
||||||
>
|
>
|
||||||
<defs>
|
<defs><pattern id="grid" width="50" height="50" patternUnits="userSpaceOnUse"><path d="M 50 0 L 0 0 0 50" fill="none" stroke="rgba(255,255,255,0.03)" strokeWidth="1"/></pattern></defs>
|
||||||
<pattern id="grid" width="50" height="50" patternUnits="userSpaceOnUse">
|
|
||||||
<path d="M 50 0 L 0 0 0 50" fill="none" stroke="rgba(255,255,255,0.03)" strokeWidth="1"/>
|
|
||||||
</pattern>
|
|
||||||
</defs>
|
|
||||||
<rect width="100%" height="100%" fill="url(#grid)" />
|
<rect width="100%" height="100%" fill="url(#grid)" />
|
||||||
|
|
||||||
{renderCellsAndPartitions()}
|
{renderCellsAndPartitions()}
|
||||||
|
|
||||||
{/* MAIN GRID X */}
|
|
||||||
{safeX.map((x, i) => (
|
{safeX.map((x, i) => (
|
||||||
<g key={`x-${i}`} onMouseMove={(e) => { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'x', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('x', i); }}>
|
<g key={`x-${i}`} onMouseMove={(e) => { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'x', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('x', i); }}>
|
||||||
<line x1={x * viewBoxW} y1="0" x2={x * viewBoxW} y2="100%" stroke="transparent" strokeWidth="40" className={mode === 'lines' ? "cursor-col-resize" : ""} />
|
<line x1={x * viewBoxW} y1="0" x2={x * viewBoxW} y2="100%" stroke="transparent" strokeWidth="40" className={mode === 'lines' ? "cursor-col-resize" : ""} />
|
||||||
<line x1={x * viewBoxW} y1="0" x2={x * viewBoxW} y2="100%" stroke={hoveredMainSplit?.axis === 'x' && hoveredMainSplit.index === i ? "#f59e0b" : "#64748b"} strokeWidth={hoveredMainSplit?.axis === 'x' && hoveredMainSplit.index === i ? 6 : 4} className="pointer-events-none" />
|
<line x1={x * viewBoxW} y1="0" x2={x * viewBoxW} y2="100%" stroke={hoveredMainSplit?.axis === 'x' && hoveredMainSplit.index === i ? "#f59e0b" : "#64748b"} strokeWidth={hoveredMainSplit?.axis === 'x' && hoveredMainSplit.index === i ? 6 : 4} className="pointer-events-none" />
|
||||||
</g>
|
</g>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
{/* MAIN GRID Y */}
|
|
||||||
{safeY.map((y, i) => (
|
{safeY.map((y, i) => (
|
||||||
<g key={`y-${i}`} onMouseMove={(e) => { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'y', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('y', i); }}>
|
<g key={`y-${i}`} onMouseMove={(e) => { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'y', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('y', i); }}>
|
||||||
<line x1="0" y1={y * viewBoxH} x2="100%" y2={y * viewBoxH} stroke="transparent" strokeWidth="40" className={mode === 'lines' ? "cursor-row-resize" : ""} />
|
<line x1="0" y1={y * viewBoxH} x2="100%" y2={y * viewBoxH} stroke="transparent" strokeWidth="40" className={mode === 'lines' ? "cursor-row-resize" : ""} />
|
||||||
<line x1="0" y1={y * viewBoxH} x2="100%" y2={y * viewBoxH} stroke={hoveredMainSplit?.axis === 'y' && hoveredMainSplit.index === i ? "#f59e0b" : "#64748b"} strokeWidth={hoveredMainSplit?.axis === 'y' && hoveredMainSplit.index === i ? 6 : 4} className="pointer-events-none" />
|
<line x1="0" y1={y * viewBoxH} x2="100%" y2={y * viewBoxH} stroke={hoveredMainSplit?.axis === 'y' && hoveredMainSplit.index === i ? "#f59e0b" : "#64748b"} strokeWidth={hoveredMainSplit?.axis === 'y' && hoveredMainSplit.index === i ? 6 : 4} className="pointer-events-none" />
|
||||||
</g>
|
</g>
|
||||||
))}
|
))}
|
||||||
|
{mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis && (
|
||||||
{/* MAIN PHANTOMS */}
|
<line x1={phantomMainAxis === 'x' ? mousePos.x * viewBoxW : 0} y1={phantomMainAxis === 'y' ? mousePos.y * viewBoxH : 0} x2={phantomMainAxis === 'x' ? mousePos.x * viewBoxW : '100%'} y2={phantomMainAxis === 'y' ? mousePos.y * viewBoxH : '100%'} stroke="#3b82f6" strokeWidth="4" strokeDasharray="8,8" className="pointer-events-none opacity-50"/>
|
||||||
{mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'x' && <line x1={mousePos.x * viewBoxW} y1="0" x2={mousePos.x * viewBoxW} y2="100%" stroke="#3b82f6" strokeWidth="4" strokeDasharray="8,8" className="pointer-events-none opacity-50"/>}
|
)}
|
||||||
{mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'y' && <line x1="0" y1={mousePos.y * viewBoxH} x2="100%" y2={mousePos.y * viewBoxH} stroke="#3b82f6" strokeWidth="4" strokeDasharray="8,8" className="pointer-events-none opacity-50"/>}
|
|
||||||
</svg>
|
</svg>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{mode === 'cells' && selectedData ? (
|
||||||
|
<div className="w-72 bg-slate-900 border-l border-slate-800 p-4 flex flex-col shrink-0 z-20">
|
||||||
|
<div className="flex justify-between items-center mb-6"><h3 className="text-sm font-bold text-white flex items-center gap-2"><Settings2 size={16} className="text-purple-400"/>Настройки</h3><button onClick={() => setSelectedPartitionId(null)} className="text-gray-400 hover:text-white"><X size={20}/></button></div>
|
||||||
|
<div className="bg-slate-800 p-4 rounded border border-slate-700 space-y-6">
|
||||||
|
<div><div className="flex justify-between text-xs text-gray-300 mb-2"><span>Высота</span> <span className="font-mono bg-slate-900 px-1.5 py-0.5 rounded text-xs">{selectedData.part.height} мм</span></div><input type="range" min="5" max={config.drawer.height || 100} step="1" value={selectedData.part.height} onChange={(e) => updatePartition(selectedData.key, selectedData.part.id, { height: parseFloat(e.target.value) })} className="w-full h-1 bg-slate-600 rounded-lg appearance-none cursor-pointer accent-purple-500"/></div>
|
||||||
|
<div className="flex items-center justify-between"><label htmlFor="rounded-check" className="text-xs text-gray-300 cursor-pointer select-none">Скруглить края</label><input type="checkbox" id="rounded-check" checked={selectedData.part.rounded} onChange={(e) => updatePartition(selectedData.key, selectedData.part.id, { rounded: e.target.checked })} className="w-4 h-4 rounded bg-slate-700 border-slate-600 text-purple-500 focus:ring-0 cursor-pointer"/></div>
|
||||||
|
<button onClick={() => removePartition(selectedData.key, selectedData.part.id)} className="w-full py-2 bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/30 rounded text-xs flex items-center justify-center gap-2 transition-colors mt-4"><Trash2 size={14}/> Удалить</button>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="mt-auto text-[10px] text-gray-500 text-center leading-relaxed">Выделите стенку для настройки.<br/>Двойной клик удаляет её.</div>
|
||||||
{/* --- SIDEBAR FOR EDITING --- */}
|
|
||||||
{mode === 'cells' && selectedData && (
|
|
||||||
<div className="absolute top-0 right-0 bottom-0 w-72 bg-slate-900 border-l border-slate-700 p-4 shadow-2xl flex flex-col z-30 animate-in slide-in-from-right duration-200">
|
|
||||||
<div className="flex justify-between items-center mb-6">
|
|
||||||
<h3 className="text-sm font-bold text-white flex items-center gap-2">
|
|
||||||
<Settings size={16} className="text-purple-400"/> Настройки стенки
|
|
||||||
</h3>
|
|
||||||
<button onClick={() => setSelectedPartitionId(null)} className="text-gray-400 hover:text-white"><X size={20}/></button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="bg-slate-800 p-4 rounded border border-slate-700 space-y-6">
|
|
||||||
{/* Height */}
|
|
||||||
<div>
|
|
||||||
<div className="flex justify-between text-xs text-gray-300 mb-2">
|
|
||||||
<span>Высота</span> <span className="font-mono bg-slate-900 px-1.5 py-0.5 rounded text-xs">{selectedData.part.height} мм</span>
|
|
||||||
</div>
|
|
||||||
<input type="range" min="5" max={config.drawer.height || 100} step="1" value={selectedData.part.height}
|
|
||||||
onChange={(e) => updatePartition(selectedData.key, selectedData.part.id, { height: parseFloat(e.target.value) })}
|
|
||||||
className="w-full h-1 bg-slate-600 rounded-lg appearance-none cursor-pointer accent-purple-500"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Rounded */}
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<label htmlFor="rounded-check" className="text-xs text-gray-300 cursor-pointer select-none">Скруглить края</label>
|
|
||||||
<input type="checkbox" id="rounded-check" checked={selectedData.part.rounded}
|
|
||||||
onChange={(e) => updatePartition(selectedData.key, selectedData.part.id, { rounded: e.target.checked })}
|
|
||||||
className="w-4 h-4 rounded bg-slate-700 border-slate-600 text-purple-500 focus:ring-0 cursor-pointer"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Delete */}
|
|
||||||
<button
|
|
||||||
onClick={() => removePartition(selectedData.key, selectedData.part.id)}
|
|
||||||
className="w-full py-2 bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/30 rounded text-xs flex items-center justify-center gap-2 transition-colors mt-4"
|
|
||||||
>
|
|
||||||
<Trash2 size={14}/> Удалить
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mt-auto text-[10px] text-gray-500 text-center leading-relaxed">
|
|
||||||
Выделите стенку для настройки.<br/>Двойной клик удаляет её.
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="w-72 bg-slate-900/50 border-l border-slate-800 p-8 flex flex-col items-center justify-center text-center text-gray-500 shrink-0">
|
||||||
|
<MousePointer2 size={32} className="mb-4 opacity-50"/>
|
||||||
|
<p className="text-sm">Выберите стенку для настройки</p>
|
||||||
|
<p className="text-xs mt-2 opacity-50">Кликните по любой перегородке внутри ячейки</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
+402
-277
@@ -1,9 +1,9 @@
|
|||||||
import React, { Suspense, useEffect, useRef, useState, useMemo } from 'react';
|
import React, { Suspense, useEffect, useRef, useState, useMemo } from 'react';
|
||||||
import { Canvas } from '@react-three/fiber';
|
import { Canvas } from '@react-three/fiber';
|
||||||
import { OrbitControls, Center, Environment } from '@react-three/drei';
|
import { OrbitControls, Center, Environment, Text } 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 } from '../types';
|
import { AppConfig, GeneratedPart, LayoutSplits, PerforationConfig } from '../types';
|
||||||
import { createBinGeometry, generateSTL, exportSTL } from '../services/geometryGenerator';
|
import { createBinGeometry, generateSTL, exportSTL } from '../services/geometryGenerator';
|
||||||
import { Download, Package, Info, Loader2, Share2, Check, Ruler } from 'lucide-react';
|
import { Download, Package, Info, Loader2, Share2, Check, Ruler } from 'lucide-react';
|
||||||
import { generateShareUrl } from '../utils/share';
|
import { generateShareUrl } from '../utils/share';
|
||||||
@@ -24,310 +24,435 @@ const DrawerFrame = ({ config }: { config: AppConfig }) => {
|
|||||||
|
|
||||||
// --- BinMesh (Ячейка) ---
|
// --- BinMesh (Ячейка) ---
|
||||||
interface BinMeshProps {
|
interface BinMeshProps {
|
||||||
part: GeneratedPart;
|
part: GeneratedPart;
|
||||||
thickness: number;
|
thickness: number;
|
||||||
cornerRadius: number;
|
cornerRadius: number;
|
||||||
isSelected: boolean;
|
perforation: PerforationConfig;
|
||||||
onClick: () => void;
|
isSelected: boolean;
|
||||||
|
onClick: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSelected, onClick }) => {
|
const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, perforation, isSelected, onClick }) => {
|
||||||
// 1. Создаем геометрию, учитывая ВНУТРЕННИЕ ПЕРЕГОРОДКИ
|
// 1. Создаем геометрию, учитывая ВНУТРЕННИЕ ПЕРЕГОРОДКИ
|
||||||
const geometry = useMemo(() => {
|
const geometry = useMemo(() => {
|
||||||
return createBinGeometry(
|
return createBinGeometry(
|
||||||
part.width,
|
part.width,
|
||||||
part.depth,
|
part.depth,
|
||||||
part.height,
|
part.height,
|
||||||
thickness,
|
thickness,
|
||||||
cornerRadius,
|
cornerRadius,
|
||||||
part.internalPartitions // <--- ВАЖНО: передаем перегородки в генератор
|
part.internalPartitions, // <--- ВАЖНО: передаем перегородки в генератор
|
||||||
|
perforation
|
||||||
|
);
|
||||||
|
}, [part, thickness, cornerRadius, 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 (
|
||||||
|
<group
|
||||||
|
position={[part.x + part.width / 2, 0, part.y + part.depth / 2]}
|
||||||
|
onClick={(e) => { e.stopPropagation(); onClick(); }}
|
||||||
|
>
|
||||||
|
{/* Сама модель */}
|
||||||
|
<mesh geometry={geometry}>
|
||||||
|
<meshStandardMaterial
|
||||||
|
color={isSelected ? '#f59e0b' : part.color}
|
||||||
|
roughness={0.5}
|
||||||
|
metalness={0.1}
|
||||||
|
side={THREE.DoubleSide}
|
||||||
|
/>
|
||||||
|
</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 && (
|
||||||
|
<lineSegments geometry={edgesGeometry}>
|
||||||
|
<lineBasicMaterial color="white" linewidth={2} />
|
||||||
|
</lineSegments>
|
||||||
|
)}
|
||||||
|
</group>
|
||||||
);
|
);
|
||||||
}, [part, thickness, cornerRadius]);
|
|
||||||
|
|
||||||
// 2. Создаем контур выделения (EdgesGeometry)
|
|
||||||
// Threshold 20 градусов скрывает линии на плавных скруглениях
|
|
||||||
const edgesGeometry = useMemo(() => {
|
|
||||||
return new THREE.EdgesGeometry(geometry, 20);
|
|
||||||
}, [geometry]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<group position={[part.x + part.width/2, 0, part.y + part.depth/2]}>
|
|
||||||
{/* Сама модель */}
|
|
||||||
<mesh geometry={geometry} onClick={(e) => { e.stopPropagation(); onClick(); }}>
|
|
||||||
<meshStandardMaterial
|
|
||||||
color={isSelected ? '#f59e0b' : part.color}
|
|
||||||
roughness={0.5}
|
|
||||||
metalness={0.1}
|
|
||||||
side={THREE.DoubleSide} // Рисуем обе стороны стенок
|
|
||||||
/>
|
|
||||||
</mesh>
|
|
||||||
|
|
||||||
{/* Белая подсветка при выборе */}
|
|
||||||
{isSelected && (
|
|
||||||
<lineSegments geometry={edgesGeometry}>
|
|
||||||
<lineBasicMaterial color="white" linewidth={2} />
|
|
||||||
</lineSegments>
|
|
||||||
)}
|
|
||||||
</group>
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- PreviewStep (Основной компонент) ---
|
// --- PreviewStep (Основной компонент) ---
|
||||||
interface Props {
|
interface Props {
|
||||||
parts: GeneratedPart[];
|
parts: GeneratedPart[];
|
||||||
config: AppConfig;
|
config: AppConfig;
|
||||||
splits: LayoutSplits;
|
splits: LayoutSplits;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
|
export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
|
||||||
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 [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.width,
|
||||||
part.depth,
|
part.depth,
|
||||||
part.height,
|
part.height,
|
||||||
config.wallThickness,
|
config.wallThickness,
|
||||||
config.cornerRadius,
|
config.cornerRadius,
|
||||||
part.internalPartitions // <--- ВАЖНО для STL
|
part.internalPartitions, // <--- ВАЖНО для STL
|
||||||
);
|
config.perforation
|
||||||
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
|
);
|
||||||
exportSTL(mesh, `${part.name.replace(/\s+/g, '_')}.stl`);
|
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
|
||||||
};
|
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 {
|
||||||
const zip = new JSZip();
|
const zip = new JSZip();
|
||||||
parts.forEach(part => {
|
parts.forEach(part => {
|
||||||
const geometry = createBinGeometry(
|
const geometry = createBinGeometry(
|
||||||
part.width,
|
part.width,
|
||||||
part.depth,
|
part.depth,
|
||||||
part.height,
|
part.height,
|
||||||
config.wallThickness,
|
config.wallThickness,
|
||||||
config.cornerRadius,
|
config.cornerRadius,
|
||||||
part.internalPartitions // <--- ВАЖНО для STL
|
part.internalPartitions, // <--- ВАЖНО для STL
|
||||||
);
|
config.perforation
|
||||||
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
|
);
|
||||||
const stlData = generateSTL(mesh);
|
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
|
||||||
zip.file(`${part.name.replace(/\s+/g, '_')}.stl`, stlData);
|
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');
|
const content = await zip.generateAsync({ type: "blob" });
|
||||||
link.href = URL.createObjectURL(content);
|
const link = document.createElement('a');
|
||||||
link.download = "PrintFit_Project.zip";
|
link.href = URL.createObjectURL(content);
|
||||||
document.body.appendChild(link);
|
link.download = "PrintFit_Project.zip";
|
||||||
link.click();
|
document.body.appendChild(link);
|
||||||
document.body.removeChild(link);
|
link.click();
|
||||||
} catch (e: any) {
|
document.body.removeChild(link);
|
||||||
alert(`Ошибка архивации: ${e.message}`);
|
} catch (e: any) {
|
||||||
} finally {
|
alert(`Ошибка архивации: ${e.message}`);
|
||||||
setIsZipping(false);
|
} finally {
|
||||||
}
|
setIsZipping(false);
|
||||||
};
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Поделиться ссылкой
|
// Поделиться ссылкой
|
||||||
const handleShare = async () => {
|
const handleShare = async () => {
|
||||||
const url = generateShareUrl(config, splits);
|
const url = generateShareUrl(config, splits);
|
||||||
let success = false;
|
let success = false;
|
||||||
try {
|
try {
|
||||||
if (navigator.clipboard && navigator.clipboard.writeText) {
|
if (navigator.clipboard && navigator.clipboard.writeText) {
|
||||||
await navigator.clipboard.writeText(url);
|
await navigator.clipboard.writeText(url);
|
||||||
success = true;
|
success = true;
|
||||||
} else { throw new Error('Clipboard API unavailable'); }
|
} else { throw new Error('Clipboard API unavailable'); }
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
try {
|
try {
|
||||||
const textArea = document.createElement("textarea");
|
const textArea = document.createElement("textarea");
|
||||||
textArea.value = url;
|
textArea.value = url;
|
||||||
textArea.style.position = "fixed";
|
textArea.style.position = "fixed";
|
||||||
textArea.style.left = "-9999px";
|
textArea.style.left = "-9999px";
|
||||||
textArea.style.top = "0";
|
textArea.style.top = "0";
|
||||||
document.body.appendChild(textArea);
|
document.body.appendChild(textArea);
|
||||||
textArea.focus();
|
textArea.focus();
|
||||||
textArea.select();
|
textArea.select();
|
||||||
const result = document.execCommand('copy');
|
const result = document.execCommand('copy');
|
||||||
document.body.removeChild(textArea);
|
document.body.removeChild(textArea);
|
||||||
if (result) success = true;
|
if (result) success = true;
|
||||||
} catch (e) { console.error("Copy failed", e); }
|
} catch (e) { console.error("Copy failed", e); }
|
||||||
}
|
}
|
||||||
if (success) {
|
if (success) {
|
||||||
setShareUrlCopied(true);
|
setShareUrlCopied(true);
|
||||||
setTimeout(() => setShareUrlCopied(false), 3000);
|
setTimeout(() => setShareUrlCopied(false), 3000);
|
||||||
} else {
|
} else {
|
||||||
prompt("Скопируйте ссылку вручную:", url);
|
prompt("Скопируйте ссылку вручную:", url);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col h-full">
|
<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-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="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">
|
<div className="hidden md:flex items-center gap-2 text-gray-300 mr-2">
|
||||||
<Ruler className="text-primary" size={20} />
|
<Ruler className="text-primary" size={20} />
|
||||||
<span className="font-medium text-sm uppercase tracking-wide opacity-70">Размеры ящика:</span>
|
<span className="font-medium text-sm uppercase tracking-wide opacity-70">Размеры ящика:</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap gap-6 font-mono text-white items-baseline">
|
<div className="flex flex-wrap gap-6 font-mono text-white items-baseline">
|
||||||
<div className="flex items-baseline gap-2">
|
<div className="flex items-baseline gap-2">
|
||||||
<span className="text-slate-500 text-sm font-bold uppercase tracking-wider">Ширина:</span>
|
<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>
|
<span className="text-2xl font-bold text-white drop-shadow-sm">{config.drawer.width}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-baseline gap-2">
|
<div className="flex items-baseline gap-2">
|
||||||
<span className="text-slate-500 text-sm font-bold uppercase tracking-wider">Глубина:</span>
|
<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>
|
<span className="text-2xl font-bold text-white drop-shadow-sm">{config.drawer.depth}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-baseline gap-2">
|
<div className="flex items-baseline gap-2">
|
||||||
<span className="text-slate-500 text-sm font-bold uppercase tracking-wider">Высота:</span>
|
<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>
|
<span className="text-2xl font-bold text-white drop-shadow-sm">{config.drawer.height}</span>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-sm text-slate-500 font-bold self-baseline">мм</span>
|
<span className="text-sm text-slate-500 font-bold self-baseline">мм</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={handleShare}
|
onClick={handleShare}
|
||||||
className={`
|
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
|
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
|
${shareUrlCopied
|
||||||
? 'bg-green-600 border-green-500 text-white shadow-green-900/20'
|
? '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'
|
: 'bg-blue-600 hover:bg-blue-500 border-blue-500 text-white shadow-blue-900/20'
|
||||||
}
|
}
|
||||||
`}
|
`}
|
||||||
>
|
>
|
||||||
{shareUrlCopied ? <Check size={18} /> : <Share2 size={18} />}
|
{shareUrlCopied ? <Check size={18} /> : <Share2 size={18} />}
|
||||||
{shareUrlCopied ? 'СКОПИРОВАНО!' : 'Поделиться'}
|
{shareUrlCopied ? 'СКОПИРОВАНО!' : 'Поделиться'}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-col lg:flex-row h-full gap-6 relative flex-1 min-h-0">
|
<div className="flex flex-col lg:flex-row h-full gap-6 relative flex-1 min-h-0">
|
||||||
{/* 3D Viewer */}
|
{/* 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">
|
||||||
<Info size={14} /> Управление
|
<Info size={14} /> Управление
|
||||||
</div>
|
</div>
|
||||||
<ul className="space-y-1">
|
<ul className="space-y-1">
|
||||||
<li>• ЛКМ: Вращение</li>
|
<li>• ЛКМ: Вращение</li>
|
||||||
<li>• ПКМ: Перемещение</li>
|
<li>• ПКМ: Перемещение</li>
|
||||||
<li>• Скролл: Масштаб</li>
|
<li>• Скролл: Масштаб</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Canvas
|
<Canvas
|
||||||
shadows
|
shadows
|
||||||
dpr={[1, 2]}
|
dpr={[1, 2]}
|
||||||
camera={{
|
camera={{
|
||||||
position: [config.drawer.width * 1.5, config.drawer.height * 3, config.drawer.depth * 1.5],
|
position: [config.drawer.width * 1.5, config.drawer.height * 3, config.drawer.depth * 1.5],
|
||||||
fov: 45,
|
fov: 45,
|
||||||
near: 1,
|
near: 1,
|
||||||
far: 20000
|
far: 20000
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<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} />
|
||||||
<Environment preset="city" />
|
<Environment preset="city" />
|
||||||
<Center>
|
<Center>
|
||||||
<group>
|
<group>
|
||||||
<DrawerFrame config={config} />
|
<DrawerFrame config={config} />
|
||||||
{parts.map(part => (
|
{parts.map(part => (
|
||||||
<BinMesh
|
<BinMesh
|
||||||
key={part.id}
|
key={part.id}
|
||||||
part={part}
|
part={part}
|
||||||
thickness={config.wallThickness}
|
thickness={config.wallThickness}
|
||||||
cornerRadius={config.cornerRadius || 0}
|
cornerRadius={config.cornerRadius || 0}
|
||||||
isSelected={selectedId === part.id}
|
perforation={config.perforation}
|
||||||
onClick={() => setSelectedId(part.id)}
|
isSelected={selectedId === part.id}
|
||||||
/>
|
onClick={() => setSelectedId(part.id)}
|
||||||
))}
|
/>
|
||||||
</group>
|
))}
|
||||||
</Center>
|
</group>
|
||||||
<OrbitControls makeDefault minDistance={10} maxDistance={10000} />
|
</Center>
|
||||||
</Suspense>
|
<OrbitControls makeDefault minDistance={10} maxDistance={10000} />
|
||||||
</Canvas>
|
</Suspense>
|
||||||
</div>
|
</Canvas>
|
||||||
|
</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="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">
|
||||||
<Package size={24} /> Детали ({parts.length})
|
<Package size={24} /> Детали ({parts.length})
|
||||||
</h2>
|
</h2>
|
||||||
<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-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} />}
|
{isZipping ? <Loader2 size={16} className="animate-spin" /> : <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-1 custom-scrollbar">
|
||||||
<div className="grid grid-cols-2 gap-3 pb-4">
|
<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-3 rounded-lg border transition-all cursor-pointer group flex flex-col gap-2 relative overflow-hidden
|
p-3 rounded-lg border transition-all cursor-pointer group flex flex-col gap-2 relative overflow-hidden
|
||||||
${selectedId === part.id
|
${selectedId === part.id
|
||||||
? 'bg-slate-800 border-accent shadow-md shadow-accent/10 ring-1 ring-accent'
|
? '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'
|
: 'bg-slate-800/50 border-slate-700 hover:border-slate-500 hover:bg-slate-800'
|
||||||
}
|
}
|
||||||
`}
|
`}
|
||||||
onClick={() => setSelectedId(part.id)}
|
onClick={() => setSelectedId(part.id)}
|
||||||
>
|
>
|
||||||
{/* Индикатор цвета */}
|
{/* Индикатор цвета */}
|
||||||
<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="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 }}
|
style={{ backgroundColor: part.color, opacity: 0.1 }}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Заголовок */}
|
{/* Заголовок */}
|
||||||
<div className="flex items-center justify-between z-10">
|
<div className="flex items-center justify-between z-10">
|
||||||
<span className="font-bold text-gray-200 text-xs truncate" title={part.name}>
|
<span className="font-bold text-gray-200 text-xs truncate" title={part.name}>
|
||||||
{part.name}
|
{part.name}
|
||||||
</span>
|
</span>
|
||||||
<div
|
<div
|
||||||
className="w-2.5 h-2.5 rounded-full border border-white/20 shadow-sm"
|
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="text-[10px] text-gray-400 font-mono z-10">
|
<div className="text-[10px] text-gray-400 font-mono z-10">
|
||||||
{part.width.toFixed(0)} × {part.depth.toFixed(0)} × {part.height.toFixed(0)}
|
{part.width.toFixed(0)} × {part.depth.toFixed(0)} × {part.height.toFixed(0)}
|
||||||
</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-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
|
<Download size={12} /> STL
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
);
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
+562
-173
@@ -1,219 +1,608 @@
|
|||||||
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 } from '../types';
|
import { AppConfig, LayoutSplits, GeneratedPart, Partition, PerforationConfig } from '../types';
|
||||||
|
|
||||||
export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => {
|
export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => {
|
||||||
const parts: GeneratedPart[] = [];
|
const parts: GeneratedPart[] = [];
|
||||||
const safeX = Array.isArray(splits?.x) ? splits.x : [];
|
const safeX = Array.isArray(splits?.x) ? splits.x : [];
|
||||||
const safeY = Array.isArray(splits?.y) ? splits.y : [];
|
const safeY = Array.isArray(splits?.y) ? splits.y : [];
|
||||||
const safeParts = splits?.partitions || {};
|
const safeParts = splits?.partitions || {};
|
||||||
|
|
||||||
const xPoints = [0, ...[...safeX].sort((a, b) => a - b), 1];
|
const xPoints = [0, ...[...safeX].sort((a, b) => a - b), 1];
|
||||||
const yPoints = [0, ...[...safeY].sort((a, b) => a - b), 1];
|
const yPoints = [0, ...[...safeY].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 rawX = xPoints[i] * config.drawer.width;
|
const rawW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width;
|
||||||
const rawY = yPoints[j] * config.drawer.depth;
|
const rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
|
||||||
const rawW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width;
|
|
||||||
const rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
|
|
||||||
|
|
||||||
const internalPartitions = safeParts[`${i}-${j}`] || [];
|
if (rawW < 5 || rawD < 5) continue;
|
||||||
|
|
||||||
const realWidth = rawW - config.printerTolerance;
|
const rawX = xPoints[i] * config.drawer.width;
|
||||||
const realDepth = rawD - config.printerTolerance;
|
const rawY = yPoints[j] * config.drawer.depth;
|
||||||
const realX = rawX + (config.printerTolerance / 2);
|
const internalPartitions = safeParts[`${i}-${j}`] || [];
|
||||||
const realY = rawY + (config.printerTolerance / 2);
|
|
||||||
|
|
||||||
if (realWidth < 5 || realDepth < 5) continue;
|
const realWidth = rawW - config.printerTolerance;
|
||||||
|
const realDepth = rawD - config.printerTolerance;
|
||||||
|
const realX = rawX + (config.printerTolerance / 2);
|
||||||
|
const realY = rawY + (config.printerTolerance / 2);
|
||||||
|
|
||||||
parts.push({
|
parts.push({
|
||||||
id: `part-${partCounter}`,
|
id: `part-${partCounter}`,
|
||||||
name: `Ячейка ${i+1}-${j+1}`,
|
name: `Ячейка ${i + 1}-${j + 1}`,
|
||||||
width: realWidth,
|
width: realWidth,
|
||||||
depth: realDepth,
|
depth: realDepth,
|
||||||
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(${Math.random() * 360}, 70%, 50%)`,
|
||||||
internalPartitions: internalPartitions
|
internalPartitions: internalPartitions
|
||||||
});
|
});
|
||||||
partCounter++;
|
partCounter++;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
return parts;
|
||||||
return parts;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- ГЕОМЕТРИЯ ---
|
// --- ГЕОМЕТРИЯ ---
|
||||||
|
|
||||||
// 1. Форма скругленного прямоугольника (для дна и внешних стенок)
|
|
||||||
const createRoundedRectShape = (width: number, height: number, radius: number): THREE.Shape => {
|
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, height / 2);
|
|
||||||
|
|
||||||
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;
|
|
||||||
};
|
|
||||||
|
|
||||||
// 2. Форма галтели (вогнутого треугольника) для углов
|
|
||||||
const createFilletShape = (radius: number): THREE.Shape => {
|
|
||||||
const shape = new THREE.Shape();
|
const shape = new THREE.Shape();
|
||||||
// Начинаем из угла (0,0)
|
const x = -width / 2;
|
||||||
shape.moveTo(0, 0);
|
const y = -height / 2;
|
||||||
// Линия вдоль одной стенки
|
const r = Math.min(radius, width / 2 - 0.1, height / 2 - 0.1);
|
||||||
shape.lineTo(radius, 0);
|
|
||||||
// Вогнутая дуга к другой стенке
|
|
||||||
// Центр окружности (radius, radius), радиус radius.
|
|
||||||
// Рисуем дугу от 270 (-PI/2) до 180 (PI) градусов по часовой стрелке
|
|
||||||
shape.absarc(radius, radius, radius, 1.5 * Math.PI, Math.PI, true);
|
|
||||||
// Замыкаем в угол
|
|
||||||
shape.lineTo(0, 0);
|
|
||||||
|
|
||||||
|
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;
|
return shape;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const createBinGeometry = (
|
const createConcaveFilletShape = (radius: number): THREE.Shape => {
|
||||||
width: number, depth: number, height: number, thickness: number, radius: number = 0, partitions: Partition[] = []
|
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,
|
||||||
|
height: number,
|
||||||
|
thickness: number,
|
||||||
|
perf: PerforationConfig,
|
||||||
|
marginLeft: number = 0,
|
||||||
|
marginRight: number = 0,
|
||||||
|
exclusions: { start: number, end: number, yMax?: number }[] = []
|
||||||
): THREE.BufferGeometry => {
|
): THREE.BufferGeometry => {
|
||||||
const geometries: THREE.BufferGeometry[] = [];
|
const shape = new THREE.Shape();
|
||||||
|
shape.moveTo(0, 0);
|
||||||
|
shape.lineTo(width, 0);
|
||||||
|
shape.lineTo(width, height);
|
||||||
|
shape.lineTo(0, height);
|
||||||
|
shape.lineTo(0, 0);
|
||||||
|
|
||||||
// ДНО
|
// Генерация отверстий
|
||||||
const floorShape = createRoundedRectShape(width, depth, radius);
|
if (perf && perf.enabled && width > perf.size && height > perf.size) {
|
||||||
const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false, curveSegments: 12 });
|
const { shape: shapeType, size, gap } = perf;
|
||||||
floorGeo.rotateX(-Math.PI / 2);
|
const step = size + gap;
|
||||||
geometries.push(floorGeo);
|
// Отступы: предотвращаем попадание отверстий на сплошные края
|
||||||
|
const startX = Math.max(gap, marginLeft + gap);
|
||||||
|
const startY = gap;
|
||||||
|
const endX = width - Math.max(gap, marginRight + gap);
|
||||||
|
const endY = height - gap;
|
||||||
|
|
||||||
// ВНЕШНИЕ СТЕНКИ
|
// Строки
|
||||||
const outerShape = createRoundedRectShape(width, depth, radius);
|
let row = 0;
|
||||||
const innerRadius = Math.max(0, radius - thickness);
|
for (let y = startY + size / 2; y < endY; y += (shapeType === 'triangle' || shapeType === 'honeycomb' ? step * 0.866 : step)) {
|
||||||
const innerWidth = width - (2 * thickness);
|
const isStaggered = (row % 2 !== 0);
|
||||||
const innerDepth = depth - (2 * thickness);
|
const xOffset = (isStaggered && (shapeType === 'honeycomb' || shapeType === 'triangle')) ? step / 2 : 0;
|
||||||
|
|
||||||
if (innerWidth > 0 && innerDepth > 0) {
|
for (let x = startX + size / 2 + xOffset; x < endX; x += step) {
|
||||||
const innerHole = createRoundedRectShape(innerWidth, innerDepth, innerRadius);
|
const hole = new THREE.Path();
|
||||||
outerShape.holes.push(innerHole);
|
const r = size / 2;
|
||||||
}
|
|
||||||
|
|
||||||
const wallHeight = height - thickness;
|
// Проверка границ
|
||||||
const wallGeo = new THREE.ExtrudeGeometry(outerShape, { depth: wallHeight, bevelEnabled: false, curveSegments: 12 });
|
if (x - r < marginLeft || x + r > width - marginRight || y - r < 0 || y + r > height) continue;
|
||||||
wallGeo.rotateX(-Math.PI / 2);
|
|
||||||
wallGeo.translate(0, thickness, 0);
|
|
||||||
geometries.push(wallGeo);
|
|
||||||
|
|
||||||
// ВНУТРЕННИЕ ПЕРЕГОРОДКИ И СКРУГЛЕНИЯ
|
// Проверка зон исключения
|
||||||
partitions.forEach(p => {
|
// Зона активна, если X отверстия входит в [start, end] И Y отверстия ниже yMax (если указан).
|
||||||
const pMin = p.min ?? 0;
|
// Если y > yMax, исключение не применяется (отверстие выше пересекающей стенки).
|
||||||
const pMax = p.max ?? 1;
|
// Примечание: y измеряется от низа (0) до верха (height).
|
||||||
const lengthRatio = pMax - pMin;
|
// yMax - высота пересекающей перегородки.
|
||||||
const midRatio = pMin + (lengthRatio / 2);
|
|
||||||
|
|
||||||
let pWidth = 0, pDepth = 0, pX = 0, pY = 0;
|
const inExclusion = exclusions.some(zone => {
|
||||||
|
if (x + r <= zone.start || x - r >= zone.end) return false; // Проверка по оси X
|
||||||
|
if (zone.yMax !== undefined && y - r > zone.yMax) return false; // Проверка по оси Y (отверстие выше стенки)
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
// Размеры самой стенки
|
if (inExclusion) continue;
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Создаем стенку
|
if (shapeType === 'circle') {
|
||||||
const partShape = createRoundedRectShape(pWidth, pDepth, 0.1); // Чуть-чуть скругляем саму стенку, чтобы не была острой
|
hole.absarc(x, y, r, 0, Math.PI * 2, true);
|
||||||
const partGeo = new THREE.ExtrudeGeometry(partShape, { depth: p.height, bevelEnabled: false, curveSegments: 2 });
|
} else if (shapeType === 'honeycomb') {
|
||||||
partGeo.rotateX(-Math.PI / 2);
|
// Шестиугольник (Соты)
|
||||||
partGeo.translate(pX, thickness, pY);
|
for (let i = 0; i < 6; i++) {
|
||||||
geometries.push(partGeo);
|
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') {
|
||||||
|
// Треугольник
|
||||||
|
const ang1 = -90 * Math.PI / 180;
|
||||||
|
const ang2 = 30 * Math.PI / 180;
|
||||||
|
const ang3 = 150 * Math.PI / 180;
|
||||||
|
hole.moveTo(x + r * Math.cos(ang1), y + r * Math.sin(ang1));
|
||||||
|
hole.lineTo(x + r * Math.cos(ang2), y + r * Math.sin(ang2));
|
||||||
|
hole.lineTo(x + r * Math.cos(ang3), y + r * Math.sin(ang3));
|
||||||
|
hole.closePath();
|
||||||
|
}
|
||||||
|
shape.holes.push(hole);
|
||||||
|
}
|
||||||
|
row++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// --- ДОБАВЛЕНИЕ ГАЛТЕЛЕЙ (FILLETS) ---
|
const geo = new THREE.ExtrudeGeometry(shape, { depth: thickness, bevelEnabled: false });
|
||||||
if (p.rounded && radius > 0.5) {
|
// Выдавливание по Z. Стенка плоская в XY.
|
||||||
// Радиус скругления такой же, как у углов ящика, но не больше разумного предела
|
// Мы хотим, чтобы "thickness" была глубиной по Z.
|
||||||
const filletR = Math.min(radius, 6);
|
return geo;
|
||||||
const filletShape = createFilletShape(filletR);
|
};
|
||||||
const filletExtrudeSettings = { depth: p.height, bevelEnabled: false, curveSegments: 8 };
|
|
||||||
|
|
||||||
// Функция для создания и позиционирования одной галтели
|
// Вспомогательная функция: Создание профиля угла (Выдавленный вертикально)
|
||||||
const addFillet = (x: number, y: number, rotation: number) => {
|
const createCornerProfile = (radius: number, thickness: number, height: number): THREE.BufferGeometry => {
|
||||||
const geo = new THREE.ExtrudeGeometry(filletShape, filletExtrudeSettings);
|
if (radius <= 0) return new THREE.BufferGeometry();
|
||||||
geo.rotateX(-Math.PI / 2); // Положить на пол
|
const shape = new THREE.Shape();
|
||||||
geo.rotateY(rotation); // Повернуть в нужный угол
|
|
||||||
|
|
||||||
// Корректировка позиции после вращения вокруг (0,0)
|
// Создаем сегмент кольца (Полый угол) как единый контур.
|
||||||
// Нам нужно сместить так, чтобы угол (0,0) галтели совпал с углом стыка
|
// Центр в (0,0).
|
||||||
geo.translate(x, thickness, y);
|
const innerRadius = Math.max(0.01, radius - thickness); // Гарантируем чуть > 0 для целостности формы
|
||||||
geometries.push(geo);
|
|
||||||
};
|
|
||||||
|
|
||||||
const halfThick = thickness / 2;
|
// 1. Начало внешней дуги
|
||||||
|
shape.moveTo(radius, 0);
|
||||||
|
|
||||||
if (p.axis === 'x') {
|
// 2. Внешняя дуга (против часовой стрелки) -> К (0, radius)
|
||||||
// Вертикальная стенка. Концы: Top (pMin) и Bottom (pMax) (в 2D координатах Y)
|
shape.absarc(0, 0, radius, 0, Math.PI / 2, false);
|
||||||
// Y координата начала: -innerDepth/2 + innerDepth * pMin
|
|
||||||
// Y координата конца: -innerDepth/2 + innerDepth * pMax
|
|
||||||
// X координата центра: pX
|
|
||||||
|
|
||||||
const startY = (-innerDepth / 2) + (innerDepth * pMin);
|
// 3. Линия к внутреннему концу (0, innerRadius)
|
||||||
const endY = (-innerDepth / 2) + (innerDepth * pMax);
|
shape.lineTo(0, innerRadius);
|
||||||
|
|
||||||
// 4 Угла:
|
// 4. Внутренняя дуга (по часовой стрелке) -> К (innerRadius, 0)
|
||||||
// 1. Start Left: X = pX - halfThick, Y = startY. Rotation: 0 (смотрит вправо-вверх? нет)
|
shape.absarc(0, 0, innerRadius, Math.PI / 2, 0, true);
|
||||||
// Галтель рисуется в +X, +Y квадранте от 0,0.
|
|
||||||
// Нам нужно заполнить угол между стенкой (идет вниз) и перпендикуляром.
|
|
||||||
|
|
||||||
// Start (Top in 2D view, actually Min Y in 3D logic here usually means "Back")
|
// 5. Замыкаем контур
|
||||||
// Let's assume standard plan view:
|
shape.lineTo(radius, 0);
|
||||||
// Min Y is "Top" edge visually in SVG usually 0. In 3D Z is Y.
|
|
||||||
|
|
||||||
// Min End (Start of wall):
|
// Выдавливание
|
||||||
addFillet(pX - halfThick, startY, 0); // Left side, pointing towards +Z (down in visual)
|
// curveSegments 32 для гладкости
|
||||||
addFillet(pX + halfThick, startY, -Math.PI/2); // Right side
|
const geo = new THREE.ExtrudeGeometry(shape, { depth: height, bevelEnabled: false, curveSegments: 32 });
|
||||||
|
return geo;
|
||||||
|
};
|
||||||
|
|
||||||
// Max End (End of wall):
|
export const createBinGeometry = (
|
||||||
addFillet(pX - halfThick, endY, Math.PI/2); // Left side
|
width: number,
|
||||||
addFillet(pX + halfThick, endY, Math.PI); // Right side
|
depth: number,
|
||||||
} else {
|
height: number,
|
||||||
// Горизонтальная стенка
|
thickness: number,
|
||||||
const startX = (-innerWidth / 2) + (innerWidth * pMin);
|
radius: number = 0,
|
||||||
const endX = (-innerWidth / 2) + (innerWidth * pMax);
|
partitions: Partition[] = [],
|
||||||
|
perforation?: PerforationConfig
|
||||||
|
): THREE.BufferGeometry => {
|
||||||
|
const geometries: THREE.BufferGeometry[] = [];
|
||||||
|
|
||||||
// Min End (Left side):
|
// ДНО (Floor) - Always same
|
||||||
addFillet(startX, pY + halfThick, -Math.PI/2);
|
const floorShape = createRoundedRectShape(width, depth, radius);
|
||||||
addFillet(startX, pY - halfThick, 0);
|
const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false });
|
||||||
|
floorGeo.rotateX(-Math.PI / 2); // Lay flat
|
||||||
|
geometries.push(floorGeo);
|
||||||
|
|
||||||
// Max End (Right side):
|
// СТЕНКИ
|
||||||
addFillet(endX, pY + halfThick, Math.PI);
|
if (!perforation || !perforation.enabled) {
|
||||||
addFillet(endX, pY - halfThick, Math.PI/2);
|
// --- ЛОГИКА ДЛЯ СПЛОШНЫХ СТЕН (Без перфорации) ---
|
||||||
}
|
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 merged = mergeBufferGeometries(geometries);
|
if (innerWidth > 0.1 && innerDepth > 0.1) {
|
||||||
if (merged) merged.computeVertexNormals();
|
const innerHole = createRoundedRectShape(innerWidth, innerDepth, innerRadius);
|
||||||
return merged || new THREE.BoxGeometry(1, 1, 1);
|
outerShape.holes.push(innerHole);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
const straightD = depth - 2 * effRadius;
|
||||||
|
|
||||||
|
// 1. Углы (4 шт)
|
||||||
|
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); // Ближняя
|
||||||
|
if ((p.min ?? 0) < 0.01) exclusionsBack.push(zone); // Дальняя
|
||||||
|
}
|
||||||
|
|
||||||
|
} else { // p.axis === 'y'
|
||||||
|
// Идет по ширине (Ось X в макете).
|
||||||
|
// Пересекает Левую и Правую стенки.
|
||||||
|
|
||||||
|
const partGlobalZ = (-effectiveInnerD / 2) + (effectiveInnerD * p.offset);
|
||||||
|
const sD = depth - 2 * effRadius;
|
||||||
|
const localXOnWall = partGlobalZ + sD / 2;
|
||||||
|
|
||||||
|
if (localXOnWall + thickness / 2 + padding > 0 && localXOnWall - thickness / 2 - padding < sD) {
|
||||||
|
const zone = {
|
||||||
|
start: localXOnWall - thickness / 2 - padding,
|
||||||
|
end: localXOnWall + thickness / 2 + padding,
|
||||||
|
yMax: hEff
|
||||||
|
};
|
||||||
|
|
||||||
|
if ((p.min ?? 0) < 0.01) {
|
||||||
|
exclusionsLeft.push(zone);
|
||||||
|
}
|
||||||
|
if ((p.max ?? 1) > 0.99) {
|
||||||
|
exclusionsRight.push(zone);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Передняя/Задняя
|
||||||
|
if (straightW > 0.1) {
|
||||||
|
// Стенка 1 (+Z). Это "Передняя" (Ближняя). Контактирует с p.max.
|
||||||
|
// Использует exclusionsFront.
|
||||||
|
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);
|
||||||
|
if (merged) merged.computeVertexNormals();
|
||||||
|
return merged || new THREE.BoxGeometry(1, 1, 1);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {
|
export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {
|
||||||
@@ -225,7 +614,7 @@ export const generateSTL = (mesh: THREE.Object3D): Uint8Array | 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], { type: 'application/octet-stream' });
|
const blob = new Blob([result as any], { 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;
|
||||||
|
|||||||
@@ -9,6 +9,16 @@ export interface AppConfig {
|
|||||||
wallThickness: number;
|
wallThickness: number;
|
||||||
printerTolerance: number;
|
printerTolerance: number;
|
||||||
cornerRadius: number;
|
cornerRadius: number;
|
||||||
|
perforation: PerforationConfig;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PerforationShape = 'circle' | 'honeycomb' | 'triangle' | 'diamond';
|
||||||
|
|
||||||
|
export interface PerforationConfig {
|
||||||
|
enabled: boolean;
|
||||||
|
shape: PerforationShape;
|
||||||
|
size: number;
|
||||||
|
gap: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Partition {
|
export interface Partition {
|
||||||
|
|||||||
Reference in New Issue
Block a user