From 272478921437dc277c78c0756feb799be2719ca8 Mon Sep 17 00:00:00 2001 From: Wassim SAMAD Date: Mon, 2 Nov 2026 09:31:42 -0500 Subject: [PATCH 1/4] Remove the generic foundation and the 8 in ground-floor seat The foundation the viewer derived under every building (a concrete footing and an 8 in CMU stem under the exterior walls) looked wrong, did not follow terrain and spread to every shared floor plate. A foundation is set explicitly (set_floor_foundation, the floor construction) instead. - The generic foundation, its geometry and drawing, the drawsFoundation capability and pluginFoundationLevelIds are gone, with the capture helper that hid its meshes. - "Set as ground floor" and set_ground_level seat the ground floor on grade: the 8 in (0.203 m) seat over grade, which the generic foundation filled, is gone, with seatAboveGrade/seatBasis/stemThickness on the foundation constructions and aboveGrade/atFoundationTop on the ground seat. A floor seated is one on grade within 5 cm; a building seated 8 in up by the old rule reads unseated and comes down when set again. - deepestDrawnY is the lowest floor's underside (no footing under it). - Basement walls against the ground keep their foundation construction (8 in CMU with furring, cast concrete in Europe). Co-Authored-By: Claude Opus 5.5 --- .../__fixtures__/structure-cases.ts | 19 +- .../src/agent-operations/set-ground-level.ts | 17 +- .../core/src/agent-operations/verify-scene.ts | 2 +- packages/core/src/agent-tools/levels.ts | 2 +- packages/core/src/building/ground-level.ts | 8 +- packages/core/src/index.ts | 2 - .../core/src/lib/below-grade-footprints.ts | 5 +- packages/core/src/lib/deepest-drawn.test.ts | 28 +- packages/core/src/lib/deepest-drawn.ts | 12 +- .../src/lib/foundation-construction.test.ts | 49 +- .../core/src/lib/foundation-construction.ts | 26 +- packages/core/src/lib/foundation-standard.ts | 5 +- packages/core/src/lib/foundation-wall.test.ts | 29 - packages/core/src/lib/foundation-wall.ts | 3 +- .../core/src/lib/generic-foundation.test.ts | 500 ------------------ packages/core/src/lib/generic-foundation.ts | 245 --------- packages/core/src/lib/ground-line.test.ts | 54 +- packages/core/src/lib/ground-seat.ts | 38 +- packages/core/src/registry/types.ts | 9 - .../core/src/systems/wall/wall-assembly.ts | 2 +- .../components/ui/floating-level-selector.tsx | 4 +- packages/editor/src/lib/add-storey.test.ts | 6 +- packages/mcp/README.md | 2 +- .../site/generic-foundation-geometry.test.ts | 68 --- .../src/site/generic-foundation-geometry.ts | 91 ---- .../src/site/generic-foundation.test.tsx | 295 ----------- .../nodes/src/site/generic-foundation.tsx | 151 ------ packages/nodes/src/site/ground-veil.test.tsx | 11 +- packages/nodes/src/site/renderer.tsx | 2 - packages/viewer/src/index.ts | 2 - .../viewer/src/lib/foundation-materials.ts | 6 +- packages/viewer/src/lib/site-surfaces.test.ts | 40 +- packages/viewer/src/lib/site-surfaces.ts | 20 - packages/viewer/src/store/use-viewer.ts | 8 - .../viewer/src/systems/wall/wall-materials.ts | 2 +- skills/pascal-3d/references/tool-workflows.md | 2 +- wiki/architecture/materials-and-themes.md | 7 +- wiki/architecture/vertical-model.md | 6 +- 38 files changed, 76 insertions(+), 1702 deletions(-) delete mode 100644 packages/core/src/lib/generic-foundation.test.ts delete mode 100644 packages/core/src/lib/generic-foundation.ts delete mode 100644 packages/nodes/src/site/generic-foundation-geometry.test.ts delete mode 100644 packages/nodes/src/site/generic-foundation-geometry.ts delete mode 100644 packages/nodes/src/site/generic-foundation.test.tsx delete mode 100644 packages/nodes/src/site/generic-foundation.tsx diff --git a/packages/core/src/agent-operations/__fixtures__/structure-cases.ts b/packages/core/src/agent-operations/__fixtures__/structure-cases.ts index f8fff294e9..d939bab0c2 100644 --- a/packages/core/src/agent-operations/__fixtures__/structure-cases.ts +++ b/packages/core/src/agent-operations/__fixtures__/structure-cases.ts @@ -614,23 +614,6 @@ export const ADD_LEVEL_CASES: AgentToolCase[] = [ mentions: ['below grade', 'cast concrete', 'Europe'], }, }, - { - name: 'set_ground_level on a site in Paris seats the building 0.15 m over grade, as cast concrete foundations do', - tool: 'set_ground_level', - scene: () => - onSite(storeysScene(), SiteNode.parse({ id: 'site_paris', dossier: dossierAt('Paris, France') })), - input: { levelId: 'level_ground' }, - expect: { - result: { - ok: true, - floorElevation: 0.15, - aboveGrade: 0.15, - foundation: { region: 'europe', construction: 'cast-concrete' }, - }, - mentions: ['cast concrete', 'Europe'], - after: { building_house: { position: [0, 0.15, 0], groundLevelId: 'level_ground' } }, - }, - }, { name: 'above the highest level of the viewed building, at the default storey height', tool: 'add_level', @@ -703,7 +686,7 @@ export const ADD_LEVEL_CASES: AgentToolCase[] = [ scene: storeysScene, input: { levelId: 'level_upper' }, expect: { - result: { ok: true, renumbered: true, floorElevation: 0.203 }, + result: { ok: true, renumbered: true, floorElevation: 0 }, after: { level_upper: { level: 0 }, level_ground: { level: -1 }, diff --git a/packages/core/src/agent-operations/set-ground-level.ts b/packages/core/src/agent-operations/set-ground-level.ts index 81ffd19bfc..49f50dabdf 100644 --- a/packages/core/src/agent-operations/set-ground-level.ts +++ b/packages/core/src/agent-operations/set-ground-level.ts @@ -9,7 +9,7 @@ type SetGroundLevelInput = { levelId: string } /** * `set_ground_level`: the level asked for becomes the building's ground floor — named on the - * building, its floor the top of the foundation over grade (as the building's region and style seat it), index 0 — the same change the level panel's "Set as ground floor" + * building, its floor on grade, index 0 — the same change the level panel's "Set as ground floor" * writes (`buildGroundLevelChanges`). */ export const setGroundLevel: AgentOperation = (nodes, input) => { @@ -32,13 +32,6 @@ export const setGroundLevel: AgentOperation = (nodes, input const { seat, moveBy } = built const floorElevation = Math.round((seat.floorElevation + moveBy) * 1e6) / 1e6 const name = level.name ?? level.id - const { aboveGrade, foundation } = seat - const construction = { - region: foundation.region, - construction: foundation.construction.id, - basis: foundation.basis, - } - const inches = Math.round(aboveGrade / 0.0254) if (built.unchanged) return { result: { @@ -47,9 +40,7 @@ export const setGroundLevel: AgentOperation = (nodes, input levelId: level.id, buildingId: built.buildingId, floorElevation: seat.floorElevation, - aboveGrade, - foundation: construction, - message: `${name} is already the ground floor, its floor ${aboveGrade} m (${inches} in) over grade (${foundation.construction.label} foundation; ${foundation.basis}).`, + message: `${name} is already the ground floor, its floor on grade.`, }, } return { @@ -59,11 +50,9 @@ export const setGroundLevel: AgentOperation = (nodes, input buildingId: built.buildingId, floorElevation, gradeElevation: seat.gradeElevation, - aboveGrade, - foundation: construction, movedBuildingBy: moveBy, renumbered: built.renumbered, - message: `${name} is the ground floor: its floor, the top of the foundation where the wood framing starts, stands ${aboveGrade} m (${inches} in) over grade (${floorElevation.toFixed(2)} m over grade ${seat.gradeElevation.toFixed(2)} m), as a ${foundation.construction.label} foundation seats it: ${foundation.construction.seatBasis}; ${foundation.basis}. The levels with a lower index are below grade${moveBy === 0 ? '' : `; the building moved ${moveBy.toFixed(2)} m in height, its plan where it was`}.`, + message: `${name} is the ground floor: its floor stands on grade (${floorElevation.toFixed(2)} m). The levels with a lower index are below grade${moveBy === 0 ? '' : `; the building moved ${moveBy.toFixed(2)} m in height, its plan where it was`}.`, }, changes: { update: built.update }, } diff --git a/packages/core/src/agent-operations/verify-scene.ts b/packages/core/src/agent-operations/verify-scene.ts index 33bb834006..03f3097946 100644 --- a/packages/core/src/agent-operations/verify-scene.ts +++ b/packages/core/src/agent-operations/verify-scene.ts @@ -444,7 +444,7 @@ export const verifyScene: AgentOperation = ( if (seat?.levelId === level.levelId && seat.explicit && !seat.seated) report( 'ground_level_unseated', - `${levelName} is the ground floor, but its floor datum stands ${seat.offset.toFixed(2)} m ${seat.offset > 0 ? 'over' : 'under'} grade (${seat.gradeElevation.toFixed(2)} m); a seated ground floor stands between grade and ${seat.aboveGrade} m (the top of the ${seat.foundation.construction.label} foundation) over it. set_ground_level on it seats the building.`, + `${levelName} is the ground floor, but its floor datum stands ${seat.offset.toFixed(2)} m ${seat.offset > 0 ? 'over' : 'under'} grade (${seat.gradeElevation.toFixed(2)} m); a seated ground floor stands on it. set_ground_level on it seats the building.`, true, ) if (content.walls > 0 && content.zones === 0) diff --git a/packages/core/src/agent-tools/levels.ts b/packages/core/src/agent-tools/levels.ts index 98ec8ad6b0..7df8609cc0 100644 --- a/packages/core/src/agent-tools/levels.ts +++ b/packages/core/src/agent-tools/levels.ts @@ -107,7 +107,7 @@ export const setGroundLevelTool = { name: 'set_ground_level', title: 'Set ground level', description: - "Make a level the building's ground floor: the one standing at grade, its floor 8 in over the ground (about 6 in on cast concrete foundations, 12 in on stone: the building's foundation construction seats it; the result names it). A building's levels stack on a ground line; the levels with a lower floor index are below grade (basements), the ones at or over it are not, and list_levels reads it as groundLevels (levelId, floorElevation, floorOverGrade, seated) and each level's gradeStanding (at-grade, partly-below-grade, below-grade) and isGroundLevel. This names the level on the building, seats the building so that level's floor datum, the top of the foundation where the wood framing starts, stands 0.203 m (8 in) over grade on a block foundation, 0.15 m on cast concrete (Europe), 0.3 m on stone (a historic style) (flat site: world Y 0.203; sculpted terrain: 0.203 m over the mean ground height under its floor), moving the building in height only — the plan stays where it is and every level keeps its place relative to the others — and renumbers the floor indices so it is 0 and the ones under it are -1, -2…. A level added below (add_level position below) stacks under the lowest level without moving the ground floor. A roof level or a support level cannot be the ground floor (not_a_storey). One undo step. Refusals: level_not_found, not_a_level, no_building, not_a_storey. Answering unchanged: true when the level is already the named ground floor, at that seat, at index 0.", + "Make a level the building's ground floor: the one standing at grade, its floor on the ground. A building's levels stack on a ground line; the levels with a lower floor index are below grade (basements), the ones at or over it are not, and list_levels reads it as groundLevels (levelId, floorElevation, floorOverGrade, seated) and each level's gradeStanding (at-grade, partly-below-grade, below-grade) and isGroundLevel. This names the level on the building, seats the building so that level's floor datum stands on grade (flat site: world Y 0; sculpted terrain: the mean ground height under its floor), moving the building in height only — the plan stays where it is and every level keeps its place relative to the others — and renumbers the floor indices so it is 0 and the ones under it are -1, -2…. A level added below (add_level position below) stacks under the lowest level without moving the ground floor. A roof level or a support level cannot be the ground floor (not_a_storey). One undo step. Refusals: level_not_found, not_a_level, no_building, not_a_storey. Answering unchanged: true when the level is already the named ground floor, on grade, at index 0.", input: { levelId: NodeId.describe('The level to stand at grade, by an id list_levels returned.'), }, diff --git a/packages/core/src/building/ground-level.ts b/packages/core/src/building/ground-level.ts index 9b5cdeb707..3f9a3fbe5f 100644 --- a/packages/core/src/building/ground-level.ts +++ b/packages/core/src/building/ground-level.ts @@ -5,9 +5,7 @@ import { getLevelElevations } from '../services/storey' /** * Making `levelId` the building's ground floor, as the level panel's "Set as ground floor" and the * agent's `set_ground_level` do: the building names it (`groundLevelId`), is seated so that level's - * floor datum, the top of the foundation, stands over grade as the building's foundation - * construction seats it (`GroundSeat.aboveGrade`: 0.203 m on block, by region and style); its - * position moves in height, the plan stays where it is, and the + * floor datum stands on grade; its position moves in height, the plan stays where it is, and the * floor indices are renumbered so it is index 0 and the ones under it are the basements. Every * floor keeps its place relative to the others. One change set, one undo step. `null` for an id * that is no level of a building. @@ -36,7 +34,7 @@ export function buildGroundLevelChanges({ const [x, y, z] = (building as BuildingNode).position // Micrometres: the seat is measured through sums of storey heights, and a stored height keeps no noise. - const moveBy = seat.atFoundationTop ? 0 : Math.round((seat.aboveGrade - seat.offset) * 1e6) / 1e6 + const moveBy = seat.seated ? 0 : Math.round(-seat.offset * 1e6) / 1e6 const shift = level.level const renumbered = Object.values(nodes).filter( (node): node is LevelNode => @@ -45,7 +43,7 @@ export function buildGroundLevelChanges({ getLevelElevations(nodes).get(node.id)?.buildingId === building.id, ) const unchanged = - before?.explicit === true && before.levelId === level.id && seat.atFoundationTop && shift === 0 + before?.explicit === true && before.levelId === level.id && seat.seated && shift === 0 return { buildingId: building.id, seat, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 5503652773..d633ea7944 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -363,7 +363,6 @@ export { framingPostTopAt, isFramingPost, } from './lib/framing-post' -export { type FoundationMember, genericFoundation } from './lib/generic-foundation' export { ceilingSeatY, isScriptedNode, @@ -390,7 +389,6 @@ export { export { type LevelGradeStanding, levelGradeStanding } from './lib/grade-standing' export { type GroundLevel, groundLevelOf, levelUnderNamedGround } from './lib/ground-level' export { - GROUND_FLOOR_ABOVE_GRADE, GROUND_SEAT_TOLERANCE, type GroundSeat, gradeUnderLevel, diff --git a/packages/core/src/lib/below-grade-footprints.ts b/packages/core/src/lib/below-grade-footprints.ts index 3e3806ce2b..688e44c6b9 100644 --- a/packages/core/src/lib/below-grade-footprints.ts +++ b/packages/core/src/lib/below-grade-footprints.ts @@ -182,9 +182,8 @@ export function belowGradeFloorY( /** How far under the top of the floor plate the pit hangs its own floor: the default plate's thickness. */ export const GROUND_PIT_FLOOR_DROP = 0.05 /** - * How far the pit's floor keeps from the plane of the plate's underside. The foundation under the - * level tops out on that plane (`genericFoundation`), and seen through the hole it has to stand - * on the pit's floor, not share its plane: two faces on one plane flicker. 2 cm is what a 24-bit + * How far the pit's floor keeps from the plane of the plate's underside: two faces on one plane + * flicker. 2 cm is what a 24-bit * depth buffer with the viewer's 0.3 m near plane tells apart out to about 300 m, further than * the hole is ever looked into from. */ diff --git a/packages/core/src/lib/deepest-drawn.test.ts b/packages/core/src/lib/deepest-drawn.test.ts index da86efae48..86031b1629 100644 --- a/packages/core/src/lib/deepest-drawn.test.ts +++ b/packages/core/src/lib/deepest-drawn.test.ts @@ -9,7 +9,6 @@ import { WallNode, } from '../schema' import { deepestDrawnY, lowestGroundY } from './deepest-drawn' -import { FOUNDATION_STANDARD } from './foundation-standard' import { FLAT_GROUND_Y } from './site-ground-height' import { encodeTerrainField } from './terrain-codec' import { createTerrainField } from './terrain-field' @@ -83,16 +82,13 @@ test('over no floor the scene draws nothing deep', () => { expect(deepestDrawnY(keyed([site()]))).toBeNull() }) -test('a house at grade is deepest at a footing under its floor', () => { - expect(deepestDrawnY(house(null))).toBeCloseTo( - 0.05 - 0.05 - FOUNDATION_STANDARD.footingThickness, - 9, - ) +test('a house at grade is deepest at the underside of its floor', () => { + expect(deepestDrawnY(house(null))).toBeCloseTo(0.05 - 0.05, 9) }) -test('a basement is deepest at the footing under its floor', () => { +test('a basement is deepest at the underside of its floor', () => { // The floor top is at -3.63 + 0.05 on a 0.05 m slab. - expect(deepestDrawnY(house(-3.63))).toBeCloseTo(-3.63 - FOUNDATION_STANDARD.footingThickness, 9) + expect(deepestDrawnY(house(-3.63))).toBeCloseTo(-3.63, 9) }) /** A basement (-1, plane at -3.63) whose floor has two slabs on different elevations. */ @@ -127,10 +123,10 @@ test('a split-level floor is deepest at its lowest slab underside, not the highe { elevation: 0.05, thickness: 0.05 }, { elevation: -1.2, thickness: 0.2 }, ]) - expect(deepestDrawnY(nodes)).toBeCloseTo(-3.63 - 1.4 - FOUNDATION_STANDARD.footingThickness, 9) + expect(deepestDrawnY(nodes)).toBeCloseTo(-3.63 - 1.4, 9) }) -test('a recessed slab counts where it is drawn: by its own underside, with no footing under it', () => { +test('a recessed slab counts where it is drawn: by its own underside', () => { // A pool basin: floor at -1.5, 0.3 thick, under a 0.05 m standing slab. const nodes = splitBasement([ { elevation: 0.05, thickness: 0.05 }, @@ -139,21 +135,11 @@ test('a recessed slab counts where it is drawn: by its own underside, with no fo expect(deepestDrawnY(nodes)).toBeCloseTo(-3.63 - 1.8, 9) }) -test('a thick recessed slab that stays shallow does not deepen the standing plate’s footing', () => { - // A raised recessed plate (top 0.45, 0.5 thick: underside -0.05) beside a thin standing plate: - // the footing under the standing plate is the deeper thing, not a thickest-slab guess. - const nodes = splitBasement([ - { elevation: 0.05, thickness: 0.05 }, - { elevation: 0.45, thickness: 0.5, recessed: true }, - ]) - expect(deepestDrawnY(nodes)).toBeCloseTo(-3.63 - FOUNDATION_STANDARD.footingThickness, 9) -}) - test('site flatwork is not a floor: a driveway laid deeper than the house’s slab does not take the dive depth down', () => { // The house on its 0.05 m plate; a driveway on the same level, top -0.3, 0.3 thick (underside -0.6). const nodes = splitBasement([ { elevation: 0.05, thickness: 0.05 }, { elevation: -0.3, thickness: 0.3, metadata: { flatwork: 'driveway' } }, ]) - expect(deepestDrawnY(nodes)).toBeCloseTo(-3.63 - FOUNDATION_STANDARD.footingThickness, 9) + expect(deepestDrawnY(nodes)).toBeCloseTo(-3.63, 9) }) diff --git a/packages/core/src/lib/deepest-drawn.ts b/packages/core/src/lib/deepest-drawn.ts index 40e8432d9b..36f0de0ed7 100644 --- a/packages/core/src/lib/deepest-drawn.ts +++ b/packages/core/src/lib/deepest-drawn.ts @@ -1,6 +1,5 @@ import type { AnyNode, AnyNodeId } from '../schema' import { getLevelElevations } from '../services/storey' -import { FOUNDATION_STANDARD } from './foundation-standard' import { isSiteFlatwork } from './site-flatwork' import { FLAT_GROUND_Y } from './site-ground-height' import { heightAtSample, type TerrainField } from './terrain-field' @@ -31,12 +30,9 @@ export function lowestGroundY(nodes: Nodes): number { } /** - * The world Y of the deepest thing the scene draws: the bottom of the footing under the lowest floor - * slab (its underside less a footing's thickness; never above the walls' base, as the footing - * itself is). A recessed slab (a basin) is drawn down to its own underside, with no footing under - * it. Site flatwork (a lawn, a driveway) is not a floor of the house and counts for nothing. A - * footing under a floor at or over grade sits about as deep, and never nearer the dive's own floor, - * so the floors alone decide. `null` for a scene with no floor. + * The world Y of the deepest thing the scene draws: the underside of the lowest floor slab. A + * recessed slab (a basin) is drawn down to its own underside. Site flatwork (a lawn, a driveway) + * is not a floor of the house and counts for nothing. `null` for a scene with no floor. */ export function deepestDrawnY(nodes: Nodes): number | null { const elevations = getLevelElevations(nodes) @@ -56,7 +52,7 @@ export function deepestDrawnY(nodes: Nodes): number | null { if (child.recessed === true) basinUnderside = Math.min(basinUnderside, underside) else floorUnderside = Math.min(floorUnderside, underside) } - const bottom = Math.min(floorUnderside - FOUNDATION_STANDARD.footingThickness, basinUnderside) + const bottom = Math.min(floorUnderside, basinUnderside) if (deepest === null || bottom < deepest) deepest = bottom } return deepest diff --git a/packages/core/src/lib/foundation-construction.test.ts b/packages/core/src/lib/foundation-construction.test.ts index 15e9891e0f..e62219ccb5 100644 --- a/packages/core/src/lib/foundation-construction.test.ts +++ b/packages/core/src/lib/foundation-construction.test.ts @@ -17,8 +17,6 @@ import { foundationRegionOf, } from './foundation-construction' import { foundationWallConstruction } from './foundation-wall' -import { genericFoundation } from './generic-foundation' -import { groundSeat } from './ground-seat' type Nodes = Record type SitePatch = Partial[0]> @@ -212,10 +210,9 @@ describe('the construction by region and style', () => { foundationReadingOf(house(site, styles), 'building_a').construction .id as FoundationConstructionId - test('a US site is block, the ground floor 0.203 m over grade', () => { + test('a US site is block', () => { const reading = foundationReadingOf(house({ address: { state: 'TX' } }), 'building_a') expect(reading.construction.id).toBe('cmu') - expect(reading.construction.seatAboveGrade).toBe(0.203) expect(foundationWallConstruction(reading.construction).thickness).toBe(0.241) }) @@ -232,12 +229,11 @@ describe('the construction by region and style', () => { ]) expect(wall.assembly.layers[2]).toMatchObject({ core: true, material: 'concrete' }) expect(wall.assembly.face).toBe('exterior') - expect(reading.construction.seatAboveGrade).toBe(0.15) expect(reading.basis).toContain('Europe') } }) - test('an unknown site keeps today’s default: block, 0.241 m, 0.203 m over grade', () => { + test('an unknown site keeps today’s default: block, 0.241 m', () => { for (const site of [null, {}, { address: { state: 'ON' } }]) { const reading = foundationReadingOf(house(site), 'building_a') expect(reading.construction).toBe(FOUNDATION_CONSTRUCTIONS.cmu) @@ -301,45 +297,4 @@ describe('what reads the construction', () => { expect(nodes['wall_old' as AnyNodeId]).toEqual(before) expect(wall.thickness).toBe(0.354) }) - - test('the generic foundation draws the stem in the matching material and width', () => { - const stems = (site: SitePatch | null) => - genericFoundation(house(site)).filter((member) => member.kind === 'stem') - // the basement's own walls are none, so the ground floor ring is the outline: stems only where the floor is above the footing - const us = stems({ address: { state: 'TX' } }) - const eu = stems({ dossier: dossier('Paris, France') }) - const unknown = stems({}) - expect(unknown.length).toBeGreaterThan(0) - for (const run of unknown) expect(run.material).toBe('cmu') - for (const run of us) expect(run.material).toBe('cmu') - for (const run of eu) expect(run.material).toBe('concrete') - expect([us.length, eu.length]).toEqual([unknown.length, unknown.length]) - for (const run of us) - expect(run.width).toBeCloseTo(FOUNDATION_CONSTRUCTIONS.cmu.stemThickness, 9) - for (const run of eu) expect(run.width).toBeCloseTo(0.25, 9) - const footings = genericFoundation(house({ dossier: dossier('Paris, France') })).filter( - (member) => member.kind === 'footing', - ) - expect(footings.length).toBeGreaterThan(0) - for (const footing of footings) expect(footing.material).toBe('concrete') - }) - - test('the ground seat reads the construction: a floor 0.15 m over grade is seated in Paris, a floor 0.3 m over it is not', () => { - const seated = (nodes: Nodes, offset: number) => { - const raised = { - ...nodes, - building_a: { ...nodes.building_a, groundLevelId: 'level_main', position: [0, offset, 0] }, - } as Nodes - return groundSeat(raised, 'building_a') - } - const paris = seated(house({ dossier: dossier('Paris, France') }), 0.15) - expect(paris).toMatchObject({ aboveGrade: 0.15, atFoundationTop: true, seated: true }) - const us = seated(house({ address: { state: 'TX' } }), 0.203) - expect(us).toMatchObject({ aboveGrade: 0.203, atFoundationTop: true }) - // a European scene seated at the block's 0.203 m before the region was read is still seated - const before = seated(house({ dossier: dossier('Paris, France') }), 0.203) - expect(before).toMatchObject({ seated: true, atFoundationTop: false }) - const tooHigh = seated(house({ dossier: dossier('Paris, France') }), 0.3) - expect(tooHigh).toMatchObject({ seated: false }) - }) }) diff --git a/packages/core/src/lib/foundation-construction.ts b/packages/core/src/lib/foundation-construction.ts index f59d522d92..ad663ebca8 100644 --- a/packages/core/src/lib/foundation-construction.ts +++ b/packages/core/src/lib/foundation-construction.ts @@ -1,6 +1,5 @@ import type { AnyNode, AnyNodeId } from '../schema' import type { Assembly } from '../schema/assembly' -import { FOUNDATION_STANDARD } from './foundation-standard' /** What a foundation wall is built of: block, or cast in place. */ export type FoundationConstructionId = 'cmu' | 'cast-concrete' @@ -16,12 +15,6 @@ export type FoundationConstruction = { description: string /** The stack a new foundation wall stores, outside in (the wall's thickness is its sum). */ assembly: Assembly - /** The course the generic foundation draws up to the floor, where the walls above it are thinner. */ - stemThickness: number - /** How far the ground floor stands over finished grade: the top of the foundation, metres. */ - seatAboveGrade: number - /** Where the seat comes from. */ - seatBasis: string /** Whether the numbers cite a standard (`standard`) or are a sensible default (`default`). */ source: 'standard' | 'default' } @@ -29,17 +22,14 @@ export type FoundationConstruction = { const INCH = 0.0254 /** - * The foundation constructions, as data: the wall a person gets below grade, the course the generic - * foundation draws, and how high the floor stands over the ground. The generic one (`cmu`) is the - * US residential practice and stays the answer wherever nothing says better. + * The foundation constructions, as data: the wall a person gets below grade. The generic one + * (`cmu`) is the US residential practice and stays the answer wherever nothing says better. * - * - `cmu`: 8 in block, 2x4 pressure-treated furring laid flat inside (IRC R404.1, R317.1), the - * floor 8 in over grade (R317.1 keeps wood framing that far off exposed ground). + * - `cmu`: 8 in block, 2x4 pressure-treated furring laid flat inside (IRC R404.1, R317.1). * - `cast-concrete`: the continental and British practice of a cast wall, 25 cm, insulated and * waterproofed on the outside. The thicknesses are the usual ones (cellar walls of 20 to 25 cm, * perimeter insulation of 10 cm, a 4 mm bitumen sheet), a sensible default rather than one - * country's code. The floor 15 cm over the ground: the damp-proof course of British practice - * (Approved Document C, NHBC) stands at least 150 mm over it, and plinths elsewhere run as high. + * country's code. */ export const FOUNDATION_CONSTRUCTIONS: Record = { cmu: { @@ -55,10 +45,6 @@ export const FOUNDATION_CONSTRUCTIONS: Record { expect(result.plan.insertedWalls[0]).toMatchObject({ thickness: 0.3 }) expect(result.plan.insertedWalls[0]!.assembly).toBeUndefined() }) - - test('the generic foundation still finds the perimeter and draws nothing under the partition', () => { - const { scene } = drawEach(house(), 'level_base', [ - ...PERIMETER, - [ - [4, 0], - [4, 6], - ], - ]) - const walls = Object.values(scene).filter((node): node is WallNode => node.type === 'wall') - const level = scene.level_base as LevelNode - const nodes: Nodes = { - ...scene, - level_base: { ...level, children: [...level.children, ...walls.map((wall) => wall.id)] }, - } as Nodes - const members = genericFoundation(nodes) - const partition = walls.find((wall) => wall.start[0] === 4 && wall.end[0] === 4)! - expect(isPlainWall(partition)).toBe(true) - expect(members.length).toBeGreaterThan(0) - for (const member of members) { - expect(member.levelId).toBe('level_base') - // every run lies on the perimeter: x or z at 0, 8 / 6, never along the x = 4 partition - const onPartition = [member.from, member.to].every(([x]) => Math.abs(x - 4) < 1e-6) - expect(onPartition).toBe(false) - } - const east = members.filter((m) => m.from[0] > 7.9 && m.to[0] > 7.9) - expect(east.length).toBeGreaterThan(0) - }) }) diff --git a/packages/core/src/lib/foundation-wall.ts b/packages/core/src/lib/foundation-wall.ts index 1609cf3731..e13c1c836a 100644 --- a/packages/core/src/lib/foundation-wall.ts +++ b/packages/core/src/lib/foundation-wall.ts @@ -52,8 +52,7 @@ export function foundationWallConstruction(construction: FoundationConstruction) * side: a room open to the sky, as the structure kernel reads it, facing air, not earth). A wall * outside the outline (a well against it) is. A wall with no closed circuit around it yet (the * first walls of a basement, an open run) counts as the outline in the making, so a basement drawn - * wall by wall is foundation all the way round. The outline is the one `genericFoundation` draws - * under. + * wall by wall is foundation all the way round. */ export function wallsAgainstGround( nodes: Record, diff --git a/packages/core/src/lib/generic-foundation.test.ts b/packages/core/src/lib/generic-foundation.test.ts deleted file mode 100644 index 107892c1ac..0000000000 --- a/packages/core/src/lib/generic-foundation.test.ts +++ /dev/null @@ -1,500 +0,0 @@ -import { afterEach, expect, test } from 'bun:test' -import { emitter } from '../events/bus' -import { isCaptureSessionOn } from '../events/capture-sessions' -import { nodeRegistry, registerNode } from '../registry' -import { - type AnyNode, - type AnyNodeId, - BaseNode, - BuildingNode, - LevelNode, - nodeType, - objectId, - railingWallDefaults, - SiteNode, - SlabNode, - WallNode, -} from '../schema' -import { GROUND_PIT_PLATE_CLEARANCE, groundPitFloorY } from './below-grade-footprints' -import { FOUNDATION_STANDARD } from './foundation-standard' -import { type FoundationMember, genericFoundation } from './generic-foundation' -import { FLAT_GROUND_Y } from './site-ground-height' -import { encodeTerrainField } from './terrain-codec' - -import { createTerrainField } from './terrain-field' - -const IN = 0.0254 -const { footingThickness, footingBelowGrade, stemThickness } = FOUNDATION_STANDARD - -type Nodes = Record -const keyed = (nodes: AnyNode[]) => Object.fromEntries(nodes.map((n) => [n.id, n])) as Nodes - -/** A 10 × 8 m ring of walls on `level`, 0.1 m thick unless told. */ -function ring(level: string, extra: Partial = {}, thickness = 0.1) { - const corners: Array<[number, number]> = [ - [0, 0], - [10, 0], - [10, 8], - [0, 8], - ] - return corners.map((start, index) => - WallNode.parse({ - id: `wall_${level}_${index}`, - parentId: level, - start, - end: corners[(index + 1) % 4], - thickness, - ...extra, - }), - ) -} - -type House = { - terrain?: string - slab?: Partial - wallExtra?: Partial - thickness?: number -} - -/** A house on a flat site: one level at grade (the floor at the datum), the site above it. */ -function flatHouse({ slab, wallExtra, thickness, terrain }: House = {}) { - const walls = ring('level_g', wallExtra, thickness) - return keyed([ - SiteNode.parse({ id: 'site_a', children: ['building_a'], ...(terrain ? { terrain } : {}) }), - BuildingNode.parse({ id: 'building_a', parentId: 'site_a', children: ['level_g'] }), - LevelNode.parse({ - id: 'level_g', - parentId: 'building_a', - level: 0, - children: [...walls.map((w) => w.id), 'slab_g'], - }), - SlabNode.parse({ - id: 'slab_g', - parentId: 'level_g', - polygon: [ - [0, 0], - [10, 0], - [10, 8], - [0, 8], - ], - elevation: 0.05, - thickness: 0.05, - ...slab, - }), - ...walls, - ]) -} - -/** - * The villa's shape: a Lower Ground at -3.63 m under a ground floor, both ringed by walls (the - * Lower Ground's first `basementWalls` of them, to leave its outline open while it is drawn). - */ -function houseOverBasement(basementWalls = 4) { - const lower = ring('level_b').slice(0, basementWalls) - const ground = ring('level_g') - const plate = (id: string, parentId: string) => - SlabNode.parse({ - id, - parentId, - polygon: [ - [0, 0], - [10, 0], - [10, 8], - [0, 8], - ], - elevation: 0.2, - }) - return keyed([ - BuildingNode.parse({ id: 'building_a', children: ['level_b', 'level_g'] }), - LevelNode.parse({ - id: 'level_b', - parentId: 'building_a', - level: -1, - baseElevation: -3.63, - height: 3.4, - children: [...lower.map((w) => w.id), 'slab_b'], - }), - LevelNode.parse({ - id: 'level_g', - parentId: 'building_a', - level: 0, - children: [...ground.map((w) => w.id), 'slab_g'], - }), - plate('slab_b', 'level_b'), - plate('slab_g', 'level_g'), - ...lower, - ...ground, - ]) -} - -/** Two storeys at grade, both ringed by walls (the ground floor's first `groundWalls` of them). */ -function twoStoreys(groundWalls = 4) { - const ground = ring('level_g').slice(0, groundWalls) - const upper = ring('level_u') - return keyed([ - BuildingNode.parse({ id: 'building_a', children: ['level_g', 'level_u'] }), - LevelNode.parse({ - id: 'level_g', - parentId: 'building_a', - level: 0, - children: ground.map((w) => w.id), - }), - LevelNode.parse({ - id: 'level_u', - parentId: 'building_a', - level: 1, - children: upper.map((w) => w.id), - }), - ...ground, - ...upper, - ]) -} - -const ofKind = (members: FoundationMember[], kind: FoundationMember['kind']) => - members.filter((member) => member.kind === kind) - -test('a house on a flat site gets a 16 x 8 in footing 12 in under grade and an 8 in wall to its floor', () => { - const members = genericFoundation(flatHouse()) - const [footing] = ofKind(members, 'footing') - const [stem] = ofKind(members, 'stem') - expect(ofKind(members, 'footing')).toHaveLength(4) - expect(ofKind(members, 'stem')).toHaveLength(4) - expect(footing?.width).toBeCloseTo(FOUNDATION_STANDARD.footingWidth, 9) - expect(footing ? footing.topY - footing.bottomY : 0).toBeCloseTo(footingThickness, 9) - expect(footing?.bottomY).toBeCloseTo(FLAT_GROUND_Y - footingBelowGrade, 9) - expect(stem?.width).toBeCloseTo(stemThickness, 9) - expect(stem?.bottomY).toBeCloseTo(footing?.topY ?? Number.NaN, 9) -}) - -test('the foundation wall rises to the underside of the lowest floor', () => { - // A floor top at 0.05 on a 0.1 m slab: its underside is 0.05 m under the level plane. - const [stem] = ofKind( - genericFoundation(flatHouse({ slab: { elevation: 0.05, thickness: 0.1 } })), - 'stem', - ) - expect(stem?.topY).toBeCloseTo(-0.05, 9) -}) - -test('the wall stops at the level plane when the floor stands higher, never inside the room', () => { - const stems = ofKind( - genericFoundation(flatHouse({ slab: { elevation: 0.35, thickness: 0.05 } })), - 'stem', - ) - expect(stems).toHaveLength(4) - for (const stem of stems) expect(stem.topY).toBe(0) -}) - -test('a floor deeper than the footing would sit leaves no wall: the footing takes the floor', () => { - const members = genericFoundation(flatHouse({ slab: { elevation: 0.05, thickness: 0.4 } })) - expect(ofKind(members, 'stem')).toHaveLength(0) - for (const footing of ofKind(members, 'footing')) expect(footing.topY).toBeCloseTo(-0.35, 9) -}) - -/** The east half of the site (x >= 5) stands 1 m over the west half, the house across the step. */ -function eastStep() { - const field = createTerrainField({ cols: 33, rows: 33, spacing: 1, origin: [-16, -16] }) - const heights = new Int16Array(field.heights) - for (let row = 0; row < field.rows; row += 1) - for (let col = 0; col < field.cols; col += 1) - if (field.origin[0] + col * field.spacing >= 5) heights[row * field.cols + col] = 100 - return encodeTerrainField({ ...field, heights }) -} - -test('on a slope the footing sits under the lowest grade of the whole house, one level all round', () => { - const footings = ofKind(genericFoundation(flatHouse({ terrain: eastStep() })), 'footing') - expect(footings).toHaveLength(4) - for (const footing of footings) expect(footing.bottomY).toBeCloseTo(0 - footingBelowGrade, 2) -}) - -test('runs are carried past the wall ends so the corners close', () => { - const [bottomWall] = ofKind(genericFoundation(flatHouse()), 'stem').filter( - (stem) => stem.from[1] === stem.to[1] && Math.abs(stem.from[1]) < 1, - ) - expect(bottomWall?.from[0]).toBeCloseTo(-stemThickness / 2, 9) - expect(bottomWall?.to[0]).toBeCloseTo(10 + stemThickness / 2, 9) -}) - -test('a wall thicker than the stem is not overhanging it, and the footing keeps 4 in each side', () => { - const thick = flatHouse({ thickness: 0.3 }) - const [stem] = ofKind(genericFoundation(thick), 'stem') - const [footing] = ofKind(genericFoundation(thick), 'footing') - expect(stem?.width).toBeCloseTo(0.3, 9) - expect(footing?.width).toBeCloseTo(0.3 + 8 * IN, 9) -}) - -test('a level below grade is its own foundation wall: only the footing, under its floor', () => { - const members = genericFoundation(houseOverBasement()) - expect(ofKind(members, 'stem')).toHaveLength(0) - const footings = ofKind(members, 'footing') - expect(footings).toHaveLength(4) - // The floor top is -3.63 + 0.2 on a 0.05 m slab; the wall's base (-3.63) is lower than the - // underside, so the footing top meets the wall's base. - for (const footing of footings) { - expect(footing.levelId).toBe('level_b') - expect(footing.topY).toBeCloseTo(-3.63, 9) - expect(footing.bottomY).toBeCloseTo(-3.63 - footingThickness, 9) - } -}) - -/** - * A basement with the default 0.05 m plate, as a person draws one: the building seated 2.697 m - * down, walls 0.25 m thick on the plate's edge, a ground floor over it. - */ -function seatedBasement(slab: Partial = {}) { - const lower = ring('level_b', {}, 0.25) - const ground = ring('level_g', {}, 0.25) - const polygon: Array<[number, number]> = [ - [0, 0], - [10, 0], - [10, 8], - [0, 8], - ] - return keyed([ - SiteNode.parse({ id: 'site_a', children: ['building_a'] }), - BuildingNode.parse({ - id: 'building_a', - parentId: 'site_a', - position: [0, -2.697, 0], - children: ['level_b', 'level_g'], - }), - LevelNode.parse({ - id: 'level_b', - parentId: 'building_a', - level: -1, - height: 2.9, - children: [...lower.map((w) => w.id), 'slab_b'], - }), - LevelNode.parse({ - id: 'level_g', - parentId: 'building_a', - level: 0, - height: 2.8, - children: [...ground.map((w) => w.id), 'slab_g'], - }), - SlabNode.parse({ - id: 'slab_b', - parentId: 'level_b', - polygon, - elevation: 0.05, - thickness: 0.05, - ...slab, - }), - SlabNode.parse({ id: 'slab_g', parentId: 'level_g', polygon, elevation: 0.05 }), - ...lower, - ...ground, - ]) -} - -test('the footing under a basement floor stands on the pit floor, never on its plane', () => { - // The default plate (0.05 on 0.05), a thick one, a thin one, a plate whose top is the level plane. - for (const slab of [ - {}, - { thickness: 0.2 }, - { thickness: 0.03 }, - { elevation: 0, thickness: 0.05 }, - ]) { - const nodes = seatedBasement(slab) - const pitFloor = groundPitFloorY(nodes, 'level_b') ?? Number.NaN - const footings = ofKind(genericFoundation(nodes), 'footing') - expect(footings).toHaveLength(4) - for (const footing of footings) - expect(Math.abs(footing.topY - pitFloor)).toBeGreaterThanOrEqual(GROUND_PIT_PLATE_CLEARANCE) - } -}) - -test('the footing follows the house’s floor, not a driveway laid deeper on its level', () => { - const plain = seatedBasement() - const level = plain.level_b as LevelNode - const drive = SlabNode.parse({ - id: 'slab_drive', - parentId: 'level_b', - polygon: [ - [0, 0], - [10, 0], - [10, 8], - [0, 8], - ], - elevation: 0, - thickness: 0.4, - metadata: { flatwork: 'driveway' }, - }) - const withDrive = { - ...plain, - slab_drive: drive, - level_b: { ...level, children: [...level.children, 'slab_drive'] }, - } as typeof plain - const tops = (nodes: typeof plain) => - ofKind(genericFoundation(nodes), 'footing').map((footing) => footing.topY) - expect(tops(withDrive)).toEqual(tops(plain)) -}) - -test('a basement still being drawn does not take the foundation away: the lowest level with a closed outline carries it', () => { - for (const walls of [1, 3]) { - const members = genericFoundation(houseOverBasement(walls)) - expect(new Set(members.map((member) => member.levelId))).toEqual(new Set(['level_g'])) - expect(ofKind(members, 'footing')).toHaveLength(4) - } - // Its outline closed, the basement is the lowest level that carries one. - expect(new Set(genericFoundation(houseOverBasement()).map((member) => member.levelId))).toEqual( - new Set(['level_b']), - ) -}) - -test('a ground floor at grade with an open outline stands on nothing drawn, the storey over it does not take the foundation', () => { - expect(new Set(genericFoundation(twoStoreys()).map((member) => member.levelId))).toEqual( - new Set(['level_g']), - ) - // One wall taken out of the ground floor: no stem rises to the upper floor's underside. - expect(genericFoundation(twoStoreys(3))).toEqual([]) -}) - -test('each building stands on the footing of its own lowest level only', () => { - const members = genericFoundation(houseOverBasement()) - expect(new Set(members.map((member) => member.levelId))).toEqual(new Set(['level_b'])) -}) - -test('a wall that stores its own stem keeps it: the footing goes under the stem, no second wall', () => { - const nodes = flatHouse({ wallExtra: { underpinning: { rim: 0.1, stem: 0.35 } } }) - const members = genericFoundation(nodes) - expect(ofKind(members, 'stem')).toHaveLength(0) - const footings = ofKind(members, 'footing') - expect(footings).toHaveLength(4) - // The stem's bottom is 0.45 m under the wall base; the grade is 0.05 under it, which is higher. - for (const footing of footings) { - expect(footing.topY).toBeCloseTo(-0.45, 9) - expect(footing.bottomY).toBeCloseTo(-0.45 - footingThickness, 9) - } -}) - -test('a slab that stores a solid foundation skirt is the foundation: nothing is drawn beside it', () => { - const nodes = flatHouse({ slab: { plateRole: 'base', foundation: { type: 'solid' } } }) - expect(genericFoundation(nodes)).toEqual([]) -}) - -test('a stored stem still gets its footing under a solid skirt', () => { - const nodes = flatHouse({ - slab: { plateRole: 'base', foundation: { type: 'solid' } }, - wallExtra: { underpinning: { rim: 0, stem: 0.3 } }, - }) - expect(ofKind(genericFoundation(nodes), 'footing')).toHaveLength(4) -}) - -test('a framing plugin that draws the foundation itself takes the generic one away', () => { - const Framer = BaseNode.extend({ id: objectId('framer'), type: nodeType('test:framer') }) - nodeRegistry._reset() - registerNode({ - kind: 'test:framer', - schemaVersion: 1, - schema: Framer, - category: 'utility', - defaults: () => ({}), - capabilities: { drawsFoundation: (node) => (node as { shown?: boolean }).shown === true }, - }) - const house = flatHouse() - const withFramer = (shown: boolean) => { - const framer = { ...Framer.parse({ id: 'framer_g', parentId: 'level_g' }), shown } as AnyNode - const level = house['level_g' as AnyNodeId] - if (level?.type !== 'level') throw new Error('fixture') - return { - ...house, - level_g: { ...level, children: [...level.children, framer.id] }, - framer_g: framer, - } as Nodes - } - expect(genericFoundation(withFramer(true))).toEqual([]) - expect(genericFoundation(withFramer(false)).length).toBeGreaterThan(0) -}) - -test('a plugin that steps aside from a picture gives the generic foundation back for as long as a capture session is on', () => { - const Framer = BaseNode.extend({ id: objectId('framer'), type: nodeType('test:picture-framer') }) - nodeRegistry._reset() - registerNode({ - kind: 'test:picture-framer', - schemaVersion: 1, - schema: Framer, - category: 'utility', - defaults: () => ({}), - capabilities: { drawsFoundation: () => !isCaptureSessionOn() }, - }) - const house = flatHouse() - const level = house['level_g' as AnyNodeId] - if (level?.type !== 'level') throw new Error('fixture') - // the same scene state throughout: a session starting changes no node - const nodes = { - ...house, - level_g: { ...level, children: [...level.children, 'framer_g'] }, - framer_g: Framer.parse({ id: 'framer_g', parentId: 'level_g' }), - } as Nodes - const session = (active: boolean) => - emitter.emit('camera-controls:capture-session', { owner: 'generic-foundation-test', active }) - expect(genericFoundation(nodes)).toEqual([]) - session(true) - try { - expect(genericFoundation(nodes)).toHaveLength(8) - expect(genericFoundation(nodes)).toBe(genericFoundation(nodes)) - } finally { - session(false) - } - expect(genericFoundation(nodes)).toEqual([]) -}) - -test('a level with no walls draws nothing, and a hidden wall is not carried', () => { - const none = keyed([ - BuildingNode.parse({ id: 'building_a', children: ['level_g'] }), - LevelNode.parse({ id: 'level_g', parentId: 'building_a', level: 0, children: [] }), - ]) - expect(genericFoundation(none)).toEqual([]) - const hidden = flatHouse({ wallExtra: { visible: false } }) - expect(genericFoundation(hidden)).toEqual([]) -}) - -test('a hidden building carries no foundation', () => { - const house = flatHouse() - const building = house['building_a' as AnyNodeId] - if (building?.type !== 'building') throw new Error('fixture') - expect( - genericFoundation({ ...house, building_a: { ...building, visible: false } } as Nodes), - ).toEqual([]) -}) - -test('the answer is worked out once per scene state', () => { - const nodes = flatHouse() - expect(genericFoundation(nodes)).toBe(genericFoundation(nodes)) -}) - -afterEach(() => nodeRegistry._reset()) - -/** `house` with a 3 × 4 m deck off its east wall, fenced by three railings. */ -function withRailedDeck(house: Nodes): Nodes { - const corners: Array<[number, number]> = [ - [10, 2], - [13, 2], - [13, 6], - [10, 6], - ] - const railings = corners.slice(1).map((end, index) => - WallNode.parse({ - id: `wall_deck_${index}`, - parentId: 'level_g', - start: corners[index], - end, - ...railingWallDefaults(), - }), - ) - const level = house['level_g' as AnyNodeId] as LevelNode - return keyed([ - ...Object.values(house), - { ...level, children: [...level.children, ...railings.map((wall) => wall.id)] }, - ...railings, - ]) -} - -test('a railing carries no foundation: a deck it fences adds none, a ring of railings stands on none', () => { - const members = genericFoundation(withRailedDeck(flatHouse())) - expect(ofKind(members, 'footing')).toHaveLength(4) - expect(ofKind(members, 'stem')).toHaveLength(4) - expect(Math.max(...members.flatMap((member) => [member.from[0], member.to[0]]))).toBeLessThan( - 10.5, - ) - expect(genericFoundation(flatHouse({ wallExtra: railingWallDefaults() }))).toEqual([]) -}) diff --git a/packages/core/src/lib/generic-foundation.ts b/packages/core/src/lib/generic-foundation.ts deleted file mode 100644 index 866383acfa..0000000000 --- a/packages/core/src/lib/generic-foundation.ts +++ /dev/null @@ -1,245 +0,0 @@ -import { isCaptureSessionOn } from '../events/capture-sessions' -import { nodeRegistry } from '../registry' -import type { AnyNode, AnyNodeId, BuildingNode, LevelNode, SlabNode, WallNode } from '../schema' -import { getLevelElevations, levelPlateUndersideWorldY } from '../services/storey' -import { getWallCenterlineSegments } from '../systems/wall/wall-curve' -import { getWallThickness } from '../systems/wall/wall-footprint' -import { getWallBodyCenterOffset } from '../systems/wall/wall-frame' -import { exteriorWallLoops } from './exterior-wall-loops' -import { type FoundationConstructionId, foundationReadingOf } from './foundation-construction' -import { FOUNDATION_STANDARD } from './foundation-standard' -import { levelGradeStanding } from './grade-standing' -import { groundHeightAt } from './site-ground-height' -import { levelLocalToWorldXZ } from './terrain-support-query' - -type Nodes = Record - -/** - * One run of the foundation under the exterior walls: a prism along `from` to `to` (world plan, - * already carried past the wall's ends so the corners close), `width` wide, from `bottomY` up to - * `topY`. A `footing` is the concrete pour under the wall, a `stem` the foundation wall on it, - * built of `material`: the footing is always concrete, the stem is what the building's - * foundation construction is (block or cast concrete, by region). - */ -export type FoundationMember = { - kind: 'footing' | 'stem' - material: 'concrete' | 'cmu' - levelId: string - from: [number, number] - to: [number, number] - width: number - bottomY: number - topY: number -} - -const STEM_MATERIAL: Record = { - cmu: 'cmu', - 'cast-concrete': 'concrete', -} - -/** The lowest grade is sampled at this many points along each wall, the generator's own count. */ -const GRADE_SAMPLES = 7 -/** A stem shorter than this is the floor sitting on the footing: nothing to draw. */ -const MIN_STEM_HEIGHT = 1e-3 - -// Per scene and per capture session: a plugin's `drawsFoundation` may step aside from a picture -// (the pictures show the finished house), a state no node holds. -const memo = new WeakMap() - -/** - * The foundation a building stands on where the scene stores none: a continuous footing and a - * foundation wall under the exterior walls of each building's lowest level with a closed outline, - * derived from those walls, never stored, so nothing in a saved scene changes. The numbers are - * {@link FOUNDATION_STANDARD}: a 16 × 8 in footing whose bottom sits 12 in under the lowest grade - * (a generic depth: core has no frost data), and a wall from the footing up to the underside of the - * lowest floor, of the building's foundation construction (`foundationReadingOf`): 8 in block by - * default, cast concrete in Europe. - * - * - A level below grade (all of it) has no second wall: its exterior walls are the foundation - * walls, so only the footing is drawn, under the underside of its floor. - * - A wall that stores its own stem (`underpinning`) keeps it; the footing goes under that stem. - * - A slab that stores a solid foundation skirt (`foundation`) is the foundation under its level: - * walls without a stored stem get nothing. - * - A node that declares `drawsFoundation` on the level (a framing plugin) draws it itself: the - * generic one steps aside. The plugin may read `isCaptureSessionOn()` to give it back to a - * picture, which shows the finished house. - */ -export function genericFoundation(nodes: Nodes): FoundationMember[] { - const capturing = isCaptureSessionOn() - const hit = memo.get(nodes) - if (hit && hit.capturing === capturing) return hit.members - const members: FoundationMember[] = [] - for (const node of Object.values(nodes)) { - if (node.type === 'building' && node.visible !== false) - members.push(...buildingFoundation(nodes, node)) - } - memo.set(nodes, { capturing, members }) - return members -} - -function buildingFoundation(nodes: Nodes, building: BuildingNode): FoundationMember[] { - const enclosed = lowestEnclosedLevel(nodes, building) - if (!enclosed || levelDrawsFoundation(nodes, enclosed.level)) return [] - const { level, walls } = enclosed - - const site = siteOf(nodes, building) - const gradeAt = (x: number, z: number) => groundHeightAt(site, x, z) - const lowestGrade = Math.min(...walls.map((wall) => lowestGradeAlong(building, wall, gradeAt))) - const floors = floorsOf(nodes, level) - const wallBaseY = building.position[1] + (getLevelElevations(nodes).get(level.id)?.baseY ?? 0) - // The footing never pokes above the wall's base into the room, nor above the floor's underside. - const floorUnderside = levelPlateUndersideWorldY(nodes, level.id) ?? wallBaseY - const { construction } = foundationReadingOf(nodes, building.id) - const stemMaterial = STEM_MATERIAL[construction.id] - const stemThickness = construction.stemThickness - const buried = levelGradeStanding(nodes, level.id) === 'below-grade' - const solidSkirt = floors.some((floor) => floor.foundation?.type === 'solid') - - const members: FoundationMember[] = [] - for (const wall of walls) { - const stored = wall.underpinning - if (!stored && solidSkirt) continue - const run = runOf(building, wall, stemThickness) - const wallWidth = Math.max(stemThickness, getWallThickness(wall)) - const footingWidth = - wallWidth + FOUNDATION_STANDARD.footingWidth - FOUNDATION_STANDARD.stemThickness - const footingTop = stored - ? Math.min(wallBaseY - stored.rim - stored.stem, lowestGradeAlong(building, wall, gradeAt)) - : footingTopUnder(floorUnderside, lowestGrade) - const footingBottom = footingTop - FOUNDATION_STANDARD.footingThickness - for (const segment of run) { - members.push({ - kind: 'footing', - material: 'concrete', - levelId: level.id, - ...segment, - width: footingWidth, - bottomY: footingBottom, - topY: footingTop, - }) - if (stored || buried || floorUnderside - footingTop < MIN_STEM_HEIGHT) continue - members.push({ - kind: 'stem', - material: stemMaterial, - levelId: level.id, - ...segment, - width: wallWidth, - bottomY: footingTop, - topY: floorUnderside, - }) - } - } - return members -} - -/** - * The footing's top: the generic depth under the lowest grade, or the floor's underside where that - * is deeper (a level below grade sits its footing right under its floor). - */ -function footingTopUnder(floorUnderside: number, lowestGrade: number): number { - const { footingBelowGrade, footingThickness } = FOUNDATION_STANDARD - return Math.min(lowestGrade - footingBelowGrade + footingThickness, floorUnderside) -} - -/** - * The building's lowest level whose walls close an outline, with those exterior walls. A level - * under the ground still being drawn (a basement's first wall, an open run) carries no foundation - * yet, and the one over it does; a level at grade whose walls close nothing stands on nothing - * drawn, whatever is over it. - */ -function lowestEnclosedLevel( - nodes: Nodes, - building: BuildingNode, -): { level: LevelNode; walls: WallNode[] } | null { - const elevations = getLevelElevations(nodes) - const levels = Object.values(nodes) - .filter( - (node): node is LevelNode => - node.type === 'level' && elevations.get(node.id)?.buildingId === building.id, - ) - .sort((a, b) => a.level - b.level) - for (const level of levels) { - if (!level.children.some((id) => nodes[id]?.type === 'wall')) continue - const walls = exteriorWalls(nodes, level) - if (walls.length > 0) return { level, walls } - if (levelGradeStanding(nodes, level.id) === 'at-grade') return null - } - return null -} - -function levelDrawsFoundation(nodes: Nodes, level: LevelNode): boolean { - return level.children.some((id) => { - const child = nodes[id] - return child - ? nodeRegistry.get(child.type)?.capabilities?.drawsFoundation?.(child) === true - : false - }) -} - -function exteriorWalls(nodes: Nodes, level: LevelNode): WallNode[] { - const walls = level.children - .map((id) => nodes[id]) - .filter((node): node is WallNode => node?.type === 'wall' && node.visible !== false) - const outside = new Set() - for (const loop of exteriorWallLoops(walls)) for (const face of loop) outside.add(face.wallId) - return walls.filter((wall) => outside.has(wall.id)) -} - -function floorsOf(nodes: Nodes, level: LevelNode): SlabNode[] { - return level.children - .map((id) => nodes[id]) - .filter((node): node is SlabNode => node?.type === 'slab' && node.recessed !== true) -} - -function siteOf(nodes: Nodes, building: BuildingNode): AnyNode | null { - const parent = building.parentId ? nodes[building.parentId as AnyNodeId] : undefined - return parent?.type === 'site' - ? parent - : (Object.values(nodes).find((node) => node.type === 'site') ?? null) -} - -function lowestGradeAlong( - building: BuildingNode, - wall: WallNode, - gradeAt: (x: number, z: number) => number, -): number { - let lowest = Number.POSITIVE_INFINITY - for (let k = 0; k < GRADE_SAMPLES; k++) { - const t = k / (GRADE_SAMPLES - 1) - const [x, z] = levelLocalToWorldXZ( - building, - wall.start[0] + (wall.end[0] - wall.start[0]) * t, - wall.start[1] + (wall.end[1] - wall.start[1]) * t, - ) - lowest = Math.min(lowest, gradeAt(x, z)) - } - return lowest -} - -/** - * A wall's body centreline in the world as consecutive runs, each carried half its width past both - * ends so the runs of a corner (or a curve's pieces) overlap and close it. - */ -function runOf( - building: BuildingNode, - wall: WallNode, - stemThickness: number, -): Array> { - const offset = getWallBodyCenterOffset(wall) - const reach = Math.max(stemThickness, getWallThickness(wall)) / 2 - return getWallCenterlineSegments(wall).flatMap(([a, b]) => { - const dx = b.x - a.x - const dz = b.y - a.y - const length = Math.hypot(dx, dz) - if (length < 1e-9) return [] - const [ux, uz] = [dx / length, dz / length] - // The wall's normal as the plan footprint takes it, so a justified wall sits where it is drawn. - const [nx, nz] = [-uz * offset, ux * offset] - return [ - { - from: levelLocalToWorldXZ(building, a.x + nx - ux * reach, a.y + nz - uz * reach), - to: levelLocalToWorldXZ(building, b.x + nx + ux * reach, b.y + nz + uz * reach), - }, - ] - }) -} diff --git a/packages/core/src/lib/ground-line.test.ts b/packages/core/src/lib/ground-line.test.ts index 93ca58100e..e0c6ed0f59 100644 --- a/packages/core/src/lib/ground-line.test.ts +++ b/packages/core/src/lib/ground-line.test.ts @@ -14,7 +14,7 @@ import { getStoreyDatum } from '../services/storey-datum' import { belowGradeFootprints } from './below-grade-footprints' import { levelGradeStanding } from './grade-standing' import { groundLevelOf } from './ground-level' -import { GROUND_FLOOR_ABOVE_GRADE, groundSeat } from './ground-seat' +import { groundSeat } from './ground-seat' import { encodeTerrainField } from './terrain-codec' import { createTerrainField } from './terrain-field' @@ -120,23 +120,18 @@ describe('the ground line', () => { test('setting the ground floor seats the building: Reception at grade, both basements under it', () => { const nodes = mansion() const changes = buildGroundLevelChanges({ nodes, levelId: 'level_reception' }) - expect(changes?.moveBy).toBeCloseTo(-3.4 + GROUND_FLOOR_ABOVE_GRADE, 9) + expect(changes?.moveBy).toBeCloseTo(-3.4, 9) expect(changes?.renumbered).toBe(false) const next = apply(nodes, changes!) - expect((next.building_a as BuildingNode).position).toEqual([ - 0, - -3.4 + GROUND_FLOOR_ABOVE_GRADE, - 0, - ]) + expect((next.building_a as BuildingNode).position).toEqual([0, -3.4, 0]) expect((next.building_a as BuildingNode).groundLevelId).toBe('level_reception') expect(groundSeat(next, 'building_a')).toMatchObject({ seated: true, - atFoundationTop: true, explicit: true, }) - expect(datum(next, 'level_reception')).toBeCloseTo(0.28 + GROUND_FLOOR_ABOVE_GRADE, 9) - expect(datum(next, 'level_lg')).toBeCloseTo(-3.4 + 0.28 + GROUND_FLOOR_ABOVE_GRADE, 9) - expect(datum(next, 'level_b2')).toBeCloseTo(-6.8 + 0.28 + GROUND_FLOOR_ABOVE_GRADE, 9) + expect(datum(next, 'level_reception')).toBeCloseTo(0.28, 9) + expect(datum(next, 'level_lg')).toBeCloseTo(-3.4 + 0.28, 9) + expect(datum(next, 'level_b2')).toBeCloseTo(-6.8 + 0.28, 9) expect(levelGradeStanding(next, 'level_reception')).toBe('at-grade') expect(levelGradeStanding(next, 'level_suites')).toBe('at-grade') expect(levelGradeStanding(next, 'level_lg')).toBe('below-grade') @@ -177,45 +172,41 @@ describe('the ground line', () => { index('level_reception'), index('level_suites'), ]).toEqual([-1, 0, 1, 2]) - // Already at grade: it only rises to the foundation's top, 8 in over the ground. - expect((next.building_a as BuildingNode).position[1]).toBe(GROUND_FLOOR_ABOVE_GRADE) + // Already at grade: the building does not move. + expect((next.building_a as BuildingNode).position[1]).toBe(0) expect(levelGradeStanding(next, 'level_b2')).toBe('below-grade') expect(levelGradeStanding(next, 'level_reception')).toBe('at-grade') }) - test('the ground floor stands 8 in (0.203 m) over finished grade on a flat site', () => { + test('the ground floor stands on finished grade on a flat site', () => { const nodes = scene([ ['level_base', -1, -2.5, 2.5, rect(0, 0, 6, 6)], ['level_ground', 0, 0, 2.5, rect(0, 0, 8, 8)], ]) const changes = buildGroundLevelChanges({ nodes, levelId: 'level_ground' }) - expect(GROUND_FLOOR_ABOVE_GRADE).toBe(0.203) expect(changes?.unchanged).toBe(false) + expect(changes?.moveBy).toBe(0) const next = apply(nodes, changes!) - expect((next.building_a as BuildingNode).position[1]).toBeCloseTo(0.203, 9) - expect(getStoreyDatum(next, 'level_ground')?.floorElevation).toBeCloseTo(0.203, 9) - expect(groundSeat(next, 'building_a')?.offset).toBeCloseTo(0.203, 9) + expect((next.building_a as BuildingNode).position[1]).toBe(0) + expect(getStoreyDatum(next, 'level_ground')?.floorElevation).toBeCloseTo(0, 9) + expect(groundSeat(next, 'building_a')).toMatchObject({ seated: true }) expect(levelGradeStanding(next, 'level_base')).toBe('below-grade') expect(levelGradeStanding(next, 'level_ground')).toBe('at-grade') }) - test('a ground floor seated before the 8 in rule, at grade, is still seated, and rises when set again', () => { + test('a ground floor seated 8 in over grade by the old rule is not seated, and comes down when set again', () => { const nodes = scene([ ['level_base', -1, -2.5, 2.5, rect(0, 0, 6, 6)], ['level_ground', 0, 0, 2.5, rect(0, 0, 8, 8)], ]) const named = { ...nodes, - building_a: { ...nodes.building_a, groundLevelId: 'level_ground' }, + building_a: { ...nodes.building_a, groundLevelId: 'level_ground', position: [0, 0.203, 0] }, } as Nodes - expect(groundSeat(named, 'building_a')).toMatchObject({ - explicit: true, - seated: true, - atFoundationTop: false, - }) + expect(groundSeat(named, 'building_a')).toMatchObject({ explicit: true, seated: false }) const changes = buildGroundLevelChanges({ nodes: named, levelId: 'level_ground' }) expect(changes?.unchanged).toBe(false) - expect(changes?.moveBy).toBeCloseTo(0.203, 9) + expect(changes?.moveBy).toBeCloseTo(-0.203, 9) }) test('a ground floor standing well over the ground, or under it, is not seated', () => { @@ -296,14 +287,11 @@ describe('a hillside', () => { ) const changes = buildGroundLevelChanges({ nodes, levelId: 'level_ground' }) expect(changes?.seat.gradeElevation).toBeCloseTo(1.5, 6) - expect(changes?.moveBy).toBeCloseTo(1.5 + GROUND_FLOOR_ABOVE_GRADE, 6) + expect(changes?.moveBy).toBeCloseTo(1.5, 6) const next = apply(nodes, changes!) - expect((next.building_a as BuildingNode).position[1]).toBeCloseTo( - 1.5 + GROUND_FLOOR_ABOVE_GRADE, - 6, - ) - expect(groundSeat(next, 'building_a')).toMatchObject({ seated: true, atFoundationTop: true }) - expect(groundSeat(next, 'building_a')?.offset).toBeCloseTo(GROUND_FLOOR_ABOVE_GRADE, 6) + expect((next.building_a as BuildingNode).position[1]).toBeCloseTo(1.5, 6) + expect(groundSeat(next, 'building_a')).toMatchObject({ seated: true }) + expect(groundSeat(next, 'building_a')?.offset).toBeCloseTo(0, 6) expect(levelGradeStanding(next, 'level_base')).toBe('below-grade') expect(levelGradeStanding(next, 'level_ground')).toBe('at-grade') }) diff --git a/packages/core/src/lib/ground-seat.ts b/packages/core/src/lib/ground-seat.ts index e8fe7f0eb8..7c8cc76196 100644 --- a/packages/core/src/lib/ground-seat.ts +++ b/packages/core/src/lib/ground-seat.ts @@ -1,27 +1,13 @@ import type { AnyNode, AnyNodeId, BuildingNode, LevelNode } from '../schema' import { getStoreyDatum } from '../services/storey-datum' -import { - FOUNDATION_CONSTRUCTIONS, - type FoundationReading, - foundationReadingOf, -} from './foundation-construction' import { footprintSamples, terrainFieldOverLevel } from './grade-standing' import { groundLevelOf } from './ground-level' import { heightAt } from './terrain-field' import { levelLocalToWorldXZ, SITE_DATUM_Y } from './terrain-support-query' -/** How far the ground floor's datum may stand from its seat and still count as seated on it. */ +/** How far the ground floor's datum may stand from grade and still count as seated on it. */ export const GROUND_SEAT_TOLERANCE = 0.05 -/** - * Where "Set as ground floor" and `set_ground_level` stand the ground floor over finished grade - * on the generic (block) foundation: the top of the foundation, where the wood framing starts, 8 - * in (0.203 m) above the ground. IRC R317.1 keeps wood framing resting on a foundation wall at - * least 8 in from exposed ground. A building's region and style can choose another construction - * and its own seat (`GroundSeat.aboveGrade`, `FOUNDATION_CONSTRUCTIONS`). - */ -export const GROUND_FLOOR_ABOVE_GRADE = FOUNDATION_CONSTRUCTIONS.cmu.seatAboveGrade - /** * The grade a level's floor is seated against: the flat datum on a flat site, and on shaped * terrain the ground's mean height over the level's floor slabs (the building's own origin when it @@ -54,19 +40,8 @@ export type GroundSeat = { gradeElevation: number /** How far the floor datum stands over grade: negative when it is sunk. */ offset: number - /** How far the building's foundation construction stands the ground floor over grade, metres. */ - aboveGrade: number - /** The construction, the region and style it was read from. */ - foundation: FoundationReading - /** - * The floor datum stands between grade and the foundation's top (`aboveGrade`, or the block's - * 8 in where that is higher), within {@link GROUND_SEAT_TOLERANCE}: what a scene seated before - * the 8 in rule, one seated by it and one seated by its own region's construction all satisfy, - * so a check has nothing to say about any of them. - */ + /** The floor datum stands on grade, within {@link GROUND_SEAT_TOLERANCE}. */ seated: boolean - /** The floor datum stands at `aboveGrade` over grade, within the tolerance. */ - atFoundationTop: boolean } /** `null` for an id that is no building, or a building with no level at or over the ground. */ @@ -79,8 +54,6 @@ export function groundSeat( if (!(ground && datum)) return null const gradeElevation = gradeUnderLevel(nodes, ground.level) const offset = datum.floorElevation - gradeElevation - const foundation = foundationReadingOf(nodes, buildingId) - const aboveGrade = foundation.construction.seatAboveGrade return { buildingId, levelId: ground.level.id, @@ -88,11 +61,6 @@ export function groundSeat( floorElevation: datum.floorElevation, gradeElevation, offset, - aboveGrade, - foundation, - seated: - offset >= -GROUND_SEAT_TOLERANCE && - offset <= Math.max(aboveGrade, GROUND_FLOOR_ABOVE_GRADE) + GROUND_SEAT_TOLERANCE, - atFoundationTop: Math.abs(offset - aboveGrade) <= GROUND_SEAT_TOLERANCE, + seated: Math.abs(offset) <= GROUND_SEAT_TOLERANCE, } } diff --git a/packages/core/src/registry/types.ts b/packages/core/src/registry/types.ts index d05aacf375..f8c45ba2e6 100644 --- a/packages/core/src/registry/types.ts +++ b/packages/core/src/registry/types.ts @@ -1819,15 +1819,6 @@ export type Capabilities = { * in the editor. */ sceneAction?: SceneActionCapability - /** - * The node draws the foundation of its parent level itself (a framing plugin that pours the - * footing and stem from the building's record). While it returns `true` the generic foundation - * the viewer derives from the walls (`genericFoundation`) is not drawn under that level, so - * nothing is drawn twice. Only the building's lowest level carries a foundation. A picture shows - * the finished house, where the plugin draws none above the ground: it returns `false` while - * `isCaptureSessionOn()`, so the generic one is drawn for the picture. - */ - drawsFoundation?: (node: AnyNode) => boolean /** * Moving parts people run: Play/Stop in the action menu, E, and the * walkthrough read this instead of a kind name, so any kind (plugins diff --git a/packages/core/src/systems/wall/wall-assembly.ts b/packages/core/src/systems/wall/wall-assembly.ts index c3e4698ab9..e0ae7a262b 100644 --- a/packages/core/src/systems/wall/wall-assembly.ts +++ b/packages/core/src/systems/wall/wall-assembly.ts @@ -903,7 +903,7 @@ export type ExposedStructure = 'cmu' | 'concrete' * block or cast concrete above grade, and from under the ground, is what it is. `null` for a wall * with a cladding (`wallAssemblyFinishRef` speaks for it), a lining outside the core (a * partition), a framed or foam core (`wood`, `lgs`, `icf`), and a wall whose exterior side is not - * yet resolved. The viewer draws it as the generic foundation draws the same structure. + * yet resolved. */ export function wallAssemblyExposedStructure( wall: Pick, diff --git a/packages/editor/src/components/ui/floating-level-selector.tsx b/packages/editor/src/components/ui/floating-level-selector.tsx index 90a79f4ed0..33133af19e 100644 --- a/packages/editor/src/components/ui/floating-level-selector.tsx +++ b/packages/editor/src/components/ui/floating-level-selector.tsx @@ -472,7 +472,6 @@ function SortableLevelRow({ type GroundLineState = { levelId: string seated: boolean - atFoundationTop: boolean offset: number } @@ -636,7 +635,6 @@ export function FloatingLevelSelector() { ? { levelId: seat.levelId, seated: seat.seated, - atFoundationTop: seat.atFoundationTop, offset: seat.offset, } : null @@ -845,7 +843,7 @@ export function FloatingLevelSelector() { } onDuplicate={(preset) => handleDuplicateLevel(level, preset)} onPaste={() => handlePasteToLevel(level)} - isGround={ground?.levelId === level.id && ground.atFoundationTop} + isGround={ground?.levelId === level.id && ground.seated} onRequestDelete={() => setDeletingLevel(level)} onSetGround={() => handleSetGround(level.id)} onSelect={() => { diff --git a/packages/editor/src/lib/add-storey.test.ts b/packages/editor/src/lib/add-storey.test.ts index 9336d27346..5619121a17 100644 --- a/packages/editor/src/lib/add-storey.test.ts +++ b/packages/editor/src/lib/add-storey.test.ts @@ -145,11 +145,11 @@ describe('setGroundFloor', () => { const standing = (id: string) => levelGradeStanding(useScene.getState().nodes, id) - test('seats the building so the level stands 8 in over grade, the ones under it below it, in one undo step', () => { + test('seats the building so the level stands on grade, the ones under it below it, in one undo step', () => { expect(standing('level_lower')).toBe('at-grade') expect(setGroundFloor('level_reception' as LevelNode['id'])).toBe(true) const nodes = useScene.getState().nodes - expect((nodes[BUILDING as AnyNodeId] as BuildingNode).position).toEqual([0, -3.197, 0]) + expect((nodes[BUILDING as AnyNodeId] as BuildingNode).position).toEqual([0, -3.4, 0]) expect((nodes[BUILDING as AnyNodeId] as BuildingNode).groundLevelId).toBe('level_reception') expect(standing('level_reception')).toBe('at-grade') expect(standing('level_lower')).toBe('below-grade') @@ -172,6 +172,6 @@ describe('setGroundFloor', () => { const basement = addStoreyBelow(BUILDING) expect(basement.level).toBe(-3) expect(standing(basement.id)).toBe('below-grade') - expect(levelFloorWorldY(useScene.getState().nodes, 'level_reception')).toBeCloseTo(0.203, 9) + expect(levelFloorWorldY(useScene.getState().nodes, 'level_reception')).toBeCloseTo(0, 9) }) }) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 3b336b036f..7b80a46f52 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -433,7 +433,7 @@ is a "pitch" fraction like `"1/4 pitch"`, which is rise over span. | `merge_windows` | Make two windows that exist one window, as the editor's Merge windows button does; nothing is recreated. On two walls that meet at a corner, each window within 0.30 m of it, they become one corner window (the `add_corner_window` result): each is slid to the corner keeping its width, the glass fused (a fixed window's; other types meet at a post), and both take the first window's height, sill and type, so name first the window whose look you want; the corner is refused over 170° or under 10°. On one wall, two windows with at most 0.30 m between them and nothing between become one window spanning both (overlapping or one inside the other, their union), from the lower sill to the higher head, with the first window's type and style. Use it for two windows already built that open a corner or one wide opening (`verify_scene`'s `corner_unjoined` names a pair for the first); `add_corner_window` builds a new pair. By hand: select two windows and use Merge windows in the multi-selection panel, or place or drag a window near a corner where one waits and click or release (Alt places it plain). | `{ windowIds: [a, b] }` | `{ kind: 'corner' \| 'same_wall', windowIds, removedIds, achieved }`; refusals `window_not_found`, `not_a_window`, `same_window`, `window_not_on_wall`, `window_already_joined` (unwrap it first), `windows_already_joined`, `windows_not_adjacent`, `opening_between`, `walls_not_meeting`, `corner_angle`, `window_not_at_corner`, `height_exceeds_wall`, `opening_overlap` | | `apply_patch` | Batched create/update/delete/move, validated and dry-run before commit. Batch-first is the default: send all create/update/delete ops for a build step in one atomic call (stable order, later ops may reference earlier created ids); do not loop one-op calls. A create with an id already in the scene is refused (`node_exists`); delete it earlier in the same patch to replace it. Updates cannot change `id` or `type` (`identity_change`), `object` or `children` (`immutable_field`), move a node under a missing or childless parent (`invalid_parent`), or add schema issues (`invalid_update`); default gutters and downspouts a delete regenerates are addressable only in a later call (`regenerated_default`). Refusals are tool errors with JSON text `{ code, patchIndex, id, message }`. A level created without a `height`, or an update that clears it, gets the height the editor's load derives from what the level holds (an empty level: 2.5 m), one line per level in `notes`. A roof the patch makes or moves onto the storey whose walls carry it is seated on the level above those walls, one line per roof in `notes`; a new storey at or above the roof level moves it up. Refused: storey content on a roof level (`roof_level`), declaring a level that holds storey content the roof level (`roof_level_holds_storey`), floor indexes that put the roof level under a storey (`roof_level_on_top`). | `{ patches: Patch[] }` | `{ applied: number, notes?: string[] }` | | `add_level` | Add an empty level to a building, as the editor does: on top of its storeys, under its roof level (which moves up one), or below the lowest for a basement (every existing floor, the ground floor included, keeps its place). Omit `buildingId` for the scene's only building. | `{ buildingId?, position?, name?, height? }` | `{ levelId, buildingId, floorIndex, height, shiftedLevelIds? }`; refusals `building_required`, `building_not_found`, `no_building` | -| `set_ground_level` | Make a level the building's ground floor, as the level panel's "Set as ground floor": the building names it, is seated so that floor stands over grade as the building's foundation construction seats it, the top of the foundation (8 in, 0.203 m, on block: the default and the US; 0.15 m on cast concrete in Europe; height only, the plan stays), and the floor indexes are renumbered so it is 0 and the levels under it are the basements. | `{ levelId }` | `{ levelId, buildingId, floorElevation, aboveGrade, foundation { region, construction, basis }, movedBuildingBy, renumbered, unchanged? }`; refusals `level_not_found`, `not_a_level`, `no_building`, `not_a_storey` | +| `set_ground_level` | Make a level the building's ground floor, as the level panel's "Set as ground floor": the building names it, is seated so that floor stands on grade (height only, the plan stays), and the floor indexes are renumbered so it is 0 and the levels under it are the basements. | `{ levelId }` | `{ levelId, buildingId, floorElevation, gradeElevation, movedBuildingBy, renumbered, unchanged? }`; refusals `level_not_found`, `not_a_level`, `no_building`, `not_a_storey` | | `add_wall` | Add a wall to a level, straight or, with `curveOffset`, an arc. Omit `levelId` for the lowest storey. wallType railing builds a guard (default 0.9144 m high); railing sets style, posts, infill and cap; postSize sets thickness. | `{ start, end, levelId?, thickness?, height?, curveOffset?, type?, wallType?, railing? }` | `{ wallId, levelId, length }`; refusals `roof_level`, `wall_too_short`, `level_not_found`, `unknown_wall_type` | | `set_wall_type` | Apply a preset or project wall assembly to existing standard walls; copies layers and total thickness. null clears the assembly. | `{ wallIds, type }` | `{ ok, wallIds, type }`; refusals `unknown_wall_type`, `target_not_found`, `curtain_wall`, `railing_wall` | | `add_column` | Add or rebuild a column. role post uses the Post tile: square pressure-treated wood, postSize 4x4, 6x6 (default), 8x8; postBase none (default), post-base (steel), pier (concrete). | `{ x?, z?, level?, role?, postSize?, postBase?, height?, nodeId?, ... }` | `{ columnId, nodeId, height, width, depth }`; `not_a_post` for post choices on an ordinary column | diff --git a/packages/nodes/src/site/generic-foundation-geometry.test.ts b/packages/nodes/src/site/generic-foundation-geometry.test.ts deleted file mode 100644 index 3b2148d20d..0000000000 --- a/packages/nodes/src/site/generic-foundation-geometry.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { expect, test } from 'bun:test' -import type { FoundationMember } from '@pascal-app/core' -import { buildFoundationMesh } from './generic-foundation-geometry' - -const run = (over: Partial = {}): FoundationMember => ({ - kind: 'stem', - levelId: 'level_g', - from: [0, 0], - to: [4, 0], - width: 0.2, - bottomY: -0.5, - topY: 0.25, - ...over, -}) - -test('a run is a closed box: eight corners over six faces, twelve triangles', () => { - const mesh = buildFoundationMesh([run()], 'stem') - expect(mesh?.positions.length).toBe(24 * 3) - expect(mesh?.indices.length).toBe(12 * 3) -}) - -test('the box spans the run, its width and its height', () => { - const mesh = buildFoundationMesh([run()], 'stem') - const axis = (offset: number) => - Array.from(mesh?.positions ?? []).filter((_, index) => index % 3 === offset) - const [xs, ys, zs] = [axis(0), axis(1), axis(2)] - expect([Math.min(...xs), Math.max(...xs)]).toEqual([0, 4]) - expect([Math.min(...ys), Math.max(...ys)]).toEqual([-0.5, 0.25]) - const [lowZ, highZ] = [Math.min(...zs), Math.max(...zs)] - expect(highZ - lowZ).toBeCloseTo(0.2, 6) -}) - -test('every triangle winds outward, as its own normal says', () => { - const mesh = buildFoundationMesh([run({ from: [1, 1], to: [-2, 3.5] })], 'stem') - if (!mesh) throw new Error('no mesh') - const point = (i: number) => [0, 1, 2].map((k) => mesh.positions[i * 3 + k] as number) - for (let t = 0; t < mesh.indices.length; t += 3) { - const [a, b, c] = [0, 1, 2].map((k) => point(mesh.indices[t + k] as number)) as number[][] - const ab = [b[0]! - a[0]!, b[1]! - a[1]!, b[2]! - a[2]!] - const ac = [c[0]! - a[0]!, c[1]! - a[1]!, c[2]! - a[2]!] - const winding = [ - ab[1]! * ac[2]! - ab[2]! * ac[1]!, - ab[2]! * ac[0]! - ab[0]! * ac[2]!, - ab[0]! * ac[1]! - ab[1]! * ac[0]!, - ] - const i = mesh.indices[t] as number - const normal = [0, 1, 2].map((k) => mesh.normals[i * 3 + k] as number) - expect( - winding[0]! * normal[0]! + winding[1]! * normal[1]! + winding[2]! * normal[2]!, - ).toBeGreaterThan(0) - } -}) - -test('the distance along the run follows the wall, from its start', () => { - const mesh = buildFoundationMesh([run()], 'stem') - expect(Math.max(...(mesh?.along ?? []))).toBeCloseTo(4, 6) - expect(Math.min(...(mesh?.along ?? []))).toBe(0) -}) - -test('a kind with no runs has no mesh, and a run with no height draws nothing', () => { - expect(buildFoundationMesh([run()], 'footing')).toBeNull() - expect(buildFoundationMesh([run({ topY: -0.5 })], 'stem')).toBeNull() -}) - -test('runs of the same kind join into one mesh', () => { - const mesh = buildFoundationMesh([run(), run({ from: [4, 0], to: [4, 3] })], 'stem') - expect(mesh?.indices.length).toBe(2 * 12 * 3) -}) diff --git a/packages/nodes/src/site/generic-foundation-geometry.ts b/packages/nodes/src/site/generic-foundation-geometry.ts deleted file mode 100644 index 9b4c32ac9a..0000000000 --- a/packages/nodes/src/site/generic-foundation-geometry.ts +++ /dev/null @@ -1,91 +0,0 @@ -import type { FoundationMember } from '@pascal-app/core' - -/** The foundation members of one kind as one indexed mesh, in world coordinates. */ -export type FoundationMesh = { - positions: Float32Array - normals: Float32Array - /** Metres along the run, for the courses of block to bond along the wall. */ - along: Float32Array - indices: Uint32Array -} - -type Vec3 = readonly [number, number, number] - -const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]] -const cross = (a: Vec3, b: Vec3): Vec3 => [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], -] -const dot = (a: Vec3, b: Vec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2] - -/** - * The runs of `kind` as closed boxes, six faces each with its own flat normal. A run is a prism on - * the plan line `from` to `to`, `width` across, from `bottomY` to `topY`. Corners are closed by the - * runs themselves (they overlap), so the boxes carry no joins. - */ -export function buildFoundationMesh( - members: readonly FoundationMember[], - kind: FoundationMember['kind'], -): FoundationMesh | null { - const runs = members.filter((member) => member.kind === kind) - if (runs.length === 0) return null - const positions: number[] = [] - const normals: number[] = [] - const along: number[] = [] - const indices: number[] = [] - - const quad = (corners: [Vec3, Vec3, Vec3, Vec3], outward: Vec3, alongAt: number[]) => { - const [a, b, c] = corners - const facing = dot(cross(sub(b, a), sub(c, a)), outward) >= 0 - const order = facing ? [0, 1, 2, 3] : [0, 3, 2, 1] - const base = positions.length / 3 - for (const index of order) { - positions.push(...(corners[index] as Vec3)) - normals.push(...outward) - along.push(alongAt[index] as number) - } - indices.push(base, base + 1, base + 2, base, base + 2, base + 3) - } - - for (const { from, to, width, bottomY, topY } of runs) { - const dx = to[0] - from[0] - const dz = to[1] - from[1] - const length = Math.hypot(dx, dz) - if (length < 1e-9 || topY - bottomY < 1e-9) continue - const [ux, uz] = [dx / length, dz / length] - const [nx, nz] = [-uz, ux] - const half = width / 2 - const at = (end: [number, number], side: number, y: number): Vec3 => [ - end[0] + nx * half * side, - y, - end[1] + nz * half * side, - ] - const [a0, a1, a2, a3] = [ - at(from, 1, bottomY), - at(to, 1, bottomY), - at(to, -1, bottomY), - at(from, -1, bottomY), - ] - const [b0, b1, b2, b3] = [ - at(from, 1, topY), - at(to, 1, topY), - at(to, -1, topY), - at(from, -1, topY), - ] - const run = [0, length, length, 0] - quad([b0, b1, b2, b3], [0, 1, 0], run) - quad([a0, a1, a2, a3], [0, -1, 0], run) - quad([a0, a1, b1, b0], [nx, 0, nz], [0, length, length, 0]) - quad([a3, a2, b2, b3], [-nx, 0, -nz], [0, length, length, 0]) - quad([a0, a3, b3, b0], [-ux, 0, -uz], [0, 0, 0, 0]) - quad([a1, a2, b2, b1], [ux, 0, uz], [length, length, length, length]) - } - if (indices.length === 0) return null - return { - positions: new Float32Array(positions), - normals: new Float32Array(normals), - along: new Float32Array(along), - indices: new Uint32Array(indices), - } -} diff --git a/packages/nodes/src/site/generic-foundation.test.tsx b/packages/nodes/src/site/generic-foundation.test.tsx deleted file mode 100644 index f455caf37b..0000000000 --- a/packages/nodes/src/site/generic-foundation.test.tsx +++ /dev/null @@ -1,295 +0,0 @@ -import { afterEach, beforeEach, expect, test } from 'bun:test' -import { - type AnyNode, - type AnyNodeId, - BaseNode, - BuildingNode, - emitter, - isCaptureSessionOn, - LevelNode, - nodeRegistry, - nodeType, - objectId, - registerNode, - SiteNode, - SlabNode, - useScene, - WallNode, -} from '@pascal-app/core' -import { SITE_FOUNDATION, siteFoundation, useViewer } from '@pascal-app/viewer' -import { act, create } from '@react-three/test-renderer' -import type { Mesh, Object3D } from 'three' -import type { MeshLambertNodeMaterial } from 'three/webgpu' -import { sameFoundation } from './generic-foundation' -import { SiteRenderer } from './renderer' - -// The generic foundation is drawn under every building's exterior walls (generic-foundation.tsx): -// two meshes, made once, shown whatever the level shown and wherever the eye is; the walkthrough -// has none. - -const corners: Array<[number, number]> = [ - [0, 0], - [8, 0], - [8, 6], - [0, 6], -] - -const lot = () => - SiteNode.parse({ - id: 'site_lot', - polygon: { - type: 'polygon', - points: [ - [-10, -10], - [10, -10], - [10, 10], - [-10, 10], - ], - }, - }) - -let previous: { - viewer: ReturnType - scene: ReturnType -} -beforeEach(() => { - previous = { viewer: useViewer.getState(), scene: useScene.getState() } -}) -afterEach(() => { - useViewer.setState(previous.viewer, true) - useScene.setState(previous.scene, true) -}) -function ringOf(levelId: string) { - return corners.map((start, index) => - WallNode.parse({ - id: `wall_${levelId}_${index}`, - parentId: levelId, - start, - end: corners[(index + 1) % 4], - }), - ) -} - -/** A house on the flat site, over a basement when `basement` is set (the villa's numbers). */ -function setHouse(basement: boolean, extra: AnyNode[] = []) { - const levels = basement ? ['level_b', 'level_g'] : ['level_g'] - const nodes: AnyNode[] = [ - BuildingNode.parse({ id: 'building_a', children: levels }), - ...levels.flatMap((levelId) => { - const walls = ringOf(levelId) - return [ - LevelNode.parse({ - id: levelId, - parentId: 'building_a', - level: levelId === 'level_b' ? -1 : 0, - baseElevation: levelId === 'level_b' ? -3.63 : 0, - height: 3.4, - children: [...walls.map((wall) => wall.id), `slab_${levelId}`], - }), - SlabNode.parse({ - id: `slab_${levelId}`, - parentId: levelId, - elevation: 0.05, - thickness: 0.05, - polygon: corners, - }), - ...walls, - ] - }), - ...extra, - ] - useScene.setState({ - nodes: Object.fromEntries(nodes.map((node) => [node.id, node])) as Record, - }) -} - -const parts = (root: Object3D) => { - const found: Mesh[] = [] - root.traverse((object) => { - if (object.userData[SITE_FOUNDATION] === true) found.push(object as Mesh) - }) - return found.sort((a, b) => - String(a.userData.genericFoundation).localeCompare(String(b.userData.genericFoundation)), - ) -} - -const names = (root: Object3D) => parts(root).map((part) => part.userData.genericFoundation) - -test('a house stands on a footing and a block wall, marked, found by captures and stripped from exports; over a basement only the footing; the walkthrough has none', async () => { - setHouse(false) - const renderer = await create() - try { - const scene = renderer.scene.instance as Object3D - const found = parts(scene) - expect(names(scene)).toEqual(['footing', 'stem']) - expect(found.every((part) => part.userData.pascalExport === 'strip')).toBe(true) - // The capture finds them by their mark, through the site the renderer registered. - expect(siteFoundation()).toEqual(found) - await act(async () => useViewer.setState({ walkthroughMode: true })) - expect(found.map((part) => part.visible)).toEqual([false, false]) - await act(async () => useViewer.setState({ walkthroughMode: false })) - expect(found.map((part) => part.visible)).toEqual([true, true]) - } finally { - await renderer.unmount() - } - setHouse(true) - const over = await create() - try { - expect(names(over.scene.instance as Object3D)).toEqual(['footing']) - } finally { - await over.unmount() - } -}) - -const paris = () => - SiteNode.parse({ - id: 'site_paris', - dossier: { - provider: 'pascal-map', - asOf: '2026-10-16', - address: { formatted: '12 Rue de Rivoli, 75004 Paris, France' }, - sections: {}, - }, - }) - -test('the stem is drawn in what the building is built of: block, concrete in Europe', async () => { - const materialOf = async (extra: AnyNode[]) => { - setHouse(false, extra) - const renderer = await create() - try { - const [footing, stem] = parts(renderer.scene.instance as Object3D) as [Mesh, Mesh] - return stem.material === footing.material ? 'concrete' : 'masonry' - } finally { - await renderer.unmount() - } - } - expect(await materialOf([])).toBe('masonry') - expect(await materialOf([paris()])).toBe('concrete') -}) - -test('switching floors and crossing the ground swap and rebuild no foundation mesh or material, and an edit that leaves the foundation as it was rebuilds none of it', async () => { - setHouse(true) - const renderer = await create() - try { - const scene = renderer.scene.instance as Object3D - const snapshot = () => - parts(scene).map((part) => { - const material = part.material as MeshLambertNodeMaterial - return { part, geometry: part.geometry, material, version: material.version } - }) - const before = snapshot() - for (const [levelId, below, under] of [ - ['level_b', true, false], - ['level_g', false, false], - ['level_b', true, true], - ['level_g', false, true], - ] as const) { - await act(async () => - useViewer.setState({ - selection: { ...useViewer.getState().selection, levelId } as never, - hideLevelsAboveSelection: below, - belowGrade: below, - gradeStanding: below ? 'below-grade' : 'at-grade', - eyeUnderGround: under, - }), - ) - await renderer.advanceFrames(2, 0.05) - const after = snapshot() - expect(after).toHaveLength(before.length) - after.forEach((entry, index) => { - expect(entry.part).toBe(before[index]?.part) - expect(entry.geometry).toBe(before[index]?.geometry) - expect(entry.material).toBe(before[index]?.material) - expect(entry.version).toBe(before[index]?.version ?? -1) - expect(entry.part.visible).toBe(true) - }) - } - await act(async () => { - const nodes = useScene.getState().nodes - const level = nodes['level_g' as AnyNodeId] - if (level?.type !== 'level') throw new Error('fixture') - useScene.setState({ nodes: { ...nodes, level_g: { ...level, name: 'Ground' } } }) - }) - expect(snapshot().map((entry) => entry.geometry)).toEqual(before.map((entry) => entry.geometry)) - } finally { - await renderer.unmount() - } -}) - -test("a plugin that draws a level's foundation under the ground takes that level's members out of the geometry, and gives them back", async () => { - setHouse(true) - const renderer = await create() - try { - const scene = renderer.scene.instance as Object3D - expect(names(scene)).toEqual(['footing']) - // another level's foundation is not this one's: nothing leaves - await act(async () => useViewer.setState({ pluginFoundationLevelIds: ['level_g'] })) - expect(names(scene)).toEqual(['footing']) - await act(async () => useViewer.setState({ pluginFoundationLevelIds: ['level_b'] })) - expect(names(scene)).toEqual([]) - await act(async () => useViewer.setState({ pluginFoundationLevelIds: [] })) - expect(names(scene)).toEqual(['footing']) - } finally { - await renderer.unmount() - } -}) - -test('a plugin that steps aside from a picture has the foundation drawn for it while a capture session is on, with no scene edit', async () => { - const Framer = BaseNode.extend({ - id: objectId('framer'), - type: nodeType('test:picture-framer-site'), - }) - const restoreRegistry = nodeRegistry._snapshot() - registerNode({ - kind: 'test:picture-framer-site', - schemaVersion: 1, - schema: Framer, - category: 'utility', - defaults: () => ({}), - capabilities: { drawsFoundation: () => !isCaptureSessionOn() }, - }) - setHouse(false) - const nodes = useScene.getState().nodes - const level = nodes['level_g' as AnyNodeId] - if (level?.type !== 'level') throw new Error('fixture') - useScene.setState({ - nodes: { - ...nodes, - level_g: { ...level, children: [...level.children, 'framer_g'] }, - framer_g: Framer.parse({ id: 'framer_g', parentId: 'level_g' }), - } as Record, - }) - const session = (active: boolean) => - emitter.emit('camera-controls:capture-session', { owner: 'foundation-site-test', active }) - const renderer = await create() - try { - const scene = renderer.scene.instance as Object3D - const names = () => parts(scene).map((part) => part.userData.genericFoundation) - expect(names()).toEqual([]) - await act(async () => session(true)) - expect(names()).toEqual(['footing', 'stem']) - await act(async () => session(false)) - expect(names()).toEqual([]) - } finally { - session(false) - await renderer.unmount() - restoreRegistry() - } -}) - -test('foundations are the same when every run is', () => { - const run = { - kind: 'stem' as const, - material: 'cmu' as const, - levelId: 'level_g', - from: [0, 0] as [number, number], - to: [4, 0] as [number, number], - width: 0.2, - bottomY: -0.3, - topY: 0, - } - expect(sameFoundation([run], [{ ...run }])).toBe(true) - expect(sameFoundation([run], [{ ...run, topY: 0.1 }])).toBe(false) - expect(sameFoundation([run], [{ ...run, material: 'concrete' }])).toBe(false) - expect(sameFoundation([run], [])).toBe(false) -}) diff --git a/packages/nodes/src/site/generic-foundation.tsx b/packages/nodes/src/site/generic-foundation.tsx deleted file mode 100644 index ab92e077f1..0000000000 --- a/packages/nodes/src/site/generic-foundation.tsx +++ /dev/null @@ -1,151 +0,0 @@ -'use client' - -import { - type FoundationMember, - genericFoundation, - isCaptureSessionOn, - subscribeCaptureSessions, - useScene, -} from '@pascal-app/core' -import { - BLOCK_MASONRY, - concreteMaterial, - masonryMaterial, - SITE_FOUNDATION, - useViewer, -} from '@pascal-app/viewer' -import { useEffect, useMemo, useRef, useSyncExternalStore } from 'react' -import { BufferAttribute, BufferGeometry } from 'three' -import type { MeshLambertNodeMaterial } from 'three/webgpu' -import { buildFoundationMesh, type FoundationMesh } from './generic-foundation-geometry' -import { noopRaycast } from './ground-veil' - -/** - * The generic foundation under the buildings (`genericFoundation` in core): a concrete footing and - * a foundation wall, drawn from the walls and never stored, of the building's foundation - * construction: block by default, cast concrete in Europe (each stem run carries its `material`). It is always drawn: the ground hides the part below it from above - * (the eye under the ground, or looking through the hole over a level below grade, is what sees - * it), and the course the building's seat leaves above grade reads as what it is built of in the - * normal view. The walkthrough draws none of it. - * - * One mesh per material in use, the materials made once; nothing about them depends on the level - * shown or on where the eye is, so a floor switch or a dive compiles nothing. Geometry is rebuilt - * only when the foundation itself changes, or when a plugin takes a level's foundation over under - * the ground (`pluginFoundationLevelIds`): that level's members leave the geometry while it draws - * them. - */ - -function geometryOf(mesh: FoundationMesh | null): BufferGeometry | null { - if (!mesh) return null - const geometry = new BufferGeometry() - geometry.setAttribute('position', new BufferAttribute(mesh.positions, 3)) - geometry.setAttribute('normal', new BufferAttribute(mesh.normals, 3)) - geometry.setAttribute('along', new BufferAttribute(mesh.along, 1)) - geometry.setIndex(new BufferAttribute(mesh.indices, 1)) - return geometry -} - -/** The stem runs built of `material` as one geometry. */ -function stemGeometry( - members: readonly FoundationMember[], - material: FoundationMember['material'], -) { - return geometryOf( - buildFoundationMesh( - members.filter((member) => member.material === material), - 'stem', - ), - ) -} - -export function sameFoundation(a: readonly FoundationMember[], b: readonly FoundationMember[]) { - return ( - a.length === b.length && - a.every((member, index) => { - const other = b[index] - return ( - other !== undefined && - member.kind === other.kind && - member.material === other.material && - member.levelId === other.levelId && - member.width === other.width && - member.bottomY === other.bottomY && - member.topY === other.topY && - member.from[0] === other.from[0] && - member.from[1] === other.from[1] && - member.to[0] === other.to[0] && - member.to[1] === other.to[1] - ) - }) - ) -} - -function useFoundationMembers(): readonly FoundationMember[] { - // Stable across store writes that leave the foundation as it was. - const kept = useRef([]) - // A capture session starting or ending changes what a plugin claims, though no node changes: - // the picture shows the finished house, with the generic course a framing plugin gives back. - useSyncExternalStore(subscribeCaptureSessions, isCaptureSessionOn, () => false) - return useScene((state) => { - const next = genericFoundation(state.nodes) - if (sameFoundation(next, kept.current)) return kept.current - kept.current = next - return next - }) -} - -function FoundationPart({ - geometry, - material, - visible, - part, -}: { - geometry: BufferGeometry | null - material: MeshLambertNodeMaterial - visible: boolean - part: FoundationMember['kind'] -}) { - useEffect(() => () => geometry?.dispose(), [geometry]) - if (!geometry) return null - return ( - - ) -} - -export function GenericFoundation() { - const derived = useFoundationMembers() - const takenOver = useViewer((state) => state.pluginFoundationLevelIds) - const members = useMemo( - () => - takenOver.length === 0 - ? derived - : derived.filter((member) => !takenOver.includes(member.levelId)), - [derived, takenOver], - ) - const shown = useViewer((state) => !state.walkthroughMode) - const concrete = useMemo(concreteMaterial, []) - const block = useMemo(() => masonryMaterial(BLOCK_MASONRY), []) - useEffect( - () => () => { - concrete.dispose() - block.dispose() - }, - [concrete, block], - ) - const footing = useMemo(() => geometryOf(buildFoundationMesh(members, 'footing')), [members]) - const blockStem = useMemo(() => stemGeometry(members, 'cmu'), [members]) - const concreteStem = useMemo(() => stemGeometry(members, 'concrete'), [members]) - return ( - <> - - - - - ) -} diff --git a/packages/nodes/src/site/ground-veil.test.tsx b/packages/nodes/src/site/ground-veil.test.tsx index 15740a6e2c..bc57ece310 100644 --- a/packages/nodes/src/site/ground-veil.test.tsx +++ b/packages/nodes/src/site/ground-veil.test.tsx @@ -5,8 +5,6 @@ import { BuildingNode, createTerrainField, encodeTerrainField, - GROUND_PIT_PLATE_CLEARANCE, - genericFoundation, groundPitFloorY, LevelNode, SiteNode, @@ -513,21 +511,14 @@ function withSeatedBasement() { }) } -test('the pit draws its floor off the plane the footing under the basement stops on', async () => { +test('the pit draws its floor where core says, off the plane of the plate underside', async () => { withSeatedBasement() const renderer = await create() await act(async () => showLevel('level_b')) groundHoleOpenNode().value = 1 await renderer.advanceFrames(3, 0.05) const { nodes } = useScene.getState() - const footings = genericFoundation(nodes).filter((member) => member.kind === 'footing') - expect(footings).toHaveLength(4) - // What the pit draws is what core says, and the footing's top is not on its plane. expect(groundPitDrawnFloorNow()).toBeCloseTo(groundPitFloorY(nodes, 'level_b') ?? Number.NaN, 9) - for (const footing of footings) - expect(Math.abs(footing.topY - groundPitDrawnFloorNow())).toBeGreaterThanOrEqual( - GROUND_PIT_PLATE_CLEARANCE - 1e-9, - ) // The pit still goes down to the floor of the level shown (the floor top, -2.647). expect(groundPitFloorNow()).toBeCloseTo(-2.647, 3) await renderer.unmount() diff --git a/packages/nodes/src/site/renderer.tsx b/packages/nodes/src/site/renderer.tsx index bb9be36513..0d3f88a16c 100644 --- a/packages/nodes/src/site/renderer.tsx +++ b/packages/nodes/src/site/renderer.tsx @@ -57,7 +57,6 @@ import { vec2, } from 'three/tsl' import { MeshLambertNodeMaterial } from 'three/webgpu' -import { GenericFoundation } from './generic-foundation' import { GroundHole, groundHoleColorNode, @@ -698,7 +697,6 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { return ( - sceneRegistry.clear()) @@ -29,17 +22,15 @@ function site() { veil.userData[SITE_GROUND] = 'veil' veil.visible = false const lotLine = new Mesh() - const foundation = new Mesh() - foundation.userData[SITE_FOUNDATION] = true - group.add(building, ground, veil, lotLine, foundation) + group.add(building, ground, veil, lotLine) sceneRegistry.nodes.set('site_a', group) sceneRegistry.byType.site?.add('site_a') - return { ground, veil, lotLine, foundation } + return { ground, veil, lotLine } } test("the site's surfaces are its own shown meshes, not the buildings it holds", () => { - const { ground, lotLine, foundation } = site() - expect(siteSurfaces()).toEqual([ground, lotLine, foundation]) + const { ground, lotLine } = site() + expect(siteSurfaces()).toEqual([ground, lotLine]) }) test('the ground is the solid surfaces and their veils, shown or not; the lines on it are not', () => { @@ -69,24 +60,3 @@ test('a capture stands the whole building on solid ground, then gives the veil b expect(ground.layers.isEnabled(SCENE_LAYER)).toBe(false) expect(veil.visible).toBe(true) }) - -test('the generic foundation is found by its mark, shown or not', () => { - const { foundation } = site() - expect(siteFoundation()).toEqual([foundation]) -}) - -test('a capture through the veil leaves the foundation out, then gives it back', () => { - const { foundation } = site() - const restore = temporarilyVeilGround(true) - expect(foundation.layers.isEnabled(SCENE_LAYER)).toBe(false) - restore() - expect(foundation.layers.isEnabled(SCENE_LAYER)).toBe(true) -}) - -test('a capture of the whole building on solid ground keeps the foundation as it is', () => { - const { foundation } = site() - const restore = temporarilyVeilGround(false) - expect(foundation.layers.isEnabled(SCENE_LAYER)).toBe(true) - restore() - expect(foundation.layers.isEnabled(SCENE_LAYER)).toBe(true) -}) diff --git a/packages/viewer/src/lib/site-surfaces.ts b/packages/viewer/src/lib/site-surfaces.ts index 2d25565f36..b64c84fccd 100644 --- a/packages/viewer/src/lib/site-surfaces.ts +++ b/packages/viewer/src/lib/site-surfaces.ts @@ -8,12 +8,6 @@ import { temporarilySetGroundAside } from './scene-visibility' */ export const SITE_GROUND = 'siteGround' -/** - * `userData` key marking the generic foundation under the buildings (footing and stem, drawn under - * the ground): a capture that sees through the veil leaves it out, as it left it out before it was drawn. - */ -export const SITE_FOUNDATION = 'siteFoundation' - /** * `solid`: the lot's fill, its sculpted terrain, the horizon disc. `veil`: what is drawn in their * place over a level below grade, the grade ring with it. @@ -36,17 +30,6 @@ export function siteSurfaces(): Object3D[] { return surfaces } -/** The site's generic foundation meshes, shown or not. */ -export function siteFoundation(): Object3D[] { - const foundation: Object3D[] = [] - for (const siteId of sceneRegistry.byType.site ?? []) { - for (const child of sceneRegistry.nodes.get(siteId)?.children ?? []) { - if (child.userData[SITE_FOUNDATION] === true) foundation.push(child) - } - } - return foundation -} - /** The site's ground by role, shown or not: the veil is hidden until a level below grade is shown. */ export function siteGround(): Record { const ground: Record = { solid: [], veil: [] } @@ -67,13 +50,10 @@ export function siteGround(): Record { export function temporarilyVeilGround(veiled: boolean): () => void { const { solid, veil } = siteGround() const restoreSolid = temporarilySetGroundAside(solid, veiled) - // Seen through a veil the footing under a floor below grade would show: the picture has none. - const restoreFoundation = veiled ? temporarilySetGroundAside(siteFoundation(), true) : () => {} const flipped = veil.filter((surface) => surface.visible !== veiled) for (const surface of flipped) surface.visible = veiled return () => { for (const surface of flipped) surface.visible = !veiled - restoreFoundation() restoreSolid() } } diff --git a/packages/viewer/src/store/use-viewer.ts b/packages/viewer/src/store/use-viewer.ts index dcd1897824..023e25ecb3 100644 --- a/packages/viewer/src/store/use-viewer.ts +++ b/packages/viewer/src/store/use-viewer.ts @@ -194,13 +194,6 @@ type ViewerState = { * viewer's underground ambiance from the camera; never persisted. */ eyeUnderGround: boolean - /** - * Levels whose foundation a plugin is drawing under the ground right now (a framing plugin pours - * the real footing and stem from the building's record). The generic foundation derived from the - * walls is not drawn under these levels, so nothing is drawn twice. Written by that plugin while - * its meshes are mounted, empty otherwise; never persisted. - */ - pluginFoundationLevelIds: readonly string[] /** * The world is turned, or turning, to earth (the underground ambiance's factor is above 0). * Its factor itself eases every frame and lives with the shaders, not here; this flips only at @@ -665,7 +658,6 @@ const useViewer = create()( hasLevelBelowGrade: false, diveAvailable: false, eyeUnderGround: false, - pluginFoundationLevelIds: [], ambianceActive: false, undergroundLook: DEFAULT_UNDERGROUND_LOOK, setUndergroundLook: (look) => diff --git a/packages/viewer/src/systems/wall/wall-materials.ts b/packages/viewer/src/systems/wall/wall-materials.ts index 5054f9cbee..dfeca2c713 100644 --- a/packages/viewer/src/systems/wall/wall-materials.ts +++ b/packages/viewer/src/systems/wall/wall-materials.ts @@ -143,7 +143,7 @@ function wallFaceExposedStructure(wallNode: WallNode, face: WallFace): ExposedSt return face === exteriorFace ? wallAssemblyExposedStructure(wallNode) : null } -// The structure as the generic foundation draws it (same courses, joints and colours), made once: +// The bare structure (courses, joints and colours), made once: // the block's bond runs along the face's world-planar U, the wall's own metres. Solid shading // keeps to a flat colour, like every other wall finish. const structureMaterials = new Map() diff --git a/skills/pascal-3d/references/tool-workflows.md b/skills/pascal-3d/references/tool-workflows.md index 9666ad9c61..d4eee7930e 100644 --- a/skills/pascal-3d/references/tool-workflows.md +++ b/skills/pascal-3d/references/tool-workflows.md @@ -39,7 +39,7 @@ Use `checkpoint` only at a meaningful milestone. A browser-visible draft and a d ### The ground line -A building's levels stand on a ground line: the level at grade (`set_ground_level` names it and seats the building with its floor 8 in over grade, the top of the foundation; until then it is the lowest level whose floor is not under the ground), the levels with a lower floor index below grade. `list_levels` reads `groundLevels` and each level's `gradeStanding`. A new wall on a level below grade is an 8 in CMU foundation wall with 2x4 pressure-treated furring laid flat inside (0.241 m); a wall given a thickness keeps it, and the result of `add_level`, `add_wall` and `create_room` says so. A basement added with `add_level` goes under the lowest floor and every existing floor keeps its place. +A building's levels stand on a ground line: the level at grade (`set_ground_level` names it and seats the building with its floor on grade; until then it is the lowest level whose floor is not under the ground), the levels with a lower floor index below grade. `list_levels` reads `groundLevels` and each level's `gradeStanding`. A new wall on a level below grade is an 8 in CMU foundation wall with 2x4 pressure-treated furring laid flat inside (0.241 m); a wall given a thickness keeps it, and the result of `add_level`, `add_wall` and `create_room` says so. A basement added with `add_level` goes under the lowest floor and every existing floor keeps its place. ## Make a bounded edit diff --git a/wiki/architecture/materials-and-themes.md b/wiki/architecture/materials-and-themes.md index dee19a2b6f..73393ad9b7 100644 --- a/wiki/architecture/materials-and-themes.md +++ b/wiki/architecture/materials-and-themes.md @@ -218,13 +218,10 @@ The walkthrough walks on its floors. `groundVeiled` / `anyGroundVeiled` are fals **Site flatwork is not a floor of the house** (`isSiteFlatwork`, core): a slab the site's works laid on a level (a lawn, a driveway, a path, `metadata.flatwork`) is outdoors. `levelGradeStanding`'s samples, the buried and cover plates of `belowGradeFootprints` / `coveredBelowGradeFootprints` and the level's ground box (`levelGroundBox`) leave it out, and so do the storey walkers that say where a level's floors are, how high and how deep (`levelFloorWorldY`, `levelLowestFloorWorldY`, `levelPlateUndersideWorldY`) and the dive's `deepestDrawnY`, so a driveway laid lower than the house's slab does not take the pit, the footing or the dive depth down with it: a lot-wide lawn on the ground level does not make that level partly below grade under a hill (and open the hole over the hillside), does not cover a basement reaching under the garden, and does not stretch the level's box over the whole lot. -**A wall with no cladding over a bare masonry or concrete core shows that structure outside** (`wallAssemblyExposedStructure`, core: `'cmu'` or `'concrete'`; the viewer's `wall-materials.ts` dresses the exterior face with it when the cladding's own `wallAssemblyFinishRef` is null): the foundation walls above grade, and from under the ground, were the white slot default because their assembly (`FOUNDATION_CONSTRUCTIONS`) has no `finish` layer, and read unlike the generic foundation under them. The face now takes the generic foundation's own materials (`viewer/src/lib/foundation-materials.ts`, shared with `nodes/src/site/generic-foundation.tsx`): courses of block with joints and the block colours for `cmu` (courses from the world's Y, so they bond with the foundation's; the bond along the face's world-planar U), the same grained concrete for `concrete`; solid shading keeps a flat colour (`STRUCTURE_COLORS`). Only the exterior face, and only when its side is resolved; paint on the face wins; a layer of cladding or lining outside the core (a partition, stucco on block), a framed core and `icf` are untouched, and no preset of `WALL_ASSEMBLY_PRESETS` changes its look. Thumbnails and captures take the viewer's wall materials, so they follow. +**A wall with no cladding over a bare masonry or concrete core shows that structure outside** (`wallAssemblyExposedStructure`, core: `'cmu'` or `'concrete'`; the viewer's `wall-materials.ts` dresses the exterior face with it when the cladding's own `wallAssemblyFinishRef` is null): the foundation walls above grade, and from under the ground, were the white slot default because their assembly (`FOUNDATION_CONSTRUCTIONS`) has no `finish` layer, and read unlike bare structure. The face now takes the bare-structure materials (`viewer/src/lib/foundation-materials.ts`): courses of block with joints and the block colours for `cmu` (courses from the world's Y, so they bond with the foundation's; the bond along the face's world-planar U), the same grained concrete for `concrete`; solid shading keeps a flat colour (`STRUCTURE_COLORS`). Only the exterior face, and only when its side is resolved; paint on the face wins; a layer of cladding or lining outside the core (a partition, stucco on block), a framed core and `icf` are untouched, and no preset of `WALL_ASSEMBLY_PRESETS` changes its look. Thumbnails and captures take the viewer's wall materials, so they follow. -Looking under any house (round 7). With the ground on Auto the orbit's eye may leave the ground for the earth under any building, whatever level is selected: the floor limit is `orbitFloorMinY(levelFloorY, diveFloor)`, the dive floor `diveFloorY` = 3 m under the lowest ground (`lowestGroundY`) or 1 m under the deepest drawn thing (`deepestDrawnY`: the footing under the lowest floor), whichever is deeper, and the floor-surface lookup is off while the dive is on (the level's slab and the ground would hold the eye over them). Solid keeps the old limit; `allowUndergroundCamera` stays the dev's free camera; the overview rule (`overviewEyeY`) and the walkthrough are unchanged. +Looking under any house (round 7). With the ground on Auto the orbit's eye may leave the ground for the earth under any building, whatever level is selected: the floor limit is `orbitFloorMinY(levelFloorY, diveFloor)`, the dive floor `diveFloorY` = 3 m under the lowest ground (`lowestGroundY`) or 1 m under the deepest drawn thing (`deepestDrawnY`: the underside of the lowest floor), whichever is deeper, and the floor-surface lookup is off while the dive is on (the level's slab and the ground would hold the eye over them). Solid keeps the old limit; `allowUndergroundCamera` stays the dev's free camera; the overview rule (`overviewEyeY`) and the walkthrough are unchanged. -The generic foundation (`genericFoundation` in core, `site/generic-foundation.tsx`): under the exterior walls of each building's lowest level, derived and never stored, a 16 × 8 in footing whose bottom is 12 in under the lowest grade (a generic depth: core has no frost data) and an 8 in foundation wall from the footing up to the underside of the lowest floor, drawn as a footing in concrete and a wall in running-bond block (a TSL pattern on the wall's own length and world height). A level wholly below grade has no second wall (its exterior walls are the foundation walls): only the footing, under its floor. A wall that stores a stem (`underpinning`) keeps it and gets only the footing under the stem; a slab with a solid `foundation` skirt is the foundation under its level. A node that declares the `drawsFoundation` capability on that level (Bones' X-ray, while its foundation is shown) replaces the generic one, so nothing is drawn twice. The standard numbers are `FOUNDATION_STANDARD` in core, read by Bones and the sections plugin as well; what depends on the jurisdiction (frost depth, wall convention) stays in Bones. The two meshes and two materials exist from the moment a building has the walls, and are not touched by a floor switch or by the eye crossing the ground (the ground hides the part under it from above); the walkthrough hides them (a flag), exports strip them (`pascalExport`), and a capture through the veil leaves them out (`SITE_FOUNDATION`, `temporarilyVeilGround`). The wall is block only where the building's foundation construction is block (the default and the US): each stem run carries a `material` (`cmu`, `concrete`), the viewer draws one stem mesh per material in use, and the stem is as wide as the construction says (8 in, 25 cm); see "The construction follows the region" in `vertical-model.md`. - -A plugin that pours the real foundation takes the level over under the ground. `drawsFoundation(node)` (a node capability) steps the generic foundation aside under a level for good while the node draws its own; and `useViewer.pluginFoundationLevelIds` does it for the levels a plugin draws only while the eye is under the ground (Bones: a building with no X-ray, or an X-ray set to Off), so `GenericFoundation` filters those levels' members out of its two geometries (the meshes and materials stay; nothing compiles). The plugin writes the ids while its meshes hold members and clears them when the eye surfaces. Bones' own meshes (`framing/underground.tsx` in `plugin-bones`, mounted by the host beside the framing reveal) are made once per level, hold one instance of no size above the ground and are refilled under it: a pipeline lives as long as the instanced mesh that draws with it (the node's cache key carries the mesh's uuid), so rebuilding the meshes on each dive would compile again. The shown level's own materials are never touched. A capture (the agent's pictures, the hero shot) renders from its own camera with `gl.render`, so the composite pieces are not in it; `temporarilyWithoutAmbiance()` (held by the thumbnail generator's set-up and the hero bake) also closes the hole, lets the sky light and the fill go back to what they were, and restores them after. diff --git a/wiki/architecture/vertical-model.md b/wiki/architecture/vertical-model.md index 638e5fd28c..2648ab6181 100644 --- a/wiki/architecture/vertical-model.md +++ b/wiki/architecture/vertical-model.md @@ -404,11 +404,11 @@ Because community autosave only persists after the first post-load edit, the mig ## Gotchas - **Only `support.kind: 'walls'` roofs follow walls.** The resolver projects the roof’s XZ centre onto its parent level’s lower neighbour, selected by `findLevelBelowId` from `getLevelElevations` in the same building stack (ordinals need not be consecutive). It uses the smallest enclosing room at that point and takes the highest resolved wall top without clamping to the storey. Conical roofs match curved walls by arc centre and radius against their transformed segment footprint, without a wall-ID binding. No matching enclosure or arc freezes Y and preserves follow intent, so redrawing walls resumes following. Negative level-local Y is valid: 2.5 m walls under a 3 m storey put the roof at −0.5 m. `RoofElevationSystem` re-derives Y only for following roofs on wall, slab, level, building, site, and roof edits, history-paused and one microtask after store updates so the spatial grid has settled. Settled updates publish a separate scene commit without adding an undo step; an outer gesture’s history pause retains commit ownership. Hosts that edit outside the editor apply the same rule synchronously through `reconcileDocument`, so their commit already carries the roof. The panel’s “Follows walls” choice enables this rule; “Custom” writes `level` and keeps Y. An explicit Y change exceeding 1e-4 m in the panel or 3D move handle switches to `level` in the same patch; XZ-only moves retain `walls` and re-resolve spatially. Undo/redo restores mode and Y together. Roof-surface attachments hide this mode control and retain their own rule. Schema version stays 3 and load never opts existing roofs into following. -- **The ground line.** A building's levels stand on a ground line: `building.groundLevelId` names the level at grade, the levels with a lower `level` index are below grade (`groundLevelOf`, `levelUnderNamedGround`; `levelGradeStanding` reads it, so the hole, the veil, the dive, `verify_scene` and the agent's pictures follow). Absent, it is the lowest level whose floor is not under the flat datum — what every scene read before the line — so existing scenes change nothing. "Set as ground floor" (the level panel, the agent's `set_ground_level`, `buildGroundLevelChanges`) names the level, seats the building so its floor datum, the top of the foundation where the wood framing starts, stands `GROUND_FLOOR_ABOVE_GRADE` = 0.203 m (8 in; IRC R317.1) over grade (height only; flat site: Y 0.203, terrain: 0.203 m over the mean ground height under its floor, `gradeUnderLevel`) and renumbers the indices so it is 0; one change set, one undo step. Levels stack up from the lowest one's own `baseElevation`, so a floor added under the line must not lift what is over it: `buildLevelBelowChanges` (the "+" below and `add_level` below) takes the lowest floor's place one storey down. Under the line a level is never at grade (on terrain that leaves it out of the ground it reads partly below); at or over it, terrain alone can bury part of a floor. `verify_scene` reports `basement_at_grade` (a negative index whose floor stands at grade) and `ground_level_unseated` (a named ground floor standing outside the seat). "Seated" is a band, grade to 0.203 m over it, within 5 cm (`GroundSeat.seated`): a scene seated before the 8 in rule, at grade, stays quiet, and the amber panel line and the finding speak only for a floor under the ground or well over the foundation top; `atFoundationTop` is the exact seat, the one "Set as ground floor" moves a floor to and the one that disables its menu entry. The panel line reads the datum over the ground (`Ground · +0.20`). +- **The ground line.** A building's levels stand on a ground line: `building.groundLevelId` names the level at grade, the levels with a lower `level` index are below grade (`groundLevelOf`, `levelUnderNamedGround`; `levelGradeStanding` reads it, so the hole, the veil, the dive, `verify_scene` and the agent's pictures follow). Absent, it is the lowest level whose floor is not under the flat datum — what every scene read before the line — so existing scenes change nothing. "Set as ground floor" (the level panel, the agent's `set_ground_level`, `buildGroundLevelChanges`) names the level, seats the building so its floor datum stands on grade (height only; flat site: Y 0, terrain: the mean ground height under its floor, `gradeUnderLevel`) and renumbers the indices so it is 0; one change set, one undo step. Levels stack up from the lowest one's own `baseElevation`, so a floor added under the line must not lift what is over it: `buildLevelBelowChanges` (the "+" below and `add_level` below) takes the lowest floor's place one storey down. Under the line a level is never at grade (on terrain that leaves it out of the ground it reads partly below); at or over it, terrain alone can bury part of a floor. `verify_scene` reports `basement_at_grade` (a negative index whose floor stands at grade) and `ground_level_unseated` (a named ground floor standing outside the seat). "Seated" is the floor datum on grade within 5 cm (`GroundSeat.seated`): the seat "Set as ground floor" moves a floor to, the one that disables its menu entry; the amber panel line and the finding speak for a floor off it. The panel line reads the datum over the ground (`Ground · +0.20`). -**The foundation wall.** A new wall against the ground on a level below grade (below grade everywhere, or under the named ground line, `levelHoldsFoundationWalls`; against the ground means on the outline of the level's walls, the outline `genericFoundation` draws under) is born as an 8 in CMU core (0.203 m, `material: 'cmu'`, `core`) with a 2x4 pressure-treated furring layer laid flat on the inside (0.038 m, `role: 'furring'`), `face: 'exterior'`, thickness the sum (0.241 m): IRC R317.1 for the treated furring on below-grade masonry, 16 in on centre not stored (no geometry). `planWallInsertion` (the editor's wall tools, rooms, zone edges) and `add_wall` ask `withFoundationConstruction` (`lib/foundation-wall.ts`) with the level's walls and the walls just drawn: a wall inside a closed circuit of other walls and not on it (`enclosedWallIds`) is a partition and keeps the ordinary wall, any other is on the outline, a wall no circuit surrounds yet counting as the outline in the making, so a basement drawn wall by wall is foundation all round and a partition drawn once the perimeter is closed is not. A wall drawn before the circuit that later encloses it stays foundation (existing walls are never rewritten, and the side classification the reconciler writes only exists once rooms do). A caller's `thickness` or `assembly` wins, existing walls are never rewritten, and a level the hillside only half buries with no ground line named holds ordinary walls. The new-building creation sites (`loadScene`, `add_level` on an empty scene, the hosted bridge) still start the building at Y 0; only "Set as ground floor" and `set_ground_level` seat the 8 in. +**The foundation wall.** A new wall against the ground on a level below grade (below grade everywhere, or under the named ground line, `levelHoldsFoundationWalls`; against the ground means on the outline of the level's walls) is born as an 8 in CMU core (0.203 m, `material: 'cmu'`, `core`) with a 2x4 pressure-treated furring layer laid flat on the inside (0.038 m, `role: 'furring'`), `face: 'exterior'`, thickness the sum (0.241 m): IRC R317.1 for the treated furring on below-grade masonry, 16 in on centre not stored (no geometry). `planWallInsertion` (the editor's wall tools, rooms, zone edges) and `add_wall` ask `withFoundationConstruction` (`lib/foundation-wall.ts`) with the level's walls and the walls just drawn: a wall inside a closed circuit of other walls and not on it (`enclosedWallIds`) is a partition and keeps the ordinary wall, any other is on the outline, a wall no circuit surrounds yet counting as the outline in the making, so a basement drawn wall by wall is foundation all round and a partition drawn once the perimeter is closed is not. A wall drawn before the circuit that later encloses it stays foundation (existing walls are never rewritten, and the side classification the reconciler writes only exists once rooms do). A caller's `thickness` or `assembly` wins, existing walls are never rewritten, and a level the hillside only half buries with no ground line named holds ordinary walls. The new-building creation sites (`loadScene`, `add_level` on an empty scene, the hosted bridge) still start the building at Y 0; only "Set as ground floor" and `set_ground_level` move it, to grade. -**The construction follows the region.** The 8 in CMU stack above is the generic and US answer; `foundationReadingOf` (`lib/foundation-construction.ts`, the table `FOUNDATION_CONSTRUCTIONS` beside `FOUNDATION_STANDARD`) picks the construction of a building: by region, read from the site with the precedence of Bones' jurisdiction guess and without importing Bones: `metadata.codeOverrides.state`, `address.state`, `parcel.state` (a US state: CMU), then the country the dossier address ends with, then a point (`dossier.point`, `parcel.originLngLat`) in a box over Europe: cast concrete (0.354 m: a 4 mm bitumen membrane and 10 cm of insulation outside a 25 cm concrete core, floor 0.15 m over grade). A site that says nothing, a Canadian province, and a point over North America keep the CMU. The browser is not read (core runs on the server too). `withFoundationConstruction` writes the chosen assembly on new walls against the ground, `groundSeat.aboveGrade` is the chosen seat (`seated` and `atFoundationTop` follow it, `GROUND_FLOOR_ABOVE_GRADE` stays the block value), and `genericFoundation` stems carry `material` (`cmu`, `concrete`) and the construction's stem width. The Europe numbers are sensible defaults (`source: 'default'`): 20 to 25 cm cellar walls and 10 cm perimeter insulation are usual, 150 mm is the damp-proof course height of British practice; none is one country's code. Existing walls are never rewritten. +**The construction follows the region.** The 8 in CMU stack above is the generic and US answer; `foundationReadingOf` (`lib/foundation-construction.ts`, the table `FOUNDATION_CONSTRUCTIONS` beside `FOUNDATION_STANDARD`) picks the construction of a building: by region, read from the site with the precedence of Bones' jurisdiction guess and without importing Bones: `metadata.codeOverrides.state`, `address.state`, `parcel.state` (a US state: CMU), then the country the dossier address ends with, then a point (`dossier.point`, `parcel.originLngLat`) in a box over Europe: cast concrete (0.354 m: a 4 mm bitumen membrane and 10 cm of insulation outside a 25 cm concrete core). A site that says nothing, a Canadian province, and a point over North America keep the CMU. The browser is not read (core runs on the server too). `withFoundationConstruction` writes the chosen assembly on new walls against the ground. The Europe numbers are sensible defaults (`source: 'default'`): 20 to 25 cm cellar walls and 10 cm perimeter insulation are usual; none is one country's code. Existing walls are never rewritten. - **Ordinals are semantic.** `level < 0` renders "Basement N"; `level === 0` is the ground-floor lookup. Never renumber without the zero anchor. - **Boundary geometry.** Auto plates store full wall footprints; manual slabs and older snapshots can still put wall/ceiling clamp samples exactly on polygon edges — always use the boundary-inclusive band-overlap helpers (`wallOverlapsSlabFootprint`, `slabCoversPoint`), never raw ray-cast point-in-polygon on those paths. From 0ec5090cc235c81d676534f10e158f3fd4489aaf Mon Sep 17 00:00:00 2001 From: Wassim SAMAD Date: Mon, 2 Nov 2026 09:56:50 -0500 Subject: [PATCH 2/4] Remove the grade ring drawn over a level below grade The dark ribbon along a basement's outline, drawn while the ground is veiled, read as black wall tops. The hole and its pit already show where the ground is cut. Its colours (UNDERGROUND_RING, the palette's ring) and anyGroundVeiled, which only it read, go with it. Co-Authored-By: Claude Opus 5.5 --- .../core/src/lib/below-grade-footprints.ts | 3 +- packages/core/src/lib/grade-standing.ts | 2 +- packages/nodes/src/site/ground-hole.tsx | 6 +- packages/nodes/src/site/ground-veil.test.tsx | 59 ++-------------- packages/nodes/src/site/ground-veil.tsx | 67 ++----------------- packages/nodes/src/site/renderer.tsx | 31 +-------- packages/viewer/src/index.ts | 2 - packages/viewer/src/lib/scene-themes.ts | 2 - packages/viewer/src/lib/site-surfaces.ts | 2 +- .../viewer/src/lib/underground-ambiance.ts | 2 - packages/viewer/src/store/use-viewer.test.ts | 8 +-- packages/viewer/src/store/use-viewer.ts | 14 ---- wiki/architecture/materials-and-themes.md | 5 +- 13 files changed, 24 insertions(+), 179 deletions(-) diff --git a/packages/core/src/lib/below-grade-footprints.ts b/packages/core/src/lib/below-grade-footprints.ts index 688e44c6b9..d9b9650dc6 100644 --- a/packages/core/src/lib/below-grade-footprints.ts +++ b/packages/core/src/lib/below-grade-footprints.ts @@ -86,8 +86,7 @@ function levelPlates(nodes: Record): LevelPlates[] { * Where the ground meets the levels below grade, in the site's plan: each such level's floor slabs * placed where its building stands and joined into outlines, the levels' together as one set (a * deeper level wider than the one over it, or under part of it, gives one outline, not overlapping - * ones). The 3D view cuts its hole in the ground and draws its grade ring along them while the - * ground is veiled. An automatic floor follows the walls' centrelines, so an outline runs half a + * ones). The 3D view cuts its hole in the ground over them while the ground is veiled. An automatic floor follows the walls' centrelines, so an outline runs half a * wall inside the outer faces. A level only partly below grade (a walk-out on a hillside) gives * the part of its floor the ground stands over by more than {@link BELOW_GRADE_TOLERANCE}, the * edge following the slope; fully buried levels give their whole floor. diff --git a/packages/core/src/lib/grade-standing.ts b/packages/core/src/lib/grade-standing.ts index 47246b7747..b1ecc47fe5 100644 --- a/packages/core/src/lib/grade-standing.ts +++ b/packages/core/src/lib/grade-standing.ts @@ -115,7 +115,7 @@ export function terrainFieldOverLevel( /** * World XZ samples over the level's floor slabs: each slab's corners plus a grid across it no * coarser than the terrain's own spacing, capped so a big plate stays cheap. Slabs are the - * footprint the grade ring already trusts (`belowGradeFootprints`). + * footprint the ground's hole already trusts (`belowGradeFootprints`). */ export function footprintSamples( nodes: Record, diff --git a/packages/nodes/src/site/ground-hole.tsx b/packages/nodes/src/site/ground-hole.tsx index b2791fbf16..af69191249 100644 --- a/packages/nodes/src/site/ground-hole.tsx +++ b/packages/nodes/src/site/ground-hole.tsx @@ -43,7 +43,7 @@ import { EDGE_LOOKS, type EdgeLook } from './underground-edge' * in a soft feather and a thin light line marks the cut itself. * * The footprint is a signed-distance field baked on the CPU into a small texture when the - * footprints change (the polygons the grade ring is drawn from), so the ground's mask costs one + * footprints change, so the ground's mask costs one * texture fetch and one noise lookup per fragment, whatever the building's outline. How far the * hole is open (0 to 1, eased, 0 in a capture) is the viewer's `groundHoleOpenNode`. */ @@ -317,8 +317,8 @@ export function groundHoleColorNode(shadeColor: string) { } /** - * Feeds the hole the footprints it is cut over (the polygons the grade ring runs along: the level - * shown and the ones between it and grade), and says to the rest of the viewer whether the scene + * Feeds the hole the footprints it is cut over (the level shown and the ones between it and + * grade), and says to the rest of the viewer whether the scene * has a level below grade at all (`present`): the ground materials carry the hole's mask, and the * eye's fill light is mounted, from then on, once, so that changing floors only changes uniforms. * diff --git a/packages/nodes/src/site/ground-veil.test.tsx b/packages/nodes/src/site/ground-veil.test.tsx index bc57ece310..5a8981fe7c 100644 --- a/packages/nodes/src/site/ground-veil.test.tsx +++ b/packages/nodes/src/site/ground-veil.test.tsx @@ -21,7 +21,7 @@ import { useViewer, } from '@pascal-app/viewer' import { act, create } from '@react-three/test-renderer' -import { Box3, type Line, type Mesh, type Object3D, Raycaster, Vector3 } from 'three' +import { type Line, type Mesh, type Object3D, Raycaster, Vector3 } from 'three' import type { MeshBasicNodeMaterial } from 'three/webgpu' import { groundHoleDistanceAt, holeRadiusAt } from './ground-hole' import { groundPitDrawnFloorNow, groundPitFloorNow } from './ground-pit' @@ -79,17 +79,6 @@ function groundPickedAt(root: Object3D, x = 0, z = 0) { const drawn = (surface: Object3D) => surface.visible && surface.layers.isEnabled(SCENE_LAYER) -/** The veil surfaces told apart: the grade ring is the narrow one, the sheets cover the lot. */ -function veilsOf(root: Object3D) { - const veils = ground(root, 'veil') - const isRing = (veil: Mesh) => { - veil.geometry.computeBoundingBox() - const box = veil.geometry.boundingBox ?? new Box3() - return box.max.x - box.min.x < 7 - } - return { sheets: veils.filter((veil) => !isRing(veil)), rings: veils.filter(isRing) } -} - /** True when the node graph under `root` reads the hole's opening uniform. */ function readsHoleOpening(root: unknown) { let reads = false @@ -159,17 +148,10 @@ test.each([false, true])( await act(async () => useViewer.setState({ belowGrade: true, gradeStanding: 'below-grade' })) groundHoleOpenNode().value = 1 await renderer.advanceFrames(2, 0.05) - // The ground stays solid and drawn (the hole is in its mask), no veil sheet over it, the grade - // ring where it meets the plate, drawn along the plate's outline (the ribbon's half-width - // widens it by 8 cm). + // The ground stays solid and drawn (the hole is in its mask), nothing veiled over it: no sheet, + // and no ring drawn round the plate. expect(solid.every(drawn)).toBe(true) - const { sheets, rings } = veilsOf(scene) - expect(sheets.filter(drawn)).toHaveLength(0) - expect(rings.filter(drawn)).toHaveLength(1) - const ring = rings[0]?.geometry.boundingBox ?? new Box3() - expect( - [ring.min.x, ring.max.x, ring.min.z, ring.max.z].map((v) => Math.abs(Math.round(v))), - ).toEqual([0, 6, 0, 4]) + expect(ground(scene, 'veil').some(drawn)).toBe(false) // Over the plate the click falls through to the floor; past the hole's reach it lands. expect(groundPickedAt(scene, 3, 2)).toHaveLength(0) expect(groundPickedAt(scene, 9, 9).length).toBeGreaterThan(0) @@ -199,12 +181,6 @@ test.each([ expect(ground(scene, 'solid').every(drawn)).toBe(true) expect(ground(scene, 'veil').some(drawn)).toBe(false) expect(groundPickedAt(scene, 3, 2).length).toBeGreaterThan(0) - // Leaving the walkthrough: the overview rule is back (the ring under the veil). - if ('walkthroughMode' in state) { - await act(async () => useViewer.setState({ walkthroughMode: false })) - await renderer.advanceFrames(2, 0.05) - expect(veilsOf(scene).rings.filter(drawn)).toHaveLength(1) - } await renderer.unmount() }) @@ -311,16 +287,6 @@ function showLevel(levelId: string) { test('the hole follows the level shown (it and the levels between it and grade, never the deeper ones) and is one outline', async () => { withFourBasements() const renderer = await create() - const scene = renderer.scene.instance as Object3D - // The grade ring's extent, rounded: the lot's own sheets are the wide ones. - const ringExtents = () => - ground(scene, 'veil') - .map((veil) => { - veil.geometry.computeBoundingBox() - const box = veil.geometry.boundingBox ?? new Box3() - return [box.min.x, box.max.x, box.min.z, box.max.z].map((v) => Math.round(v)) - }) - .filter(([x0, x1]) => (x1 ?? 0) - (x0 ?? 0) < 19) expect(useViewer.getState().hasLevelBelowGrade).toBe(true) groundHoleOpenNode().value = 1 @@ -330,7 +296,6 @@ test('the hole follows the level shown (it and the levels between it and grade, expect(groundHoleDistanceAt(0, 0)).toBeLessThan(0) expect(groundHoleDistanceAt(8, 1)).toBeGreaterThan(3) expect(groundHoleDistanceAt(-7, 6)).toBeGreaterThan(3) - expect(ringExtents()).toEqual([[-3, 3, -3, 3]]) // The pit goes down to the floor of the level shown, which is shallow here. expect(groundPitFloorNow()).toBeLessThan(0) expect(groundPitFloorNow()).toBeGreaterThan(-4) @@ -341,7 +306,6 @@ test('the hole follows the level shown (it and the levels between it and grade, // east, is not opened (it is deeper than the level shown). expect(groundHoleDistanceAt(-7, 6)).toBeLessThan(0) expect(groundHoleDistanceAt(8.5, 1)).toBeGreaterThan(0.3) - expect(ringExtents()).toEqual([[-8, 8, -8, 7]]) await act(async () => showLevel('level_m4')) await renderer.advanceFrames(2, 0.05) @@ -356,7 +320,6 @@ test('the hole follows the level shown (it and the levels between it and grade, [-6, 5], ] as const) expect(groundHoleDistanceAt(x, z)).toBeLessThan(0) - expect(ringExtents()).toEqual([[-8, 9, -8, 7]]) // -4 sits 12 m down (its 0.2 m plate on top). expect(groundPitFloorNow()).toBeCloseTo(-11.8, 1) @@ -555,7 +518,7 @@ function withHillsideHouse(walkoutEast: number) { return site } -test('on a hillside the hole, the grade ring and the pit stop where the ground does: the valley side of a walk-out stays closed', async () => { +test('on a hillside the hole and the pit stop where the ground does: the valley side of a walk-out stays closed', async () => { const site = withHillsideHouse(9) const renderer = await create() const scene = renderer.scene.instance as Object3D @@ -569,18 +532,6 @@ test('on a hillside the hole, the grade ring and the pit stop where the ground d expect(groundHoleDistanceAt(7, 0)).toBeLessThan(0) expect(groundHoleDistanceAt(-6, 0)).toBeGreaterThan(1) - // The grade ring runs along the same outline. (The sheets are transparent: the terrain's cut - // round the opening under the walk-out, where the house covers the cellar, is one of them.) - const rings = ground(scene, 'veil').filter((veil) => { - veil.geometry.computeBoundingBox() - const box = veil.geometry.boundingBox ?? new Box3() - return box.max.x - box.min.x < 15 && !(veil.material as { transparent?: boolean }).transparent - }) - expect(rings).toHaveLength(1) - const ringBox = rings[0]!.geometry.boundingBox ?? new Box3() - expect(ringBox.min.x).toBeGreaterThan(-2.5) - expect(ringBox.max.x).toBeLessThan(9.5) - await renderer.unmount() }) diff --git a/packages/nodes/src/site/ground-veil.tsx b/packages/nodes/src/site/ground-veil.tsx index 81afdec636..6d5bcb88f4 100644 --- a/packages/nodes/src/site/ground-veil.tsx +++ b/packages/nodes/src/site/ground-veil.tsx @@ -1,36 +1,18 @@ -import type { TerrainField } from '@pascal-app/core' import { - anyGroundVeiled, groundWindowEnabledNode, inGroundWindowNode, SITE_GROUND, - UNDERGROUND_RING, - undergroundAmbianceNode, useViewer, } from '@pascal-app/viewer' import { type BufferGeometry, DoubleSide, type Material } from 'three' -import { - color, - float, - mix, - mrt, - output, - positionWorld, - select, - smoothstep, - vec2, - vec4, -} from 'three/tsl' +import { color, float, mrt, output, positionWorld, select, smoothstep, vec2, vec4 } from 'three/tsl' import { MeshBasicNodeMaterial, type Node } from 'three/webgpu' -import { buildPatternedRibbon } from './line-ribbon' import { insideLotNode } from './lot-mask' -import { buildDrapedPolyline } from './terrain-drape' // The ground over a level below grade. Wholesale (a level fully below grade, the ground on Auto) // the solid ground stays and a hole opens in it (`ground-hole.ts`); the veil sheets here are the // faint see-through ground of the ground window (a hillside in the eye's way) and of a capture -// (which sets the solid ground aside and shows them), and the grade ring is drawn where the ground -// meets the level below grade, in either. +// (which sets the solid ground aside and shows them). /** Presentation-only meshes are never picked: clicks fall through to what lies under them. */ export const noopRaycast = () => {} @@ -88,60 +70,25 @@ export function horizonVeilMaterial( return veilMaterial(groundColor, select(outsideLot, fade, float(0))) } -/** The grade ring: dark as the lot line, a little narrower, just over the ground. */ -const GRADE_RING_COLOR = '#1c1917' -const GRADE_RING_WIDTH = 0.16 -const GRADE_RING_LIFT = 0.015 -/** One run, never broken: a ribbon pattern with no gap. */ -const UNBROKEN: readonly number[] = [Number.POSITIVE_INFINITY, 0] - -/** The grade ring's ribbon along one outline where the ground meets a level below grade. */ -export function gradeRingGeometry( - outline: ReadonlyArray, - field: TerrainField | null, -): BufferGeometry { - const drape = buildDrapedPolyline({ points: outline, field, lift: GRADE_RING_LIFT, closed: true }) - return buildPatternedRibbon(drape.positions, UNBROKEN, GRADE_RING_WIDTH) -} - -export function gradeRingMaterial() { - const material = new MeshBasicNodeMaterial({ color: GRADE_RING_COLOR, side: DoubleSide }) - // Under the ground's ambiance the ring is a light rim: a dark ring would vanish in the dark mode. - material.colorNode = mix( - color(GRADE_RING_COLOR), - color(UNDERGROUND_RING), - undergroundAmbianceNode(), - ) - return material -} - /** * Drawn only while the ground is veiled: the veil of one solid ground surface (the same geometry - * in the same place), or the grade ring. A direct child of the site, as the surfaces are, so the - * captures find it (`siteGround`) and hide it with the site's other surfaces. - * - * `shows` says when a live view draws it: `'window'` (a sheet: only where the ground window veils - * a hillside in the eye's way; wholesale the ground is a hole, not a sheet) or `'veiled'` (the - * ring: wherever any ground is veiled). A capture shows both by setting `visible` itself. + * in the same place). A direct child of the site, as the surfaces are, so the captures find it + * (`siteGround`) and hide it with the site's other surfaces. A live view draws it only where the + * ground window veils a hillside in the eye's way (wholesale the ground is a hole, not a sheet); a + * capture shows it by setting `visible` itself. */ export function GroundVeil({ geometry, material, position, rotation, - shows = 'window', }: { geometry: BufferGeometry material: Material position?: [number, number, number] rotation?: [number, number, number] - shows?: 'window' | 'veiled' }) { - const veiled = useViewer((state) => - shows === 'veiled' - ? anyGroundVeiled(state) - : state.groundMode === 'auto' && state.groundWindowVeiled, - ) + const veiled = useViewer((state) => state.groundMode === 'auto' && state.groundWindowVeiled) return ( { }, [polygonPoints]) // Where the ground meets the levels below grade. `all` says whether the scene has any (the - // ground materials carry the hole's mask from then on); `shown` is what the hole is cut over and - // the grade ring runs along under the veil: the level shown and the ones between it and grade, as + // ground materials carry the hole's mask from then on); `shown` is what the hole is cut over under + // the veil: the level shown and the ones between it and grade, as // the level display hides them. While the level shown is not below grade the last such set is // kept, so a hole easing shut keeps its shape. `covered` is the part of them under the house // itself, whatever level is shown: the ground stands open there (see `holes`). @@ -432,19 +425,6 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { return covered.length > 0 ? [...slabPolygons, ...covered] : slabPolygons }, [coverOpen, buried.covered, polygonPoints, slabPolygons]) - const gradeRings = useMemo( - () => buried.shown.map((outline) => gradeRingGeometry(outline, persistedField)), - [buried.shown, persistedField], - ) - useEffect( - () => () => { - for (const ring of gradeRings) ring.dispose() - }, - [gradeRings], - ) - const gradeRing = useMemo(gradeRingMaterial, []) - useEffect(() => () => gradeRing.dispose(), [gradeRing]) - // Ground shape: site polygon with slab footprints punched as holes const groundShape = useMemo(() => { if (!polygonPoints || polygonPoints.length < 3) return null @@ -763,11 +743,6 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { /> )} - {showSiteSurfaces && - gradeRings.map((geometry, index) => ( - - ))} - {showSiteSurfaces && ribbons && ( <> {/* The property line: dark, thick, long dash + two dots, on the ground */} diff --git a/packages/viewer/src/index.ts b/packages/viewer/src/index.ts index 484fae7233..a02614af96 100644 --- a/packages/viewer/src/index.ts +++ b/packages/viewer/src/index.ts @@ -296,14 +296,12 @@ export { stepAmbianceProgress, temporarilyWithoutAmbiance, UNDERGROUND_RIM, - UNDERGROUND_RING, undergroundAmbianceNode, } from './lib/underground-ambiance' export { createZoneShape, createZoneWallGeometry } from './lib/zone-geometry' export type { LightSource } from './store/use-item-light-pool' export { catalogLightSource, useItemLightPool } from './store/use-item-light-pool' export { - anyGroundVeiled, applyCountryUnitDefault, DEFAULT_UNDERGROUND_LOOK, default as useViewer, diff --git a/packages/viewer/src/lib/scene-themes.ts b/packages/viewer/src/lib/scene-themes.ts index 60def0fb6a..6732e454c1 100644 --- a/packages/viewer/src/lib/scene-themes.ts +++ b/packages/viewer/src/lib/scene-themes.ts @@ -262,8 +262,6 @@ export const UNDERGROUND_PALETTE = { vignette: '#0c0c0c', /** The thin rim along the cut of the hole in the ground, from above. */ rim: '#3c3c3c', - /** The grade ring under the ground: a light rim where the ground meets the level. */ - ring: '#b4b4b4', /** The sky light's tint (ambient and hemisphere pulled toward it under the ground). */ tint: '#c8c8c8', } as const diff --git a/packages/viewer/src/lib/site-surfaces.ts b/packages/viewer/src/lib/site-surfaces.ts index b64c84fccd..0f50620640 100644 --- a/packages/viewer/src/lib/site-surfaces.ts +++ b/packages/viewer/src/lib/site-surfaces.ts @@ -10,7 +10,7 @@ export const SITE_GROUND = 'siteGround' /** * `solid`: the lot's fill, its sculpted terrain, the horizon disc. `veil`: what is drawn in their - * place over a level below grade, the grade ring with it. + * place over a level below grade. */ export type SiteGroundRole = 'solid' | 'veil' diff --git a/packages/viewer/src/lib/underground-ambiance.ts b/packages/viewer/src/lib/underground-ambiance.ts index 9a3e554568..052a3ade69 100644 --- a/packages/viewer/src/lib/underground-ambiance.ts +++ b/packages/viewer/src/lib/underground-ambiance.ts @@ -52,8 +52,6 @@ const BACKDROP = { } as const /** The thin rim along the cut of the hole in the ground, from above. */ export const UNDERGROUND_RIM = UNDERGROUND_PALETTE.rim -/** The grade ring, where the ground meets the level below grade: a light rim in the dark mode. */ -export const UNDERGROUND_RING = UNDERGROUND_PALETTE.ring /** The corners the vignette closes in to. */ export const UNDERGROUND_VIGNETTE = UNDERGROUND_PALETTE.vignette diff --git a/packages/viewer/src/store/use-viewer.test.ts b/packages/viewer/src/store/use-viewer.test.ts index 13ac153219..9a86d13344 100644 --- a/packages/viewer/src/store/use-viewer.test.ts +++ b/packages/viewer/src/store/use-viewer.test.ts @@ -1,7 +1,7 @@ // @ts-expect-error — bun:test is provided by the Bun runtime; viewer does not // include Bun ambient types in its production declaration build. import { afterEach, beforeEach, describe, expect, test } from 'bun:test' -import useViewer, { anyGroundVeiled, groundVeiled, siteGroundShown } from './use-viewer' +import useViewer, { groundVeiled, siteGroundShown } from './use-viewer' const resetMeasurementPreferences = () => { useViewer.setState({ @@ -180,12 +180,6 @@ describe('the ground over a level below grade', () => { test('is solid in the walkthrough, whatever level the overview had shown', () => { expect(groundVeiled({ ...below, walkthroughMode: true })).toBe(false) - expect(anyGroundVeiled({ ...below, groundWindowVeiled: true, walkthroughMode: true })).toBe( - false, - ) - expect(anyGroundVeiled({ ...below, groundWindowVeiled: true, walkthroughMode: false })).toBe( - true, - ) }) }) diff --git a/packages/viewer/src/store/use-viewer.ts b/packages/viewer/src/store/use-viewer.ts index 023e25ecb3..71dd489938 100644 --- a/packages/viewer/src/store/use-viewer.ts +++ b/packages/viewer/src/store/use-viewer.ts @@ -887,20 +887,6 @@ export function groundVeiled(state: { ) } -/** Whether any ground is veiled now, wholesale or through the eye's window. */ -export function anyGroundVeiled(state: { - belowGrade: boolean - groundMode: GroundMode - gradeStanding?: LevelGradeStanding - groundWindowVeiled: boolean - walkthroughMode?: boolean -}): boolean { - return ( - groundVeiled(state) || - (state.groundMode === 'auto' && state.groundWindowVeiled && state.walkthroughMode !== true) - ) -} - /** * Whether the site draws its own ground. `showGround: false` says other geometry supplies the * ground (an authored landscape), which stands on a level above a basement; while a level below diff --git a/wiki/architecture/materials-and-themes.md b/wiki/architecture/materials-and-themes.md index 73393ad9b7..addc901446 100644 --- a/wiki/architecture/materials-and-themes.md +++ b/wiki/architecture/materials-and-themes.md @@ -188,7 +188,7 @@ The editor UI chrome follows the host's theme and is independent of `appearance` The ground is the medium, and the eye is above it or below it. -**Above the ground, a level below grade shown** (`groundVeiled`): the ground stays solid and a hole opens in it over the below-grade footprint (`nodes/src/site/ground-hole.tsx`). The footprint is baked on the CPU into a signed-distance texture (the polygons the grade ring runs along); the ground's `maskNode` compares that distance to a radius that wanders with one perlin lookup (`HOLE_MARGIN` ± `HOLE_ERODE`), so the cut is a scalloped, noise-thresholded edge with a thin slate rim, and the solid ground's shadow reception is off while it is open. How far it is open is the viewer's `groundHoleOpenNode` (eased with the same 0.7 s, instant with Animation Off). Picks and Follow's sight drop hits inside the hole's guaranteed core (`groundHoleContains`, same bake, the noise not replayed). The faint veil sheets (`ground-veil.tsx`) are now only the ground window's (a hillside in the eye's way) and a capture's (`temporarilyVeilGround`, which sets the solid ground aside); the grade ring draws in all of them. A level only partly below grade (a walk-out) opens the hole over the part of each floor slab the ground stands over, judged at that slab's own floor (`levelPlaneWorldY` plus its elevation, in `belowGradeFootprints` and in `levelGradeStanding`'s samples): the sunken room of a split level is buried by ground the raised part's top is above. On a flat site the datum is that ground: each floor slab is buried or not against it, so a split level whose raised part is at grade is partly below grade over its sunken room (`levelGradeStanding`, not `isLevelBelowGrade`, which is the level as a whole and derives the ground level). No dark mode in this state. **The pit** (`nodes/src/site/ground-pit.tsx`, `ground-pit-geometry.ts`): over a deep level the hole reads as the ground cut open, not a white plate. The walls are cut once per footprint change by walking the hole's own threshold (`distance < radius`) on a fine grid, with the shader's fractal noise ported to the CPU (`hole-noise.ts`, three's MaterialX perlin; keep the two in step if the hole's noise changes); each wall carries a `drop` attribute, and the shader drops it from grade to the shown level's floor (`belowGradeFloorY` in core) by a uniform, so a floor switch moves uniforms and swaps the geometry, never a material. Section look: topsoil, then two anthracite strata cut by a noise threshold, darkening with depth; a dark floor (`PIT_FLOOR`) fills the hole under what the level does not cover (`false` keeps the walls alone), drawn at `groundPitFloorY` in core: 5 cm under the top of the lowest floor plate (the sunken room of a split level, not its raised part), and 2 cm under the plate's underside where that would meet it, because the footing and the walls on it stop on that underside (`levelPlateUndersideWorldY`, which `genericFoundation` reads too) and two faces on one plane flicker. The pit is not a site ground surface (no `SITE_GROUND` role): it opens and closes with `groundHoleOpenNode`, so Off, a capture and the dive draw none of it. +**Above the ground, a level below grade shown** (`groundVeiled`): the ground stays solid and a hole opens in it over the below-grade footprint (`nodes/src/site/ground-hole.tsx`). The footprint is baked on the CPU into a signed-distance texture; the ground's `maskNode` compares that distance to a radius that wanders with one perlin lookup (`HOLE_MARGIN` ± `HOLE_ERODE`), so the cut is a scalloped, noise-thresholded edge with a thin slate rim, and the solid ground's shadow reception is off while it is open. How far it is open is the viewer's `groundHoleOpenNode` (eased with the same 0.7 s, instant with Animation Off). Picks and Follow's sight drop hits inside the hole's guaranteed core (`groundHoleContains`, same bake, the noise not replayed). The faint veil sheets (`ground-veil.tsx`) are now only the ground window's (a hillside in the eye's way) and a capture's (`temporarilyVeilGround`, which sets the solid ground aside). A level only partly below grade (a walk-out) opens the hole over the part of each floor slab the ground stands over, judged at that slab's own floor (`levelPlaneWorldY` plus its elevation, in `belowGradeFootprints` and in `levelGradeStanding`'s samples): the sunken room of a split level is buried by ground the raised part's top is above. On a flat site the datum is that ground: each floor slab is buried or not against it, so a split level whose raised part is at grade is partly below grade over its sunken room (`levelGradeStanding`, not `isLevelBelowGrade`, which is the level as a whole and derives the ground level). No dark mode in this state. **The pit** (`nodes/src/site/ground-pit.tsx`, `ground-pit-geometry.ts`): over a deep level the hole reads as the ground cut open, not a white plate. The walls are cut once per footprint change by walking the hole's own threshold (`distance < radius`) on a fine grid, with the shader's fractal noise ported to the CPU (`hole-noise.ts`, three's MaterialX perlin; keep the two in step if the hole's noise changes); each wall carries a `drop` attribute, and the shader drops it from grade to the shown level's floor (`belowGradeFloorY` in core) by a uniform, so a floor switch moves uniforms and swaps the geometry, never a material. Section look: topsoil, then two anthracite strata cut by a noise threshold, darkening with depth; a dark floor (`PIT_FLOOR`) fills the hole under what the level does not cover (`false` keeps the walls alone), drawn at `groundPitFloorY` in core: 5 cm under the top of the lowest floor plate (the sunken room of a split level, not its raised part), and 2 cm under the plate's underside where that would meet it, because the footing and the walls on it stop on that underside (`levelPlateUndersideWorldY`, which `genericFoundation` reads too) and two faces on one plane flicker. The pit is not a site ground surface (no `SITE_GROUND` role): it opens and closes with `groundHoleOpenNode`, so Off, a capture and the dive draw none of it. **The underground look: edge and crossing variants** (`useViewer.undergroundLook`, `{ edge, transition }`, `setUndergroundLook`, never persisted; default `{ noise, fade }`: the fade is chosen, the edge stays until the owner picks between `section` and `section-earth`). `edge` is one of `UndergroundEdge`: `noise` (today's eroded rim), `quiet` (the same noise, fine and faint: rim almost straight from the default camera), `section` (an architect's section cut: a constant 0.6 m offset of the footprint, no noise, a crisp dark line on the cut, the pit's wall one flat tone with a thin dark line at grade; the offset's convex corners are rounded, a distance-field offset) and `section-earth` (the same outline exactly, the pit's walls the earth's: topsoil band, flat strata, `quiet`'s low crumble that is zero at the rim, so the top edge is the section's clean line). The numbers are `EDGE_LOOKS` (`nodes/src/site/underground-edge.ts`): margin, erosion, noise scale, feather, line, wall roughness, section flag. The shader reads them as uniforms (`setGroundHoleEdge`, `setGroundPitEdge`) and the CPU twin (`holeRadiusAt`, the picks' sure core, the walls' contour) reads the same table, so choosing a look compiles nothing and swaps no mesh or material; only the pit's walls are cut again (`GroundHole` re-runs on the edge). `transition` is `UndergroundTransition`: `noise` (the noise-mask crossing, `AMBIANCE_SECONDS` 0.7) or `fade` (the whole frame fades at once over `FADE_SECONDS` 0.4; `undergroundDissolve` mixes the amount with the mask by the `grainWeightNode` uniform, the hole's own opening stays 0.7 s). The sky going to black is in both. @@ -202,11 +202,10 @@ The ground is the medium, and the eye is above it or below it. | Crossing | `post-processing.tsx` (`undergroundDissolve`) | a screen-space perlin mask: soft blobs of the dark world spread over the screen, 0 everywhere above and 1 everywhere below; weighs the three above | | Sky light | `lib/underground-ambiance.ts` | ambient and hemisphere come down and tint toward the palette's neutral light grey for the frame about to be drawn and are given back before `Lights` lerps them; the sun and the IBL are untouched | | Eye light | `lights.tsx` `UndergroundFill` | its intensity is the ambiance's: the veil's 1 (or 0) at rest, up to `EYE_FILL_INTENSITY` under the ground | -| Grade ring | `ground-veil.tsx` | `#1c1917` → the palette's light grey, a light rim | Changing floors changes uniforms only, never a material or the light count (adding a light or swapping a material is a runtime shader compile, ~430 ms on the villa). The ground's hole mask is on the ground materials from the moment the scene has a level below grade (`hasLevelBelowGrade`, set by `GroundHole`; scenes without one keep the plain window mask), and the eye's fill, once mounted, stays: only its intensity moves. Tests: `ground-veil.test.tsx` and `lights.test.tsx` ("switching floors…"). -Several levels below grade (round 5). The hole and the grade ring are cut over `belowGradeFootprints(nodes, shownLevelId)`: the shown level and the levels between it and grade (the ones the level display hides above it), unioned into one outline set, so a deeper level wider than the one over it, or under part of it, is one hole and a deeper level than the one shown stays under solid ground; the materials still follow "any level below grade" (`hasLevelBelowGrade`) and never change between floors. The fog keeps clear `levelStackGroundBox` (the shown level and the ones under it), not the host's single-level window box. The orbit overview keeps the eye over the ground when the pivot goes down to a deep level (`overviewEyeY`, `OVERVIEW_GROUND_CLEARANCE` 2 m: the eye stays where it was and looks down through the hole); only the person orbiting under the ground dives. The editor's "add a basement" (`addStoreyBelow`, core `buildLevelBelowChanges`) gives the new lowest level the offset that puts it one storey under the old lowest, which gives its own offset up: a new lowest level at offset 0 used to lift every floor above it by its height, which stood the basement above the terrain. +Several levels below grade (round 5). The hole is cut over `belowGradeFootprints(nodes, shownLevelId)`: the shown level and the levels between it and grade (the ones the level display hides above it), unioned into one outline set, so a deeper level wider than the one over it, or under part of it, is one hole and a deeper level than the one shown stays under solid ground; the materials still follow "any level below grade" (`hasLevelBelowGrade`) and never change between floors. The fog keeps clear `levelStackGroundBox` (the shown level and the ones under it), not the host's single-level window box. The orbit overview keeps the eye over the ground when the pivot goes down to a deep level (`overviewEyeY`, `OVERVIEW_GROUND_CLEARANCE` 2 m: the eye stays where it was and looks down through the hole); only the person orbiting under the ground dives. The editor's "add a basement" (`addStoreyBelow`, core `buildLevelBelowChanges`) gives the new lowest level the offset that puts it one storey under the old lowest, which gives its own offset up: a new lowest level at offset 0 used to lift every floor above it by its height, which stood the basement above the terrain. The walkthrough walks on its floors. `groundVeiled` / `anyGroundVeiled` are false while `walkthroughMode` (solid ground: no hole, no veil, no ground window, no ring; the part under the house, below, stays open), and the dark mode's factor stays 0 there (`ambianceTarget`: the rooms keep their normal light, no fog, no vignette); only what is seen outside turns to earth, with its own eased factor (`earthTarget`, `undergroundEarthNode`, the backdrop and the sky only) when the eye goes under the ground. The walker's collision ground is cut open over the same part (`cutGroundCollider`, `first-person/ground-holes.ts`, on the rings of `coveredBelowGradeFootprints`, flat slab or terrain alike, whatever the view does with the ground): a sheet across the stairwell would hold the walker at grade on the stair down, so inside the covered footprint he follows the building's floors and stairs, and outside it the ground holds him as before. Leaving the walkthrough returns to the overview rule. To change it: the walkthrough clause in `ambianceTarget` / `groundVeiled`, and the backdrop's `undergroundEarthNode` in `post-processing.tsx`. From 8f286c58d0c88aabd9273d5a37f52a261ccce47a Mon Sep 17 00:00:00 2001 From: Wassim SAMAD Date: Mon, 2 Nov 2026 10:29:51 -0500 Subject: [PATCH 3/4] A floor's foundation skirt reaches the ground as the site draws it A flat site's fill lies 5 cm under the datum (FLAT_GROUND_Y) so floors at grade never sink into it, but a base plate's solid foundation, a porch's concrete edge and a plate filled to the terrain stopped at the datum. The 5 cm gap under them showed what stood behind it: the top of a basement's foundation wall, read as a band above the ground. Co-Authored-By: Claude Opus 5.5 --- packages/nodes/src/slab/__tests__/geometry.test.ts | 9 ++++++--- packages/nodes/src/slab/geometry.ts | 4 +++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/nodes/src/slab/__tests__/geometry.test.ts b/packages/nodes/src/slab/__tests__/geometry.test.ts index 63f8fdfad6..a04b40e83b 100644 --- a/packages/nodes/src/slab/__tests__/geometry.test.ts +++ b/packages/nodes/src/slab/__tests__/geometry.test.ts @@ -4,6 +4,7 @@ import { BuildingNode, createTerrainField, encodeTerrainField, + FLAT_GROUND_Y, type GeometryContext, getRenderableSlabPolygon, LevelNode, @@ -229,7 +230,7 @@ describe('buildSlabGeometry', () => { expect(fill.geometry.boundingBox?.max.y).toBeCloseTo(0.6) }) - test('follows the flat datum before the site has a persisted terrain field', () => { + test('follows the flat ground before the site has a persisted terrain field', () => { const site = SiteNode.parse({ id: 'site_test', children: ['building_test'] }) const slab = SlabNode.parse({ elevation: 0.4, @@ -246,7 +247,8 @@ describe('buildSlabGeometry', () => { const group = buildSlabGeometry(slab, geometryContext(site), 'solid', false) const fill = group.children.filter((child): child is Mesh => child instanceof Mesh)[2]! fill.geometry.computeBoundingBox() - expect(fill.geometry.boundingBox?.min.y).toBeCloseTo(0) + // Down to the ground as the site draws it, a hand under the datum. + expect(fill.geometry.boundingBox?.min.y).toBeCloseTo(FLAT_GROUND_Y) expect(fill.geometry.boundingBox?.max.y).toBeCloseTo(0.3) }) @@ -276,7 +278,8 @@ describe('buildSlabGeometry', () => { ).find((mesh) => mesh.userData.slotId === 'foundation')! expect(skirt).toBeDefined() skirt.geometry.computeBoundingBox() - expect(skirt.geometry.boundingBox?.min.y).toBeCloseTo(0) + // Down to the ground as the site draws it, a hand under the datum. + expect(skirt.geometry.boundingBox?.min.y).toBeCloseTo(FLAT_GROUND_Y) expect(skirt.geometry.boundingBox?.max.y).toBeCloseTo(0.3) // A plate a step down inside the house stays as it is. const sunken = { ...porch, metadata: { floor: 'porch-slab' } } diff --git a/packages/nodes/src/slab/geometry.ts b/packages/nodes/src/slab/geometry.ts index 578e0dc5c4..9e4d26f34b 100644 --- a/packages/nodes/src/slab/geometry.ts +++ b/packages/nodes/src/slab/geometry.ts @@ -6,6 +6,7 @@ import { computePlateSurfacePartition, cutterContextNodes, FenceNode, + FLAT_GROUND_Y, FOUNDATION_SLOT_DEFAULT, floorPlateRoom, type GeometryContext, @@ -265,7 +266,8 @@ function buildSlabTerrainFillGeometry( const localPoints = points.map(([x, z]) => ({ x, z })) const bottomY = points.map(([x, z]) => { const [siteX, siteZ] = toSite(x, z) - const ground = terrain.field ? surfaceHeightAt(terrain.field, siteX, siteZ) : 0 + // Down to the ground as the site draws it: a flat site's fill lies a hand under the datum. + const ground = terrain.field ? surfaceHeightAt(terrain.field, siteX, siteZ) : FLAT_GROUND_Y return Math.min(top, ground - terrain.baseWorldY) }) const geometry = buildTerrainPerimeterFillGeometry(localPoints, bottomY, top, 1e-4) From 85281199ae915d31163044ffeb9b22796f1ef5c2 Mon Sep 17 00:00:00 2001 From: Wassim SAMAD Date: Mon, 2 Nov 2026 10:59:01 -0500 Subject: [PATCH 4/4] The terrain never shows over a floor inside its own plate The ground was cut open only where it stood more than 0.3 m (BELOW_GRADE_TOLERANCE) over a floor, so on a hillside the slope the terrain interpolates between the floor and 0.3 m over it showed as thin wedges inside a walk-out's rooms. terrainOverFloors gives the part of every visible floor plate the rendered terrain stands over at all, and the site cuts the ground there with the cover under the house. The tolerance still decides grade standing, the hole and the pit. Co-Authored-By: Claude Opus 5.5 --- packages/core/src/index.ts | 1 + .../src/lib/below-grade-footprints.test.ts | 26 ++++++++++++ .../core/src/lib/below-grade-footprints.ts | 41 +++++++++++++++++++ packages/nodes/src/site/renderer.tsx | 18 ++++++-- 4 files changed, 83 insertions(+), 3 deletions(-) diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index d633ea7944..54c1e2c9fa 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -165,6 +165,7 @@ export { GROUND_PIT_FLOOR_DROP, GROUND_PIT_PLATE_CLEARANCE, groundPitFloorY, + terrainOverFloors, } from './lib/below-grade-footprints' export { CEILING_BUILD_UP_PRESETS, diff --git a/packages/core/src/lib/below-grade-footprints.test.ts b/packages/core/src/lib/below-grade-footprints.test.ts index f3b4a3df77..ce989e916c 100644 --- a/packages/core/src/lib/below-grade-footprints.test.ts +++ b/packages/core/src/lib/below-grade-footprints.test.ts @@ -13,6 +13,7 @@ import { coveredBelowGradeFootprints, GROUND_PIT_PLATE_CLEARANCE, groundPitFloorY, + terrainOverFloors, } from './below-grade-footprints' import { levelGradeStanding } from './grade-standing' import { levelGroundBox, levelStackGroundBox, terrainBetweenEyeAndBox } from './ground-window' @@ -337,6 +338,31 @@ test('a walk-out whose buried part is wider than the cellar opens it, the edge f expect(belowGradeFootprints(nodes, 'level_walkout')).toHaveLength(1) }) +test('the terrain is cut wherever it stands over a floor inside its plate, the tolerance band included', () => { + // The ground climbs 0.4 m: over the walk-out's 0.2 m floor, under the 0.5 m below-grade bar. + const nodes = houseOnHillside({ walkoutEast: 9, riseCm: 40 }) + expect(belowGradeFootprints(nodes, 'level_walkout')).toEqual([]) + // Over the floor from x = -0.5 (0.2 m reached on the 0.4 m climb between -1 and 0) to the east + // edge; the cellar, under the ground everywhere, whole: one outline. + const [outline, ...more] = terrainOverFloors(nodes) + expect(more).toEqual([]) + const { x, z } = extent(outline ?? []) + expect(x[0]).toBeCloseTo(-2, 3) + expect(x[1]).toBe(9) + expect(z).toEqual([-4, 4]) + const walkoutOnly = { + ...nodes, + slab_cellar: { ...nodes.slab_cellar, visible: false }, + } as typeof nodes + const [walkout] = terrainOverFloors(walkoutOnly) + expect(extent(walkout ?? []).x[0]).toBeCloseTo(-0.5 + 0.005 / 0.4, 3) +}) + +test('a floor the terrain stays under cuts nothing: on flat ground only the cellar under it is cut', () => { + const cut = terrainOverFloors(houseOnHillside({ riseCm: 0 })) + expect(cut.map(extent)).toEqual([{ x: [-2, 5], z: [-4, 4] }]) +}) + test('a level under the ground line that the ground leaves out of the ground opens nothing', () => { // A flat site at 0 m, the walk-out's floor at 0.2 m: the main floor over it is the ground line, // so the walk-out reads partly below grade, and nothing stands over it. diff --git a/packages/core/src/lib/below-grade-footprints.ts b/packages/core/src/lib/below-grade-footprints.ts index d9b9650dc6..65cab203f2 100644 --- a/packages/core/src/lib/below-grade-footprints.ts +++ b/packages/core/src/lib/below-grade-footprints.ts @@ -164,6 +164,47 @@ export function coveredBelowGradeFootprints(nodes: Record): return rings } +/** Ground this little over a floor counts as level with it, not over it: the terrain's centimetre steps. */ +const OVER_FLOOR_EPSILON = 0.005 +const overFloorsMemo = new WeakMap() + +/** + * The part of every floor plate the rendered terrain stands over, in the site's plan: each visible + * level's floor slabs (not a recessed pit, not site flatwork), cut where the ground (the triangle + * plane the terrain draws) is higher than that slab's own top. Inside a storey's floor the ground + * is never seen over it: the terrain is cut open there, whatever the level's grade standing. Unlike + * the below-grade outlines this takes no {@link BELOW_GRADE_TOLERANCE}: a slope interpolated a few + * centimetres to 0.3 m over a walk-out's floor near where the ground rises is cut too. Rings only, + * as the cover: an outline with an inner outline is left out. Empty on a site with no terrain. + */ +export function terrainOverFloors(nodes: Record): Point2D[][] { + const hit = overFloorsMemo.get(nodes) + if (hit) return hit + const elevations = getLevelElevations(nodes) + const pieces: Point2D[][] = [] + for (const level of Object.values(nodes)) { + if (level.type !== 'level' || level.visible === false) continue + const field = terrainFieldOverLevel(nodes, level) + const plane = field ? levelPlaneWorldY(nodes, level.id) : null + if (!field || plane === null) continue + const buildingId = elevations.get(level.id)?.buildingId + const building = buildingId ? nodes[buildingId as AnyNodeId] : undefined + const placed = building?.type === 'building' ? building : null + for (const childId of level.children) { + const slab = nodes[childId as AnyNodeId] + if (slab?.type !== 'slab' || slab.recessed === true || isSiteFlatwork(slab)) continue + if (slab.visible === false) continue + const plate = slab.polygon.map(([x, z]) => levelLocalToWorldXZ(placed, x, z)) + pieces.push(...groundOverPart(plate, field, plane + slab.elevation + OVER_FLOOR_EPSILON)) + } + } + const rings = union(pieces) + .filter((polygon) => polygon.holes.length === 0) + .map((polygon) => polygon.outer) + overFloorsMemo.set(nodes, rings) + return rings +} + /** * How deep the pit under the hole goes: the world Y of the top of the lowest floor of the level * shown (the sunken room of a split level, not its raised part), the deepest of the levels the hole diff --git a/packages/nodes/src/site/renderer.tsx b/packages/nodes/src/site/renderer.tsx index 6351a6e36b..6d4fd5aa26 100644 --- a/packages/nodes/src/site/renderer.tsx +++ b/packages/nodes/src/site/renderer.tsx @@ -16,6 +16,7 @@ import { type TerrainField, terrainContours, terrainFieldOf, + terrainOverFloors, union, unionPolygons, useLiveNodeOverrides, @@ -407,6 +408,16 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { return next }) + // Inside a storey's own floor the ground never shows over it: the part of each floor plate the + // terrain stands over (a slope interpolated just over a walk-out's floor included) is cut too. + const overFloorsCache = useRef<[number, number][][]>([]) + const overFloors = useScene((state: S) => { + const next = terrainOverFloors(state.nodes) + if (polygonsMatch(next, overFloorsCache.current)) return overFloorsCache.current + overFloorsCache.current = next + return next + }) + // What the ground is cut open over: the recessed slabs, and the basement under the house. The // house covers that part of a basement, so the ground there is open whatever level is shown: // from outside nothing changes, and a stairwell, a floor opening or a walkthrough on the stair @@ -418,12 +429,13 @@ export const SiteRenderer = ({ node }: { node: SiteNode }) => { // the triangulation. const coverOpen = !(belowGrade && groundMode === 'solid') const holes = useMemo(() => { - if (!coverOpen || buried.covered.length === 0 || !polygonPoints || polygonPoints.length < 3) + const open = [...buried.covered, ...overFloors] + if (!coverOpen || open.length === 0 || !polygonPoints || polygonPoints.length < 3) return slabPolygons - const inLot = intersection(union(buried.covered), polygonPoints as [number, number][]) + const inLot = intersection(union(open), polygonPoints as [number, number][]) const covered = inLot.filter((piece) => piece.holes.length === 0).map((piece) => piece.outer) return covered.length > 0 ? [...slabPolygons, ...covered] : slabPolygons - }, [coverOpen, buried.covered, polygonPoints, slabPolygons]) + }, [coverOpen, buried.covered, overFloors, polygonPoints, slabPolygons]) // Ground shape: site polygon with slab footprints punched as holes const groundShape = useMemo(() => {