viewer: Fix Dutch roof trim artifacts (#452)
* 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 * Fix spiral stair openings and fence handle arrows * Implement roof trim planes and ridge vent clipping * Fix mansard roof and ridge vent placement * Fix mansard merged roof cutouts * Fix Dutch roof gable overhang * Refactor roof segment, ridge vent, and surface geometry Remove Dutch ridge axis abstraction and rework roof edit system, ridge vent clipping geometry, and roof surface placement. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * Simplify Dutch roof shape * Add Dutch roof gable top geometry controls * Fix Dutch roof slope material slots * Render dutch roof tops as double-sided faces * Add auto ridge vent toggle to roof segments Track ridge vent auto-generation via an `autoRidgeVent` metadata flag so geometry changes only regenerate default vents when enabled, treating legacy segments with generated vents as auto-enabled for back-compat. Expose a panel toggle to opt in/out per segment. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * Snap new walls to the floor below Feed the walls of the level directly beneath the active one into the draft snap pipeline as extra references, so a new wall can align with the floor below. They share the same local XZ origin, and the list is kept separate from the current-level walls so the measurement HUD and wall splitting only act on the active level. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * Set Dutch roof shape defaults on type switch Seed the Dutch shape parameters (waist width/height/length, top rake thickness/length) with sensible defaults whenever a segment is created as or switched to Dutch, so the gablet is well-formed regardless of leftover values from the previous roof type. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * Use green accent for corner and endpoint snap markers Color the corner/endpoint snap markers and the vertical cursor pillar green across the 2D floorplan beacon, the 3D alignment guide dots, and the wall snap beacon so snap targets read as a consistent accent. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * Add magnetic wall snapping to the roof tool Snap roof draft corners onto wall corners, midpoints, crossings, and bodies on the active level and the floor below, reusing the wall tool's snap pipeline so the beacon and coloring match. The cursor's ground dot/ring is hidden while a wall snap is active to avoid overlapping the beacon glyph. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * Update auto-generated Next.js route types path Regenerated next-env.d.ts now references ./.next/dev/types/routes.d.ts. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * Show cutaway outline while dragging roof trim Slice an untrimmed segment volume generated from the live node instead of the registry mesh, whose CSG rebuild lags a few frames behind the drag and may still hold placeholder geometry — so the section outline now renders deterministically. Use LineBasicNodeMaterial so the outline draws under the WebGPU pipeline, and export generateRoofSegmentGeometry for the slice source. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * Fill and clip roof trim cutaway, gate it to active drag Add a violet silhouette fill behind the cutaway outline, extend the section slicing to angled diagonal/corner trims via a generic vertical cut plane, and clip each slice to its footprint span so the infinite plane no longer sprouts stray lines across the rest of the roof. The cutaway now renders only while a trim handle is being dragged. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * Separate and extend Dutch roof end slopes Pull the Dutch hip end slopes out of the watertight shingle shell into their own slab wedge so they can be reshaped independently, and extend each end slope inward up its own hip plane until the top edge meets the gablet's inner triangle. Refactor roof-segment shape geometry into a shared roof-segment-shape module. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * Render roof trim cutaway as a material-only section cut Replace the triangle-mesh slicer with a CSG intersection of a thin slab against the untrimmed roof shell, so the cutaway shows red only on real material (wall + deck bands) and leaves the hollow attic empty. Add an analytic surface-edge outline, style both solid red like a SketchUp section, and make the cutaway persist whenever a segment is trimmed. Keep the merged roof shell visible during trim editing (re-trimmed live from each segment's drag override) instead of swapping in the per-segment meshes, whose abutting end-cap faces showed as stray white planes the commit never had. Extend each slab past free cut-line ends only — trimmed ends clamp to the cut line — so the red section stays inside the trim box. Re-export INTERSECTION from the viewer CSG surface for the editor. * Outline roof cutaway by fill silhouette, restyle to destructive red Derive the section-cut outline from the fill geometry's edges (EdgesGeometry) so it traces the real cut shape — wall/deck band boundaries and the hollow-attic edge — instead of just the top surface line. Drop the fill to 85% opacity and recolor both fill and outline to the app's destructive red, matching the delete/destructive UI. * Include roof accessories in trim clipping and red cutaway Roof accessories (chimney, vents, skylight, dormer, gutter, downspout, solar-panel, cupola) now slice at the trim plane like the roof shell and appear in the red section-cut while dragging a trim handle: - Export clipGeometryBySegmentTrim from the viewer as a reusable segment-local trim-clip primitive. - Add a shared useSegmentTrimClippedGeometry hook + TrimClippedMesh wrapper (nodes) that slice accessory geometry by the host segment's live trim override, so the cut tracks the drag. - Wire the clip into all 11 accessory renderers, including skylight glass panes and dormer window glass/frame/sill. - Feed every hosted accessory mesh into the editor's red cutaway, welding triangle-soup geometry (e.g. ridge vent) so CSG INTERSECTION yields a cross-section. - Register skylight in the scene-graph tree-node map so it shows in the outliner when placed on a roof. Co-Authored-By: Claude <noreply@anthropic.com> * Add smooth spline fences with editable curve handles Fences can now be drawn as one continuous Catmull-Rom/Bezier curve via an optional `path` (+ per-point `tangents`), selectable in a Straight/Curved mode toggle. Selected spline fences expose draggable control-point dots (hexagon) and symmetric tangent handles (circle) joined by a violet line, editable in both 2D plan and 3D. Side-move arrows are dropped for splines. Co-Authored-By: Claude <noreply@anthropic.com> * Fix dutch roof ridge vent handling * Fix Dutch ridge vent placement and support * Fix Dutch roof trim artifacts * Fix Dutch roof trim preview geometry * Tag roof trim overlay meshes with EDITOR_LAYER Child meshes relied on a parent group's layer, which three.js does not propagate, so the trim section/rail/plane overlays rendered on the scene layer — getting inked/SSGI-darkened and leaking into thumbnail exports. Co-Authored-By: Claude <noreply@anthropic.com> * Apply Biome cleanup * fix(core): address Dutch roof review feedback * chore: apply biome check cleanup * fix(core): relax Dutch roof surface helper input * fix * Fix biome checks and dev verification * fixes * Remove unsupported Biome noShadow override * Improve roof interactions and fence editing * Fix fence drag and ridge vent default handling * editor: drop wall-snap debug log, gate curved-fence finish hint on draft start Remove the leftover TEMP DIAGNOSTIC console.log in the wall tool's onMove hot path. Curved fences commit on a closing gesture (double-click / Enter) rather than per-click, so surface a 'Finish curve' hint in the fence HUD — but only once a point has been placed and a curve is actually in flight. The draft point count is published from SplineFenceDraft into a small ephemeral editor store (useFenceCurveDraft) that the contextual helper reads, mirroring the existing useSegmentDraftChain pattern. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: Wassim SAMAD <wass08@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
Wassim SAMAD
parent
c51e673421
commit
bf25af6add
@@ -83,7 +83,7 @@ export function resolveElevatorServiceLevels(
|
||||
|
||||
export function getElevatorLevelHeight(levelId: string, nodes: Record<string, AnyNode>): number {
|
||||
const level = nodes[levelId as AnyNodeId] as LevelNode | undefined
|
||||
if (!level || level.type !== 'level') return DEFAULT_ELEVATOR_LEVEL_HEIGHT
|
||||
if (level?.type !== 'level') return DEFAULT_ELEVATOR_LEVEL_HEIGHT
|
||||
|
||||
let maxTop = 0
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { FenceNode } from '../../schema'
|
||||
import { getWallCurveFrameAt, getWallCurveLength, sampleWallCenterline } from '../wall/wall-curve'
|
||||
import type { Point2D } from '../wall/wall-mitering'
|
||||
import {
|
||||
getFenceSplineFrameAt,
|
||||
getFenceSplineLength,
|
||||
isSplineFence,
|
||||
sampleFenceSpline,
|
||||
} from './fence-spline'
|
||||
|
||||
/**
|
||||
* Unified fence centerline accessors. A fence is either:
|
||||
* - a spline fence (`path` of >= 2 control points) → smooth Catmull-Rom, or
|
||||
* - a straight / single-arc fence (`start`/`end` + optional `curveOffset`).
|
||||
*
|
||||
* These wrappers branch on `isSplineFence` and return the SAME shapes the wall
|
||||
* arc helpers return, so every consumer (3D geometry, 2D floor-plan, length,
|
||||
* handles) can sample the centerline without caring which kind it is. Wall arc
|
||||
* math in `wall-curve.ts` is untouched — walls never carry a `path`.
|
||||
*/
|
||||
|
||||
const DEFAULT_SAMPLE_SEGMENTS = 96
|
||||
|
||||
type CurveFrame = {
|
||||
point: Point2D
|
||||
tangent: Point2D
|
||||
normal: Point2D
|
||||
}
|
||||
|
||||
export function getFenceCenterlineFrameAt(fence: FenceNode, t: number): CurveFrame {
|
||||
if (isSplineFence(fence) && fence.path) {
|
||||
return getFenceSplineFrameAt(fence.path, t, fence.tangents)
|
||||
}
|
||||
return getWallCurveFrameAt(fence, t)
|
||||
}
|
||||
|
||||
export function sampleFenceCenterline(
|
||||
fence: FenceNode,
|
||||
segments = DEFAULT_SAMPLE_SEGMENTS,
|
||||
): Point2D[] {
|
||||
if (isSplineFence(fence) && fence.path) {
|
||||
// Spread the requested sample budget across the spans so a long path still
|
||||
// reads smoothly without exploding the point count.
|
||||
const spanCount = Math.max(1, fence.path.length - 1)
|
||||
const perSpan = Math.max(2, Math.ceil(segments / spanCount))
|
||||
return sampleFenceSpline(fence.path, fence.tangents, perSpan)
|
||||
}
|
||||
return sampleWallCenterline(fence, segments)
|
||||
}
|
||||
|
||||
export function getFenceCenterlineLength(
|
||||
fence: FenceNode,
|
||||
segments = DEFAULT_SAMPLE_SEGMENTS,
|
||||
): number {
|
||||
if (isSplineFence(fence) && fence.path) {
|
||||
const spanCount = Math.max(1, fence.path.length - 1)
|
||||
const perSpan = Math.max(2, Math.ceil(segments / spanCount))
|
||||
return getFenceSplineLength(fence.path, fence.tangents, perSpan)
|
||||
}
|
||||
return getWallCurveLength(fence, segments)
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
import {
|
||||
getFenceControlHandle,
|
||||
getFenceSplineFrameAt,
|
||||
getFenceSplineLength,
|
||||
getTwoPointFenceCurveTangents,
|
||||
isSplineFence,
|
||||
sampleFenceSpline,
|
||||
} from './fence-spline'
|
||||
|
||||
describe('isSplineFence', () => {
|
||||
test('false without a path or with < 2 points', () => {
|
||||
expect(isSplineFence({ path: undefined })).toBe(false)
|
||||
expect(isSplineFence({ path: [[0, 0]] })).toBe(false)
|
||||
})
|
||||
|
||||
test('true with >= 2 points', () => {
|
||||
expect(
|
||||
isSplineFence({
|
||||
path: [
|
||||
[0, 0],
|
||||
[1, 0],
|
||||
],
|
||||
}),
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('sampleFenceSpline', () => {
|
||||
test('honors the control points as on-curve anchors', () => {
|
||||
const path: Array<[number, number]> = [
|
||||
[0, 0],
|
||||
[2, 2],
|
||||
[4, 0],
|
||||
]
|
||||
const sampled = sampleFenceSpline(path, undefined, 8)
|
||||
// First and last sample equal the path endpoints exactly.
|
||||
expect(sampled[0]).toEqual({ x: 0, y: 0 })
|
||||
expect(sampled[sampled.length - 1]).toEqual({ x: 4, y: 0 })
|
||||
// The interior control point is interpolated: some sample lands on (2, 2).
|
||||
const hitsMiddle = sampled.some((p) => Math.hypot(p.x - 2, p.y - 2) < 1e-6)
|
||||
expect(hitsMiddle).toBe(true)
|
||||
})
|
||||
|
||||
test('two-point path with no tangents is a straight segment', () => {
|
||||
expect(
|
||||
sampleFenceSpline(
|
||||
[
|
||||
[0, 0],
|
||||
[3, 0],
|
||||
],
|
||||
undefined,
|
||||
8,
|
||||
),
|
||||
).toEqual([
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 3, y: 0 },
|
||||
])
|
||||
})
|
||||
|
||||
test('a stored tangent bends an otherwise straight two-point span', () => {
|
||||
const path: Array<[number, number]> = [
|
||||
[0, 0],
|
||||
[4, 0],
|
||||
]
|
||||
// Pull the first point's handle up — the span should bow off the X axis.
|
||||
const sampled = sampleFenceSpline(path, [[0, 2], null], 12)
|
||||
expect(sampled[0]).toEqual({ x: 0, y: 0 })
|
||||
expect(sampled[sampled.length - 1]).toEqual({ x: 4, y: 0 })
|
||||
const maxY = Math.max(...sampled.map((p) => Math.abs(p.y)))
|
||||
expect(maxY).toBeGreaterThan(0.1)
|
||||
})
|
||||
|
||||
test('generated two-point curve tangents create a gentle arc', () => {
|
||||
const path: Array<[number, number]> = [
|
||||
[0, 0],
|
||||
[4, 0],
|
||||
]
|
||||
const sampled = sampleFenceSpline(path, getTwoPointFenceCurveTangents(path), 16)
|
||||
expect(sampled[0]).toEqual({ x: 0, y: 0 })
|
||||
expect(sampled[sampled.length - 1]).toEqual({ x: 4, y: 0 })
|
||||
const maxY = Math.max(...sampled.map((p) => p.y))
|
||||
expect(maxY).toBeGreaterThan(0.4)
|
||||
})
|
||||
|
||||
test('produces a smooth (no-cusp) curve on uneven spacing', () => {
|
||||
const path: Array<[number, number]> = [
|
||||
[0, 0],
|
||||
[1, 0.2],
|
||||
[5, 0.3],
|
||||
[6, 0],
|
||||
]
|
||||
const sampled = sampleFenceSpline(path, undefined, 16)
|
||||
let maxTurn = 0
|
||||
for (let i = 2; i < sampled.length; i += 1) {
|
||||
const a = sampled[i - 2]!
|
||||
const b = sampled[i - 1]!
|
||||
const c = sampled[i]!
|
||||
const t1 = Math.atan2(b.y - a.y, b.x - a.x)
|
||||
const t2 = Math.atan2(c.y - b.y, c.x - b.x)
|
||||
let d = Math.abs(t2 - t1)
|
||||
if (d > Math.PI) d = 2 * Math.PI - d
|
||||
maxTurn = Math.max(maxTurn, d)
|
||||
}
|
||||
expect(maxTurn).toBeLessThan(Math.PI / 2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getFenceControlHandle', () => {
|
||||
test('returns the stored tangent when present', () => {
|
||||
expect(
|
||||
getFenceControlHandle(
|
||||
[
|
||||
[0, 0],
|
||||
[4, 0],
|
||||
],
|
||||
[[1, 2], null],
|
||||
0,
|
||||
),
|
||||
).toEqual({ x: 1, y: 2 })
|
||||
})
|
||||
|
||||
test('falls back to the automatic distance-aware tangent', () => {
|
||||
const path: Array<[number, number]> = [
|
||||
[0, 0],
|
||||
[3, 0],
|
||||
[6, 0],
|
||||
]
|
||||
expect(getFenceControlHandle(path, undefined, 1)).toEqual({ x: 1, y: 0 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('getFenceSplineFrameAt', () => {
|
||||
const path: Array<[number, number]> = [
|
||||
[0, 0],
|
||||
[2, 0],
|
||||
[4, 0],
|
||||
]
|
||||
|
||||
test('t=0 / t=1 land on the endpoints', () => {
|
||||
expect(getFenceSplineFrameAt(path, 0).point).toEqual({ x: 0, y: 0 })
|
||||
expect(getFenceSplineFrameAt(path, 1).point).toEqual({ x: 4, y: 0 })
|
||||
})
|
||||
|
||||
test('returns a unit tangent and perpendicular normal', () => {
|
||||
const frame = getFenceSplineFrameAt(path, 0.5)
|
||||
expect(Math.hypot(frame.tangent.x, frame.tangent.y)).toBeCloseTo(1, 5)
|
||||
const dot = frame.tangent.x * frame.normal.x + frame.tangent.y * frame.normal.y
|
||||
expect(dot).toBeCloseTo(0, 5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getFenceSplineLength', () => {
|
||||
test('roughly matches the straight distance for a straight path', () => {
|
||||
expect(
|
||||
getFenceSplineLength(
|
||||
[
|
||||
[0, 0],
|
||||
[3, 4],
|
||||
],
|
||||
undefined,
|
||||
8,
|
||||
),
|
||||
).toBeCloseTo(5, 5)
|
||||
})
|
||||
|
||||
test('a curved path is longer than its endpoint chord', () => {
|
||||
const path: Array<[number, number]> = [
|
||||
[0, 0],
|
||||
[2, 2],
|
||||
[4, 0],
|
||||
]
|
||||
const chord = Math.hypot(4, 0)
|
||||
expect(getFenceSplineLength(path, undefined, 16)).toBeGreaterThan(chord)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,257 @@
|
||||
import type { FenceNode } from '../../schema'
|
||||
import type { Point2D } from '../wall/wall-mitering'
|
||||
|
||||
/**
|
||||
* Pure 2D spline sampling for fences whose centerline is defined by a `path`
|
||||
* of control points (the "flying path" curved fence).
|
||||
*
|
||||
* Each control point carries an OUT-handle offset vector. When the user has
|
||||
* not adjusted it, the handle defaults to a distance-aware Catmull-Rom-style
|
||||
* tangent: direction comes from neighbouring points, while length is capped by
|
||||
* the shorter adjacent span. When the user drags a tangent handle (stored in
|
||||
* `tangents[i]`), that point's handle becomes the stored vector and the IN
|
||||
* handle is its mirror, so the curve stays smooth (C1) through the point but
|
||||
* bends to taste. Each span is then a cubic Bézier between consecutive points
|
||||
* using their handles.
|
||||
*
|
||||
* Lives in `@pascal-app/core` and imports NO Three.js — the same `CurveFrame`
|
||||
* shape that `wall-curve.ts` returns (point / tangent / normal) is produced
|
||||
* here so the spline branch is a drop-in for the arc branch in every consumer.
|
||||
*/
|
||||
|
||||
const EPSILON = 1e-6
|
||||
const DEFAULT_SEGMENTS_PER_SPAN = 32
|
||||
const TWO_POINT_CURVE_SAGITTA_RATIO = 0.18
|
||||
const TWO_POINT_CURVE_MIN_SAGITTA = 0.18
|
||||
const TWO_POINT_CURVE_MAX_SAGITTA = 1.2
|
||||
|
||||
type FenceSplineLike = Pick<FenceNode, 'path'>
|
||||
type TangentList = ReadonlyArray<readonly [number, number] | null> | undefined
|
||||
|
||||
export function isSplineFence(fence: FenceSplineLike): boolean {
|
||||
return Array.isArray(fence.path) && fence.path.length >= 2
|
||||
}
|
||||
|
||||
type CurveFrame = {
|
||||
point: Point2D
|
||||
tangent: Point2D
|
||||
normal: Point2D
|
||||
}
|
||||
|
||||
function toPoints(path: ReadonlyArray<readonly [number, number]>): Point2D[] {
|
||||
return path.map(([x, y]) => ({ x, y }))
|
||||
}
|
||||
|
||||
function distance(a: Point2D, b: Point2D): number {
|
||||
return Math.hypot(b.x - a.x, b.y - a.y)
|
||||
}
|
||||
|
||||
function clamp01(value: number): number {
|
||||
return Math.max(0, Math.min(1, value))
|
||||
}
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.max(min, Math.min(max, value))
|
||||
}
|
||||
|
||||
/**
|
||||
* OUT-handle offset vector for control point `index` — the stored tangent if
|
||||
* the user has adjusted it, otherwise the automatic distance-aware tangent
|
||||
* (endpoints duplicate the neighbour so the ends stay tangent to their single
|
||||
* span). The IN handle is the negation of this.
|
||||
*
|
||||
* Exported so the editing UI can draw the tangent line / handle dots at the
|
||||
* right place even before the user has dragged them.
|
||||
*/
|
||||
export function getFenceControlHandle(
|
||||
path: ReadonlyArray<readonly [number, number]>,
|
||||
tangents: TangentList,
|
||||
index: number,
|
||||
): Point2D {
|
||||
const stored = tangents?.[index]
|
||||
if (stored) {
|
||||
return { x: stored[0], y: stored[1] }
|
||||
}
|
||||
const prev = path[index - 1] ?? path[index]!
|
||||
const next = path[index + 1] ?? path[index]!
|
||||
const prevDistance = distance(
|
||||
{ x: path[index]![0], y: path[index]![1] },
|
||||
{
|
||||
x: prev[0],
|
||||
y: prev[1],
|
||||
},
|
||||
)
|
||||
const nextDistance = distance(
|
||||
{ x: path[index]![0], y: path[index]![1] },
|
||||
{
|
||||
x: next[0],
|
||||
y: next[1],
|
||||
},
|
||||
)
|
||||
const handleLength = Math.min(prevDistance || nextDistance, nextDistance || prevDistance) / 3
|
||||
const vx = next[0] - prev[0]
|
||||
const vy = next[1] - prev[1]
|
||||
const len = Math.hypot(vx, vy)
|
||||
if (len < EPSILON || handleLength < EPSILON) {
|
||||
return { x: 0, y: 0 }
|
||||
}
|
||||
|
||||
return {
|
||||
x: (vx / len) * handleLength,
|
||||
y: (vy / len) * handleLength,
|
||||
}
|
||||
}
|
||||
|
||||
export function getTwoPointFenceCurveTangents(
|
||||
path: ReadonlyArray<readonly [number, number]>,
|
||||
): Array<[number, number] | null> | undefined {
|
||||
if (path.length !== 2) return undefined
|
||||
const start = path[0]!
|
||||
const end = path[1]!
|
||||
const dx = end[0] - start[0]
|
||||
const dy = end[1] - start[1]
|
||||
const chordLength = Math.hypot(dx, dy)
|
||||
if (chordLength < EPSILON) return undefined
|
||||
|
||||
const tangentX = dx / 3
|
||||
const tangentY = dy / 3
|
||||
const normalX = -dy / chordLength
|
||||
const normalY = dx / chordLength
|
||||
const sagitta = clamp(
|
||||
chordLength * TWO_POINT_CURVE_SAGITTA_RATIO,
|
||||
TWO_POINT_CURVE_MIN_SAGITTA,
|
||||
TWO_POINT_CURVE_MAX_SAGITTA,
|
||||
)
|
||||
const bendX = normalX * sagitta * (4 / 3)
|
||||
const bendY = normalY * sagitta * (4 / 3)
|
||||
|
||||
return [
|
||||
[tangentX + bendX, tangentY + bendY],
|
||||
[tangentX - bendX, tangentY - bendY],
|
||||
]
|
||||
}
|
||||
|
||||
function cubicBezier(p0: Point2D, p1: Point2D, p2: Point2D, p3: Point2D, u: number): Point2D {
|
||||
const mu = 1 - u
|
||||
const a = mu * mu * mu
|
||||
const b = 3 * mu * mu * u
|
||||
const c = 3 * mu * u * u
|
||||
const d = u * u * u
|
||||
return {
|
||||
x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,
|
||||
y: a * p0.y + b * p1.y + c * p2.y + d * p3.y,
|
||||
}
|
||||
}
|
||||
|
||||
function hasAnyTangent(tangents: TangentList): boolean {
|
||||
return Array.isArray(tangents) && tangents.some((t) => t != null)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample the spline centerline into a polyline. Control points are honored as
|
||||
* on-curve anchors; `segmentsPerSpan` controls smoothness between them.
|
||||
* Returns `(segmentsPerSpan * spanCount) + 1` points, first == path[0],
|
||||
* last == path[-1].
|
||||
*/
|
||||
export function sampleFenceSpline(
|
||||
path: ReadonlyArray<readonly [number, number]>,
|
||||
tangents?: TangentList,
|
||||
segmentsPerSpan = DEFAULT_SEGMENTS_PER_SPAN,
|
||||
): Point2D[] {
|
||||
const pts = toPoints(path)
|
||||
if (pts.length === 0) return []
|
||||
if (pts.length === 1) return [pts[0]!]
|
||||
// Two points with no adjusted tangents is a straight segment.
|
||||
if (pts.length === 2 && !hasAnyTangent(tangents)) return [pts[0]!, pts[1]!]
|
||||
|
||||
const steps = Math.max(1, Math.floor(segmentsPerSpan))
|
||||
const result: Point2D[] = [pts[0]!]
|
||||
|
||||
for (let i = 0; i < pts.length - 1; i += 1) {
|
||||
const p1 = pts[i]!
|
||||
const p2 = pts[i + 1]!
|
||||
const outHandle = getFenceControlHandle(path, tangents, i)
|
||||
const nextHandle = getFenceControlHandle(path, tangents, i + 1)
|
||||
// Bézier controls: leave p1 along its OUT handle, arrive at p2 along its
|
||||
// IN handle (= negated OUT handle).
|
||||
const c1: Point2D = { x: p1.x + outHandle.x, y: p1.y + outHandle.y }
|
||||
const c2: Point2D = { x: p2.x - nextHandle.x, y: p2.y - nextHandle.y }
|
||||
|
||||
for (let s = 1; s <= steps; s += 1) {
|
||||
result.push(cubicBezier(p1, c1, c2, p2, s / steps))
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
function frameFromPolyline(points: Point2D[], t: number): CurveFrame {
|
||||
if (points.length === 0) {
|
||||
return {
|
||||
point: { x: 0, y: 0 },
|
||||
tangent: { x: 1, y: 0 },
|
||||
normal: { x: 0, y: 1 },
|
||||
}
|
||||
}
|
||||
if (points.length === 1) {
|
||||
return {
|
||||
point: points[0]!,
|
||||
tangent: { x: 1, y: 0 },
|
||||
normal: { x: 0, y: 1 },
|
||||
}
|
||||
}
|
||||
|
||||
const clamped = clamp01(t)
|
||||
const lastIndex = points.length - 1
|
||||
const scaled = clamped * lastIndex
|
||||
const lower = Math.min(lastIndex - 1, Math.floor(scaled))
|
||||
const upper = lower + 1
|
||||
const localU = scaled - lower
|
||||
|
||||
const a = points[lower]!
|
||||
const b = points[upper]!
|
||||
const point = {
|
||||
x: a.x + (b.x - a.x) * localU,
|
||||
y: a.y + (b.y - a.y) * localU,
|
||||
}
|
||||
|
||||
const dx = b.x - a.x
|
||||
const dy = b.y - a.y
|
||||
const len = Math.hypot(dx, dy)
|
||||
const tangent = len < EPSILON ? { x: 1, y: 0 } : { x: dx / len, y: dy / len }
|
||||
|
||||
return {
|
||||
point,
|
||||
tangent,
|
||||
normal: { x: -tangent.y, y: tangent.x },
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Frame (point + tangent + normal) at parameter `t` in [0, 1] along the spline
|
||||
* centerline. Same return shape as `getWallCurveFrameAt` so it is a drop-in for
|
||||
* the arc branch. `t` is uniform over the sampled polyline (arc length is not
|
||||
* reparameterised — adequate for marching posts / rails and far cheaper).
|
||||
*/
|
||||
export function getFenceSplineFrameAt(
|
||||
path: ReadonlyArray<readonly [number, number]>,
|
||||
t: number,
|
||||
tangents?: TangentList,
|
||||
segmentsPerSpan = DEFAULT_SEGMENTS_PER_SPAN,
|
||||
): CurveFrame {
|
||||
return frameFromPolyline(sampleFenceSpline(path, tangents, segmentsPerSpan), t)
|
||||
}
|
||||
|
||||
/** Total polyline length of the sampled spline centerline. */
|
||||
export function getFenceSplineLength(
|
||||
path: ReadonlyArray<readonly [number, number]>,
|
||||
tangents?: TangentList,
|
||||
segmentsPerSpan = DEFAULT_SEGMENTS_PER_SPAN,
|
||||
): number {
|
||||
const points = sampleFenceSpline(path, tangents, segmentsPerSpan)
|
||||
let total = 0
|
||||
for (let i = 1; i < points.length; i += 1) {
|
||||
total += distance(points[i - 1]!, points[i]!)
|
||||
}
|
||||
return total
|
||||
}
|
||||
@@ -149,6 +149,19 @@ function straightStairAABB(
|
||||
|
||||
const ARC_SAMPLES = 48
|
||||
|
||||
function getSpiralLandingSweep(stair: StairNode, sweepAngle: number) {
|
||||
if ((stair.topLandingMode ?? 'none') !== 'integrated') return 0
|
||||
|
||||
const innerRadius = Math.max(0.05, stair.innerRadius ?? 0.9)
|
||||
const width = Math.max(stair.width ?? 1, 0.4)
|
||||
const landingDepth = Math.max(0.3, stair.topLandingDepth ?? Math.max(width * 0.9, 0.8))
|
||||
|
||||
return (
|
||||
Math.min(Math.PI * 0.75, landingDepth / Math.max(innerRadius + width / 2, 0.1)) *
|
||||
Math.sign(sweepAngle || 1)
|
||||
)
|
||||
}
|
||||
|
||||
/** Bounding box of a curved / spiral stair's annular sector (plus the
|
||||
* integrated spiral top landing when present). */
|
||||
function arcStairAABB(stair: StairNode): StairFootprintAABB | null {
|
||||
@@ -158,7 +171,8 @@ function arcStairAABB(stair: StairNode): StairFootprintAABB | null {
|
||||
const width = Math.max(stair.width ?? 1, 0.4)
|
||||
const outerRadius = innerRadius + width
|
||||
|
||||
let sweep = stair.sweepAngle ?? (isSpiral ? Math.PI * 2 : Math.PI / 2)
|
||||
const rawSweep = stair.sweepAngle ?? (isSpiral ? Math.PI * 2 : Math.PI / 2)
|
||||
let sweep = rawSweep
|
||||
// A full revolution would make the arc degenerate; clamp just under 2π the
|
||||
// same way the floor-plan emitter does so the sampled box stays correct.
|
||||
if (Math.abs(sweep) >= Math.PI * 2) sweep = Math.sign(sweep || 1) * (Math.PI * 2 - 0.001)
|
||||
@@ -175,17 +189,17 @@ function arcStairAABB(stair: StairNode): StairFootprintAABB | null {
|
||||
extendByLocal(box, stair, cos * outerRadius, sin * outerRadius)
|
||||
}
|
||||
|
||||
// Integrated spiral top landing — a rectangle hung off the outer rim.
|
||||
// Integrated spiral top landing renders as an angular extension of the
|
||||
// annular stair body, not as a rectangular box outside the outer rim.
|
||||
if (isSpiral && stair.topLandingMode === 'integrated') {
|
||||
const depth = Math.max(stair.topLandingDepth ?? 0.9, 0.1)
|
||||
const halfWidth = width / 2
|
||||
for (const [cornerX, cornerZ] of [
|
||||
[outerRadius, -halfWidth],
|
||||
[outerRadius + depth, -halfWidth],
|
||||
[outerRadius + depth, halfWidth],
|
||||
[outerRadius, halfWidth],
|
||||
] as const) {
|
||||
extendByLocal(box, stair, cornerX, cornerZ)
|
||||
const landingSweep = getSpiralLandingSweep(stair, rawSweep)
|
||||
const landingSteps = Math.max(1, Math.ceil(Math.abs(landingSweep) / (Math.PI / 24)))
|
||||
for (let step = 0; step <= landingSteps; step += 1) {
|
||||
const angle = rawSweep / 2 + (landingSweep * step) / landingSteps
|
||||
const cos = Math.cos(angle)
|
||||
const sin = Math.sin(angle)
|
||||
extendByLocal(box, stair, cos * innerRadius, sin * innerRadius)
|
||||
extendByLocal(box, stair, cos * outerRadius, sin * outerRadius)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -508,4 +508,48 @@ describe('syncAutoStairOpenings', () => {
|
||||
expect(landingUpdate?.data.holes).toEqual([manualOpening])
|
||||
expect(landingUpdate?.data.holeMetadata).toEqual([{ source: 'manual' }])
|
||||
})
|
||||
|
||||
test('does not add a separate rectangular hole for an integrated spiral top landing', () => {
|
||||
const building = BuildingNode.parse({ name: 'Building' })
|
||||
const ground = LevelNode.parse({ name: 'Ground', level: 0, parentId: building.id })
|
||||
const upper = LevelNode.parse({ name: 'Upper', level: 1, parentId: building.id })
|
||||
const landingSlab = SlabNode.parse({
|
||||
name: 'Landing Slab',
|
||||
parentId: upper.id,
|
||||
polygon: [
|
||||
[-4, -4],
|
||||
[4, -4],
|
||||
[4, 4],
|
||||
[-4, 4],
|
||||
],
|
||||
})
|
||||
const stair = StairNode.parse({
|
||||
id: 'stair_spiral_landing',
|
||||
name: 'Spiral Landing Stair',
|
||||
parentId: ground.id,
|
||||
position: [0, 0, 0],
|
||||
rotation: Math.PI / 2,
|
||||
stairType: 'spiral',
|
||||
fromLevelId: ground.id,
|
||||
toLevelId: upper.id,
|
||||
slabOpeningMode: 'destination',
|
||||
innerRadius: 0.35,
|
||||
width: 1.2,
|
||||
sweepAngle: Math.PI * 1.6,
|
||||
topLandingMode: 'integrated',
|
||||
topLandingDepth: 1.1,
|
||||
})
|
||||
const nodes = Object.fromEntries(
|
||||
[building, ground, upper, landingSlab, stair].map((node) => [node.id, node]),
|
||||
) as Record<string, AnyNode>
|
||||
|
||||
const updates = syncAutoStairOpenings(nodes)
|
||||
const landingUpdate = updates.find((update) => update.id === landingSlab.id)
|
||||
const holes = landingUpdate?.data.holes ?? []
|
||||
const rectangularHoles = holes.filter((hole) => hole.length === 4)
|
||||
|
||||
expect(holes).toHaveLength(1)
|
||||
expect(rectangularHoles).toHaveLength(0)
|
||||
expect(landingUpdate?.data.holeMetadata).toEqual([{ source: 'stair', stairId: stair.id }])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -454,22 +454,6 @@ function getSpiralOpeningPolygon(stair: StairNode, offset: number = 0): Point2D[
|
||||
})
|
||||
}
|
||||
|
||||
function getSpiralLandingPolygon(stair: StairNode, offset: number = 0): Point2D[] {
|
||||
const width = Math.max(stair.width ?? 1, 0.4)
|
||||
const outerRadius = Math.max(0.05, (stair.innerRadius ?? 0.9) + width)
|
||||
const depth = Math.max(stair.topLandingDepth ?? 0.9, 0.1)
|
||||
const halfWidth = width / 2
|
||||
|
||||
const localPoints: Point2D[] = [
|
||||
[outerRadius - offset, -halfWidth - offset],
|
||||
[outerRadius + depth + offset, -halfWidth - offset],
|
||||
[outerRadius + depth + offset, halfWidth + offset],
|
||||
[outerRadius - offset, halfWidth + offset],
|
||||
]
|
||||
|
||||
return localPoints.map(([x, z]) => toWorldPlanPoint(stair, x, z))
|
||||
}
|
||||
|
||||
function getStraightOpeningPolygonsForSurface(
|
||||
stair: StairNode,
|
||||
nodes: Record<string, AnyNode>,
|
||||
@@ -575,11 +559,7 @@ function getStairOpeningPolygons(
|
||||
|
||||
if (stair.stairType === 'spiral') {
|
||||
const offset = Math.max(openingOffset - STAIR_SLAB_OPENING_TIGHTENING, 0)
|
||||
const polygons = [getSpiralOpeningPolygon(stair, offset)]
|
||||
if (stair.topLandingMode === 'integrated') {
|
||||
polygons.push(getSpiralLandingPolygon(stair, offset))
|
||||
}
|
||||
return polygons
|
||||
return [getSpiralOpeningPolygon(stair, offset)]
|
||||
}
|
||||
|
||||
if (typeof targetElevation === 'number') {
|
||||
|
||||
Reference in New Issue
Block a user