12
This commit is contained in:
+142
-226
@@ -1,17 +1,18 @@
|
|||||||
import React, { Suspense, useEffect, useRef, useState, useMemo } from 'react';
|
import React, { useMemo, Suspense, useEffect, useRef, useState } from 'react';
|
||||||
import { Canvas } from '@react-three/fiber';
|
import { Canvas } from '@react-three/fiber';
|
||||||
import { OrbitControls, Center, Environment } from '@react-three/drei';
|
import { OrbitControls, Center, Environment } from '@react-three/drei';
|
||||||
import * as THREE from 'three';
|
import * as THREE from 'three';
|
||||||
import JSZip from 'jszip';
|
import JSZip from 'jszip';
|
||||||
import { AppConfig, GeneratedPart, LayoutSplits } from '../types';
|
import { AppConfig, GeneratedPart } from '../types';
|
||||||
import { createBinGeometry, generateSTL, exportSTL } from '../services/geometryGenerator';
|
import { createBinGeometry, exportSTL, generateSTL } from '../services/geometryGenerator';
|
||||||
import { Download, Package, Info, Loader2, Share2, Check, Ruler } from 'lucide-react';
|
import { Download, Package, Info, Loader2 } from 'lucide-react';
|
||||||
import { generateShareUrl } from '../utils/share';
|
|
||||||
|
// --- 3D Helper Components ---
|
||||||
|
|
||||||
// --- DrawerFrame (Каркас ящика) ---
|
|
||||||
const DrawerFrame = ({ config }: { config: AppConfig }) => {
|
const DrawerFrame = ({ config }: { config: AppConfig }) => {
|
||||||
const { width, depth, height } = config.drawer;
|
const { width, depth, height } = config.drawer;
|
||||||
const offset = 0.5;
|
const offset = 0.5;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<group position={[width / 2, height / 2, depth / 2]}>
|
<group position={[width / 2, height / 2, depth / 2]}>
|
||||||
<lineSegments>
|
<lineSegments>
|
||||||
@@ -22,49 +23,43 @@ const DrawerFrame = ({ config }: { config: AppConfig }) => {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- BinMesh (Ячейка) ---
|
// --- Bin Component ---
|
||||||
|
|
||||||
interface BinMeshProps {
|
interface BinMeshProps {
|
||||||
part: GeneratedPart;
|
part: GeneratedPart;
|
||||||
thickness: number;
|
config: AppConfig;
|
||||||
cornerRadius: number;
|
|
||||||
isSelected: boolean;
|
isSelected: boolean;
|
||||||
onClick: () => void;
|
onClick: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSelected, onClick }) => {
|
const BinMesh: React.FC<BinMeshProps> = ({ part, config, isSelected, onClick }) => {
|
||||||
// 1. Создаем геометрию, учитывая ВНУТРЕННИЕ ПЕРЕГОРОДКИ
|
// Мемоизация геометрии для производительности
|
||||||
const geometry = useMemo(() => {
|
const geometry = useMemo(() => {
|
||||||
return createBinGeometry(
|
return createBinGeometry(
|
||||||
part.width,
|
part.width,
|
||||||
part.depth,
|
part.depth,
|
||||||
part.height,
|
part.height,
|
||||||
thickness,
|
config.wallThickness,
|
||||||
cornerRadius,
|
config.perforation // Передаем конфиг перфорации!
|
||||||
part.internalPartitions // <--- ВАЖНО: передаем перегородки в генератор
|
|
||||||
);
|
);
|
||||||
}, [part, thickness, cornerRadius]);
|
}, [part, config.wallThickness, config.perforation]);
|
||||||
|
|
||||||
// 2. Создаем контур выделения (EdgesGeometry)
|
|
||||||
// Threshold 20 градусов скрывает линии на плавных скруглениях
|
|
||||||
const edgesGeometry = useMemo(() => {
|
|
||||||
return new THREE.EdgesGeometry(geometry, 20);
|
|
||||||
}, [geometry]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<group position={[part.x + part.width/2, 0, part.y + part.depth/2]}>
|
<group position={[part.x + part.width/2, 0, part.y + part.depth/2]}>
|
||||||
{/* Сама модель */}
|
<mesh
|
||||||
<mesh geometry={geometry} onClick={(e) => { e.stopPropagation(); onClick(); }}>
|
geometry={geometry}
|
||||||
|
onClick={(e) => { e.stopPropagation(); onClick(); }}
|
||||||
|
>
|
||||||
<meshStandardMaterial
|
<meshStandardMaterial
|
||||||
color={isSelected ? '#f59e0b' : part.color}
|
color={isSelected ? '#f59e0b' : part.color}
|
||||||
roughness={0.5}
|
roughness={0.5}
|
||||||
metalness={0.1}
|
metalness={0.1}
|
||||||
side={THREE.DoubleSide} // Рисуем обе стороны стенок
|
|
||||||
/>
|
/>
|
||||||
</mesh>
|
</mesh>
|
||||||
|
|
||||||
{/* Белая подсветка при выборе */}
|
|
||||||
{isSelected && (
|
{isSelected && (
|
||||||
<lineSegments geometry={edgesGeometry}>
|
<lineSegments position={[0, part.height/2, 0]}>
|
||||||
|
<edgesGeometry args={[new THREE.BoxGeometry(part.width, part.height, part.depth)]} />
|
||||||
<lineBasicMaterial color="white" linewidth={2} />
|
<lineBasicMaterial color="white" linewidth={2} />
|
||||||
</lineSegments>
|
</lineSegments>
|
||||||
)}
|
)}
|
||||||
@@ -72,162 +67,84 @@ const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSele
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- PreviewStep (Основной компонент) ---
|
|
||||||
interface Props {
|
interface Props {
|
||||||
parts: GeneratedPart[];
|
parts: GeneratedPart[];
|
||||||
config: AppConfig;
|
config: AppConfig;
|
||||||
splits: LayoutSplits;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
|
export const PreviewStep: React.FC<Props> = ({ parts, config }) => {
|
||||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||||
const [isZipping, setIsZipping] = useState(false);
|
const [isZipping, setIsZipping] = useState(false);
|
||||||
const [shareUrlCopied, setShareUrlCopied] = useState(false);
|
|
||||||
const itemRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});
|
const itemRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});
|
||||||
|
|
||||||
// Скролл к выбранной детали в списке
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (selectedId && itemRefs.current[selectedId]) {
|
if (selectedId && itemRefs.current[selectedId]) {
|
||||||
itemRefs.current[selectedId]?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
itemRefs.current[selectedId]?.scrollIntoView({
|
||||||
|
behavior: 'smooth',
|
||||||
|
block: 'center'
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}, [selectedId]);
|
}, [selectedId]);
|
||||||
|
|
||||||
// Скачивание одной детали
|
|
||||||
const handleDownload = (part: GeneratedPart) => {
|
const handleDownload = (part: GeneratedPart) => {
|
||||||
const geometry = createBinGeometry(
|
const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness, config.perforation);
|
||||||
part.width,
|
|
||||||
part.depth,
|
|
||||||
part.height,
|
|
||||||
config.wallThickness,
|
|
||||||
config.cornerRadius,
|
|
||||||
part.internalPartitions // <--- ВАЖНО для STL
|
|
||||||
);
|
|
||||||
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
|
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
|
||||||
exportSTL(mesh, `${part.name.replace(/\s+/g, '_')}.stl`);
|
exportSTL(mesh, `${part.name.replace(/\s+/g, '_')}.stl`);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Скачивание всего архивом
|
|
||||||
const handleDownloadAll = async () => {
|
const handleDownloadAll = async () => {
|
||||||
if (isZipping) return;
|
if (isZipping) return;
|
||||||
setIsZipping(true);
|
setIsZipping(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
console.log("Starting ZIP generation...");
|
||||||
|
if (typeof JSZip === 'undefined' && !JSZip) {
|
||||||
|
throw new Error("Библиотека JSZip не загружена.");
|
||||||
|
}
|
||||||
|
|
||||||
const zip = new JSZip();
|
const zip = new JSZip();
|
||||||
|
|
||||||
parts.forEach(part => {
|
parts.forEach(part => {
|
||||||
const geometry = createBinGeometry(
|
const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness, config.perforation);
|
||||||
part.width,
|
|
||||||
part.depth,
|
|
||||||
part.height,
|
|
||||||
config.wallThickness,
|
|
||||||
config.cornerRadius,
|
|
||||||
part.internalPartitions // <--- ВАЖНО для STL
|
|
||||||
);
|
|
||||||
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
|
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
|
||||||
const stlData = generateSTL(mesh);
|
const stlData = generateSTL(mesh);
|
||||||
zip.file(`${part.name.replace(/\s+/g, '_')}.stl`, stlData);
|
zip.file(`${part.name.replace(/\s+/g, '_')}.stl`, stlData);
|
||||||
});
|
});
|
||||||
|
|
||||||
const content = await zip.generateAsync({ type: "blob" });
|
const content = await zip.generateAsync({ type: "blob" });
|
||||||
|
|
||||||
const link = document.createElement('a');
|
const link = document.createElement('a');
|
||||||
link.href = URL.createObjectURL(content);
|
link.href = URL.createObjectURL(content);
|
||||||
link.download = "PrintFit_Project.zip";
|
link.download = "PrintFit_Project.zip";
|
||||||
document.body.appendChild(link);
|
document.body.appendChild(link);
|
||||||
link.click();
|
link.click();
|
||||||
document.body.removeChild(link);
|
document.body.removeChild(link);
|
||||||
|
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
alert(`Ошибка архивации: ${e.message}`);
|
console.error("Failed to create zip archive", e);
|
||||||
|
alert(`Ошибка при создании архива: ${e.message || 'Неизвестная ошибка'}`);
|
||||||
} finally {
|
} finally {
|
||||||
setIsZipping(false);
|
setIsZipping(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Поделиться ссылкой
|
|
||||||
const handleShare = async () => {
|
|
||||||
const url = generateShareUrl(config, splits);
|
|
||||||
let success = false;
|
|
||||||
try {
|
|
||||||
if (navigator.clipboard && navigator.clipboard.writeText) {
|
|
||||||
await navigator.clipboard.writeText(url);
|
|
||||||
success = true;
|
|
||||||
} else { throw new Error('Clipboard API unavailable'); }
|
|
||||||
} catch (err) {
|
|
||||||
try {
|
|
||||||
const textArea = document.createElement("textarea");
|
|
||||||
textArea.value = url;
|
|
||||||
textArea.style.position = "fixed";
|
|
||||||
textArea.style.left = "-9999px";
|
|
||||||
textArea.style.top = "0";
|
|
||||||
document.body.appendChild(textArea);
|
|
||||||
textArea.focus();
|
|
||||||
textArea.select();
|
|
||||||
const result = document.execCommand('copy');
|
|
||||||
document.body.removeChild(textArea);
|
|
||||||
if (result) success = true;
|
|
||||||
} catch (e) { console.error("Copy failed", e); }
|
|
||||||
}
|
|
||||||
if (success) {
|
|
||||||
setShareUrlCopied(true);
|
|
||||||
setTimeout(() => setShareUrlCopied(false), 3000);
|
|
||||||
} else {
|
|
||||||
prompt("Скопируйте ссылку вручную:", url);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col h-full">
|
<div className="flex flex-col lg:flex-row h-full gap-6">
|
||||||
{/* Верхняя панель: Размеры + Поделиться */}
|
{/* 3D Viewer */}
|
||||||
<div className="flex flex-col xl:flex-row justify-between items-center bg-slate-800/80 p-4 rounded-xl border border-slate-700 mb-4 gap-4 backdrop-blur-sm shadow-lg">
|
<div className="flex-1 bg-slate-900 rounded-xl overflow-hidden shadow-2xl border border-slate-800 relative min-h-[400px]">
|
||||||
|
<div className="absolute top-4 right-4 z-10 bg-black/60 p-3 rounded-lg text-xs text-gray-300 backdrop-blur pointer-events-none border border-slate-700">
|
||||||
|
<div className="flex items-center gap-2 mb-1 text-primary font-bold">
|
||||||
|
<Info size={14} /> Управление
|
||||||
|
</div>
|
||||||
|
<ul className="space-y-1">
|
||||||
|
<li>• ЛКМ: Вращение</li>
|
||||||
|
<li>• ПКМ: Перемещение</li>
|
||||||
|
<li>• Скролл: Масштаб</li>
|
||||||
|
<li className="text-accent mt-2 font-semibold">• Клик по детали для выбора</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-wrap items-center gap-6 justify-center md:justify-start">
|
<Canvas
|
||||||
<div className="hidden md:flex items-center gap-2 text-gray-300 mr-2">
|
|
||||||
<Ruler className="text-primary" size={20} />
|
|
||||||
<span className="font-medium text-sm uppercase tracking-wide opacity-70">Размеры ящика:</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-wrap gap-6 font-mono text-white items-baseline">
|
|
||||||
<div className="flex items-baseline gap-2">
|
|
||||||
<span className="text-slate-500 text-sm font-bold uppercase tracking-wider">Ширина:</span>
|
|
||||||
<span className="text-2xl font-bold text-white drop-shadow-sm">{config.drawer.width}</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-baseline gap-2">
|
|
||||||
<span className="text-slate-500 text-sm font-bold uppercase tracking-wider">Глубина:</span>
|
|
||||||
<span className="text-2xl font-bold text-white drop-shadow-sm">{config.drawer.depth}</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-baseline gap-2">
|
|
||||||
<span className="text-slate-500 text-sm font-bold uppercase tracking-wider">Высота:</span>
|
|
||||||
<span className="text-2xl font-bold text-white drop-shadow-sm">{config.drawer.height}</span>
|
|
||||||
</div>
|
|
||||||
<span className="text-sm text-slate-500 font-bold self-baseline">мм</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={handleShare}
|
|
||||||
className={`
|
|
||||||
flex items-center gap-2 px-6 py-3 rounded-lg text-sm font-bold transition-all border shadow-md active:scale-95 shrink-0
|
|
||||||
${shareUrlCopied
|
|
||||||
? 'bg-green-600 border-green-500 text-white shadow-green-900/20'
|
|
||||||
: 'bg-blue-600 hover:bg-blue-500 border-blue-500 text-white shadow-blue-900/20'
|
|
||||||
}
|
|
||||||
`}
|
|
||||||
>
|
|
||||||
{shareUrlCopied ? <Check size={18} /> : <Share2 size={18} />}
|
|
||||||
{shareUrlCopied ? 'СКОПИРОВАНО!' : 'Поделиться'}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-col lg:flex-row h-full gap-6 relative flex-1 min-h-0">
|
|
||||||
{/* 3D Viewer */}
|
|
||||||
<div className="flex-1 bg-slate-900 rounded-xl overflow-hidden shadow-2xl border border-slate-800 relative min-h-[400px]">
|
|
||||||
<div className="absolute top-4 right-4 z-10 bg-black/60 p-3 rounded-lg text-xs text-gray-300 backdrop-blur pointer-events-none border border-slate-700">
|
|
||||||
<div className="flex items-center gap-2 mb-1 text-primary font-bold">
|
|
||||||
<Info size={14} /> Управление
|
|
||||||
</div>
|
|
||||||
<ul className="space-y-1">
|
|
||||||
<li>• ЛКМ: Вращение</li>
|
|
||||||
<li>• ПКМ: Перемещение</li>
|
|
||||||
<li>• Скролл: Масштаб</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Canvas
|
|
||||||
shadows
|
shadows
|
||||||
dpr={[1, 2]}
|
dpr={[1, 2]}
|
||||||
camera={{
|
camera={{
|
||||||
@@ -236,96 +153,95 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
|
|||||||
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} />
|
|
||||||
<directionalLight position={[100, 200, 50]} intensity={1.2} />
|
<ambientLight intensity={0.7} />
|
||||||
<Environment preset="city" />
|
<directionalLight position={[100, 200, 50]} intensity={1.2} />
|
||||||
<Center>
|
<directionalLight position={[-100, 100, -50]} intensity={0.5} />
|
||||||
<group>
|
<Environment preset="city" />
|
||||||
<DrawerFrame config={config} />
|
|
||||||
{parts.map(part => (
|
<Center>
|
||||||
<BinMesh
|
<group>
|
||||||
key={part.id}
|
<DrawerFrame config={config} />
|
||||||
part={part}
|
{parts.map(part => (
|
||||||
thickness={config.wallThickness}
|
<BinMesh
|
||||||
cornerRadius={config.cornerRadius || 0}
|
key={part.id}
|
||||||
isSelected={selectedId === part.id}
|
part={part}
|
||||||
onClick={() => setSelectedId(part.id)}
|
config={config}
|
||||||
/>
|
isSelected={selectedId === part.id}
|
||||||
))}
|
onClick={() => setSelectedId(part.id)}
|
||||||
</group>
|
/>
|
||||||
</Center>
|
))}
|
||||||
<OrbitControls makeDefault minDistance={10} maxDistance={10000} />
|
</group>
|
||||||
</Suspense>
|
</Center>
|
||||||
</Canvas>
|
|
||||||
|
<OrbitControls makeDefault minDistance={10} maxDistance={10000} />
|
||||||
|
</Suspense>
|
||||||
|
</Canvas>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Sidebar List */}
|
||||||
|
<div className="w-full lg:w-96 bg-slate-900 p-6 rounded-xl border border-slate-800 flex flex-col h-full shadow-xl">
|
||||||
|
<div className="flex justify-between items-center mb-6 shrink-0">
|
||||||
|
<h2 className="text-xl font-bold flex items-center gap-2 text-primary">
|
||||||
|
<Package size={24} /> Детали ({parts.length})
|
||||||
|
</h2>
|
||||||
|
<button
|
||||||
|
onClick={handleDownloadAll}
|
||||||
|
disabled={isZipping || parts.length === 0}
|
||||||
|
className={`bg-green-600 hover:bg-green-700 text-white px-3 py-1.5 rounded-md text-sm font-medium flex items-center gap-1 transition-all active:scale-95 disabled:opacity-50 disabled:scale-100 disabled:cursor-not-allowed`}
|
||||||
|
>
|
||||||
|
{isZipping ? (
|
||||||
|
<>
|
||||||
|
<Loader2 size={16} className="animate-spin" /> ZIP...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Download size={16} /> Скачать все
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Sidebar List (Grid Layout) */}
|
<div className="flex-1 overflow-y-auto pr-2 space-y-3 custom-scrollbar">
|
||||||
<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">
|
{parts.map(part => (
|
||||||
<div className="flex justify-between items-center mb-6 shrink-0">
|
<div
|
||||||
<h2 className="text-xl font-bold flex items-center gap-2 text-primary">
|
key={part.id}
|
||||||
<Package size={24} /> Детали ({parts.length})
|
ref={(el) => { itemRefs.current[part.id] = el }}
|
||||||
</h2>
|
className={`p-4 rounded-lg border transition-all cursor-pointer group ${selectedId === part.id ? 'bg-slate-800 border-accent shadow-md shadow-accent/10 ring-1 ring-accent' : 'bg-slate-800/50 border-slate-700 hover:border-slate-500 hover:bg-slate-800'}`}
|
||||||
<button
|
onClick={() => setSelectedId(part.id)}
|
||||||
onClick={handleDownloadAll}
|
>
|
||||||
disabled={isZipping || parts.length === 0}
|
<div className="flex justify-between items-start mb-2">
|
||||||
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"
|
<span className="font-semibold text-gray-200 group-hover:text-white transition-colors">{part.name}</span>
|
||||||
>
|
<div
|
||||||
{isZipping ? <Loader2 size={16} className="animate-spin" /> : <Download size={16} />}
|
className="w-3 h-3 rounded-full border border-white/10"
|
||||||
Архив
|
style={{ backgroundColor: part.color }}
|
||||||
</button>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="grid grid-cols-3 gap-2 text-xs text-gray-400 mb-3">
|
||||||
<div className="flex-1 overflow-y-auto pr-1 custom-scrollbar">
|
<div className="bg-slate-900/50 p-1.5 rounded">
|
||||||
<div className="grid grid-cols-2 gap-3 pb-4">
|
<span className="block text-gray-500 uppercase text-[9px] mb-0.5">Ширина</span>
|
||||||
{parts.map(part => (
|
{part.width.toFixed(1)}
|
||||||
<div
|
</div>
|
||||||
key={part.id}
|
<div className="bg-slate-900/50 p-1.5 rounded">
|
||||||
ref={(el) => { itemRefs.current[part.id] = el }}
|
<span className="block text-gray-500 uppercase text-[9px] mb-0.5">Глубина</span>
|
||||||
className={`
|
{part.depth.toFixed(1)}
|
||||||
p-3 rounded-lg border transition-all cursor-pointer group flex flex-col gap-2 relative overflow-hidden
|
</div>
|
||||||
${selectedId === part.id
|
<div className="bg-slate-900/50 p-1.5 rounded">
|
||||||
? 'bg-slate-800 border-accent shadow-md shadow-accent/10 ring-1 ring-accent'
|
<span className="block text-gray-500 uppercase text-[9px] mb-0.5">Высота</span>
|
||||||
: 'bg-slate-800/50 border-slate-700 hover:border-slate-500 hover:bg-slate-800'
|
{part.height.toFixed(1)}
|
||||||
}
|
</div>
|
||||||
`}
|
</div>
|
||||||
onClick={() => setSelectedId(part.id)}
|
<button
|
||||||
>
|
onClick={(e) => { e.stopPropagation(); handleDownload(part); }}
|
||||||
{/* Индикатор цвета */}
|
className="w-full py-2 bg-slate-700 hover:bg-primary hover:text-white text-gray-300 rounded text-xs flex items-center justify-center gap-2 transition-colors font-medium"
|
||||||
<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"
|
<Download size={14} /> Скачать STL
|
||||||
style={{ backgroundColor: part.color, opacity: 0.1 }}
|
</button>
|
||||||
/>
|
</div>
|
||||||
|
))}
|
||||||
{/* Заголовок */}
|
|
||||||
<div className="flex items-center justify-between z-10">
|
|
||||||
<span className="font-bold text-gray-200 text-xs truncate" title={part.name}>
|
|
||||||
{part.name}
|
|
||||||
</span>
|
|
||||||
<div
|
|
||||||
className="w-2.5 h-2.5 rounded-full border border-white/20 shadow-sm"
|
|
||||||
style={{ backgroundColor: part.color }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Размеры */}
|
|
||||||
<div className="text-[10px] text-gray-400 font-mono z-10">
|
|
||||||
{part.width.toFixed(0)} × {part.depth.toFixed(0)} × {part.height.toFixed(0)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Кнопка скачивания */}
|
|
||||||
<button
|
|
||||||
onClick={(e) => { e.stopPropagation(); handleDownload(part); }}
|
|
||||||
className="w-full py-1.5 bg-slate-700 hover:bg-primary hover:text-white text-gray-300 rounded text-xs flex items-center justify-center gap-1.5 transition-colors font-medium border border-slate-600 hover:border-primary z-10 mt-1"
|
|
||||||
>
|
|
||||||
<Download size={12} /> STL
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import { AppConfig, LayoutSplits, GeneratedPart, PerforationConfig } from '../ty
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 1. Расчет списка ящиков на основе сетки
|
* 1. Расчет списка ящиков на основе сетки
|
||||||
* Это создает массив отдельных коробочек, которые визуально образуют органайзер
|
|
||||||
*/
|
*/
|
||||||
export const calculateParts = (
|
export const calculateParts = (
|
||||||
config: AppConfig,
|
config: AppConfig,
|
||||||
@@ -12,7 +11,7 @@ export const calculateParts = (
|
|||||||
): GeneratedPart[] => {
|
): GeneratedPart[] => {
|
||||||
const parts: GeneratedPart[] = [];
|
const parts: GeneratedPart[] = [];
|
||||||
|
|
||||||
// Сортируем линии реза и добавляем границы (0 и 1)
|
// Сортируем линии реза
|
||||||
const xPoints = [0, ...[...splits.x].sort((a, b) => a - b), 1];
|
const xPoints = [0, ...[...splits.x].sort((a, b) => a - b), 1];
|
||||||
const yPoints = [0, ...[...splits.y].sort((a, b) => a - b), 1];
|
const yPoints = [0, ...[...splits.y].sort((a, b) => a - b), 1];
|
||||||
|
|
||||||
@@ -21,26 +20,24 @@ export const calculateParts = (
|
|||||||
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 segmentX = xPoints[i] * config.drawer.width;
|
const segmentX = xPoints[i] * config.drawer.width;
|
||||||
const segmentY = yPoints[j] * config.drawer.depth;
|
const segmentY = yPoints[j] * config.drawer.depth;
|
||||||
const segmentW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width;
|
const segmentW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width;
|
||||||
const segmentD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
|
const segmentD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
|
||||||
|
|
||||||
// Применяем толерантность (зазор между ящиками)
|
// Применяем Tolerance (зазор)
|
||||||
// Уменьшаем размер ящика, сдвигаем его к центру
|
|
||||||
const realWidth = segmentW - config.printerTolerance;
|
const realWidth = segmentW - config.printerTolerance;
|
||||||
const realDepth = segmentD - config.printerTolerance;
|
const realDepth = segmentD - config.printerTolerance;
|
||||||
const realX = segmentX + (config.printerTolerance / 2);
|
const realX = segmentX + (config.printerTolerance / 2);
|
||||||
const realY = segmentY + (config.printerTolerance / 2);
|
const realY = segmentY + (config.printerTolerance / 2);
|
||||||
|
|
||||||
// Защита от слишком мелких (фантомных) ячеек
|
// Фильтр слишком мелких ячеек
|
||||||
if (realWidth < 2 || realDepth < 2) {
|
if (realWidth < 1 || realDepth < 1) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
parts.push({
|
parts.push({
|
||||||
id: `part-${partCounter}-${Date.now()}`, // Уникальный ID
|
id: `part-${partCounter}`,
|
||||||
name: `Ячейка ${i+1}-${j+1}`,
|
name: `Ячейка ${i+1}-${j+1}`,
|
||||||
width: realWidth,
|
width: realWidth,
|
||||||
depth: realDepth,
|
depth: realDepth,
|
||||||
@@ -57,9 +54,7 @@ export const calculateParts = (
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 2. Создание 2D профиля стены с отверстиями
|
* 2. Создание формы стены с отверстиями (алгоритм из архива)
|
||||||
* ВАЖНО: Контур стены -> CCW (Против часовой)
|
|
||||||
* ВАЖНО: Отверстия -> CW (По часовой)
|
|
||||||
*/
|
*/
|
||||||
const createPerforatedWallShape = (
|
const createPerforatedWallShape = (
|
||||||
width: number,
|
width: number,
|
||||||
@@ -67,8 +62,7 @@ const createPerforatedWallShape = (
|
|||||||
perf: PerforationConfig
|
perf: PerforationConfig
|
||||||
): THREE.Shape => {
|
): THREE.Shape => {
|
||||||
const shape = new THREE.Shape();
|
const shape = new THREE.Shape();
|
||||||
|
// Основной контур
|
||||||
// Внешний прямоугольник (Против часовой стрелки)
|
|
||||||
shape.moveTo(0, 0);
|
shape.moveTo(0, 0);
|
||||||
shape.lineTo(width, 0);
|
shape.lineTo(width, 0);
|
||||||
shape.lineTo(width, height);
|
shape.lineTo(width, height);
|
||||||
@@ -79,7 +73,7 @@ const createPerforatedWallShape = (
|
|||||||
|
|
||||||
const { size, spacing, shape: type, border } = perf;
|
const { size, spacing, shape: type, border } = perf;
|
||||||
|
|
||||||
// Эффективная зона перфорации
|
// Эффективная зона
|
||||||
const startX = border;
|
const startX = border;
|
||||||
const endX = width - border;
|
const endX = width - border;
|
||||||
const startY = border;
|
const startY = border;
|
||||||
@@ -87,22 +81,21 @@ const createPerforatedWallShape = (
|
|||||||
|
|
||||||
if (startX >= endX || startY >= endY) return shape;
|
if (startX >= endX || startY >= endY) return shape;
|
||||||
|
|
||||||
// Функция добавления одной дырки
|
const cellSize = size + spacing;
|
||||||
|
|
||||||
|
// Хелпер добавления отверстия
|
||||||
const addHole = (cx: number, cy: number) => {
|
const addHole = (cx: number, cy: number) => {
|
||||||
// Проверка границ (центр отверстия не должен выходить за рамки)
|
// Проверка границ
|
||||||
if (cx - size/2 < startX || cx + size/2 > endX || cy - size/2 < startY || cy + size/2 > endY) return;
|
if (cx - size/2 < startX || cx + size/2 > endX || cy - size/2 < startY || cy + size/2 > endY) return;
|
||||||
|
|
||||||
const holePath = new THREE.Path();
|
const holePath = new THREE.Path();
|
||||||
const r = size / 2;
|
|
||||||
|
|
||||||
if (type === 'circle') {
|
if (type === 'circle') {
|
||||||
// aClockwise = true (По часовой стрелке)
|
holePath.absarc(cx, cy, size / 2, 0, Math.PI * 2, true);
|
||||||
holePath.absarc(cx, cy, r, 0, Math.PI * 2, true);
|
|
||||||
} else if (type === 'hexagon') {
|
} else if (type === 'hexagon') {
|
||||||
// Шестиугольник (По часовой стрелке)
|
const r = size / 2;
|
||||||
// angle идет в минус: 90, 30, -30...
|
|
||||||
for (let k = 0; k < 6; k++) {
|
for (let k = 0; k < 6; k++) {
|
||||||
const angle = (-k * 60 + 90) * (Math.PI / 180);
|
const angle = (k * 60 + 30) * (Math.PI / 180);
|
||||||
const px = cx + r * Math.cos(angle);
|
const px = cx + r * Math.cos(angle);
|
||||||
const py = cy + r * Math.sin(angle);
|
const py = cy + r * Math.sin(angle);
|
||||||
if (k === 0) holePath.moveTo(px, py);
|
if (k === 0) holePath.moveTo(px, py);
|
||||||
@@ -110,8 +103,8 @@ const createPerforatedWallShape = (
|
|||||||
}
|
}
|
||||||
holePath.closePath();
|
holePath.closePath();
|
||||||
} else if (type === 'triangle') {
|
} else if (type === 'triangle') {
|
||||||
// Треугольник (По часовой стрелке)
|
const r = size / 2;
|
||||||
const angles = [90, -30, 210]; // 90 -> -30 (CW)
|
const angles = [90, 210, 330];
|
||||||
angles.forEach((deg, idx) => {
|
angles.forEach((deg, idx) => {
|
||||||
const rad = deg * (Math.PI / 180);
|
const rad = deg * (Math.PI / 180);
|
||||||
const px = cx + r * Math.cos(rad);
|
const px = cx + r * Math.cos(rad);
|
||||||
@@ -127,24 +120,21 @@ const createPerforatedWallShape = (
|
|||||||
|
|
||||||
// Генерация сетки
|
// Генерация сетки
|
||||||
if (type === 'hexagon') {
|
if (type === 'hexagon') {
|
||||||
// Сотовая структура (смещенные ряды)
|
const hexHeight = size;
|
||||||
const hexWidth = size * 0.866; // sqrt(3)/2
|
const hexWidth = size * 0.866;
|
||||||
const colDist = hexWidth + spacing;
|
const colDist = hexWidth + spacing;
|
||||||
const rowDist = (size * 0.75) + spacing;
|
const rowDist = (hexHeight * 0.75) + spacing;
|
||||||
|
|
||||||
let rowIndex = 0;
|
let row = 0;
|
||||||
for (let y = startY + size/2; y < endY; y += rowDist) {
|
for (let y = startY + size/2; y < endY; y += rowDist) {
|
||||||
const isOddRow = rowIndex % 2 === 1;
|
const offset = (row % 2) === 1 ? colDist / 2 : 0;
|
||||||
const offset = isOddRow ? colDist / 2 : 0;
|
|
||||||
|
|
||||||
for (let x = startX + size/2 + offset; x < endX; x += colDist) {
|
for (let x = startX + size/2 + offset; x < endX; x += colDist) {
|
||||||
addHole(x, y);
|
addHole(x, y);
|
||||||
}
|
}
|
||||||
rowIndex++;
|
row++;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Обычная сетка (Круг, Треугольник)
|
// Обычная сетка
|
||||||
const cellSize = size + spacing;
|
|
||||||
for (let x = startX + size/2; x < endX; x += cellSize) {
|
for (let x = startX + size/2; x < endX; x += cellSize) {
|
||||||
for (let y = startY + size/2; y < endY; y += cellSize) {
|
for (let y = startY + size/2; y < endY; y += cellSize) {
|
||||||
addHole(x, y);
|
addHole(x, y);
|
||||||
@@ -156,7 +146,7 @@ const createPerforatedWallShape = (
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 3. Создание 3D геометрии для ОДНОГО ящика
|
* 3. Генерация 3D геометрии одного ящика
|
||||||
*/
|
*/
|
||||||
export const createBinGeometry = (
|
export const createBinGeometry = (
|
||||||
width: number,
|
width: number,
|
||||||
@@ -168,7 +158,8 @@ export const createBinGeometry = (
|
|||||||
const geometries: THREE.BufferGeometry[] = [];
|
const geometries: THREE.BufferGeometry[] = [];
|
||||||
const perfConfig = perforation || { enabled: false, shape: 'circle', size: 0, spacing: 0, border: 0 };
|
const perfConfig = perforation || { enabled: false, shape: 'circle', size: 0, spacing: 0, border: 0 };
|
||||||
|
|
||||||
// 1. Пол (Всегда сплошной)
|
// 1. Пол - Всегда сплошной
|
||||||
|
// ВАЖНО: .toNonIndexed() нужен для корректного слияния с ExtrudeGeometry
|
||||||
const floorGeo = new THREE.BoxGeometry(width, thickness, depth).toNonIndexed();
|
const floorGeo = new THREE.BoxGeometry(width, thickness, depth).toNonIndexed();
|
||||||
floorGeo.translate(0, thickness / 2, 0);
|
floorGeo.translate(0, thickness / 2, 0);
|
||||||
geometries.push(floorGeo);
|
geometries.push(floorGeo);
|
||||||
@@ -182,58 +173,47 @@ export const createBinGeometry = (
|
|||||||
};
|
};
|
||||||
|
|
||||||
// 2. Левая и Правая стенки (Полная глубина)
|
// 2. Левая и Правая стенки (Полная глубина)
|
||||||
// Рисуем профиль (Ширина профиля = Глубине ящика)
|
// Рисуем профиль шириной = глубине ящика
|
||||||
const lrShape = createPerforatedWallShape(depth, wallHeight, perfConfig);
|
const lrShape = createPerforatedWallShape(depth, wallHeight, perfConfig);
|
||||||
|
// ВАЖНО: .toNonIndexed()
|
||||||
const lrGeo = new THREE.ExtrudeGeometry(lrShape, extrudeSettings).toNonIndexed();
|
const lrGeo = new THREE.ExtrudeGeometry(lrShape, extrudeSettings).toNonIndexed();
|
||||||
|
|
||||||
// Центрируем геометрию для удобного вращения
|
// Left Wall
|
||||||
lrGeo.center();
|
|
||||||
|
|
||||||
// Левая стенка (Left)
|
|
||||||
// Поворачиваем: Профиль лежит вдоль X -> поворот на 90 -> вдоль Z
|
|
||||||
const leftWall = lrGeo.clone();
|
const leftWall = lrGeo.clone();
|
||||||
leftWall.rotateY(Math.PI / 2);
|
leftWall.rotateY(-Math.PI / 2);
|
||||||
// Позиция: X = -width/2 + thickness/2, Y = пол + пол_стены
|
leftWall.translate(-(width/2) + thickness, thickness, -(depth/2));
|
||||||
leftWall.translate(-(width/2) + thickness/2, thickness + wallHeight/2, 0);
|
|
||||||
geometries.push(leftWall);
|
geometries.push(leftWall);
|
||||||
|
|
||||||
// Правая стенка (Right)
|
// Right Wall
|
||||||
const rightWall = lrGeo.clone();
|
const rightWall = lrGeo.clone();
|
||||||
rightWall.rotateY(Math.PI / 2);
|
rightWall.rotateY(-Math.PI / 2);
|
||||||
rightWall.translate((width/2) - thickness/2, thickness + wallHeight/2, 0);
|
rightWall.translate((width/2), thickness, -(depth/2));
|
||||||
geometries.push(rightWall);
|
geometries.push(rightWall);
|
||||||
|
|
||||||
// 3. Передняя и Задняя стенки (Вставляются МЕЖДУ боковыми)
|
// 3. Передняя и Задняя стенки (Вставляются между боковыми)
|
||||||
// Их ширина меньше на 2 толщины
|
// Ширина уменьшена на 2 толщины
|
||||||
const wallFBWidth = width - (2 * thickness);
|
const wallFBWidth = Math.max(0, width - (2 * thickness));
|
||||||
|
|
||||||
if (wallFBWidth > 0) {
|
if (wallFBWidth > 0) {
|
||||||
const fbShape = createPerforatedWallShape(wallFBWidth, wallHeight, perfConfig);
|
const fbShape = createPerforatedWallShape(wallFBWidth, wallHeight, perfConfig);
|
||||||
const fbGeo = new THREE.ExtrudeGeometry(fbShape, extrudeSettings).toNonIndexed();
|
const fbGeo = new THREE.ExtrudeGeometry(fbShape, extrudeSettings).toNonIndexed();
|
||||||
|
|
||||||
fbGeo.center();
|
// Front Wall
|
||||||
|
|
||||||
// Передняя стенка (Front)
|
|
||||||
const frontWall = fbGeo.clone();
|
const frontWall = fbGeo.clone();
|
||||||
frontWall.translate(0, thickness + wallHeight/2, (depth/2) - thickness/2);
|
frontWall.translate(-(wallFBWidth/2), thickness, (depth/2) - thickness);
|
||||||
geometries.push(frontWall);
|
geometries.push(frontWall);
|
||||||
|
|
||||||
// Задняя стенка (Back)
|
// Back Wall
|
||||||
const backWall = fbGeo.clone();
|
const backWall = fbGeo.clone();
|
||||||
backWall.translate(0, thickness + wallHeight/2, -(depth/2) + thickness/2);
|
backWall.translate(-(wallFBWidth/2), thickness, -(depth/2));
|
||||||
geometries.push(backWall);
|
geometries.push(backWall);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Сливаем всё в один меш
|
// Слияние в один меш
|
||||||
const merged = mergeBufferGeometries(geometries);
|
const merged = mergeBufferGeometries(geometries);
|
||||||
if (merged) merged.computeVertexNormals();
|
|
||||||
|
|
||||||
return merged || new THREE.BoxGeometry(1, 1, 1).toNonIndexed();
|
return merged || new THREE.BoxGeometry(1, 1, 1).toNonIndexed();
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- ЭКСПОРТ (без изменений) ---
|
|
||||||
|
|
||||||
export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {
|
export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {
|
||||||
const exporter = new STLExporter();
|
const exporter = new STLExporter();
|
||||||
const result = exporter.parse(mesh, { binary: true });
|
const result = exporter.parse(mesh, { binary: true });
|
||||||
|
|||||||
Reference in New Issue
Block a user