import type { BoundingBox, ModelingCmd } from '@kittycad/lib' import { getBodiesFromArtifactGraph } from '@src/lang/std/artifactGraph' import { useSingletons } from '@src/lib/boot' import { isModelingResponse } from '@src/lib/kcSdkGuards' import { engineStreamZoomToFit, engineViewIsometric } from '@src/lib/utils' import { uuidv4 } from '@src/lib/utils' import { useEffect, useMemo, useRef, useState } from 'react' import toast from 'react-hot-toast' import { buildExplodeOffsets, createBomCsv, createEngineeringSheetHtml, getOverallBounds, groupBodiesIntoBom, type BodyMeasurement, type BomRow, type ExplodeOffset, } from './manufacturing' type ModelingResponse = { type: string data?: unknown } type BomOverrides = Record< string, { material?: string process?: string } > type BrandSettings = { name: string logoUrl: string } function downloadText(filename: string, text: string, type: string) { const blob = new Blob([text], { type }) const url = URL.createObjectURL(blob) const anchor = document.createElement('a') anchor.href = url anchor.download = filename anchor.click() URL.revokeObjectURL(url) } function collectArtifactIds( value: unknown, ids: Set, seen = new WeakSet(), depth = 0 ) { if (depth > 8 || value === null || typeof value !== 'object') return if (seen.has(value)) return seen.add(value) if ('artifactId' in value && typeof value.artifactId === 'string') { ids.add(value.artifactId) } if ('artifact_id' in value && typeof value.artifact_id === 'string') { ids.add(value.artifact_id) } if ('id' in value && typeof value.id === 'string') { ids.add(value.id) } for (const nested of Object.values(value)) { collectArtifactIds(nested, ids, seen, depth + 1) } } function resolveBodyName( bodyId: string, variables: Record, fallbackIndex: number ) { for (const [name, value] of Object.entries(variables)) { const ids = new Set() collectArtifactIds(value, ids) if (ids.has(bodyId)) return name } return `零件 ${String(fallbackIndex + 1).padStart(2, '0')}` } function modelingResponseData(response: unknown): ModelingResponse { const normalized = Array.isArray(response) ? response[0] : response if (!isModelingResponse(normalized)) { throw new Error('HiCAD 引擎未返回有效结果') } return normalized.resp.data.modeling_response as ModelingResponse } function numberValue(data: unknown, key: string) { if (typeof data !== 'object' || data === null) return undefined const value = (data as Record)[key] return typeof value === 'number' ? value : undefined } function formatNumber(value: number | undefined) { if (value === undefined) return '-' return Math.round(value * 100) / 100 } function dataUrlFromSnapshot(contents: string) { return contents.startsWith('data:') ? contents : `data:image/png;base64,${contents}` } export function HicadManufacturingPanel({ hideTrigger = false, initialOpen = false, onRequestClose, projectName, }: { hideTrigger?: boolean initialOpen?: boolean onRequestClose?: () => void projectName: string }) { const { kclManager } = useSingletons() const [open, setOpen] = useState(initialOpen) const [busy, setBusy] = useState(false) const [bodies, setBodies] = useState([]) const [snapshot, setSnapshot] = useState() const [exploded, setExploded] = useState(false) const [overrides, setOverrides] = useState({}) const [brand, setBrand] = useState({ name: '由壹点AI', logoUrl: '/api/favicon?surface=hicad', }) const [notes, setNotes] = useState( '材料、表面处理、公差、连接方式和检验标准须在投产前由工程人员复核。' ) const explodeOffsetsRef = useRef([]) const resolvedProjectName = projectName || 'HiCAD 模型' const loadBrandSettings = async () => { try { const response = await fetch('/api/site-settings?scope=chat', { credentials: 'same-origin', }) if (!response.ok) return const settings = (await response.json()) as Record const name = typeof settings.siteName === 'string' && settings.siteName.trim() ? settings.siteName.trim() : '由壹点AI' const configuredLogo = typeof settings.siteLogo === 'string' && settings.siteLogo.trim() ? settings.siteLogo.trim() : typeof settings.siteLogoDark === 'string' && settings.siteLogoDark.trim() ? settings.siteLogoDark.trim() : '/api/favicon?surface=hicad' setBrand({ name, logoUrl: configuredLogo }) } catch { // Keep the built-in website branding when settings are unavailable. } } const sendModelingCommand = async (cmd: ModelingCmd) => { const maxAttempts = 15 for (let attempt = 0; attempt < maxAttempts; attempt += 1) { const response = await kclManager.engineCommandManager.sendSceneCommand({ type: 'modeling_cmd_req', cmd_id: uuidv4(), cmd, }) const normalized = Array.isArray(response) ? response[0] : response if (isModelingResponse(normalized)) { return modelingResponseData(normalized) } if (response !== null && response !== undefined) { return modelingResponseData(response) } await new Promise((resolve) => setTimeout(resolve, 200)) } throw new Error('HiCAD 引擎连接尚未就绪,请稍后重新分析') } const captureSnapshot = async () => { const response = await sendModelingCommand({ type: 'take_snapshot', format: 'png', }) if ( response.type !== 'take_snapshot' || typeof response.data !== 'object' || response.data === null || !('contents' in response.data) || typeof response.data.contents !== 'string' ) { return undefined } const dataUrl = dataUrlFromSnapshot(response.data.contents) setSnapshot(dataUrl) return dataUrl } const resetExplodeTransforms = async () => { const offsets = explodeOffsetsRef.current if (offsets.length === 0) return await Promise.allSettled( offsets.map(({ id, offset }) => sendModelingCommand({ type: 'set_object_transform', object_id: id, transforms: [ { translate: { property: { x: -offset.x, y: -offset.y, z: -offset.z, }, set: false, origin: { type: 'global' }, }, }, ], }) ) ) explodeOffsetsRef.current = [] setExploded(false) } const analyzeModel = async (manageBusy = true) => { if (manageBusy) setBusy(true) try { if (explodeOffsetsRef.current.length > 0) { await resetExplodeTransforms() } const bodyEntries = [...getBodiesFromArtifactGraph(kclManager.artifactGraph)] if (bodyEntries.length === 0) { throw new Error('当前模型还没有可识别的实体') } const variables = kclManager.variablesSignal.value as Record< string, unknown > const measured = await Promise.all( bodyEntries.map(async ([bodyId], index): Promise => { const boundingResponse = await sendModelingCommand({ type: 'bounding_box', entity_ids: [bodyId], output_unit: 'mm', }) if ( boundingResponse.type !== 'bounding_box' || typeof boundingResponse.data !== 'object' || boundingResponse.data === null ) { throw new Error(`无法读取零件 ${index + 1} 的尺寸`) } const boundingBox = boundingResponse.data as BoundingBox const [volumeResponse, areaResponse] = await Promise.allSettled([ sendModelingCommand({ type: 'volume', entity_ids: [bodyId], output_unit: 'mm3', }), sendModelingCommand({ type: 'surface_area', entity_ids: [bodyId], output_unit: 'mm2', }), ]) return { id: bodyId, name: resolveBodyName(bodyId, variables, index), center: boundingBox.center, dimensions: boundingBox.dimensions, volume: volumeResponse.status === 'fulfilled' ? numberValue(volumeResponse.value.data, 'volume') : undefined, surfaceArea: areaResponse.status === 'fulfilled' ? numberValue(areaResponse.value.data, 'surface_area') : undefined, } }) ) setBodies(measured) await engineViewIsometric({ engineCommandManager: kclManager.engineCommandManager, padding: 0.22, }) await engineStreamZoomToFit({ engineCommandManager: kclManager.engineCommandManager, padding: 0.24, }) await new Promise((resolve) => setTimeout(resolve, 180)) await captureSnapshot() return measured } catch (error) { const message = error instanceof Error ? error.message : '工程数据分析失败' toast.error(message) return [] } finally { if (manageBusy) setBusy(false) } } // This component is lazy-mounted by the launcher, so automatic analysis only // starts after the user explicitly opens the engineering tools. useEffect(() => { if (!initialOpen) return void loadBrandSettings() void analyzeModel() }, [initialOpen]) const handleOpen = () => { setOpen(true) void loadBrandSettings() if (bodies.length === 0) { void analyzeModel() } } const toggleExplodedView = async () => { if (busy) return setBusy(true) try { if (exploded) { await resetExplodeTransforms() } else { const measured = bodies.length > 0 ? bodies : await analyzeModel(false) if (measured.length < 2) { throw new Error( '爆炸图需要至少两个独立实体;当前模型可能已经布尔合并为一个整体' ) } const offsets = buildExplodeOffsets(measured) const transformResults = await Promise.allSettled( offsets.map(({ id, offset }) => sendModelingCommand({ type: 'set_object_transform', object_id: id, transforms: [ { translate: { property: offset, set: false, origin: { type: 'global' }, }, }, ], }) ) ) const successfulOffsets = offsets.filter( (_, index) => transformResults[index]?.status === 'fulfilled' ) explodeOffsetsRef.current = successfulOffsets const failedCount = transformResults.length - successfulOffsets.length if (failedCount > 0) { await resetExplodeTransforms() throw new Error( `${failedCount} 个实体无法移动,已自动复原装配,请检查模型实体` ) } explodeOffsetsRef.current = offsets setExploded(true) } await engineViewIsometric({ engineCommandManager: kclManager.engineCommandManager, padding: 0.18, }) await engineStreamZoomToFit({ engineCommandManager: kclManager.engineCommandManager, padding: 0.18, }) await new Promise((resolve) => setTimeout(resolve, 240)) await captureSnapshot() } catch (error) { toast.error(error instanceof Error ? error.message : '爆炸图生成失败') } finally { setBusy(false) } } const bomRows = useMemo( () => groupBodiesIntoBom(bodies).map((row) => ({ ...row, ...overrides[row.key], })), [bodies, overrides] ) const overall = useMemo(() => getOverallBounds(bodies), [bodies]) const updateRow = ( row: BomRow, field: 'material' | 'process', value: string ) => { setOverrides((current) => ({ ...current, [row.key]: { ...current[row.key], [field]: value, }, })) } const downloadBom = () => { if (bomRows.length === 0) { toast.error('请先分析模型') return } downloadText( `${resolvedProjectName}-BOM.csv`, createBomCsv(resolvedProjectName, bomRows), 'text/csv;charset=utf-8' ) } const printEngineeringSheet = () => { if (bomRows.length === 0) { toast.error('请先分析模型') return } const reportWindow = window.open('', '_blank') if (!reportWindow) { toast.error('浏览器阻止了工艺图窗口,请允许本站打开新窗口') return } reportWindow.opener = null reportWindow.document.open() reportWindow.document.write( createEngineeringSheetHtml({ projectName: resolvedProjectName, generatedAt: new Date().toLocaleString('zh-CN'), overallDimensions: overall.dimensions, brandName: brand.name, brandLogoUrl: brand.logoUrl, snapshotDataUrl: snapshot, bomRows, notes, }) ) reportWindow.document.close() } const handleClose = async () => { if (busy) return setBusy(true) try { if (explodeOffsetsRef.current.length > 0) { await resetExplodeTransforms() await engineStreamZoomToFit({ engineCommandManager: kclManager.engineCommandManager, padding: 0.24, }) } setOpen(false) onRequestClose?.() } finally { setBusy(false) } } return ( <> {!hideTrigger && ( )} {open && (

工程出图

真实实体爆炸、尺寸、BOM 与可打印生产工艺图

{bodies.length} 个独立实体 · {bomRows.length} 类零件 · 总尺寸{' '} {formatNumber(overall.dimensions.x)} ×{' '} {formatNumber(overall.dimensions.y)} ×{' '} {formatNumber(overall.dimensions.z)} mm

装配 / 爆炸预览

{snapshot ? ( {exploded ) : ( {busy ? '正在读取工程数据…' : '暂无预览'} )}

生产说明