* Add roof surface placement support for items Items (e.g. solar panels) can now be placed on sloped roof surfaces. The placement system computes euler rotation from the roof surface normal so items sit flush on the slope instead of going inside. - Add roofStrategy to placement-strategies with enter/move/click/leave - Wire roof:enter/move/click/leave events in the placement coordinator - Add calculateRoofRotation in placement-math using surface normals - Support full 3D cursor rotation for sloped surfaces - Items on roofs are parented to the level with world-space rotation Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fixed conflict * feat(duct): ceiling-snap drawing + connected-joint endpoint move Duct draw tool's ceiling mode now hangs each path point just below the ceiling actually covering it (per-room heights tracked), with a translucent surface highlight and a plumb line to the floor so the in-flight point reads clearly from any angle. Dragging a duct corner that sits on a fitting now carries the fitting's other ducts along (port-connectivity second hop), so the joint moves together instead of tearing apart. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(mep): detach + vertical modifiers for duct/pipe joint editing Alt detaches a dragged duct/pipe endpoint or fitting from its connected joint (no elbow re-aim, no connectivity follow); Ctrl/Cmd drives vertical riser movement on the fitting move. Behavioral parity across 2D and 3D. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(mep): full DWV pipe parity for joint editing Bring pipe-segment endpoint drags and pipe-fitting moves to parity with duct: free-drag endpoints, Alt-detach, Ctrl/Cmd-vertical riser, elbow re-aim, and connectivity follow. Generalizes the shared elbow-reaim and auto-fitting helpers to dispatch by run kind so 2D and 3D share one path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(mep): wall-style arrow handles for duct fittings + segments Add violet directional arrow affordances to duct-fitting selection (height, move cross, rotate arc) mirroring the duct-segment rig: portaled into the parent frame to stay out of the selection outline, rendered via the shared HandleArrow, and carrying mated-run connectivity through the single-undo dance. The move cross engages press-drag-release (placementDragMode) the same way the floating drag does, so the markup hit-areas go inert and the fitting move tool commits on pointer-up. Also re-export the HandleArrow primitives from @pascal-app/editor and extend the duct-segment side-move/floorplan affordances. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(mep): click-to-latch cube handles for duct + fitting editing Replace the hover-reveal / multi-handle selection rigs with a single click-to-latch cube that opens a directional cluster, shared between duct segments and fittings via a new selection-handles module (HandleCube / MoveChevron / RotateArc, all sized to the roof pitch cube). - Duct segment: per-vertex + run-center cubes reveal axis-locked move chevrons (down arrow always shown), plus a roll arc at the run center. - Duct fitting: center cube reveals six ±XYZ move arrows and three per-axis rotation arcs (oriented in place), replacing the old height/move/rotate trio with axis-cycling. - Rotation (fitting arcs + duct roll) snaps to 45° steps; Shift = smooth. - thin chevron profile + press-drag-release commit retained. * fix(mep): orient duct roll arc consistently + drop Ctrl-vertical drag Build a fully-determined basis for the duct roll gizmo so the curved arrow always seats at the top-outer 45° corner regardless of run direction, instead of an arbitrary apex from a single setFromUnitVectors. The selection-rig ±Y arrows now own vertical movement, so the redundant Ctrl-modifier riser drag is removed from the fitting move tool. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(mep): run-aligned duct handles, swing snapping, elbow flatten Align the duct run-center cube + horizontal arrows to the run axis (matching the per-vertex handles) while keeping whole-run translate. Endpoint side / up-down swing arrows now follow grid snap points and port-snap onto nearby collars (Shift sweeps smoothly). Relax elbow realign + fitting schemas to flatten to a straight 0° coupling. Surface HVAC-specific hints in the select-mode helper panel for duct / fitting. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(mep): per-segment linesets/liquid-lines with joint-follow editing Linesets and liquid lines now commit one independent two-point node per drawn segment instead of folding into a single mitered polyline, so each line selects and deletes on its own. Endpoint caps fill shared-coordinate joints so connected segments still read as continuous pipe. Dragging a shared endpoint carries mated segments along via port connectivity (Alt detaches), so a run still edits as one welded piece. Liquid-line follow mode traces the whole connected lineset run, laying a per-segment parallel line down its full assembled length. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(mep): vertical-offset auto-routing on duct center-cube ±Y drag Lifting/lowering a connected run with the run-center cube now keeps each connected end welded to its stationary partner instead of dragging the whole network. Run-to-run ends get the classic S/Z offset (two elbows + plumb riser, partner trimmed back one leg); elbow-connected ends form a clean L — the existing elbow stays put and re-aims its collar vertical, with one new top elbow + riser reconnecting to the lifted endpoint. The offset is ghosted live and minted as a single undo step on release. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * Add roof accessory placement guides Measure roof accessory placement against the active roof face using visible surface bounds and preview geometry footprints. Add dormer-local guides and special linear handling for ridge vents and gutters. * Improve duct and placement routing * Fix duct vertical movement routing * Fix duct vertical offsets and roof accessory movement * Add DWV movement parity and line endpoint controls * Fix MEP handle review issues * Fix chimney placement and duct offset cleanup * Use snapped targets for roof accessory commits * fix(nodes): repair MEP movement review issues - auto-fitting: tee branch now follows the drawn lateral angle; update the stale square-tee test + doc comment that contradicted the rewrite - duct-segment: re-enable the vertical auto-offset rewind (the disabled stub left mintedIds empty, so re-dragging a tagged duct stranded old elbows/risers and stacked duplicates); remove the dead stub - duct-segment: strip the stale auto-offset tag on manual corner/roll commits so the horizontal-move path no longer trusts an out-of-date base - chimney: resume history before mutating segment children arrays so a cross-segment move reparents in one tracked transaction (undo stays consistent) - dormer: align schema test with the new windowSill=false default * fix: address mep movement review issues * fix: address follow-up mep review comments * fix: address additional mep review comments --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: pascal-open-bot <open@pascal.app>
327 lines
11 KiB
TypeScript
327 lines
11 KiB
TypeScript
'use client'
|
|
|
|
import {
|
|
type AlignmentAnchor,
|
|
type AnyNode,
|
|
type AnyNodeId,
|
|
emitter,
|
|
type GridEvent,
|
|
LinesetNode,
|
|
sceneRegistry,
|
|
useScene,
|
|
} from '@pascal-app/core'
|
|
import {
|
|
DragBoundingBox,
|
|
EDITOR_LAYER,
|
|
markToolCancelConsumed,
|
|
stripPlacementMetadataFlags,
|
|
triggerSFX,
|
|
useAlignmentGuides,
|
|
useEditor,
|
|
} from '@pascal-app/editor'
|
|
import { useViewer } from '@pascal-app/viewer'
|
|
import { useEffect, useRef, useState } from 'react'
|
|
import { Vector3 } from 'three'
|
|
import {
|
|
type Aabb2D,
|
|
collectGhostAlignmentCandidates,
|
|
resolveGhostAlignment,
|
|
} from '../shared/ghost-alignment'
|
|
import { type RunMoveConnectivity, startRunMoveConnectivity } from '../shared/run-move-connectivity'
|
|
|
|
type Vec3 = [number, number, number]
|
|
|
|
const GHOST_COLOR = '#818cf8'
|
|
const GHOST_OPACITY = 0.5
|
|
const IN_TO_M = 0.0254
|
|
|
|
/** Snap a coordinate to the editor's live grid step. */
|
|
function snapToGridStep(value: number): number {
|
|
const step = useEditor.getState().gridSnapStep
|
|
if (step <= 0) return value
|
|
return Math.round(value / step) * step
|
|
}
|
|
|
|
function pathCenterXZ(path: readonly Vec3[]): [number, number] {
|
|
let x = 0
|
|
let z = 0
|
|
for (const p of path) {
|
|
x += p[0]
|
|
z += p[2]
|
|
}
|
|
const n = path.length || 1
|
|
return [x / n, z / n]
|
|
}
|
|
|
|
/** The lineset's footprint radius (meters) — half the suction OD (the
|
|
* bigger of the pair), used as box / footprint padding and ghost radius. */
|
|
function linesetRadiusM(lineset: LinesetNode): number {
|
|
return (lineset.suctionDiameter * IN_TO_M) / 2
|
|
}
|
|
|
|
/** XZ bounds of a path padded by the lineset's radius. */
|
|
function pathAabb(path: readonly Vec3[], r: number): Aabb2D {
|
|
let minX = Number.POSITIVE_INFINITY
|
|
let maxX = Number.NEGATIVE_INFINITY
|
|
let minZ = Number.POSITIVE_INFINITY
|
|
let maxZ = Number.NEGATIVE_INFINITY
|
|
for (const p of path) {
|
|
if (p[0] < minX) minX = p[0]
|
|
if (p[0] > maxX) maxX = p[0]
|
|
if (p[2] < minZ) minZ = p[2]
|
|
if (p[2] > maxZ) maxZ = p[2]
|
|
}
|
|
return { minX: minX - r, maxX: maxX + r, minZ: minZ - r, maxZ: maxZ + r }
|
|
}
|
|
|
|
/**
|
|
* Ghost-preview duplicate / move tool for refrigerant linesets — the
|
|
* refrigerant-loop sibling of `MovePipeSegmentTool`. A lineset is a
|
|
* suction + liquid copper pair; the ghost stands in with a single
|
|
* translucent cylinder at the suction OD per section (mirrors the draw
|
|
* tool's `PreviewSegment`).
|
|
*
|
|
* **Duplicate** (`metadata.isNew`): pure drag-to-place — NOTHING is
|
|
* inserted into the scene until the commit click. A translucent ghost of
|
|
* the run rides the cursor inside a footprint bounding box — the same
|
|
* affordance other items get — and Figma-style alignment guides snap the
|
|
* box's edges to nearby geometry. The next grid click calls `createNode`;
|
|
* Esc discards. The run's Y coords ride along untouched: the move only
|
|
* shifts XZ.
|
|
*
|
|
* **Move** (existing run): the real node's mesh is hidden while the same
|
|
* ghost + box tracks the cursor; the commit click writes the translated
|
|
* `path` and reveals it, Esc reveals it unchanged.
|
|
*
|
|
* Wired via `def.affordanceTools.move`.
|
|
*/
|
|
export const MoveLinesetTool: React.FC<{ node: AnyNode }> = ({ node }) => {
|
|
const lineset = node as LinesetNode
|
|
const originalPathRef = useRef<Vec3[]>(lineset.path.map((p) => [...p] as Vec3))
|
|
|
|
const isNew =
|
|
typeof node.metadata === 'object' &&
|
|
node.metadata !== null &&
|
|
!Array.isArray(node.metadata) &&
|
|
(node.metadata as Record<string, unknown>).isNew === true
|
|
|
|
const [previewPath, setPreviewPath] = useState<Vec3[]>(originalPathRef.current)
|
|
const previewPathRef = useRef<Vec3[]>(originalPathRef.current)
|
|
const hasMovedRef = useRef(false)
|
|
const activatedAtRef = useRef<number>(Date.now())
|
|
const prevSnapRef = useRef<[number, number] | null>(null)
|
|
|
|
useEffect(() => {
|
|
const nodeId = node.id as AnyNodeId
|
|
const originalPath = originalPathRef.current
|
|
const [centerX, centerZ] = pathCenterXZ(originalPath)
|
|
const r = linesetRadiusM(lineset)
|
|
const baseAabb = pathAabb(originalPath, r)
|
|
|
|
useScene.temporal.getState().pause()
|
|
let committed = false
|
|
|
|
const candidates: AlignmentAnchor[] = collectGhostAlignmentCandidates(
|
|
useScene.getState().nodes,
|
|
nodeId,
|
|
useViewer.getState().selection.levelId ?? node.parentId,
|
|
)
|
|
|
|
// Moving an existing run: hide its 3D MESH imperatively (NOT the store
|
|
// `visible` flag — the 2D floor plan skips `visible:false` nodes, so a
|
|
// store hide makes the run vanish in 2D / split view). The ghost stands
|
|
// in until commit; the real mesh is restored on cancel / unmount.
|
|
const existedAtStart = !isNew && !!useScene.getState().nodes[nodeId]
|
|
const setMeshHidden = (hidden: boolean) => {
|
|
const obj = sceneRegistry.nodes.get(nodeId)
|
|
if (obj) obj.visible = !hidden
|
|
}
|
|
if (existedAtStart) setMeshHidden(true)
|
|
|
|
// Carry connected fittings (+ their other runs) as the whole run slides.
|
|
// Snapshot once at drag start; only existing runs are mated to anything.
|
|
const connectivity: RunMoveConnectivity | null = existedAtStart
|
|
? startRunMoveConnectivity(node)
|
|
: null
|
|
|
|
const setPreview = (path: Vec3[]) => {
|
|
previewPathRef.current = path
|
|
setPreviewPath(path)
|
|
}
|
|
|
|
const onMove = (event: GridEvent) => {
|
|
const bypass = event.nativeEvent?.shiftKey === true
|
|
const snap = bypass ? (v: number) => v : snapToGridStep
|
|
let dx = snap(event.localPosition[0] - centerX)
|
|
let dz = snap(event.localPosition[2] - centerZ)
|
|
|
|
// Figma-style alignment: snap the run's footprint box edges onto
|
|
// nearby geometry and publish the guides (Shift bypass).
|
|
if (!bypass) {
|
|
const proposed: Aabb2D = {
|
|
minX: baseAabb.minX + dx,
|
|
maxX: baseAabb.maxX + dx,
|
|
minZ: baseAabb.minZ + dz,
|
|
maxZ: baseAabb.maxZ + dz,
|
|
}
|
|
const { dx: sdx, dz: sdz, guides } = resolveGhostAlignment(nodeId, proposed, candidates)
|
|
dx += sdx
|
|
dz += sdz
|
|
useAlignmentGuides.getState().set(guides)
|
|
} else {
|
|
useAlignmentGuides.getState().clear()
|
|
}
|
|
|
|
const cur: [number, number] = [centerX + dx, centerZ + dz]
|
|
if (
|
|
!bypass &&
|
|
(!prevSnapRef.current ||
|
|
prevSnapRef.current[0] !== cur[0] ||
|
|
prevSnapRef.current[1] !== cur[1])
|
|
) {
|
|
triggerSFX('sfx:grid-snap')
|
|
}
|
|
prevSnapRef.current = cur
|
|
hasMovedRef.current = true
|
|
const nextPath = originalPath.map(([x, y, z]) => [x + dx, y, z + dz] as Vec3)
|
|
setPreview(nextPath)
|
|
connectivity?.preview({ path: nextPath })
|
|
}
|
|
|
|
const commit = (event: GridEvent) => {
|
|
if (committed) return
|
|
if (Date.now() - activatedAtRef.current < 150) {
|
|
event.nativeEvent?.stopPropagation?.()
|
|
return
|
|
}
|
|
if (!hasMovedRef.current) {
|
|
event.nativeEvent?.stopPropagation?.()
|
|
return
|
|
}
|
|
committed = true
|
|
const finalPath = previewPathRef.current
|
|
|
|
useScene.temporal.getState().resume()
|
|
let selectId = nodeId
|
|
if (isNew && !useScene.getState().nodes[nodeId]) {
|
|
const created = LinesetNode.parse({
|
|
...(node as Record<string, unknown>),
|
|
path: finalPath,
|
|
metadata: stripPlacementMetadataFlags(node.metadata),
|
|
visible: true,
|
|
})
|
|
useScene.getState().createNode(created as AnyNode, node.parentId as AnyNodeId)
|
|
selectId = created.id as AnyNodeId
|
|
} else {
|
|
// Fold connected-fitting / sibling-run follow-updates into the SAME
|
|
// batch as the moved run so the whole joint is one undo step.
|
|
const followUpdates = connectivity?.commitUpdates({ path: finalPath }) ?? []
|
|
useScene
|
|
.getState()
|
|
.updateNodes([
|
|
{ id: nodeId, data: { path: finalPath } as Partial<AnyNode> },
|
|
...followUpdates,
|
|
])
|
|
useScene.getState().markDirty(nodeId)
|
|
}
|
|
useScene.temporal.getState().pause()
|
|
// Followers are committed to the store — drop their live overrides so
|
|
// renderers read the canonical path/position.
|
|
connectivity?.clear()
|
|
setMeshHidden(false)
|
|
|
|
useAlignmentGuides.getState().clear()
|
|
triggerSFX('sfx:item-place')
|
|
useViewer.getState().setSelection({ selectedIds: [selectId] })
|
|
useEditor.getState().setMovingNodeOrigin('3d')
|
|
useEditor.getState().setMovingNode(null)
|
|
event.nativeEvent?.stopPropagation?.()
|
|
}
|
|
|
|
const onCancel = () => {
|
|
connectivity?.clear()
|
|
if (existedAtStart) {
|
|
setMeshHidden(false)
|
|
useViewer.getState().setSelection({ selectedIds: [nodeId] })
|
|
}
|
|
useAlignmentGuides.getState().clear()
|
|
useScene.temporal.getState().resume()
|
|
markToolCancelConsumed()
|
|
useEditor.getState().setMovingNodeOrigin('3d')
|
|
useEditor.getState().setMovingNode(null)
|
|
}
|
|
|
|
emitter.on('grid:move', onMove)
|
|
emitter.on('grid:click', commit)
|
|
emitter.on('tool:cancel', onCancel)
|
|
|
|
return () => {
|
|
emitter.off('grid:move', onMove)
|
|
emitter.off('grid:click', commit)
|
|
emitter.off('tool:cancel', onCancel)
|
|
connectivity?.clear()
|
|
useAlignmentGuides.getState().clear()
|
|
if (existedAtStart) setMeshHidden(false)
|
|
useScene.temporal.getState().resume()
|
|
}
|
|
}, [lineset, isNew, node])
|
|
|
|
const segments: Array<{ a: Vec3; b: Vec3 }> = []
|
|
for (let i = 0; i < previewPath.length - 1; i++) {
|
|
segments.push({ a: previewPath[i]!, b: previewPath[i + 1]! })
|
|
}
|
|
|
|
// Footprint box spanning the whole run (axis-aligned), drawn around the
|
|
// ghost the same way items get one. Recomputed from the live preview path.
|
|
const r = linesetRadiusM(lineset)
|
|
const box = pathAabb(previewPath, r)
|
|
const boxY = previewPath[0]?.[1] ?? 0
|
|
|
|
return (
|
|
<group>
|
|
{segments.map((seg, i) => (
|
|
<GhostSegment a={seg.a} b={seg.b} radius={r} key={`ghost-${i}`} />
|
|
))}
|
|
<DragBoundingBox
|
|
centerY={0}
|
|
nodeId={node.id}
|
|
position={[(box.minX + box.maxX) / 2, boxY, (box.minZ + box.maxZ) / 2]}
|
|
size={[box.maxX - box.minX, lineset.suctionDiameter * IN_TO_M, box.maxZ - box.minZ]}
|
|
/>
|
|
</group>
|
|
)
|
|
}
|
|
|
|
/** Translucent stand-in for one lineset section — mirrors the draw tool's
|
|
* `PreviewSegment` so the ghost matches what actually lands. */
|
|
function GhostSegment({ a, b, radius }: { a: Vec3; b: Vec3; radius: number }) {
|
|
const start = new Vector3(...a)
|
|
const end = new Vector3(...b)
|
|
const dir = new Vector3().subVectors(end, start)
|
|
const length = dir.length()
|
|
if (length < 1e-4) return null
|
|
dir.normalize()
|
|
const mid = new Vector3().addVectors(start, end).multiplyScalar(0.5)
|
|
|
|
return (
|
|
<mesh
|
|
layers={EDITOR_LAYER}
|
|
position={mid.toArray()}
|
|
ref={(m) => {
|
|
if (!m) return
|
|
m.quaternion.setFromUnitVectors(new Vector3(0, 1, 0), dir)
|
|
}}
|
|
>
|
|
<cylinderGeometry args={[radius, radius, length, 16, 1, false]} />
|
|
<meshBasicMaterial
|
|
color={GHOST_COLOR}
|
|
depthTest={false}
|
|
opacity={GHOST_OPACITY}
|
|
transparent
|
|
/>
|
|
</mesh>
|
|
)
|
|
}
|
|
|
|
export default MoveLinesetTool
|