From e75ff46145b4a0ced2e82a0cc495e6fccee9f806 Mon Sep 17 00:00:00 2001 From: WuYongJie Date: Sat, 5 Dec 2026 11:47:37 +0800 Subject: [PATCH] fix(reference-estimator): place QT-01 on cabinet exterior corners --- .../standard/CabinetCornerGuardControls.tsx | 37 +++++- .../standard/CabinetCornerGuardLayer.tsx | 16 ++- .../standard/CabinetModelView.tsx | 7 +- .../standard/ModelWorkspace.tsx | 1 + .../standard/StandardModelPanel.tsx | 5 +- .../cabinet-corner-guard-controls.test.tsx | 31 ++++- ...net-hardware-placement-controls.module.css | 1 + .../standard/useCabinetCornerGuard.ts | 52 ++++++-- .../standard/cabinet-corner-anchors.ts | 124 ++++++++++++++++++ .../standard/cabinet-corner-guard.test.ts | 51 ++++++- .../standard/cabinet-corner-guard.ts | 65 ++++----- .../cabinet-skill-surface-hardware.ts | 3 +- .../standard/stage-surface-hardware.ts | 3 +- .../standard/surface-hardware.ts | 9 +- .../standard/variant-hardware.test.ts | 19 +++ .../standard/variant-hardware.ts | 13 +- 16 files changed, 361 insertions(+), 76 deletions(-) create mode 100644 furniture-3d-system/src/lib/reference-estimator/standard/cabinet-corner-anchors.ts diff --git a/furniture-3d-system/src/app/reference-estimator/standard/CabinetCornerGuardControls.tsx b/furniture-3d-system/src/app/reference-estimator/standard/CabinetCornerGuardControls.tsx index e7380d6b2..6b4a133bd 100644 --- a/furniture-3d-system/src/app/reference-estimator/standard/CabinetCornerGuardControls.tsx +++ b/furniture-3d-system/src/app/reference-estimator/standard/CabinetCornerGuardControls.tsx @@ -1,17 +1,50 @@ +import { useState } from 'react' import Button from '@/components/ui/Button' +import { cornerGuardAdjustmentLimitMm, cornerGuardLabels, cornerGuardLocations, noCornerGuardAdjustment, + type CornerGuardLocation } from '@/lib/reference-estimator/standard/cabinet-corner-guard' import type { CabinetCornerGuardController } from './useCabinetCornerGuard' import styles from './cabinet-hardware-placement-controls.module.css' +const axes = ['左右', '前后', '上下'] as const + +function OffsetField({ axis, value, busy, onChange }: { + axis: typeof axes[number]; value: number; busy: boolean; onChange: (next: number) => void +}) { + const [text, setText] = useState() + const limit = cornerGuardAdjustmentLimitMm + return +} + export function CabinetCornerGuardControls({ guard }: { guard: CabinetCornerGuardController }) { const { preview, feedback, busy, confirm, cancel } = guard if (!preview && !feedback) return null - return
+ const offset = preview?.rows.find(row => row.location === preview.corner)?.cornerAdjustmentMm ?? noCornerGuardAdjustment + return
{preview && <> {preview.item.name} · {preview.item.code} × 4 -

顶板左前、右前、左后、右后各 1 个 · 免打孔

+

预览柜体上外角 · 免打孔

+ +
+ {([0, 1, 2] as const).map(axis => guard.adjustCorner(axis, value)}/>)} +
+

正值向右、向后、向上。

+
} {feedback &&

{feedback.text}

} diff --git a/furniture-3d-system/src/app/reference-estimator/standard/CabinetCornerGuardLayer.tsx b/furniture-3d-system/src/app/reference-estimator/standard/CabinetCornerGuardLayer.tsx index 11183ba3f..d0bda4a01 100644 --- a/furniture-3d-system/src/app/reference-estimator/standard/CabinetCornerGuardLayer.tsx +++ b/furniture-3d-system/src/app/reference-estimator/standard/CabinetCornerGuardLayer.tsx @@ -1,15 +1,16 @@ import { useMemo } from 'react' import { Html } from '@react-three/drei' -import { cornerGuardLabels } from '@/lib/reference-estimator/standard/cabinet-corner-guard' +import { cornerGuardLabels, type CornerGuardLocation } from '@/lib/reference-estimator/standard/cabinet-corner-guard' import type { CornerGuardModels } from './useCornerGuardModels' import { cornerGuardRotation } from './corner-guard-model' import type { cabinetSurfacePositions } from './cabinet-surface-selection' import { CabinetSurfacePickTarget } from './CabinetSurfacePickTarget' import styles from './estimate-workbench.module.css' -export function CabinetCornerGuardLayer({ rows, preview, models, selected, onPick }: { +export function CabinetCornerGuardLayer({ rows, preview, models, editing, selected, onPick }: { rows: ReturnType['guards']; preview: boolean models?: CornerGuardModels['models'] + editing?: CornerGuardLocation selected?: ReadonlySet; onPick?: (key: string) => void }) { const clones = useMemo(() => rows.map(row => models?.[row.accessoryId]?.clone(true)), [rows, models]) @@ -17,14 +18,15 @@ export function CabinetCornerGuardLayer({ rows, preview, models, selected, onPic return {rows.map(({ key, location, scenePoint, left, front }, index) => { const clone = clones[index] - if (!clone) return null + if (!clone && !preview) return null + const active = preview && location === editing const inX = left ? 1 : -1 const inZ = front ? -1 : 1 - return onPick(key) : undefined}> - - {preview && - {cornerGuardLabels[location]} + {clone && } + {preview && + {cornerGuardLabels[location]} } })} diff --git a/furniture-3d-system/src/app/reference-estimator/standard/CabinetModelView.tsx b/furniture-3d-system/src/app/reference-estimator/standard/CabinetModelView.tsx index 36aedca0f..c45019588 100644 --- a/furniture-3d-system/src/app/reference-estimator/standard/CabinetModelView.tsx +++ b/furniture-3d-system/src/app/reference-estimator/standard/CabinetModelView.tsx @@ -34,7 +34,7 @@ import { isSeamPlacement } from './cabinet-sg0164-seam' import { useCabinetFinishTextures } from './cabinet-finish-textures' import { CabinetModelCapture, type CabinetCapture } from './CabinetModelCapture' import type { SurfaceHardware } from '@/lib/reference-estimator/standard/surface-hardware' -import { isCornerGuardLocation } from '@/lib/reference-estimator/standard/cabinet-corner-guard' +import { isCornerGuardLocation, type CornerGuardLocation } from '@/lib/reference-estimator/standard/cabinet-corner-guard' import { useSurfaceHardwareModels } from './useSurfaceHardwareModels' import { CabinetSurfaceHardware } from './CabinetSurfaceHardware' import { CabinetCornerGuardLayer } from './CabinetCornerGuardLayer' @@ -120,7 +120,7 @@ function ModelFrame({model,distance,position,preset,controls,showDimensions,prev return null } -export default function CabinetModelView({model,readOnly=false,showHoleInspection=false,showDimensions,onDimensionsChange,stepExport,boardPicking,onToggleBoardPicking,previewLibrary,hardwareEditor,hardwareSnapshot,appearance,surfaceHardware=noSurfaceHardware,cornerGuardPreview,cornerGuardModels,surfaceSelection,capture}:{ +export default function CabinetModelView({model,readOnly=false,showHoleInspection=false,showDimensions,onDimensionsChange,stepExport,boardPicking,onToggleBoardPicking,previewLibrary,hardwareEditor,hardwareSnapshot,appearance,surfaceHardware=noSurfaceHardware,cornerGuardPreview,cornerGuardEditCorner,cornerGuardModels,surfaceSelection,capture}:{ model: CabinetModel appearance?: ModelAppearance readOnly?: boolean @@ -135,6 +135,7 @@ export default function CabinetModelView({model,readOnly=false,showHoleInspectio hardwareSnapshot?: Pick surfaceHardware?: SurfaceHardware cornerGuardPreview?: SurfaceHardware + cornerGuardEditCorner?: CornerGuardLocation cornerGuardModels?: CornerGuardModels surfaceSelection?: CabinetSurfaceSelectionState capture?: CabinetCapture @@ -365,7 +366,7 @@ export default function CabinetModelView({model,readOnly=false,showHoleInspectio + editing={cornerGuardEditCorner} selected={surfaceSelection?.keys} onPick={surfacePickable ? pickSurface : undefined}/> {hardwarePreview.active ? diff --git a/furniture-3d-system/src/app/reference-estimator/standard/ModelWorkspace.tsx b/furniture-3d-system/src/app/reference-estimator/standard/ModelWorkspace.tsx index 7f8e25abd..da5930eb4 100644 --- a/furniture-3d-system/src/app/reference-estimator/standard/ModelWorkspace.tsx +++ b/furniture-3d-system/src/app/reference-estimator/standard/ModelWorkspace.tsx @@ -104,6 +104,7 @@ export function ModelWorkspace({c, showDimensions, onDimensionsChange, hardwareL showDimensions={showDimensions} onDimensionsChange={onDimensionsChange} previewLibrary={historical && (historical.surfaceHardware?.length || historical.hardwarePlacementEdits || historical.hardwareSeamEdits) ? hardwareLibrary : previewLibrary} cornerGuardPreview={cornerGuard.preview?.rows} + cornerGuardEditCorner={cornerGuard.preview?.corner} cornerGuardModels={historical ? undefined : cornerGuard.modelState} surfaceSelection={surfaceSelection} hardwareEditor={placementEditor}/> diff --git a/furniture-3d-system/src/app/reference-estimator/standard/StandardModelPanel.tsx b/furniture-3d-system/src/app/reference-estimator/standard/StandardModelPanel.tsx index dcf8974cb..9dc7be6cb 100644 --- a/furniture-3d-system/src/app/reference-estimator/standard/StandardModelPanel.tsx +++ b/furniture-3d-system/src/app/reference-estimator/standard/StandardModelPanel.tsx @@ -13,11 +13,12 @@ import workspace from './model-workspace.module.css' import workbench from './estimate-workbench.module.css' import { modelVersionHardware } from './model-version-hardware' import type { SurfaceHardware } from '@/lib/reference-estimator/standard/surface-hardware' +import type { CornerGuardLocation } from '@/lib/reference-estimator/standard/cabinet-corner-guard' import type { CornerGuardModels } from './useCornerGuardModels' import type { CabinetSurfaceSelectionState } from './cabinet-surface-selection' const ModelView=dynamic(()=>import('./CabinetModelView'),{ssr:false,loading:()=>

加载三维模型…

}) -export function StandardModelPanel({c,historical,onReturn,showDimensions,onDimensionsChange,boardPicking,onToggleBoardPicking,previewLibrary,hardwareEditor,cornerGuardPreview,cornerGuardModels,surfaceSelection}:{ +export function StandardModelPanel({c,historical,onReturn,showDimensions,onDimensionsChange,boardPicking,onToggleBoardPicking,previewLibrary,hardwareEditor,cornerGuardPreview,cornerGuardEditCorner,cornerGuardModels,surfaceSelection}:{ c:StandardController;historical?:ModelRevision;onReturn:()=>void showDimensions: boolean onDimensionsChange: (show: boolean) => void @@ -26,6 +27,7 @@ export function StandardModelPanel({c,historical,onReturn,showDimensions,onDimen previewLibrary?: EstimateHardwareLibraryState hardwareEditor?: CabinetHardwareEdits cornerGuardPreview?: SurfaceHardware + cornerGuardEditCorner?: CornerGuardLocation cornerGuardModels?: CornerGuardModels surfaceSelection?: CabinetSurfaceSelectionState }){ @@ -51,6 +53,7 @@ export function StandardModelPanel({c,historical,onReturn,showDimensions,onDimen hardwareSnapshot={hardwareSnapshot} surfaceHardware={historical ? historical.surfaceHardware : c.document.surfaceHardware} cornerGuardPreview={historical ? undefined : cornerGuardPreview} + cornerGuardEditCorner={historical ? undefined : cornerGuardEditCorner} cornerGuardModels={cornerGuardModels} surfaceSelection={surfaceSelection} stepExport={historical ? undefined : { diff --git a/furniture-3d-system/src/app/reference-estimator/standard/cabinet-corner-guard-controls.test.tsx b/furniture-3d-system/src/app/reference-estimator/standard/cabinet-corner-guard-controls.test.tsx index 44f4b29ec..111f0bd05 100644 --- a/furniture-3d-system/src/app/reference-estimator/standard/cabinet-corner-guard-controls.test.tsx +++ b/furniture-3d-system/src/app/reference-estimator/standard/cabinet-corner-guard-controls.test.tsx @@ -1,4 +1,4 @@ -import { act, renderHook } from '@testing-library/react' +import { act, fireEvent, render, renderHook, screen } from '@testing-library/react' import type { AccessoryDraft } from '@/lib/intake-accessory-models' import { cabinetInputSchema } from '@/lib/reference-estimator/standard/cabinet-contracts' import { applyCabinetWorkflow } from '@/lib/reference-estimator/standard/cabinet-workflow' @@ -7,6 +7,7 @@ import { newStandardDocument } from '@/lib/reference-estimator/standard/workbook import { useCabinetCornerGuard } from './useCabinetCornerGuard' import type { StandardController } from './useStandardEstimator' import { useCornerGuardModels } from './useCornerGuardModels' +import { CabinetCornerGuardControls } from './CabinetCornerGuardControls' jest.mock('./useCornerGuardModels', () => ({ useCornerGuardModels: jest.fn() })) @@ -56,4 +57,32 @@ test('previews without saving, can retry a failed confirmation, and saves one fo expect(save).toHaveBeenCalledTimes(2) expect(result.current.feedback?.text).toContain('QT-01 × 4') expect(controller.document.surfaceHardware).toHaveLength(5) + + function Controls({ c }: { c: StandardController }) { + const guard = useCabinetCornerGuard(c) + return <> + } + const controls = render() + fireEvent.click(screen.getByRole('button', { name: '安装四角' })) + fireEvent.change(screen.getByLabelText('微调位置'), { target: { value: 'rear-right' } }) + fireEvent.change(screen.getByLabelText('前后(mm)'), { target: { value: '-3.5' } }) + expect(save).toHaveBeenCalledTimes(2) + fireEvent.click(screen.getByRole('button', { name: '取消预览' })) + expect(save).toHaveBeenCalledTimes(2) + + fireEvent.click(screen.getByRole('button', { name: '安装四角' })) + fireEvent.change(screen.getByLabelText('微调位置'), { target: { value: 'rear-right' } }) + fireEvent.change(screen.getByLabelText('前后(mm)'), { target: { value: '-3.5' } }) + await act(async () => { fireEvent.click(screen.getByRole('button', { name: '确认安装 4 个' })) }) + expect(save).toHaveBeenCalledTimes(3) + expect(controller.document.surfaceHardware?.filter(row => row.cornerAdjustmentMm)).toEqual([ + expect.objectContaining({ location: 'rear-right', cornerAdjustmentMm: [0, -3.5, 0] }), + ]) + controls.rerender() + fireEvent.click(screen.getByRole('button', { name: '安装四角' })) + fireEvent.change(screen.getByLabelText('微调位置'), { target: { value: 'rear-right' } }) + expect((screen.getByLabelText('前后(mm)') as HTMLInputElement).valueAsNumber).toBe(-3.5) + fireEvent.click(screen.getByRole('button', { name: '还原此角' })) + expect((screen.getByLabelText('前后(mm)') as HTMLInputElement).valueAsNumber).toBe(0) + expect(save).toHaveBeenCalledTimes(3) }) diff --git a/furniture-3d-system/src/app/reference-estimator/standard/cabinet-hardware-placement-controls.module.css b/furniture-3d-system/src/app/reference-estimator/standard/cabinet-hardware-placement-controls.module.css index c055695c7..2b4951247 100644 --- a/furniture-3d-system/src/app/reference-estimator/standard/cabinet-hardware-placement-controls.module.css +++ b/furniture-3d-system/src/app/reference-estimator/standard/cabinet-hardware-placement-controls.module.css @@ -20,6 +20,7 @@ border-top: 1px solid var(--obs-shell-border, #dce4e9); } .seamFields { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.6fr); gap: 8px; } +.cornerFields { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; } .seamField { display: grid; gap: 3px; font-size: 11px; color: var(--obs-shell-muted, #59636b); } .seamField input, .seamField select { width: 100%; diff --git a/furniture-3d-system/src/app/reference-estimator/standard/useCabinetCornerGuard.ts b/furniture-3d-system/src/app/reference-estimator/standard/useCabinetCornerGuard.ts index 289682a4f..da1daa411 100644 --- a/furniture-3d-system/src/app/reference-estimator/standard/useCabinetCornerGuard.ts +++ b/furniture-3d-system/src/app/reference-estimator/standard/useCabinetCornerGuard.ts @@ -1,13 +1,15 @@ import { useRef, useState } from 'react' import type { AccessoryDraft } from '@/lib/intake-accessory-models' -import { isCabinetCornerGuard, isCornerGuardLocation, previewTopCornerGuards } from '@/lib/reference-estimator/standard/cabinet-corner-guard' -import { surfaceHardwareSchema, type SurfaceHardware } from '@/lib/reference-estimator/standard/surface-hardware' +import { cornerGuardAdjustmentLimitMm, isCabinetCornerGuard, isCornerGuardLocation, noCornerGuardAdjustment, previewTopCornerGuards, + type CornerGuardLocation } from '@/lib/reference-estimator/standard/cabinet-corner-guard' +import { surfaceHardwareKey, surfaceHardwareSchema, type SurfaceHardware, type SurfaceHardwarePlacement } from '@/lib/reference-estimator/standard/surface-hardware' import type { StandardController } from './useStandardEstimator' import type { EstimateHardwareLibraryState } from './useEstimateHardwareLibrary' import { useCornerGuardModels } from './useCornerGuardModels' type CornerPreview = { document: StandardController['document']; model: StandardController['standard']['cabinet']; - item: AccessoryDraft; rows: SurfaceHardware } + item: AccessoryDraft; rows: SurfaceHardware; corner: CornerGuardLocation } +type Adjustment = NonNullable export function useCabinetCornerGuard(c: StandardController, library?: EstimateHardwareLibraryState) { const [draft, setDraft] = useState() @@ -25,14 +27,46 @@ export function useCabinetCornerGuard(c: StandardController, library?: EstimateH setDraft(undefined) setFeedback(undefined) try { - setDraft({ document: c.document, model, item, rows: previewTopCornerGuards(model, item.id) }) + const existing = new Map(c.document.surfaceHardware?.filter(row => row.accessoryId === item.id) + .map(row => [surfaceHardwareKey(row), row])) + const rows = previewTopCornerGuards(model, item.id).map(row => existing.get(surfaceHardwareKey(row)) ?? row) + setDraft({ document: c.document, model, item, rows, corner: 'front-left' }) return true } catch (error) { - fail(error instanceof Error ? error.message : '无法预览这块顶板的护角。') + fail(error instanceof Error ? error.message : '无法预览柜体四角的护角。') return false } } + function selectCorner(corner: CornerGuardLocation) { + if (busy) return + setDraft(current => current && { ...current, corner }) + } + + function adjustCorner(axis: 0 | 1 | 2, value: number) { + if (busy || !Number.isFinite(value) || Math.abs(value) > cornerGuardAdjustmentLimitMm) return + updateAdjustment(previous => { + const next: Adjustment = [...previous] + next[axis] = value + return next + }) + } + + function resetCorner() { + if (!busy) updateAdjustment(() => [...noCornerGuardAdjustment]) + } + + function updateAdjustment(update: (previous: Readonly) => Adjustment) { + setDraft(current => current && { ...current, rows: current.rows.map(row => { + if (row.location !== current.corner) return row + const next = { ...row } + const adjustment = update(row.cornerAdjustmentMm ?? noCornerGuardAdjustment) + if (adjustment.some(Boolean)) next.cornerAdjustmentMm = adjustment + else delete next.cornerAdjustmentMm + return next + }) }) + } + function cancel() { if (inFlight.current) return setDraft(undefined) @@ -44,7 +78,9 @@ export function useCabinetCornerGuard(c: StandardController, library?: EstimateH const existing = c.document.surfaceHardware ?? [] const current = existing.filter(row => isCornerGuardLocation(row.location)) const alreadyInstalled = current.length === preview.rows.length && preview.rows.every(row => - current.some(placed => placed.boardKey === row.boardKey && placed.accessoryId === row.accessoryId && placed.location === row.location)) + current.some(placed => surfaceHardwareKey(placed) === surfaceHardwareKey(row) && + (placed.cornerAdjustmentMm ?? noCornerGuardAdjustment) + .every((value, axis) => value === (row.cornerAdjustmentMm ?? noCornerGuardAdjustment)[axis]))) if (!alreadyInstalled && c.dirty) { fail('请先保存当前模型,再安装四角护角。'); return } const placements = surfaceHardwareSchema.safeParse([...existing.filter(row => !isCornerGuardLocation(row.location)), ...preview.rows]) if (!placements.success) { fail('已达到测算单的安装点数量上限。'); return } @@ -58,7 +94,7 @@ export function useCabinetCornerGuard(c: StandardController, library?: EstimateH return } setDraft(undefined) - setFeedback({ text: '顶板四角已安装 QT-01 × 4,重新生成包装和成本可更新用量。', error: false }) + setFeedback({ text: '柜体上外角已安装 QT-01 × 4,重新生成包装和成本可更新用量。', error: false }) } catch { fail('保存失败,已保留上次安装结果。') } finally { @@ -66,7 +102,7 @@ export function useCabinetCornerGuard(c: StandardController, library?: EstimateH setSaving(false) } } - return { preview, open, cancel, confirm, feedback, busy, modelState, available: Boolean(model) } + return { preview, open, cancel, confirm, selectCorner, adjustCorner, resetCorner, feedback, busy, modelState, available: Boolean(model) } } export type CabinetCornerGuardController = ReturnType diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-corner-anchors.ts b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-corner-anchors.ts new file mode 100644 index 000000000..fad870a34 --- /dev/null +++ b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-corner-anchors.ts @@ -0,0 +1,124 @@ +import type { CabinetModel, CabinetPart } from './cabinet-contracts' +import { cylinderRings, type CadPoint } from './cad-geometry' +import { profileAxes } from './cabinet-image-contract' + +type Edge = [CadPoint, CadPoint] +type Seat = { part: CabinetPart; start: CadPoint; index: number } +type Anchor = Seat & { point: CadPoint } +const epsilon = .001 +const maximumMeshTriangles = 16_000 +const maximumEdgeChecks = 120_000 +const cache = new WeakMap() + +function closedEdges(points: CadPoint[]): Edge[] { + return points.map((point, index) => [point, points[(index + 1) % points.length]]) +} + +function upperEdges(part: CabinetPart, useMesh: boolean): Edge[] { + const mesh = useMesh && part.cadOutput + if (mesh) { + const { triangles, vertices, min } = mesh + const edges: Edge[] = [] + const vertex = (index: number): CadPoint => [ + vertices[3 * index] - min[0], vertices[3 * index + 1] - min[1], vertices[3 * index + 2] - min[2], + ] + for (let i = 0; i < triangles.length; i += 3) { + const a = vertex(triangles[i]), b = vertex(triangles[i + 1]), c = vertex(triangles[i + 2]) + // Only upward facing surfaces can seat a guard. A groove on the underside + // doesn't change these surfaces; an actual cut in the outer top does. + if ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) > 1e-8) + edges.push([a, b], [b, c], [c, a]) + } + if (edges.length) return edges + } + if (part.cylinder) { + const [first, second] = cylinderRings(part.cylinder) + return [...closedEdges(first), ...closedEdges(second), ...first.map((point, i): Edge => [point, second[i]])] + } + if (part.profile) { + const [u, v, axis] = profileAxes(part.profile.axis) + const face = (offset: number) => part.profile!.points.map(([a, b]) => { + const point: CadPoint = [0, 0, 0] + point[u] = a; point[v] = b; point[axis] = offset + return point + }) + const end = face(part.size[axis]) + if (axis === 2) return closedEdges(end) + const start = face(0) + return [...closedEdges(start), ...closedEdges(end), ...start.map((point, i): Edge => [point, end[i]])] + } + return [] +} + +function closestOnEdge([a, b]: Edge, x: number, y: number): CadPoint { + const dx = b[0] - a[0], dy = b[1] - a[1] + const lengthSquared = dx * dx + dy * dy + if (!lengthSquared) return a[2] >= b[2] ? a : b + const t = Math.min(1, Math.max(0, ((x - a[0]) * dx + (y - a[1]) * dy) / lengthSquared)) + return [a[0] + t * dx, a[1] + t * dy, a[2] + t * (b[2] - a[2])] +} + +function findAnchors(model: CabinetModel): Anchor[] { + const top = (seat: Seat) => seat.start[2] + seat.part.size[2] + let highest = -Infinity + const all = model.parts.flatMap(part => part.positions.map((start, index) => { + const seat: Seat = { part, start, index } + highest = Math.max(highest, top(seat)) + return seat + })) + const tops = all.filter(({ part }) => part.role === 'top') + const seats = tops.length ? tops : all.filter(seat => highest - top(seat) <= epsilon) + if (!seats.length) return [] + let left = Infinity, right = -Infinity, front = Infinity, rear = -Infinity + for (const { start, part } of seats) { + left = Math.min(left, start[0]); right = Math.max(right, start[0] + part.size[0]) + front = Math.min(front, start[1]); rear = Math.max(rear, start[1] + part.size[1]) + } + const outlines = new Map() + let meshBudget = maximumMeshTriangles + // Bound geometry work for complicated imported models; use the board's box + // as a starting position when there is no usable or reasonably sized outline. + return ([[left, front], [right, front], [left, rear], [right, rear]] as const).flatMap(([x, y]) => { + let anchor: Anchor | undefined + let best = Infinity + let remaining = maximumEdgeChecks / 4 + for (const seat of seats) { + const { start, part } = seat + const u = x - start[0], v = y - start[1] + const cx = Math.min(part.size[0], Math.max(0, u)), cy = Math.min(part.size[1], Math.max(0, v)) + const lower = Math.hypot(cx - u, cy - v) + if (lower > best + epsilon || anchor && lower >= best - epsilon && top(seat) <= anchor.point[2] + epsilon) continue + let edges = outlines.get(part) + if (!edges && remaining > 0) { + const triangles = (part.cadOutput?.triangles.length ?? 0) / 3 + const useMesh = triangles > 0 && triangles <= meshBudget + if (useMesh) meshBudget -= triangles + edges = upperEdges(part, useMesh) + outlines.set(part, edges) + } + function consider([a, b, c]: CadPoint) { + const distance = Math.hypot(a - u, b - v) + const z = start[2] + c + if (!anchor || distance < best - epsilon || Math.abs(distance - best) <= epsilon && z > anchor.point[2] + epsilon) { + best = distance + anchor = { ...seat, point: [start[0] + a, start[1] + b, z] } + } + } + if (edges?.length && remaining > 0) { + const stride = Math.max(1, Math.ceil(edges.length / remaining)) + for (let i = 0; i < edges.length; i += stride) { + consider(closestOnEdge(edges[i], u, v)) + remaining-- + } + } else if (!anchor || remaining > 0) consider([cx, cy, part.size[2]]) + } + return anchor ? [anchor] : [] + }) +} + +// Same order as the four corners in the install controls: left/right, front/rear. +export function cabinetCornerAnchors(model: CabinetModel) { + let anchors = cache.get(model) + if (!anchors) { anchors = findAnchors(model); cache.set(model, anchors) } + return anchors +} diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-corner-guard.test.ts b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-corner-guard.test.ts index 3ee7efb20..1d1003b8c 100644 --- a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-corner-guard.test.ts +++ b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-corner-guard.test.ts @@ -18,7 +18,7 @@ const model = base.standardTemplate!.cabinet! const top = model.parts.find(part => part.role === 'top')! const withTop = (part: CabinetPart): CabinetModel => ({ ...model, parts: model.parts.map(item => item === top ? part : item) }) -test('uses the actual top panel origin and footprint for all four corners; a cut corner is rejected', () => { +test('uses the top panel origin and follows a chamfered corner instead of rejecting it', () => { const part: CabinetPart = { ...top, positions: [[12, 23, 680]], size: [960, 280, 15] } const shifted = withTop(part) const rows = previewTopCornerGuards(shifted, guard.id) @@ -28,15 +28,56 @@ test('uses the actual top panel origin and footprint for all four corners; a cut ['rear-left', [12, 303, 695]], ['rear-right', [972, 303, 695]], ]) const cut = withTop({ ...part, profile: { axis: 'z', points: [[30, 0], [960, 0], [960, 280], [0, 280], [0, 30]] } }) - expect(() => previewTopCornerGuards(cut, guard.id)).toThrow('顶板外形和尺寸') - expect(resolveTopCornerGuards(cut, rows)).toEqual([]) - expect(() => previewTopCornerGuards(withTop({ ...part, positions: [[12, 23, 680], [972, 23, 680]] }), guard.id)).toThrow('顶板') + expect(resolveTopCornerGuards(cut, previewTopCornerGuards(cut, guard.id)).map(row => row.point)) + .toEqual([[27, 38, 695], [972, 23, 695], [12, 303, 695], [972, 303, 695]]) +}) + +test('installs at all four exterior corners of the SG0164 02 top despite its underside groove', () => { + const grooved = withTop({ ...top, positions: [[0, 0, 710]], size: [960, 300, 15], solid: { + body: { kind: 'box', min: [0, 0, 0], max: [960, 300, 15] }, + actions: [{ kind: 'cut', tool: { kind: 'box', min: [0, 291, 0], max: [960, 294, 5] } }], + } }) + const rows = previewTopCornerGuards(grooved, guard.id) + expect(resolveTopCornerGuards(grooved, rows).map(row => row.point)) + .toEqual([[0, 0, 725], [960, 0, 725], [0, 300, 725], [960, 300, 725]]) +}) + +test('uses the assembled exterior of split tops even when their heights differ', () => { + const split = withTop({ ...top, size: [480, 300, 15], positions: [[0, 0, 710], [480, 0, 700]] }) + const rows = previewTopCornerGuards(split, guard.id) + const corners = resolveTopCornerGuards(split, rows) + expect(corners.map(row => [row.panel.index, row.point])).toEqual([ + [0, [0, 0, 725]], [1, [960, 0, 715]], [0, [0, 300, 725]], [1, [960, 300, 715]], + ]) + const standardTemplate = { ...base.standardTemplate!, cabinet: split } + const result = resolveStageHardware({ ...base, standardTemplate, surfaceHardware: rows }, undefined, [guard]) + expect(result.connections.find(row => row.code === guard.code)).toMatchObject({ + location: expect.stringContaining('柜体上外角'), count: 4, holes: [], + }) +}) + +test('can suggest positions on a rounded top without a top role', () => { + const rounded: CabinetModel = { ...model, parts: [{ + ...top, role: 'other', size: [300, 300, 15], positions: [[20, 50, 100]], + cylinder: { diameter: 300, start: [150, 150, 0], end: [150, 150, 15], levelEnds: false }, + }] } + const points = resolveTopCornerGuards(rounded, previewTopCornerGuards(rounded, guard.id)).map(row => row.point) + expect(points).toHaveLength(4) + for (const [x, y, z] of points) { + expect(Math.hypot(x - 170, y - 200)).toBeCloseTo(150, 4) + expect(z).toBe(115) + } }) test('reloads QT-01 as four no-drill accessories and regenerates packing and cost at the library price', () => { + const rows = previewTopCornerGuards(model, guard.id) + const initial = resolveTopCornerGuards(model, rows)[0].point + rows[0].cornerAdjustmentMm = [2, -3.5, 1] const modelWithGuards = estimateDocumentSchema.parse(JSON.parse(JSON.stringify({ - ...initializeStageResults(base), surfaceHardware: previewTopCornerGuards(model, guard.id), + ...initializeStageResults(base), surfaceHardware: rows, }))) + expect(resolveTopCornerGuards(modelWithGuards.standardTemplate!.cabinet!, modelWithGuards.surfaceHardware!)[0].point) + .toEqual([initial[0] + 2, initial[1] - 3.5, initial[2] + 1]) expect(pendingStages(modelWithGuards)).toMatchObject({ sampling: true, packing: true, cost: true }) const sampling = regenerateStage(modelWithGuards, 'sampling', [], undefined, [guard]) expect(sampling.stageResults?.sampling.connections).toEqual([expect.objectContaining({ diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-corner-guard.ts b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-corner-guard.ts index 1499f1d08..409172e15 100644 --- a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-corner-guard.ts +++ b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-corner-guard.ts @@ -1,8 +1,8 @@ import type { AccessoryDraft } from '@/lib/intake-accessory-models' import type { CabinetModel, CabinetPart } from './cabinet-contracts' -import { holeFitsHardwareStock, supportedHardwareStock } from './cabinet-hardware-stock' +import { cabinetCornerAnchors } from './cabinet-corner-anchors' import { cabinetHardwareBoard } from './hardware-board-connections' -import type { SurfaceHardware, SurfaceHardwarePlacement } from './surface-hardware' +import type { SurfaceHardware } from './surface-hardware' export const cornerGuardCode = 'QT-01' export const cornerGuardLocations = ['front-left', 'front-right', 'rear-left', 'rear-right'] as const @@ -11,62 +11,45 @@ export const cornerGuardLabels: Record = { 'front-left': '左前角', 'front-right': '右前角', 'rear-left': '左后角', 'rear-right': '右后角', } export const cornerGuardSize = { arm: 35, height: 15 } -const epsilon = .001 +export const cornerGuardAdjustmentLimitMm = 100 +export const noCornerGuardAdjustment = [0, 0, 0] as const export const isCabinetCornerGuard = (item: Pick) => item.code.trim().toUpperCase() === cornerGuardCode -export const isCornerGuardLocation = (location: SurfaceHardwarePlacement['location']): location is CornerGuardLocation => +export const isCornerGuardLocation = (location: string): location is CornerGuardLocation => cornerGuardLocations.some(corner => corner === location) -type Seat = { part: CabinetPart; start: CabinetPart['positions'][number]; index: number } +function anchorsForCorners(model: CabinetModel) { + return cabinetCornerAnchors(model).map(({ point, ...seat }, index) => ({ + panel: { ...seat, ...cabinetHardwareBoard(seat.part, seat.start, seat.index) }, + point, location: cornerGuardLocations[index], + })) +} -function topPanel(model: CabinetModel) { - let seats: Seat[] = [] - let height = -Infinity - for (const part of model.parts) { - if (part.role !== 'top') continue - part.positions.forEach((start, index) => { - const top = start[2] + part.size[2] - if (top > height + epsilon) { seats = []; height = top } - if (Math.abs(top - height) <= epsilon) seats.push({ part, start, index }) - }) - } - if (seats.length !== 1) return - const seat = seats[0] - const { part, start, index } = seat - const [width, depth, thickness] = part.size - const margin = cornerGuardSize.arm - if (width < margin * 2 || depth < margin * 2 || Math.abs(thickness - part.thickness) > epsilon || - part.notch || part.cylinder) return - const recipe = part.cadOutput?.recipe ?? part.solid - const body = recipe?.body - const simpleBox = body?.kind === 'box' && !recipe?.actions.length && - part.size.every((size, axis) => Math.abs(size - (body.max[axis] - body.min[axis])) <= epsilon) - if (!simpleBox && (!supportedHardwareStock(part) || ![margin / 2, width - margin / 2].every(x => - [margin / 2, depth - margin / 2].every(y => holeFitsHardwareStock( - seat, [start[0] + x, start[1] + y, start[2] + thickness], [0, 0, -1], margin, thickness, - ))))) return - return { ...seat, ...cabinetHardwareBoard(part, start, index) } +export function cornerGuardBoardKeys(model: CabinetModel) { + return new Map(anchorsForCorners(model).map(({ location, panel }) => [location, panel.key])) } export function previewTopCornerGuards(model: CabinetModel, accessoryId: string): SurfaceHardware { - const panel = topPanel(model) - if (!panel) throw new Error('当前模型没有一块可安装四角护角的顶板,请检查顶板外形和尺寸。') - return cornerGuardLocations.map(location => ({ boardKey: panel.key, accessoryId, location })) + const anchors = anchorsForCorners(model) + if (!anchors.length) throw new Error('当前模型没有板件,无法定位四个上外角。') + return anchors.map(({ panel, location }) => ({ boardKey: panel.key, accessoryId, location })) } export function resolveTopCornerGuards(model: CabinetModel, placements: SurfaceHardware) { if (!placements.some(row => isCornerGuardLocation(row.location))) return [] - const panel = topPanel(model) - if (!panel) return [] - const { part, start } = panel + const anchors = anchorsForCorners(model) return placements.flatMap(row => { const { location } = row - if (row.boardKey !== panel.key || !isCornerGuardLocation(location)) return [] + if (!isCornerGuardLocation(location)) return [] + const anchor = anchors[cornerGuardLocations.indexOf(location)] + if (!anchor || row.boardKey !== anchor.panel.key) return [] const left = location.endsWith('left') const front = location.startsWith('front') + const [dx, dy, dz] = row.cornerAdjustmentMm ?? noCornerGuardAdjustment + const [x, y, z] = anchor.point const point: CabinetPart['positions'][number] = [ - start[0] + (left ? 0 : part.size[0]), start[1] + (front ? 0 : part.size[1]), start[2] + part.size[2], + x + dx, y + dy, z + dz, ] - return [{ ...row, location, panel, point, left, front }] + return [{ ...row, location, panel: anchor.panel, point, left, front }] }) } diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-skill-surface-hardware.ts b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-skill-surface-hardware.ts index 12373c1af..b813788a8 100644 --- a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-skill-surface-hardware.ts +++ b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-skill-surface-hardware.ts @@ -1,12 +1,13 @@ import rules from '../../../../.agents/skills/cabinet-standard-bom/规则.json' import type { AccessoryDraft } from '@/lib/intake-accessory-models' import type { CabinetModel } from './cabinet-contracts' +import { isCornerGuardLocation } from './cabinet-corner-guard' import { backPanelBoards, backPanelClipPlacements, surfaceHardwareIssue, type BackPanelClipCount, type SurfaceHardware } from './surface-hardware' export function fillSkillSurfaceHardware(model: CabinetModel, items: readonly AccessoryDraft[], existing: SurfaceHardware, excluded: ReadonlySet) { const settings = rules.cabinetHardwareSkill.backPanelClip - const occupied = new Set(existing.map(row => row.boardKey)) + const occupied = new Set(existing.filter(row => !isCornerGuardLocation(row.location)).map(row => row.boardKey)) const parts = model.parts.filter(part => part.role === 'back' && !excluded.has(part.code) && part.length <= rules.hardware.backLengthLimit) const keys = backPanelBoards({ ...model, parts }).map(board => board.key).filter(key => !occupied.has(key)) if (!keys.length) return { placements: existing, added: 0 } diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/stage-surface-hardware.ts b/furniture-3d-system/src/lib/reference-estimator/standard/stage-surface-hardware.ts index 452a967b5..00b9f8331 100644 --- a/furniture-3d-system/src/lib/reference-estimator/standard/stage-surface-hardware.ts +++ b/furniture-3d-system/src/lib/reference-estimator/standard/stage-surface-hardware.ts @@ -14,8 +14,9 @@ export function stageCornerGuardHardware(model: CabinetModel, rows: SurfaceHardw location: '顶板四角', hardware: cornerGuardCode + ' · 硅胶防撞护角', count: null, holes: [], pending: first && !item ? '护角在配件库中不可用,请检查配件资料。' : '顶板或护角位置已变化,请重新确认四角安装。', }] + const location = group.every(row => row.panel.key === first.panel.key) ? first.panel.label : '柜体上外角' return [{ - location: first.panel.label + ' · ' + group.map(row => cornerGuardLabels[row.location].replace(/角$/, '')).join('、') + ' · 免打孔', + location: location + ' · ' + group.map(row => cornerGuardLabels[row.location].replace(/角$/, '')).join('、') + ' · 免打孔', hardware: [item.code, item.name, item.spec].filter(Boolean).join(' · '), count: group.length, holes: [], code: item.code, name: item.name, unit: item.priceUnit ?? '个', accessoryId: item.id, }] diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/surface-hardware.ts b/furniture-3d-system/src/lib/reference-estimator/standard/surface-hardware.ts index 75f324fdb..9517613ce 100644 --- a/furniture-3d-system/src/lib/reference-estimator/standard/surface-hardware.ts +++ b/furniture-3d-system/src/lib/reference-estimator/standard/surface-hardware.ts @@ -2,7 +2,7 @@ import { z } from 'zod' import type { AccessoryDraft } from '@/lib/intake-accessory-models' import type { CabinetModel } from './cabinet-contracts' import { cabinetHardwareBoard } from './hardware-board-connections' -import { cornerGuardLocations, isCornerGuardLocation } from './cabinet-corner-guard' +import { cornerGuardAdjustmentLimitMm, cornerGuardLocations, isCornerGuardLocation } from './cabinet-corner-guard' const corners = ['bottom-left', 'bottom-right', 'top-left', 'top-right'] as const const midpoints = ['bottom-middle', 'top-middle', 'left-middle', 'right-middle'] as const @@ -11,11 +11,14 @@ export function backPanelBoards(model: CabinetModel) { return model.parts.filter(part => part.role === 'back').flatMap(part => part.positions.map((origin, index) => cabinetHardwareBoard(part, origin, index))) } +const adjustmentMm = z.number().finite().min(-cornerGuardAdjustmentLimitMm).max(cornerGuardAdjustmentLimitMm) export const surfaceHardwareSchema = z.array(z.object({ boardKey: z.string().min(1).max(1000), accessoryId: z.string().min(1).max(100), location: z.enum([...corners, ...midpoints, ...cornerGuardLocations]), -}).strict()).max(2400).refine(rows => new Set(rows.map(row => JSON.stringify([row.boardKey, row.accessoryId, row.location]))).size === rows.length, + cornerAdjustmentMm: z.tuple([adjustmentMm, adjustmentMm, adjustmentMm]).optional(), +}).strict().refine(row => !row.cornerAdjustmentMm || isCornerGuardLocation(row.location), + '只有护角支持位置微调')).max(2400).refine(rows => new Set(rows.map(row => JSON.stringify([row.boardKey, row.accessoryId, row.location]))).size === rows.length, '同一位置不能重复安装同一配件') export type SurfaceHardware = z.infer export type SurfaceHardwarePlacement = SurfaceHardware[number] @@ -45,7 +48,7 @@ export function backPanelClipPlacements(model: CabinetModel, item: AccessoryDraf const keys = new Set(boards.map(board => board.key)) const locations = [...corners, ...midpoints.slice(0, perPanel - 4)] return surfaceHardwareSchema.parse([ - ...existing.filter(row => !keys.has(row.boardKey)), + ...existing.filter(row => isCornerGuardLocation(row.location) || !keys.has(row.boardKey)), ...boards.flatMap(board => locations.map(location => ({ boardKey: board.key, accessoryId: item.id, location }))), ]) } diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/variant-hardware.test.ts b/furniture-3d-system/src/lib/reference-estimator/standard/variant-hardware.test.ts index 98b43f096..1ccfcd906 100644 --- a/furniture-3d-system/src/lib/reference-estimator/standard/variant-hardware.test.ts +++ b/furniture-3d-system/src/lib/reference-estimator/standard/variant-hardware.test.ts @@ -8,6 +8,25 @@ import { readSeamEdits } from './hardware-seam-edits' import { carryVariantHardware } from './variant-hardware' import { copyVariant, resizeVariant } from './variant-copy' import { newStandardDocument } from './workbook' +import { previewTopCornerGuards, resolveTopCornerGuards } from './cabinet-corner-guard' + +it('keeps a confirmed guard offset when a copied cabinet uses a different board at that corner', () => { + const base = applyCabinetWorkflow(newStandardDocument(), cabinetInputSchema.parse({ referenceCase: '6G-960-B' })) + const standard = base.standardTemplate! + const cabinet = standard.cabinet! + const top = cabinet.parts.find(part => part.role === 'top')! + const guards = previewTopCornerGuards(cabinet, 'guard') + guards[1].cornerAdjustmentMm = [-5, 2, 1] + const split = { ...cabinet, parts: cabinet.parts.filter(part => part !== top).concat({ + ...top, id: 'split-top', size: [480, 300, 15], positions: [[0, 0, 710], [480, 0, 710]], + }) } + const { document, skipped } = carryVariantHardware({ ...base, surfaceHardware: guards }, + { ...base, standardTemplate: { ...standard, cabinet: split } }) + const after = resolveTopCornerGuards(split, document.surfaceHardware!) + expect(skipped).toBe(0) + expect(after).toHaveLength(4) + expect(after[1]).toMatchObject({ location: 'front-right', point: [955, 2, 726], panel: { index: 1 } }) +}) it.each([[64, 3], [128, 0]])('缩短板件时保持 %i mm 排距,对应孔位可加工才迁移整排', (pitch, count) => { const base = applyCabinetWorkflow(newStandardDocument(), cabinetInputSchema.parse({ referenceCase: '6G-960-B' })) diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/variant-hardware.ts b/furniture-3d-system/src/lib/reference-estimator/standard/variant-hardware.ts index e7c9883c3..590aaa4ba 100644 --- a/furniture-3d-system/src/lib/reference-estimator/standard/variant-hardware.ts +++ b/furniture-3d-system/src/lib/reference-estimator/standard/variant-hardware.ts @@ -9,6 +9,7 @@ import { fitsSeamOffset, readSeamEdits, type SeamEdit } from './hardware-seam-ed import { fitsSeamRow, layoutSeamRow, readSeamRowSpacing } from './hardware-seam-rows' import type { HardwarePlacementEdits } from './hardware-placement-edits' import { surfaceHardwareKey } from './surface-hardware' +import { cornerGuardBoardKeys, isCornerGuardLocation } from './cabinet-corner-guard' function instances(model: CabinetModel) { return model.parts.flatMap(part => part.positions.map((origin, index) => ({ @@ -119,10 +120,16 @@ export function carryVariantHardware(before: EstimateDocument, after: EstimateDo } } const usedSurface = new Set() + const hasGuards = before.surfaceHardware?.some(row => isCornerGuardLocation(row.location)) + const sourceCorners = hasGuards ? cornerGuardBoardKeys(oldModel) : undefined + const targetCorners = hasGuards ? cornerGuardBoardKeys(newModel) : undefined const surfaceHardware = before.surfaceHardware?.flatMap(item => { - const board = mapped.get(item.boardKey) - if (!board) { skipped++; return [] } - const next = { ...item, boardKey: board.key } + const { location } = item + const boardKey = isCornerGuardLocation(location) + ? sourceCorners?.get(location) === item.boardKey ? targetCorners?.get(location) : undefined + : mapped.get(item.boardKey)?.key + if (!boardKey) { skipped++; return [] } + const next = { ...item, boardKey } const key = surfaceHardwareKey(next) if (usedSurface.has(key)) { skipped++; return [] } usedSurface.add(key)