diff --git a/packages/core/src/procedural-items/__fixtures__/recessed_downlight.json b/packages/core/src/procedural-items/__fixtures__/recessed_downlight.json new file mode 100644 index 0000000000..cb4f4befea --- /dev/null +++ b/packages/core/src/procedural-items/__fixtures__/recessed_downlight.json @@ -0,0 +1,392 @@ +{ + "version": 2, + "name": "Recessed square downlight", + "description": "Square trim flush with the ceiling, an open can recessed into the ceiling and a glowing lens set back inside it.", + "classification": { + "category": "lighting", + "functionTags": ["downlight", "ceiling-light"], + "tags": ["recessed"] + }, + "mounting": { + "attachTo": "ceiling", + "reference": "plane" + }, + "cuts": [ + { + "shape": "rect", + "size": ["size", "size"] + } + ], + "surfaces": [ + { + "id": "plane", + "label": "Ceiling plane", + "position": [0, 0.01, 0], + "size": [ + { + "op": "add", + "args": ["size", 0.04] + }, + { + "op": "add", + "args": ["size", 0.04] + } + ] + } + ], + "parameters": [ + { + "id": "size", + "label": "Aperture", + "default": 0.12, + "min": 0.08, + "max": 0.2, + "step": 0.01, + "unit": "m", + "axis": "x" + }, + { + "id": "depth", + "label": "Recess depth", + "default": 0.12, + "min": 0.08, + "max": 0.2, + "step": 0.01, + "unit": "m" + } + ], + "slots": [ + { + "id": "trim", + "label": "Trim", + "color": "#f4f4f2", + "finish": "metal" + }, + { + "id": "can", + "label": "Can", + "color": "#2b2b2b" + }, + { + "id": "lens", + "label": "Lens", + "color": "#fff4e0" + } + ], + "parts": [ + { + "id": "trim", + "label": "Trim", + "count": 1, + "shapes": [ + { + "id": "north", + "primitive": "box", + "slot": "trim", + "size": [ + { + "op": "add", + "args": ["size", 0.04] + }, + 0.01, + 0.02 + ], + "position": [ + 0, + 0.005, + { + "op": "mul", + "args": [ + { + "op": "add", + "args": [ + { + "op": "div", + "args": ["size", 2] + }, + 0.01 + ] + }, + -1 + ] + } + ] + }, + { + "id": "south", + "primitive": "box", + "slot": "trim", + "size": [ + { + "op": "add", + "args": ["size", 0.04] + }, + 0.01, + 0.02 + ], + "position": [ + 0, + 0.005, + { + "op": "add", + "args": [ + { + "op": "div", + "args": ["size", 2] + }, + 0.01 + ] + } + ] + }, + { + "id": "east", + "primitive": "box", + "slot": "trim", + "size": [0.02, 0.01, "size"], + "position": [ + { + "op": "add", + "args": [ + { + "op": "div", + "args": ["size", 2] + }, + 0.01 + ] + }, + 0.005, + 0 + ] + }, + { + "id": "west", + "primitive": "box", + "slot": "trim", + "size": [0.02, 0.01, "size"], + "position": [ + { + "op": "mul", + "args": [ + { + "op": "add", + "args": [ + { + "op": "div", + "args": ["size", 2] + }, + 0.01 + ] + }, + -1 + ] + }, + 0.005, + 0 + ] + } + ] + }, + { + "id": "can", + "label": "Can", + "count": 1, + "shapes": [ + { + "id": "north", + "primitive": "box", + "slot": "can", + "size": ["size", "depth", 0.004], + "position": [ + 0, + { + "op": "add", + "args": [ + 0.01, + { + "op": "div", + "args": ["depth", 2] + } + ] + }, + { + "op": "mul", + "args": [ + { + "op": "sub", + "args": [ + { + "op": "div", + "args": ["size", 2] + }, + 0.002 + ] + }, + -1 + ] + } + ] + }, + { + "id": "south", + "primitive": "box", + "slot": "can", + "size": ["size", "depth", 0.004], + "position": [ + 0, + { + "op": "add", + "args": [ + 0.01, + { + "op": "div", + "args": ["depth", 2] + } + ] + }, + { + "op": "sub", + "args": [ + { + "op": "div", + "args": ["size", 2] + }, + 0.002 + ] + } + ] + }, + { + "id": "east", + "primitive": "box", + "slot": "can", + "size": [ + 0.004, + "depth", + { + "op": "sub", + "args": ["size", 0.008] + } + ], + "position": [ + { + "op": "sub", + "args": [ + { + "op": "div", + "args": ["size", 2] + }, + 0.002 + ] + }, + { + "op": "add", + "args": [ + 0.01, + { + "op": "div", + "args": ["depth", 2] + } + ] + }, + 0 + ] + }, + { + "id": "west", + "primitive": "box", + "slot": "can", + "size": [ + 0.004, + "depth", + { + "op": "sub", + "args": ["size", 0.008] + } + ], + "position": [ + { + "op": "mul", + "args": [ + { + "op": "sub", + "args": [ + { + "op": "div", + "args": ["size", 2] + }, + 0.002 + ] + }, + -1 + ] + }, + { + "op": "add", + "args": [ + 0.01, + { + "op": "div", + "args": ["depth", 2] + } + ] + }, + 0 + ] + }, + { + "id": "top", + "primitive": "box", + "slot": "can", + "size": ["size", 0.004, "size"], + "position": [ + 0, + { + "op": "sub", + "args": [ + { + "op": "add", + "args": [0.01, "depth"] + }, + 0.002 + ] + }, + 0 + ] + } + ] + }, + { + "id": "lens", + "label": "Lens", + "count": 1, + "light": { + "position": [0, 0.045, 0], + "color": "#fff4e0", + "intensity": 1.5, + "distance": 4, + "emissiveSlot": "lens" + }, + "shapes": [ + { + "id": "lens", + "primitive": "box", + "slot": "lens", + "size": [ + { + "op": "sub", + "args": ["size", 0.01] + }, + 0.006, + { + "op": "sub", + "args": ["size", 0.01] + } + ], + "position": [0, 0.05, 0] + } + ] + } + ], + "constraints": [] +} diff --git a/packages/core/src/procedural-items/ceiling-cut.test.ts b/packages/core/src/procedural-items/ceiling-cut.test.ts new file mode 100644 index 0000000000..bd3e9046c7 --- /dev/null +++ b/packages/core/src/procedural-items/ceiling-cut.test.ts @@ -0,0 +1,207 @@ +import { describe, expect, test } from 'bun:test' +import { CeilingNode } from '../schema/nodes/ceiling' +import { LevelNode } from '../schema/nodes/level' +import pendantJson from './__fixtures__/pendant_lamp.json' +import downlightJson from './__fixtures__/recessed_downlight.json' +import { radiatorRecipe, shelfRecipe } from './fixtures' +import { ProceduralItemNode } from './node' +import { proceduralCeilingHole, validateProceduralRelations } from './query' +import { evaluateRecipe, parseRecipe, type Recipe } from './recipe' + +const downlight = () => structuredClone(downlightJson) as Recipe + +describe('recipe ceiling cuts (version 2)', () => { + test('a recessed design evaluates its cut ring around the mounting reference', () => { + const evaluation = evaluateRecipe(parseRecipe(downlight()), { size: 0.16 }) + expect(evaluation.cuts).toHaveLength(1) + const ring = evaluation.cuts[0]!.ring + expect(ring).toHaveLength(4) + for (const [x, z] of ring) { + expect(Math.abs(x)).toBeCloseTo(0.08) + expect(Math.abs(z)).toBeCloseTo(0.08) + } + // The can rises into the plenum above the reference; the trim stays below it. + expect(evaluation.max[1]).toBeGreaterThan(0.01 + 0.1) + }) + + test('a circle cut is a closed 32-gon, offset and turned with the reference', () => { + const recipe = downlight() + recipe.cuts = [ + { shape: 'circle', diameter: { op: 'mul', args: ['size', 1.6] }, center: [0.01, 0] }, + ] + recipe.surfaces![0]!.rotation = [0, Math.PI / 2, 0] + const ring = evaluateRecipe(parseRecipe(recipe), { size: 0.2 }).cuts[0]!.ring + expect(ring).toHaveLength(32) + const center = ring.reduce((sum, [x, z]) => [sum[0] + x / 32, sum[1] + z / 32], [0, 0]) + // The reference's local +x runs along design -z after a quarter turn about Y. + expect(center[0]).toBeCloseTo(0) + expect(center[1]).toBeCloseTo(-0.01) + for (const [x, z] of ring) expect(Math.hypot(x - center[0], z - center[1])).toBeCloseTo(0.16) + }) + + test('only the part inside a cut may rise above the ceiling reference', () => { + const recipe = downlight() + recipe.cuts = [{ shape: 'rect', size: [{ op: 'sub', args: ['size', 0.02] }, 'size'] }] + expect(() => parseRecipe(recipe)).toThrow('outside its cut') + const flush = structuredClone(pendantJson) as Recipe + flush.version = 2 + flush.surfaces![0]!.position[1] = 0.1 + expect(() => parseRecipe(flush)).toThrow('top of the design') + }) + + test('cuts are v2-only and need a ceiling mount', () => { + expect(() => parseRecipe({ ...downlight(), version: 1 })).toThrow('version 2') + const cuts = downlight().cuts + expect(() => parseRecipe({ ...shelfRecipe, version: 2, cuts })).toThrow('ceiling') + expect(() => parseRecipe({ ...radiatorRecipe, version: 2, cuts })).toThrow('ceiling') + }) + + test('v1 designs evaluate no cuts', () => { + expect(evaluateRecipe(shelfRecipe).cuts).toEqual([]) + expect(evaluateRecipe(parseRecipe(structuredClone(pendantJson))).cuts).toEqual([]) + }) + + test('a recessed design may sit in the plenum up to the level height', () => { + const level = LevelNode.parse({ id: 'level_cut', height: 3 }) + const ceiling = CeilingNode.parse({ + id: 'ceiling_cut', + parentId: level.id, + height: 2.7, + polygon: [ + [-2, -2], + [2, -2], + [2, 2], + [-2, 2], + ], + }) + const node = ProceduralItemNode.parse({ + id: 'procedural-item_cut', + recipe: downlight(), + parentId: ceiling.id, + }) + const nodes = { [level.id]: level, [ceiling.id]: ceiling, [node.id]: node } + expect(() => validateProceduralRelations(node, nodes)).not.toThrow() + const shallow = { ...nodes, [ceiling.id]: { ...ceiling, height: 2.95 } } + expect(() => validateProceduralRelations(node, shallow)).toThrow('level height') + }) + + test('the hole follows the node onto its ceiling, turned with its yaw', () => { + const recipe = downlight() + recipe.cuts = [{ shape: 'rect', size: [{ op: 'mul', args: ['size', 1.5] }, 'size'] }] + const node = ProceduralItemNode.parse({ + recipe, + parentId: 'ceiling_hole', + position: [1, 0, 2], + rotation: [0, Math.PI / 2, 0], + }) + const ring = proceduralCeilingHole(node)! + expect(ring).toHaveLength(4) + const xs = ring.map(([x]) => x), + zs = ring.map(([, z]) => z) + expect(Math.min(...xs)).toBeCloseTo(0.94) + expect(Math.max(...xs)).toBeCloseTo(1.06) + expect(Math.min(...zs)).toBeCloseTo(1.91) + expect(Math.max(...zs)).toBeCloseTo(2.09) + expect( + proceduralCeilingHole({ ...node, recipe: parseRecipe(structuredClone(pendantJson)) }), + ).toBe(null) + }) + + test('a round can fits a circle cut of its own diameter', () => { + const recipe = downlight() + recipe.cuts = [{ shape: 'circle', diameter: 'size' }] + const can = recipe.parts.find((part) => part.id === 'can')! + can.shapes = [ + { + id: 'can', + primitive: 'cylinder', + slot: 'can', + size: ['size', 'depth', 'size'], + position: [0, { op: 'add', args: [0.01, { op: 'div', args: ['depth', 2] }] }, 0], + }, + ] + recipe.parts = recipe.parts.filter((part) => part.id !== 'lens') + expect(() => parseRecipe(recipe)).not.toThrow() + can.shapes[0]!.size = [{ op: 'mul', args: ['size', 1.1] }, 'depth', 'size'] + expect(() => parseRecipe(recipe)).toThrow('outside its cut') + }) + + test('a moving part may swing inside the cut, not outside it', () => { + const recipe = downlight() + const lens = recipe.parts.find((part) => part.id === 'lens')! + lens.motion = { kind: 'hinge', pivot: [0, 0.05, 0], axis: 'x', angle: 0.4 } + expect(() => parseRecipe(recipe)).not.toThrow() + lens.motion.pivot = [0, 0.05, 0.3] + expect(() => parseRecipe(recipe)).toThrow('rises above the ceiling reference') + }) +}) + +describe('ceiling cut review fixes (AK-D2 round 2)', () => { + const level = LevelNode.parse({ id: 'level_cut2', height: 3 }) + const ceilingOf = (half: number, holes: [number, number][][] = []) => + CeilingNode.parse({ + id: 'ceiling_cut2', + parentId: level.id, + height: 2.7, + polygon: [ + [-half, -half], + [half, -half], + [half, half], + [-half, half], + ], + holes, + }) + const place = (recipe: Recipe, ceiling: ReturnType) => { + const node = ProceduralItemNode.parse({ + id: 'procedural-item_cut2', + recipe, + parentId: ceiling.id, + }) + return () => + validateProceduralRelations(node, { + [level.id]: level, + [ceiling.id]: ceiling, + [node.id]: node, + }) + } + test('the cut ring must lie inside the ceiling and clear of its holes', () => { + const wide = downlight() + wide.cuts = [{ shape: 'rect', size: [1, 1] }] + expect(place(wide, ceilingOf(0.25))).toThrow('cut') + expect(place(downlight(), ceilingOf(2))).not.toThrow() + const hole: [number, number][] = [ + [0.02, 0.02], + [0.3, 0.02], + [0.3, 0.3], + [0.02, 0.3], + ] + expect(place(downlight(), ceilingOf(2, [hole]))).toThrow('holes') + }) + test('a recessed part may not move up through the storey above', () => { + const recipe = downlight() + recipe.parts.find((part) => part.id === 'lens')!.motion = { + kind: 'slide', + axis: 'y', + distance: 1, + } + expect(() => parseRecipe(recipe)).not.toThrow() + expect(place(recipe, ceilingOf(2))).toThrow('level height') + }) + test('a round can spinning inside a circle cut of its own diameter is accepted', () => { + const recipe = downlight() + recipe.cuts = [{ shape: 'circle', diameter: 'size' }] + recipe.parts = recipe.parts.filter((part) => part.id !== 'lens') + const can = recipe.parts.find((part) => part.id === 'can')! + can.shapes = [ + { + id: 'can', + primitive: 'cylinder', + slot: 'can', + size: ['size', 'depth', 'size'], + position: [0, { op: 'add', args: [0.01, { op: 'div', args: ['depth', 2] }] }, 0], + }, + ] + can.motion = { kind: 'spin', pivot: [0, 0.07, 0], axis: 'y', radiansPerSecond: 1 } + expect(() => parseRecipe(recipe)).not.toThrow() + }) +}) diff --git a/packages/core/src/procedural-items/query.ts b/packages/core/src/procedural-items/query.ts index 9194e997e1..c3ac4a545a 100644 --- a/packages/core/src/procedural-items/query.ts +++ b/packages/core/src/procedural-items/query.ts @@ -74,6 +74,20 @@ export function proceduralLocalPose(node: ProceduralItemNode, nodes: QueryNodes) position[2] = sign * (getWallThickness(wall) / 2 - reference.position[2] + node.position[2]) return { position, rotation } } +/** A ceiling design's cut as a hole ring in its ceiling's local [x, z], or null. */ +export function proceduralCeilingHole(node: ProceduralItemNode): [number, number][] | null { + if (node.recipe.mounting?.attachTo !== 'ceiling') return null + const e = evaluateRecipe(node.recipe, node.parameters) + const cut = e.cuts.find((c) => c.host === 'ceiling') + const reference = e.surfaces.find((s) => s.id === node.recipe.mounting?.reference) + if (!(cut && reference)) return null + // Same pose as proceduralLocalPose: the reference sits at the node's ceiling position. + const f = frame(node.position, node.rotation) + return cut.ring.map(([x, z]) => { + const p = transformPoint(f, [x - reference.position[0], 0, z - reference.position[2]]) + return [p[0], p[2]] + }) +} export function proceduralFootprint(node: ProceduralItemNode) { const e = evaluateRecipe(node.recipe, node.parameters) const center = e.min.map((v, i) => (v + e.max[i]!) / 2) as Vec3 @@ -326,12 +340,16 @@ export function validateProceduralRelations(raw: AnyNode | ProceduralItemNode, n throw new Error('The top reference must be flush with the ceiling') const pose = proceduralLocalPose(node, nodes) const f = frame(pose.position, pose.rotation) - const b = boundsOf(boxCorners(evaluation.min, evaluation.max).map((p) => transformPoint(f, p))) + // Moving parts of a recessed design must stay within the storey through their whole travel. + const extent = evaluation.reach ?? evaluation + const b = boundsOf(boxCorners(extent.min, extent.max).map((p) => transformPoint(f, p))) const height = nodeLevelFrame(ceiling.id, nodes).position[1] const level = ceiling.parentId ? nodes[ceiling.parentId] : undefined + // A recessed design rises into the plenum through its own cut. + const recessed = evaluation.cuts.length > 0 if ( b.min[1] + height < -1e-6 || - b.max[1] > 1e-6 || + (!recessed && b.max[1] > 1e-6) || b.max[1] + height > getStoredLevelHeight(level?.type === 'level' ? level : {}) + 1e-6 ) throw new Error('The hanging design must fit below the ceiling within the level height') @@ -349,6 +367,13 @@ export function validateProceduralRelations(raw: AnyNode | ProceduralItemNode, n ceiling.holes.some((hole) => polygonsOverlap(hole, footprint)) ) throw new Error('The hanging design must fit inside the ceiling, outside its holes') + const ring = proceduralCeilingHole(node) + if ( + ring && + (!ceilingContainsFootprint(ceiling.polygon, ring) || + ceiling.holes.some((hole) => polygonsOverlap(hole, ring))) + ) + throw new Error('The design’s ceiling cut must fit inside the ceiling, outside its holes') } else if (node.recipe.mounting?.attachTo === 'wall-side' && !awaitingHost) { const wall = node.wallId ? nodes[node.wallId] : undefined if (wall?.type !== 'wall' || node.parentId !== wall.id) diff --git a/packages/core/src/procedural-items/recipe.ts b/packages/core/src/procedural-items/recipe.ts index 7ff00028cf..8738b033cb 100644 --- a/packages/core/src/procedural-items/recipe.ts +++ b/packages/core/src/procedural-items/recipe.ts @@ -1,5 +1,5 @@ import { z } from 'zod' -import { boxCorners, frame, rotateVector, transformPoint } from './spatial' +import { boundsOf, boxCorners, frame, rotateVector, transformPoint } from './spatial' export type Expr = | number @@ -34,6 +34,15 @@ const timing = { duration: expression.optional(), easing: z.enum(['linear', 'smooth', 'soft']).optional(), } +const cutCenter = z.tuple([expression, expression]).optional() +const cut = z.discriminatedUnion('shape', [ + z.strictObject({ + shape: z.literal('rect'), + size: z.tuple([expression, expression]), + center: cutCenter, + }), + z.strictObject({ shape: z.literal('circle'), diameter: expression, center: cutCenter }), +]) const motion = z.discriminatedUnion('kind', [ z.strictObject({ kind: z.literal('hinge'), @@ -72,6 +81,9 @@ const RecipeObject = z.strictObject({ .optional(), // v2, floor designs: the design-space height that rests on the host floor. base: expression.optional(), + // v2, ceiling designs: an opening in the host ceiling, drawn in the mounting reference's x/z + // plane around it. The design may rise above the reference only inside its cut. + cuts: z.array(cut).min(1).max(1).optional(), surfaces: z .array( z.strictObject({ @@ -198,6 +210,11 @@ export type EvaluatedLight = { distance: number emissiveSlot?: string } +export type EvaluatedCut = { + host: 'ceiling' + /** Closed ring in design-space [x, z], at the mounting reference. */ + ring: [number, number][] +} export type Surface = { id: string label: string @@ -212,11 +229,14 @@ export type Evaluation = { lights: EvaluatedLight[] motionGroupByInstance: Record surfaces: Surface[] + cuts: EvaluatedCut[] min: Vec3 max: Vec3 dimensions: Vec3 parameters: Record triangles: number + /** Recessed ceiling designs with motion: the rest bounds grown by every motion sample. */ + reach?: { min: Vec3; max: Vec3 } } export const RECIPE_LIMITS = { bytes: 131072, @@ -250,6 +270,10 @@ function versionIssue(recipe: Recipe): string | null { if (recipe.mounting) return 'A declared base applies to floor designs; mounted designs use their reference' } + if (recipe.cuts !== undefined) { + if (recipe.version !== 2) return 'Cuts require recipe version 2' + if (recipe.mounting?.attachTo !== 'ceiling') return 'Cuts need a ceiling-mounted design' + } return null } export function parseRecipe(input: unknown): Recipe { @@ -311,6 +335,40 @@ function shapeCorners(size: Vec3, position: Vec3, rotation: Vec3): Vec3[] { return boxCorners(localMin, localMax).map((point) => transformPoint(shapeFrame, point)) } +function shapeBounds(shape: Pick) { + if (shape.primitive !== 'ellipsoid') + return boundsOf(shapeCorners(shape.size, shape.position, shape.rotation)) + const axes = [0, 1, 2].map((axis) => + rotateVector([0, 1, 2].map((j) => (j === axis ? 1 : 0)) as Vec3, shape.rotation), + ) + const extent = [0, 1, 2].map((k) => + Math.hypot(...axes.map((axis, j) => (axis[k]! * shape.size[j]!) / 2)), + ) as Vec3 + return boundsOf([ + shape.position.map((v, k) => v - extent[k]!) as Vec3, + shape.position.map((v, k) => v + extent[k]!) as Vec3, + ]) +} + +// Points whose hull contains the shape: a cylinder's rim vertices (as rendered), otherwise the +// corners of its oriented box (exact for boxes, conservative for the rest). +function shapeFootprint(shape: EvaluatedShape): Vec3[] { + if (shape.primitive !== 'cylinder') + return shapeCorners(shape.size, shape.position, shape.rotation) + const f = frame(shape.position, shape.rotation) + return [-0.5, 0.5].flatMap((y) => + Array.from({ length: 24 }, (_, k) => { + const r = y > 0 ? 0.5 * shape.topScale : 0.5 + const theta = (2 * Math.PI * k) / 24 + return transformPoint(f, [ + r * Math.sin(theta) * shape.size[0], + y * shape.size[1], + r * Math.cos(theta) * shape.size[2], + ]) + }), + ) +} + function movedPoint(point: Vec3, motion: EvaluatedMotion, fraction: number): Vec3 { if (motion.kind === 'slide') return point.map( @@ -641,25 +699,88 @@ export function evaluateRecipe(recipe: Recipe, values: Record = }) } } + const cuts: EvaluatedCut[] = [] + // Recessed designs: whether a design-space [x, z] lies inside one of their cuts. + let insideCut: ((x: number, z: number) => boolean) | null = null if (recipe.mounting) { const reference = surfaces.find((s) => s.id === recipe.mounting!.reference) if (!reference || reference.id.includes(':')) throw new Error('Missing mounting reference') if (recipe.mounting.attachTo === 'ceiling') { if (Math.abs(reference.normal[1] - 1) > 1e-6) throw new Error('Ceiling mounting reference must face local +Y') - if (Math.abs(reference.position[1] - max[1]) > 1e-6) + const recessed = recipe.version === 2 && recipe.cuts !== undefined + if ( + recessed + ? reference.position[1] > max[1] + 1e-6 + : Math.abs(reference.position[1] - max[1]) > 1e-6 + ) throw new Error('Ceiling mounting reference must lie at the top of the design') + if (recessed) { + const u = rotateVector([1, 0, 0], reference.rotation), + v = rotateVector([0, 0, 1], reference.rotation) + const inside: ((x: number, z: number) => boolean)[] = [] + for (const c of recipe.cuts!) { + const [cu, cv] = (c.center ?? [0, 0]).map((e) => expr(e)) as [number, number] + const cx = reference.position[0] + u[0] * cu + v[0] * cv, + cz = reference.position[2] + u[2] * cu + v[2] * cv + const half = + c.shape === 'rect' + ? (c.size.map((e) => expr(e) / 2) as [number, number]) + : ([expr(c.diameter) / 2, expr(c.diameter) / 2] as [number, number]) + if (half.some((h) => !(h >= 0.005 && h <= 15))) throw new Error('Invalid cut size') + const local: [number, number][] = + c.shape === 'rect' + ? [ + [-half[0], -half[1]], + [half[0], -half[1]], + [half[0], half[1]], + [-half[0], half[1]], + ] + : Array.from({ length: 32 }, (_, k) => [ + half[0] * Math.cos((k * Math.PI) / 16), + half[0] * Math.sin((k * Math.PI) / 16), + ]) + cuts.push({ + host: 'ceiling', + ring: local.map(([a, b]) => [cx + u[0] * a + v[0] * b, cz + u[2] * a + v[2] * b]), + }) + inside.push((x, z) => { + const a = (x - cx) * u[0] + (z - cz) * u[2], + b = (x - cx) * v[0] + (z - cz) * v[2] + return c.shape === 'rect' + ? Math.abs(a) <= half[0] + 1e-6 && Math.abs(b) <= half[1] + 1e-6 + : Math.hypot(a, b) <= half[0] + 1e-6 + }) + } + for (const shape of shapes) { + if (shapeBounds(shape).max[1] <= reference.position[1] + 1e-6) continue + const footprint = shapeFootprint(shape) + if (!inside.some((test) => footprint.every(([x, , z]) => test(x, z)))) + throw new Error(`${shape.partId} rises above the ceiling reference outside its cut`) + } + insideCut = (x, z) => inside.some((test) => test(x, z)) + } } else if (Math.abs(reference.normal[2] + 1) > 1e-6) throw new Error('Wall-side mounting reference must face local -Z') } const reference = recipe.mounting && surfaces.find((s) => s.id === recipe.mounting!.reference) + const reach = insideCut ? { min: [...min] as Vec3, max: [...max] as Vec3 } : undefined for (const shape of shapes) { if (!shape.motionGroup) continue const motion = motions.find((m) => m.id === shape.motionGroup)! const steps = motion.kind === 'slide' ? 1 : motion.kind === 'hinge' ? 8 : 16 - for (const corner of shapeCorners(shape.size, shape.position, shape.rotation)) + // Inside a cut, sample the rendered footprint so round parts may turn in round cuts. + const points = insideCut + ? shapeFootprint(shape) + : shapeCorners(shape.size, shape.position, shape.rotation) + for (const corner of points) for (let step = 0; step <= steps; step++) { const point = movedPoint(corner, motion, step / steps) + if (reach) + for (let k = 0; k < 3; k++) { + reach.min[k] = Math.min(reach.min[k]!, point[k]!) + reach.max[k] = Math.max(reach.max[k]!, point[k]!) + } if (!recipe.mounting && point[1] < base - 0.001) throw new Error(`Motion envelope for ${shape.partId} extends below the floor`) if ( @@ -671,7 +792,8 @@ export function evaluateRecipe(recipe: Recipe, values: Record = if ( recipe.mounting?.attachTo === 'ceiling' && reference && - point[1] > reference.position[1] + 0.001 + point[1] > reference.position[1] + 0.001 && + !insideCut?.(point[0], point[2]) ) throw new Error(`Motion envelope for ${shape.partId} rises above the ceiling reference`) } @@ -703,11 +825,13 @@ export function evaluateRecipe(recipe: Recipe, values: Record = lights, motionGroupByInstance, surfaces, + cuts, min, max, dimensions, parameters, triangles, + ...(reach && motions.length > 0 && { reach }), } } diff --git a/packages/nodes/src/procedural-item/ceiling-cut.test.ts b/packages/nodes/src/procedural-item/ceiling-cut.test.ts new file mode 100644 index 0000000000..34c794e6d6 --- /dev/null +++ b/packages/nodes/src/procedural-item/ceiling-cut.test.ts @@ -0,0 +1,117 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { + type AnyNode, + type AnyNodeId, + CeilingNode, + nodeRegistry, + registerNode, + useLiveNodeOverrides, +} from '@pascal-app/core' +import { + ProceduralItemNode, + parseRecipe, + type Recipe, + shelfRecipe, +} from '@pascal-app/core/procedural-items' +import { usePlacementPreview } from '@pascal-app/editor' +import { proceduralItemDefinition } from './definition' + +// A 0.2 m square trim flush with the ceiling and a can recessed 0.1 m above it, inside the cut. +const recessed = parseRecipe({ + version: 2, + name: 'Recessed can', + description: 'Trim below the ceiling plane, can above it.', + mounting: { attachTo: 'ceiling', reference: 'plane' }, + cuts: [{ shape: 'rect', size: [0.16, 0.16] }], + surfaces: [{ id: 'plane', label: 'Plane', position: [0, 0.01, 0], size: [0.2, 0.2] }], + parameters: [ + { id: 'depth', label: 'Depth', default: 0.1, min: 0.05, max: 0.2, step: 0.01, unit: 'm' }, + ], + slots: [{ id: 'trim', label: 'Trim', color: '#ffffff' }], + parts: [ + { + id: 'trim', + label: 'Trim', + count: 1, + shapes: [ + { + id: 'plate', + primitive: 'box', + slot: 'trim', + size: [0.2, 0.01, 0.2], + position: [0, 0.005, 0], + }, + ], + }, + { + id: 'can', + label: 'Can', + count: 1, + shapes: [ + { + id: 'body', + primitive: 'box', + slot: 'trim', + size: [0.15, 'depth', 0.15], + position: [0, { op: 'add', args: [0.01, { op: 'div', args: ['depth', 2] }] }, 0], + }, + ], + }, + ], + constraints: [], +} satisfies Recipe) + +let restore: () => void +beforeEach(() => { + restore = nodeRegistry._snapshot() + registerNode(proceduralItemDefinition) +}) +afterEach(() => restore()) + +test('a recessed design publishes its ceiling hole through the registry capability', () => { + const ceiling = CeilingNode.parse({ + id: 'ceiling_recessed', + polygon: [ + [-2, -2], + [2, -2], + [2, 2], + [-2, 2], + ], + }) + const node = ProceduralItemNode.parse({ + id: 'procedural-item_recessed', + recipe: recessed, + parentId: ceiling.id, + position: [0.5, 0, -0.25], + rotation: [0, Math.PI / 4, 0], + }) + const cut = nodeRegistry.get('procedural-item')?.capabilities.ceilingCut + const ring = cut?.buildCeilingHole(node as unknown as AnyNode) + expect(ring).toHaveLength(4) + for (const [x, z] of ring!) expect(Math.hypot(x - 0.5, z + 0.25)).toBeCloseTo(0.08 * Math.SQRT2) + // A quarter-turn-by-half puts the square's corners on the axes through the node. + expect(Math.max(...ring!.map(([x]) => x))).toBeCloseTo(0.5 + 0.08 * Math.SQRT2) + + const flush = ProceduralItemNode.parse({ ...node, recipe: shelfRecipe, parentId: null }) + expect(cut?.buildCeilingHole(flush as unknown as AnyNode)).toBe(null) +}) + +test('the hole follows live overrides and the move preview, and hides with its design', () => { + const node = ProceduralItemNode.parse({ + id: 'procedural-item_live', + recipe: recessed, + parentId: 'ceiling_live', + position: [0, 0, 0], + }) + const cut = nodeRegistry.get('procedural-item')!.capabilities.ceilingCut! + const centre = (ring: [number, number][] | null) => + ring!.reduce((sum, [x, z]) => [sum[0] + x / ring!.length, sum[1] + z / ring!.length], [0, 0]) + useLiveNodeOverrides.getState().set(node.id as AnyNodeId, { position: [1, 0, 0.5] } as never) + expect(centre(cut.buildCeilingHole(node as unknown as AnyNode))[0]).toBeCloseTo(1) + useLiveNodeOverrides.getState().set(node.id as AnyNodeId, { visible: false } as never) + expect(cut.buildCeilingHole(node as unknown as AnyNode)).toBe(null) + usePlacementPreview.getState().set({ ...node, position: [-1, 0, 0] } as unknown as AnyNode) + expect(centre(cut.buildCeilingHole(node as unknown as AnyNode))[0]).toBeCloseTo(-1) + usePlacementPreview.getState().clear() + useLiveNodeOverrides.getState().clear(node.id as AnyNodeId) +}) diff --git a/packages/nodes/src/procedural-item/definition.ts b/packages/nodes/src/procedural-item/definition.ts index f1760bca46..e6bdab2f0c 100644 --- a/packages/nodes/src/procedural-item/definition.ts +++ b/packages/nodes/src/procedural-item/definition.ts @@ -1,5 +1,5 @@ import type { AnyNode, FloorplanGeometry, HandleDescriptor, NodeDefinition } from '@pascal-app/core' -import { type AnyNodeId, useInteractive, useScene } from '@pascal-app/core' +import { type AnyNodeId, getEffectiveNode, useInteractive, useScene } from '@pascal-app/core' import { boundsOf, boxCorners, @@ -7,6 +7,7 @@ import { frame, ProceduralItemNode, parameterPatch, + proceduralCeilingHole, proceduralFootprint, proceduralSlotColor, queryProceduralItem, @@ -17,6 +18,7 @@ import { transformPoint, validateProceduralRelations, } from '@pascal-app/core/procedural-items' +import { usePlacementPreview } from '@pascal-app/editor' import { decorateProceduralEmission } from '@pascal-app/viewer' import { itemPaint } from '../item/paint' import { @@ -137,6 +139,18 @@ export const proceduralItemDefinition: NodeDefinition align: 'face', }, hostRefFields: ['wallId', 'side', 'supportSlabId'], + // A v2 ceiling design with `cuts` opens its host ceiling (CeilingSystem dispatch). + ceilingCut: { + // Follows the live gesture (R2): a move preview cuts where it sits; handle and slider + // overrides cut at their live values; a hidden design (the move's source) cuts nothing. + buildCeilingHole: (n) => { + const preview = usePlacementPreview.getState().node + if (preview?.id === n.id && preview.type === 'procedural-item') + return preview.parentId === n.parentId ? proceduralCeilingHole(preview) : null + const node = getEffectiveNode(n as unknown as ProceduralItemNode) + return node.visible === false ? null : proceduralCeilingHole(node) + }, + }, floorPlaced: { footprint: (n) => proceduralFootprint(n as unknown as ProceduralItemNode), applies: (n) => !(n as unknown as ProceduralItemNode).recipe.mounting, diff --git a/packages/nodes/src/procedural-item/renderer.tsx b/packages/nodes/src/procedural-item/renderer.tsx index 94f0116b36..07009d71e5 100644 --- a/packages/nodes/src/procedural-item/renderer.tsx +++ b/packages/nodes/src/procedural-item/renderer.tsx @@ -13,6 +13,7 @@ import { ProceduralMotionController, proceduralLocalPose, } from '@pascal-app/core/procedural-items' +import { usePlacementPreview } from '@pascal-app/editor' import { cloneWithProceduralEmission, createSurfaceRoleMaterial, @@ -72,6 +73,35 @@ export default function ProceduralRenderer({ node }: { node: ProceduralItemNode return lease.release }, [key]) useEffect(() => () => useInteractive.getState().removeProcedural(node.id), [node.id]) + // A recessed design's host ceiling re-cuts whenever its cut can move, live values included. + const cutKey = effective.recipe.cuts + ? JSON.stringify([ + node.parentId, + effective.position, + effective.rotation, + effective.parameters, + effective.visible, + effective.recipe.cuts, + effective.recipe.surfaces, + effective.recipe.mounting?.reference, + ]) + : '' + useEffect(() => { + const parentId = node.parentId as AnyNodeId | null + if (!(cutKey && parentId)) return + const recut = () => { + if (useScene.getState().nodes[parentId]) useScene.getState().markDirty(parentId) + } + recut() + // A move preview of this design re-cuts its ceiling on every step. + const unsubscribe = usePlacementPreview.subscribe((state, previous) => { + if (state.node?.id === node.id || previous.node?.id === node.id) recut() + }) + return () => { + unsubscribe() + recut() + } + }, [cutKey, node.parentId, node.id]) useLayoutEffect(() => { controller.current = built ? new ProceduralMotionController(built.evaluation.motions) : null lastCommand.current = 0