From ed6ceb404991236f98942e4beb316f3744d34585 Mon Sep 17 00:00:00 2001 From: kruschdev Date: Wed, 25 Nov 2026 19:52:28 +0000 Subject: [PATCH 1/2] terrain: add planar ground slope, slope brush, and two-point grade picker --- packages/core/src/index.ts | 19 + packages/core/src/lib/terrain-brush.test.ts | 36 ++ packages/core/src/lib/terrain-brush.ts | 19 +- packages/core/src/lib/terrain-slope.test.ts | 151 ++++++++ packages/core/src/lib/terrain-slope.ts | 253 +++++++++++++ .../tools/site/terrain-brush-cursor.tsx | 130 ++++++- .../tools/site/terrain-sculpt-tool.tsx | 72 +++- .../ui/controls/terrain-sculpt-panel.tsx | 340 +++++++++++++++++- .../components/ui/helpers/helper-manager.tsx | 37 +- .../editor/src/i18n/locales/en-XA/messages.ts | 2 +- .../editor/src/i18n/locales/en/messages.po | 104 ++++++ .../editor/src/i18n/locales/en/messages.ts | 2 +- .../editor/src/i18n/locales/es/messages.po | 208 +++++++++++ .../editor/src/i18n/locales/fr/messages.po | 208 +++++++++++ .../editor/src/i18n/locales/ja/messages.po | 208 +++++++++++ .../editor/src/i18n/locales/zh-CN/messages.po | 208 +++++++++++ packages/editor/src/index.tsx | 2 + packages/editor/src/lib/hud-title.ts | 6 + packages/editor/src/lib/sfx-bus.ts | 1 + .../editor/src/lib/terrain-panel-model.ts | 56 ++- .../editor/src/lib/terrain-sculpt.test.ts | 82 +++++ packages/editor/src/lib/terrain-sculpt.ts | 52 +++ .../editor/src/lib/terrain-verb-color.test.ts | 2 +- packages/editor/src/lib/terrain-verb-color.ts | 1 + .../src/store/terrain-sculpt-mode.test.ts | 34 ++ packages/editor/src/store/use-editor.tsx | 96 ++++- 26 files changed, 2273 insertions(+), 56 deletions(-) create mode 100644 packages/core/src/lib/terrain-slope.test.ts create mode 100644 packages/core/src/lib/terrain-slope.ts diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 6ce0d3c07f..a0695c639c 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -849,6 +849,7 @@ export { } from './lib/structure-reconcile' export { advanceStroke, + type BaseTerrainVerb, type BrushSettings, type BrushShape, beginStroke, @@ -893,6 +894,24 @@ export { type TerrainField, } from './lib/terrain-field' export { raycastTerrain, type TerrainHit } from './lib/terrain-raycast' +export { + buildSlopedTerrainField, + clampTerrainSlopePitch, + DEFAULT_TERRAIN_SLOPE_SPEC, + type DerivedTerrainSlope, + deriveTerrainSlopeFromPoints, + evaluateTerrainSlopePlane, + MAX_TERRAIN_SLOPE_PITCH, + normalizeTerrainSlopeDirection, + resolveLotSlopePlane, + type TerrainSlopeAnchor, + type TerrainSlopePlane, + type TerrainSlopePoint, + type TerrainSlopeSpec, + terrainSlopeDirectionVector, + terrainSlopeElevationRange, + terrainSlopeGradePercent, +} from './lib/terrain-slope' export { commitTerrainField, persistedTerrainFieldOf, diff --git a/packages/core/src/lib/terrain-brush.test.ts b/packages/core/src/lib/terrain-brush.test.ts index 22f284cbc1..d97ae1b8eb 100644 --- a/packages/core/src/lib/terrain-brush.test.ts +++ b/packages/core/src/lib/terrain-brush.test.ts @@ -455,3 +455,39 @@ describe('highestOver', () => { expect(highestOver(raised, -8, -8, -6, -6)).toBeCloseTo(0, 6) }) }) + +describe('slope verb', () => { + test('grades brushed samples toward the target inclined plane without compounding', () => { + const base = field() + const slope = { + anchorX: 0, + anchorZ: 0, + anchorY: 0, + direction: 0, + pitch: Math.atan(0.2) * (180 / Math.PI), + } + + const once = stroke( + base, + { verb: 'slope', slope, settings: { radius: 4, strength: 1, falloff: 0 } }, + [[0, 0]], + ) + expect(heightAt(once, 0, 0)).toBeCloseTo(0, 2) + expect(heightAt(once, 2, 0)).toBeCloseTo(0.4, 2) + expect(heightAt(once, -2, 0)).toBeCloseTo(-0.4, 2) + // Untouched area outside brush radius remains flat at datum. + expect(heightAt(once, 8, 8)).toBeCloseTo(0, 6) + + // Re-crossing the same area within one stroke never overshoots or compounds. + const recrossed = stroke( + base, + { verb: 'slope', slope, settings: { radius: 4, strength: 0.5, falloff: 0 } }, + [ + [0, 0], + [2, 0], + [0, 0], + ], + ) + expect(heightAt(recrossed, 2, 0)).toBeCloseTo(0.2, 2) + }) +}) diff --git a/packages/core/src/lib/terrain-brush.ts b/packages/core/src/lib/terrain-brush.ts index 5c2e4c6e09..03216964ea 100644 --- a/packages/core/src/lib/terrain-brush.ts +++ b/packages/core/src/lib/terrain-brush.ts @@ -38,6 +38,7 @@ import { quantize, type TerrainField, } from './terrain-field' +import { evaluateTerrainSlopePlane, type TerrainSlopePlane } from './terrain-slope' export type BrushShape = 'round' | 'square' @@ -47,7 +48,8 @@ export type BrushShape = 'round' | 'square' * it converges on a target height, which is the operation that makes two * disjoint building pads provably equal — the thing freehand push/pull cannot do. */ -export type TerrainVerb = 'raise' | 'lower' | 'flatten' | 'smooth' +export type BaseTerrainVerb = 'raise' | 'lower' | 'flatten' | 'smooth' +export type TerrainVerb = BaseTerrainVerb | 'slope' export type BrushSettings = { /** Brush radius in metres. */ @@ -124,6 +126,8 @@ export type TerrainStroke = { readonly snapshot: TerrainField /** Absolute target height in metres. Only meaningful for `flatten`. */ readonly target: number + /** Target inclined plane in world space. Only meaningful for `slope`. */ + readonly slope: TerrainSlopePlane | null /** Sample index → saturating coverage in 0–1. */ readonly mask: Map /** Lazily computed diffused snapshot, for `smooth`. */ @@ -139,12 +143,15 @@ export function beginStroke(options: { settings?: Partial /** Absolute height for `flatten`, in metres. Ignored by the other verbs. */ target?: number + /** Target inclined plane for `slope`. Ignored by the other verbs. */ + slope?: TerrainSlopePlane }): TerrainStroke { return { verb: options.verb, settings: { ...DEFAULT_BRUSH_SETTINGS, ...options.settings }, snapshot: options.field, target: options.target ?? 0, + slope: options.slope ?? null, mask: new Map(), smoothed: null, lastX: null, @@ -268,10 +275,14 @@ function resolveSample(stroke: TerrainStroke, index: number, col: number, row: n const goal = (smoothed[index] ?? base) * field.step return quantize(field, baseMetres + (goal - baseMetres) * amount) } + case 'slope': { + if (!stroke.slope) return base + const sampleX = field.origin[0] + col * field.spacing + const sampleZ = field.origin[1] + row * field.spacing + const goal = evaluateTerrainSlopePlane(stroke.slope, sampleX, sampleZ) + return quantize(field, baseMetres + (goal - baseMetres) * amount) + } default: - // `col`/`row` are carried for future verbs that need position (terrace). - void col - void row return base } } diff --git a/packages/core/src/lib/terrain-slope.test.ts b/packages/core/src/lib/terrain-slope.test.ts new file mode 100644 index 0000000000..71643af785 --- /dev/null +++ b/packages/core/src/lib/terrain-slope.test.ts @@ -0,0 +1,151 @@ +import { describe, expect, test } from 'bun:test' +import { isDatumField } from './terrain-codec' +import { createTerrainField, heightAt } from './terrain-field' +import { + buildSlopedTerrainField, + clampTerrainSlopePitch, + deriveTerrainSlopeFromPoints, + evaluateTerrainSlopePlane, + MAX_TERRAIN_SLOPE_PITCH, + normalizeTerrainSlopeDirection, + resolveLotSlopePlane, + terrainSlopeElevationRange, + terrainSlopeGradePercent, +} from './terrain-slope' + +const LOT: Array<[number, number]> = [ + [-10, -20], + [10, -20], + [10, 20], + [-10, 20], +] + +describe('terrain-slope math', () => { + test('clamps pitch and normalizes direction cleanly', () => { + expect(clampTerrainSlopePitch(-5)).toBe(0) + expect(clampTerrainSlopePitch(Number.NaN)).toBe(0) + expect(clampTerrainSlopePitch(12.5)).toBe(12.5) + expect(clampTerrainSlopePitch(90)).toBe(MAX_TERRAIN_SLOPE_PITCH) + + expect(normalizeTerrainSlopeDirection(0)).toBe(0) + expect(normalizeTerrainSlopeDirection(-0)).toBe(0) + expect(normalizeTerrainSlopeDirection(360)).toBe(0) + expect(normalizeTerrainSlopeDirection(-90)).toBe(270) + expect(normalizeTerrainSlopeDirection(450)).toBe(90) + expect(normalizeTerrainSlopeDirection(Number.POSITIVE_INFINITY)).toBe(0) + }) + + test('computes grade percentage accurately', () => { + expect(terrainSlopeGradePercent(0)).toBe(0) + expect(terrainSlopeGradePercent(45)).toBeCloseTo(100, 6) + expect(terrainSlopeGradePercent(Math.atan(0.08) * (180 / Math.PI))).toBeCloseTo(8, 6) + }) + + test('center anchor pins baseElevation at lot center', () => { + const plane = resolveLotSlopePlane(LOT, { + pitch: 45, + direction: 0, + baseElevation: 1.5, + anchor: 'center', + }) + expect(evaluateTerrainSlopePlane(plane, 0, 0)).toBeCloseTo(1.5, 6) + expect(evaluateTerrainSlopePlane(plane, 10, 0)).toBeCloseTo(11.5, 6) + expect(evaluateTerrainSlopePlane(plane, -10, 0)).toBeCloseTo(-8.5, 6) + }) + + test('low-edge anchor pins baseElevation at minimum projection vertex', () => { + const plane = resolveLotSlopePlane(LOT, { + pitch: 45, + direction: 90, + baseElevation: 0.5, + anchor: 'low-edge', + }) + expect(evaluateTerrainSlopePlane(plane, 0, -20)).toBeCloseTo(0.5, 6) + expect(evaluateTerrainSlopePlane(plane, 0, 0)).toBeCloseTo(20.5, 6) + expect(evaluateTerrainSlopePlane(plane, 0, 20)).toBeCloseTo(40.5, 6) + }) + + test('reports lot min/max/rise range', () => { + const range = terrainSlopeElevationRange(LOT, { + pitch: Math.atan(0.1) * (180 / Math.PI), + direction: 90, + baseElevation: 0, + anchor: 'center', + }) + expect(range.gradePercent).toBeCloseTo(10, 5) + expect(range.min).toBeCloseTo(-2, 5) + expect(range.max).toBeCloseTo(2, 5) + expect(range.rise).toBeCloseTo(4, 5) + }) +}) + +describe('deriveTerrainSlopeFromPoints', () => { + test('derives exact uphill plane from two points', () => { + const derived = deriveTerrainSlopeFromPoints([0, 0, 1], [10, 0, 3]) + expect(derived).not.toBeNull() + expect(derived!.direction).toBeCloseTo(0, 5) + expect(derived!.pitch).toBeCloseTo((Math.atan(0.2) * 180) / Math.PI, 5) + expect(derived!.clamped).toBe(false) + + const plane = { + anchorX: derived!.anchor[0], + anchorZ: derived!.anchor[1], + anchorY: derived!.anchor[2], + direction: derived!.direction, + pitch: derived!.pitch, + } + expect(evaluateTerrainSlopePlane(plane, 0, 0)).toBeCloseTo(1, 5) + expect(evaluateTerrainSlopePlane(plane, 5, 0)).toBeCloseTo(2, 5) + expect(evaluateTerrainSlopePlane(plane, 10, 0)).toBeCloseTo(3, 5) + }) + + test('flips uphill direction when end point is lower than start point', () => { + const derived = deriveTerrainSlopeFromPoints([0, 0, 4], [0, 10, 2]) + expect(derived).not.toBeNull() + expect(derived!.direction).toBeCloseTo(270, 5) + const plane = { + anchorX: derived!.anchor[0], + anchorZ: derived!.anchor[1], + anchorY: derived!.anchor[2], + direction: derived!.direction, + pitch: derived!.pitch, + } + expect(evaluateTerrainSlopePlane(plane, 0, 0)).toBeCloseTo(4, 5) + expect(evaluateTerrainSlopePlane(plane, 0, 10)).toBeCloseTo(2, 5) + }) + + test('handles flat, steep-clamped, and coincident points', () => { + const flat = deriveTerrainSlopeFromPoints([0, 0, 2], [5, 5, 2]) + expect(flat?.pitch).toBe(0) + expect(flat?.verticalDelta).toBe(0) + + const steep = deriveTerrainSlopeFromPoints([0, 0, 0], [1, 0, 10]) + expect(steep?.pitch).toBe(MAX_TERRAIN_SLOPE_PITCH) + expect(steep?.clamped).toBe(true) + + expect(deriveTerrainSlopeFromPoints([2, 3, 1], [2, 3, 5])).toBeNull() + }) +}) + +describe('buildSlopedTerrainField', () => { + test('grades the full heightfield accurately and returns datum when flat at 0', () => { + const base = createTerrainField({ origin: [-12, -22], cols: 65, rows: 129, spacing: 0.5 }) + const sloped = buildSlopedTerrainField(base, LOT, { + pitch: Math.atan(0.05) * (180 / Math.PI), + direction: 90, + baseElevation: 0, + anchor: 'center', + }) + expect(isDatumField(sloped)).toBe(false) + expect(heightAt(sloped, 0, 0)).toBeCloseTo(0, 2) + expect(heightAt(sloped, 0, 20)).toBeCloseTo(1, 2) + expect(heightAt(sloped, 0, -20)).toBeCloseTo(-1, 2) + + const flatZero = buildSlopedTerrainField(sloped, LOT, { + pitch: 0, + direction: 90, + baseElevation: 0, + }) + expect(isDatumField(flatZero)).toBe(true) + }) +}) diff --git a/packages/core/src/lib/terrain-slope.ts b/packages/core/src/lib/terrain-slope.ts new file mode 100644 index 0000000000..83fbfeee88 --- /dev/null +++ b/packages/core/src/lib/terrain-slope.ts @@ -0,0 +1,253 @@ +/** + * Pure planar slope and linear grade math for heightfield terrain. + * + * Uses the same plan azimuth convention as sloped slabs (`0° = +X`, `90° = +Z`, + * `180° = -X`, `270° = -Z`), where `direction` points uphill and `pitch` is the + * inclination angle in degrees (`0..45°`). + * + * Pure data — no Three.js, per the core layer rule. + */ + +import { quantize, type TerrainField } from './terrain-field' + +export const MAX_TERRAIN_SLOPE_PITCH = 45 + +export type TerrainSlopeAnchor = 'center' | 'low-edge' + +export type TerrainSlopeSpec = { + /** Inclination angle in degrees (`0..45`). */ + readonly pitch: number + /** Uphill azimuth in degrees (`0 = +X`, `90 = +Z`). */ + readonly direction: number + /** Elevation in metres at the resolved anchor (`center` or `low-edge`). */ + readonly baseElevation: number + /** Where `baseElevation` is pinned on the lot polygon. Defaults to `center`. */ + readonly anchor?: TerrainSlopeAnchor +} + +export type TerrainSlopePlane = { + readonly anchorX: number + readonly anchorZ: number + readonly anchorY: number + /** Uphill azimuth in degrees (`0 = +X`, `90 = +Z`). */ + readonly direction: number + /** Inclination angle in degrees (`0..45`). */ + readonly pitch: number +} + +export type TerrainSlopePoint = readonly [x: number, z: number, y: number] + +export type DerivedTerrainSlope = { + readonly pitch: number + readonly direction: number + readonly anchor: [number, number, number] + readonly horizontalDistance: number + readonly verticalDelta: number + readonly clamped: boolean +} + +export const DEFAULT_TERRAIN_SLOPE_SPEC: TerrainSlopeSpec = { + pitch: 5, + direction: 0, + baseElevation: 0, + anchor: 'center', +} + +/** Clamp pitch to `[0, MAX_TERRAIN_SLOPE_PITCH]`, guarding against NaN/Infinity. */ +export function clampTerrainSlopePitch(pitch: number): number { + if (!Number.isFinite(pitch) || pitch <= 0) return 0 + return Math.min(MAX_TERRAIN_SLOPE_PITCH, pitch) +} + +/** Wrap azimuth degrees cleanly into `[0, 360)`. */ +export function normalizeTerrainSlopeDirection(direction: number): number { + if (!Number.isFinite(direction)) return 0 + const wrapped = ((direction % 360) + 360) % 360 + return wrapped === 360 || Object.is(wrapped, -0) ? 0 : wrapped +} + +/** Unit vector in XZ pointing uphill along `direction` degrees. */ +export function terrainSlopeDirectionVector(direction: number): { dx: number; dz: number } { + const rad = (normalizeTerrainSlopeDirection(direction) * Math.PI) / 180 + return { dx: Math.cos(rad), dz: Math.sin(rad) } +} + +/** Grade percentage (`rise / run * 100`) for a pitch in degrees. */ +export function terrainSlopeGradePercent(pitch: number): number { + const clamped = clampTerrainSlopePitch(pitch) + if (clamped === 0) return 0 + return Math.tan((clamped * Math.PI) / 180) * 100 +} + +/** Evaluate a planar terrain slope at world `(x, z)` in metres. */ +export function evaluateTerrainSlopePlane(plane: TerrainSlopePlane, x: number, z: number): number { + const anchorY = Number.isFinite(plane.anchorY) ? plane.anchorY : 0 + const pitch = clampTerrainSlopePitch(plane.pitch) + if (pitch === 0) return anchorY + const { dx, dz } = terrainSlopeDirectionVector(plane.direction) + const tanPitch = Math.tan((pitch * Math.PI) / 180) + const projection = (x - plane.anchorX) * dx + (z - plane.anchorZ) * dz + return anchorY + projection * tanPitch +} + +/** + * Resolve a whole-lot `TerrainSlopeSpec` into an anchored plane over `polygon`. + * + * - `center` (default) pins `baseElevation` at the polygon bounding-box centre, + * matching the site datum convention used by USGS DEM lot imports (`y = 0` at + * lot centre so a centred building stays on grade). + * - `low-edge` pins `baseElevation` at the lowest-projection vertex along the + * uphill vector, so the entire lot rises monotonically from `baseElevation`. + */ +export function resolveLotSlopePlane( + polygon: ReadonlyArray, + spec: TerrainSlopeSpec, +): TerrainSlopePlane { + const pitch = clampTerrainSlopePitch(spec.pitch) + const direction = normalizeTerrainSlopeDirection(spec.direction) + const baseElevation = Number.isFinite(spec.baseElevation) ? spec.baseElevation : 0 + const anchor = spec.anchor ?? 'center' + + if (polygon.length === 0) { + return { anchorX: 0, anchorZ: 0, anchorY: baseElevation, direction, pitch } + } + + if (anchor === 'low-edge') { + const { dx, dz } = terrainSlopeDirectionVector(direction) + let minProj = Number.POSITIVE_INFINITY + for (const [x, z] of polygon) { + const proj = x * dx + z * dz + if (proj < minProj) minProj = proj + } + return { + anchorX: minProj * dx, + anchorZ: minProj * dz, + anchorY: baseElevation, + direction, + pitch, + } + } + + let minX = Number.POSITIVE_INFINITY + let maxX = Number.NEGATIVE_INFINITY + let minZ = Number.POSITIVE_INFINITY + let maxZ = Number.NEGATIVE_INFINITY + for (const [x, z] of polygon) { + if (x < minX) minX = x + if (x > maxX) maxX = x + if (z < minZ) minZ = z + if (z > maxZ) maxZ = z + } + return { + anchorX: (minX + maxX) / 2, + anchorZ: (minZ + maxZ) / 2, + anchorY: baseElevation, + direction, + pitch, + } +} + +/** Min/max elevation, total rise, and grade % across `polygon` for `spec`. */ +export function terrainSlopeElevationRange( + polygon: ReadonlyArray, + spec: TerrainSlopeSpec, +): { min: number; max: number; rise: number; gradePercent: number } { + const plane = resolveLotSlopePlane(polygon, spec) + const gradePercent = terrainSlopeGradePercent(plane.pitch) + if (polygon.length === 0) { + return { min: plane.anchorY, max: plane.anchorY, rise: 0, gradePercent } + } + + let min = Number.POSITIVE_INFINITY + let max = Number.NEGATIVE_INFINITY + for (const [x, z] of polygon) { + const y = evaluateTerrainSlopePlane(plane, x, z) + if (y < min) min = y + if (y > max) max = y + } + return { min, max, rise: Math.max(0, max - min), gradePercent } +} + +/** + * Derive an exact planar slope passing through two 3D ground points `[x, z, y]`. + * + * Returns `null` when the two points coincide horizontally or contain non-finite + * coordinates. The uphill direction automatically orients from the lower point + * toward the higher point; pitch is clamped to `MAX_TERRAIN_SLOPE_PITCH`. + */ +export function deriveTerrainSlopeFromPoints( + start: TerrainSlopePoint, + end: TerrainSlopePoint, +): DerivedTerrainSlope | null { + const [x1, z1, y1] = start + const [x2, z2, y2] = end + if ( + !( + Number.isFinite(x1) && + Number.isFinite(z1) && + Number.isFinite(y1) && + Number.isFinite(x2) && + Number.isFinite(z2) && + Number.isFinite(y2) + ) + ) { + return null + } + + const dx = x2 - x1 + const dz = z2 - z1 + const horizontalDistance = Math.hypot(dx, dz) + if (horizontalDistance < 1e-4) return null + + const verticalDelta = y2 - y1 + if (Math.abs(verticalDelta) < 1e-4) { + return { + pitch: 0, + direction: normalizeTerrainSlopeDirection((Math.atan2(dz, dx) * 180) / Math.PI), + anchor: [x1, z1, y1], + horizontalDistance, + verticalDelta: 0, + clamped: false, + } + } + + const uphillDx = verticalDelta >= 0 ? dx : -dx + const uphillDz = verticalDelta >= 0 ? dz : -dz + const direction = normalizeTerrainSlopeDirection((Math.atan2(uphillDz, uphillDx) * 180) / Math.PI) + const rawPitch = (Math.atan2(Math.abs(verticalDelta), horizontalDistance) * 180) / Math.PI + const pitch = clampTerrainSlopePitch(rawPitch) + + return { + pitch, + direction, + anchor: [x1, z1, y1], + horizontalDistance, + verticalDelta, + clamped: rawPitch > MAX_TERRAIN_SLOPE_PITCH, + } +} + +/** + * Evaluate a planar slope across every sample of `field` (including its padded + * margin outside `polygon` so the property boundary sits on continuous sloped + * ground without a cliff). + */ +export function buildSlopedTerrainField( + field: TerrainField, + polygon: ReadonlyArray, + spec: TerrainSlopeSpec, +): TerrainField { + const plane = resolveLotSlopePlane(polygon, spec) + const heights = new Int16Array(field.cols * field.rows) + + for (let row = 0; row < field.rows; row += 1) { + const z = field.origin[1] + row * field.spacing + const rowBase = row * field.cols + for (let col = 0; col < field.cols; col += 1) { + const x = field.origin[0] + col * field.spacing + heights[rowBase + col] = quantize(field, evaluateTerrainSlopePlane(plane, x, z)) + } + } + + return { ...field, heights } +} diff --git a/packages/editor/src/components/tools/site/terrain-brush-cursor.tsx b/packages/editor/src/components/tools/site/terrain-brush-cursor.tsx index 08a7fa638d..a6d587970d 100644 --- a/packages/editor/src/components/tools/site/terrain-brush-cursor.tsx +++ b/packages/editor/src/components/tools/site/terrain-brush-cursor.tsx @@ -7,6 +7,7 @@ import { surfaceHeightAt, type TerrainField, terrainFieldOf, + terrainSlopeDirectionVector, useLiveTerrain, } from '@pascal-app/core' import { useViewer } from '@pascal-app/viewer' @@ -23,12 +24,14 @@ import { } from 'three' import { EDITOR_LAYER } from '../../../lib/constants' import { sculptFieldForSite, terrainPointInsideSite } from '../../../lib/terrain-sculpt' -import { brushRingColor } from '../../../lib/terrain-verb-color' -import useEditor from '../../../store/use-editor' +import { brushRingColor, TERRAIN_SAMPLING_COLOR } from '../../../lib/terrain-verb-color' +import useEditor, { selectActiveTerrainVerb } from '../../../store/use-editor' import { formatMeasurement } from '../../editor/measurement-pill' /** Segments in the cursor ring. 64 reads as a circle at any usable brush size. */ const RING_SEGMENTS = 64 +const ARROW_POINTS = 5 +const PICK_LINE_SEGMENTS = 16 /** * Lift above the surface, so the ring is not z-fighting the ground it traces. @@ -75,13 +78,17 @@ export const TerrainBrushCursor: React.FC<{ // The ring is the only thing at the point of action that can say what the next // drag will do — its geometry is identical for all four verbs, so colour is the // one channel left. Keep the mapping centralized in `lib/terrain-verb-color`. - const verb = useEditor((state) => state.terrainVerb) + const verb = useEditor(selectActiveTerrainVerb) const sampling = useEditor((state) => state.terrainSampling) + const slopeDirection = useEditor((state) => state.terrainSlope.direction) + const slopePickStart = useEditor((state) => state.terrainSlopePickStart) const color = brushRingColor(verb, sampling) const unit = useViewer((state) => state.unit) const metricNotation = useViewer((state) => state.metricNotation) const lineRef = useRef(null) + const arrowLineRef = useRef(null) + const pickLineRef = useRef(null) const centerRef = useRef(null) const heightRef = useRef(null) const lastHeightLabelRef = useRef('') @@ -95,7 +102,25 @@ export const TerrainBrushCursor: React.FC<{ buffer.setAttribute('position', new Float32BufferAttribute(positions, 3)) return buffer }, []) - useEffect(() => () => geometry.dispose(), [geometry]) + const arrowGeometry = useMemo(() => { + const positions = new Float32Array(ARROW_POINTS * 3) + const buffer = new BufferGeometry() + buffer.setAttribute('position', new Float32BufferAttribute(positions, 3)) + return buffer + }, []) + const pickLineGeometry = useMemo(() => { + const positions = new Float32Array((PICK_LINE_SEGMENTS + 1) * 3) + const buffer = new BufferGeometry() + buffer.setAttribute('position', new Float32BufferAttribute(positions, 3)) + return buffer + }, []) + useEffect(() => { + return () => { + geometry.dispose() + arrowGeometry.dispose() + pickLineGeometry.dispose() + } + }, [geometry, arrowGeometry, pickLineGeometry]) useEffect(() => { const canvas = gl.domElement @@ -119,11 +144,15 @@ export const TerrainBrushCursor: React.FC<{ useFrame(() => { const line = lineRef.current + const arrowLine = arrowLineRef.current + const pickLine = pickLineRef.current const center = centerRef.current const pointer = pointerRef.current if (!(line && center)) return if (!(pointer || focusRef.current)) { line.visible = false + if (arrowLine) arrowLine.visible = false + if (pickLine) pickLine.visible = false center.visible = false if (heightRef.current) heightRef.current.style.display = 'none' return @@ -161,6 +190,8 @@ export const TerrainBrushCursor: React.FC<{ } if (!hit) { line.visible = false + if (arrowLine) arrowLine.visible = false + if (pickLine) pickLine.visible = false center.visible = false if (heightRef.current) heightRef.current.style.display = 'none' return @@ -194,6 +225,68 @@ export const TerrainBrushCursor: React.FC<{ attribute.needsUpdate = true line.geometry.computeBoundingSphere() + // Uphill direction arrow inside the brush ring when in slope mode (not while picking). + if (arrowLine) { + if (verb === 'slope' && !sampling) { + const { dx, dz } = terrainSlopeDirectionVector(slopeDirection) + const perpX = -dz + const perpZ = dx + const halfLen = drawn * 0.55 + const headLen = drawn * 0.25 + const headHalfWidth = drawn * 0.2 + const tailX = hit.x - dx * halfLen + const tailZ = hit.z - dz * halfLen + const tipX = hit.x + dx * halfLen + const tipZ = hit.z + dz * halfLen + const leftX = tipX - dx * headLen - perpX * headHalfWidth + const leftZ = tipZ - dz * headLen - perpZ * headHalfWidth + const rightX = tipX - dx * headLen + perpX * headHalfWidth + const rightZ = tipZ - dz * headLen + perpZ * headHalfWidth + + const pts: Array<[number, number]> = [ + [tailX, tailZ], + [tipX, tipZ], + [leftX, leftZ], + [tipX, tipZ], + [rightX, rightZ], + ] + const arrowAttr = arrowLine.geometry.getAttribute('position') + const arrowArr = arrowAttr.array as Float32Array + for (let i = 0; i < pts.length; i++) { + const [px, pz] = pts[i]! + arrowArr[i * 3] = px + arrowArr[i * 3 + 1] = surfaceHeightAt(surface, px, pz) + RING_LIFT + arrowArr[i * 3 + 2] = pz + } + arrowAttr.needsUpdate = true + arrowLine.geometry.computeBoundingSphere() + arrowLine.visible = true + } else { + arrowLine.visible = false + } + } + + // Two-point A -> B guide line while picking the second slope point. + if (pickLine) { + if (verb === 'slope' && sampling && slopePickStart) { + const pickAttr = pickLine.geometry.getAttribute('position') + const pickArr = pickAttr.array as Float32Array + for (let i = 0; i <= PICK_LINE_SEGMENTS; i++) { + const t = i / PICK_LINE_SEGMENTS + const px = slopePickStart[0] + (hit.x - slopePickStart[0]) * t + const pz = slopePickStart[1] + (hit.z - slopePickStart[1]) * t + pickArr[i * 3] = px + pickArr[i * 3 + 1] = surfaceHeightAt(surface, px, pz) + RING_LIFT + pickArr[i * 3 + 2] = pz + } + pickAttr.needsUpdate = true + pickLine.geometry.computeBoundingSphere() + pickLine.visible = true + } else { + pickLine.visible = false + } + } + const centerHeight = surfaceHeightAt(surface, hit.x, hit.z) center.position.set(hit.x, centerHeight + RING_LIFT, hit.z) const heightLabel = `H ${formatMeasurement(centerHeight, unit, metricNotation)}` @@ -219,6 +312,35 @@ export const TerrainBrushCursor: React.FC<{ > + element conflicts with SVG type + ref={arrowLineRef} + renderOrder={13} + visible={false} + > + + + element conflicts with SVG type + ref={pickLineRef} + renderOrder={13} + visible={false} + > + + { const brushFocusRef = useRef(null) const nodes = useScene((state) => state.nodes) const rootNodeIds = useScene((state) => state.rootNodeIds) - const verb = useEditor((state) => state.terrainVerb) + const verb = useEditor(selectActiveTerrainVerb) const brush = useEditor((state) => state.terrainBrush) const flattenTarget = useEditor((state) => state.terrainFlattenTarget) const sampling = useEditor((state) => state.terrainSampling) + const slope = useEditor((state) => state.terrainSlope) + const slopeAnchor = useEditor((state) => state.terrainSlopeAnchor) + const slopePickStart = useEditor((state) => state.terrainSlopePickStart) const siteNode = rootNodeIds[0] ? nodes[rootNodeIds[0]] : null const site = siteNode?.type === 'site' ? (siteNode as SiteNode) : null @@ -72,8 +77,26 @@ export const TerrainSculptTool: React.FC = () => { // Everything the pointer handlers need, mirrored into refs so the listener // effect depends only on the canvas and camera. Re-attaching listeners because // the brush radius changed would drop an in-flight stroke. - const latest = useRef({ site, verb, brush, flattenTarget, sampling }) - latest.current = { site, verb, brush, flattenTarget, sampling } + const latest = useRef({ + site, + verb, + brush, + flattenTarget, + sampling, + slope, + slopeAnchor, + slopePickStart, + }) + latest.current = { + site, + verb, + brush, + flattenTarget, + sampling, + slope, + slopeAnchor, + slopePickStart, + } const strokeRef = useRef<{ stroke: TerrainStroke @@ -161,7 +184,27 @@ export const TerrainSculptTool: React.FC = () => { // Eyedropper: sample and consume the click. Sampling *is* the gesture, so // it must not also deposit a dab. if (latest.current.sampling) { - useEditor.getState().setTerrainFlattenTarget(resolveFlattenTarget(field, null, ...point)) + const sampledHeight = resolveFlattenTarget(field, null, ...point) + if (activeVerb === 'slope') { + const picked: [number, number, number] = [point[0], point[1], sampledHeight] + const start = latest.current.slopePickStart + if (!start) { + useEditor.getState().setTerrainSlopePickStart(picked) + return + } + const derived = deriveTerrainSlopeFromPoints(start, picked) + if (derived) { + const editor = useEditor.getState() + editor.setTerrainSlope({ + pitch: Math.round(derived.pitch * 10) / 10, + direction: Math.round(derived.direction), + }) + editor.setTerrainSlopeAnchor(derived.anchor) + editor.setTerrainSampling(false) + } + return + } + useEditor.getState().setTerrainFlattenTarget(sampledHeight) return } @@ -178,6 +221,16 @@ export const TerrainSculptTool: React.FC = () => { settings: { ...settings, radius: Math.max(settings.radius, minBrushRadius(field)) }, target: activeVerb === 'flatten' ? resolveFlattenTarget(field, explicit, ...point) : undefined, + slope: + activeVerb === 'slope' + ? resolveSlopeStrokePlane( + field, + latest.current.slope, + point[0], + point[1], + latest.current.slopeAnchor, + ) + : undefined, }) strokeRef.current = { stroke, @@ -306,7 +359,14 @@ export const TerrainSculptTool: React.FC = () => { const onCancel = () => { // Only claim the key when there was something to abandon, or Escape with no // stroke live would be swallowed and never exit the mode. - if (abandonStroke()) markToolCancelConsumed() + if (abandonStroke()) { + markToolCancelConsumed() + return + } + if (useEditor.getState().terrainSampling) { + useEditor.getState().setTerrainSampling(false) + markToolCancelConsumed() + } } // `pointercancel` abandons rather than commits, unlike `pointerup`: the diff --git a/packages/editor/src/components/ui/controls/terrain-sculpt-panel.tsx b/packages/editor/src/components/ui/controls/terrain-sculpt-panel.tsx index ebf64f2a12..21c656162a 100644 --- a/packages/editor/src/components/ui/controls/terrain-sculpt-panel.tsx +++ b/packages/editor/src/components/ui/controls/terrain-sculpt-panel.tsx @@ -2,34 +2,59 @@ import { type AnyNodeId, + MAX_TERRAIN_SLOPE_PITCH, + normalizeTerrainSlopeDirection, RAISE_METRES_PER_STROKE, type SiteNode, + type TerrainSlopeAnchor, type TerrainVerb, + terrainSlopeElevationRange, + usePascalI18n, useScene, } from '@pascal-app/core' -import { Mountain, Pipette } from 'lucide-react' -import { brushRadiusRange, flattenSite, resetSiteTerrain } from '../../../lib/terrain-sculpt' -import useEditor from '../../../store/use-editor' +import { useViewer } from '@pascal-app/viewer' import { Button } from '@pascal-app/viewer/ui' +import { ArrowLeftRight, Mountain, Pipette, RotateCw, TrendingUp, X } from 'lucide-react' +import { + brushRadiusRange, + flattenSite, + resetSiteTerrain, + slopeSite, +} from '../../../lib/terrain-sculpt' +import useEditor, { selectActiveTerrainVerb } from '../../../store/use-editor' +import { formatMeasurement } from '../../editor/measurement-pill' import { SegmentedControl } from './segmented-control' import { SliderControl } from './slider-control' -const VERB_OPTIONS: Array<{ value: TerrainVerb; iconSrc: string; hint: string }> = [ +const VERB_OPTIONS: Array<{ value: TerrainVerb; iconSrc?: string; hint?: string }> = [ { value: 'raise', iconSrc: '/icons/terrain-raise.webp', hint: 'Raise' }, { value: 'lower', iconSrc: '/icons/terrain-lower.webp', hint: 'Lower' }, { value: 'flatten', iconSrc: '/icons/terrain-flatten.webp', hint: 'Flatten' }, { value: 'smooth', iconSrc: '/icons/terrain-smooth.webp', hint: 'Smooth' }, + { value: 'slope' }, ] -const VERB_HINTS: Record = { +const VERB_HINTS: Record, string> = { raise: `Drag to raise the ground. One pass moves it up to ${RAISE_METRES_PER_STROKE} m — release and drag again to go further.`, lower: `Drag to lower the ground. One pass moves it down to ${RAISE_METRES_PER_STROKE} m.`, flatten: 'Drag to level the ground toward the target height. It never overshoots.', smooth: 'Drag to soften slopes and remove ridges. Flat ground stays flat.', } +const SLOPE_PRESETS: Array<{ id: string; pitch: number; rawLabel?: string }> = [ + { id: 'flat', pitch: 0 }, + { id: '2pct', pitch: Math.round(Math.atan(0.02) * (180 / Math.PI) * 10) / 10, rawLabel: '2%' }, + { id: '5pct', pitch: Math.round(Math.atan(0.05) * (180 / Math.PI) * 10) / 10, rawLabel: '5%' }, + { + id: '1to12', + pitch: Math.round(Math.atan(1 / 12) * (180 / Math.PI) * 10) / 10, + rawLabel: '1:12', + }, + { id: '12pct', pitch: Math.round(Math.atan(0.12) * (180 / Math.PI) * 10) / 10, rawLabel: '12%' }, +] + /** - * Sculpt controls for terrain mode — verb, brush, and the two lot-wide actions. + * Sculpt controls for terrain mode — verb, brush, and lot-wide actions. * * A panel rather than a floating HUD because the brush settings are the sort of * thing a user adjusts between strokes and then leaves alone, and because @@ -41,14 +66,23 @@ const VERB_HINTS: Record = { * `MaterialPaintPanel`. */ export function TerrainSculptPanel() { - const verb = useEditor((state) => state.terrainVerb) - const setTerrainVerb = useEditor((state) => state.setTerrainVerb) + const i18n = usePascalI18n() + const verb = useEditor(selectActiveTerrainVerb) + const setTerrainVerb = useEditor((state) => state.setActiveTerrainVerb) const brush = useEditor((state) => state.terrainBrush) const setTerrainBrush = useEditor((state) => state.setTerrainBrush) const flattenTarget = useEditor((state) => state.terrainFlattenTarget) const setTerrainFlattenTarget = useEditor((state) => state.setTerrainFlattenTarget) const sampling = useEditor((state) => state.terrainSampling) const setTerrainSampling = useEditor((state) => state.setTerrainSampling) + const slope = useEditor((state) => state.terrainSlope) + const setTerrainSlope = useEditor((state) => state.setTerrainSlope) + const slopeAnchor = useEditor((state) => state.terrainSlopeAnchor) + const setTerrainSlopeAnchor = useEditor((state) => state.setTerrainSlopeAnchor) + const slopePickStart = useEditor((state) => state.terrainSlopePickStart) + + const unit = useViewer((state) => state.unit) + const metricNotation = useViewer((state) => state.metricNotation) const nodes = useScene((state) => state.nodes) const rootNodeIds = useScene((state) => state.rootNodeIds) @@ -57,6 +91,18 @@ export function TerrainSculptPanel() { const site = siteNode?.type === 'site' ? (siteNode as SiteNode) : null const [minRadius, maxRadius] = brushRadiusRange(site) + const slopeRange = + verb === 'slope' ? terrainSlopeElevationRange(site?.polygon?.points ?? [], slope) : null + + const verbHintText = + verb === 'slope' + ? i18n._({ + id: 'editor.controls.terrainSculptPanel.slopeHint', + message: + 'Drag to grade the ground along an inclined plane, pick A → B to match two points, or apply the slope to the whole lot.', + }) + : VERB_HINTS[verb] + return (
@@ -67,22 +113,35 @@ export function TerrainSculptPanel() { value, label: ( - - {hint} + {iconSrc ? ( + + ) : ( + + + + )} + + {value === 'slope' + ? i18n._({ + id: 'editor.controls.terrainSculptPanel.slope', + message: 'Slope', + }) + : hint} + ), }))} value={verb} /> -

{VERB_HINTS[verb]}

+

{verbHintText}

@@ -165,6 +224,249 @@ export function TerrainSculptPanel() {
)} + {verb === 'slope' && ( +
+
+ {SLOPE_PRESETS.map((preset) => { + const active = Math.abs(slope.pitch - preset.pitch) < 0.05 + const label = + preset.rawLabel ?? + i18n._({ + id: 'editor.controls.terrainSculptPanel.presetFlat', + message: 'Flat', + }) + return ( + + ) + })} +
+ + setTerrainSlope({ pitch })} + precision={1} + step={0.5} + unit="°" + value={slope.pitch} + /> + +
+
+ + setTerrainSlope({ direction: normalizeTerrainSlopeDirection(direction) }) + } + precision={0} + step={5} + unit="°" + value={slope.direction} + /> +
+ + +
+ +
+
+ setTerrainSlope({ baseElevation })} + precision={2} + step={0.1} + unit="m" + value={slope.baseElevation} + /> +
+ +
+ + setTerrainSlope({ anchor })} + options={[ + { + value: 'center', + label: i18n._({ + id: 'editor.controls.terrainSculptPanel.anchorCenter', + message: 'Anchor: Center', + }), + }, + { + value: 'low-edge', + label: i18n._({ + id: 'editor.controls.terrainSculptPanel.anchorLowEdge', + message: 'Low edge', + }), + }, + ]} + value={slope.anchor ?? 'center'} + /> + + {slopeRange && ( +
+ + {i18n._({ + id: 'editor.controls.terrainSculptPanel.gradeReadout', + message: 'Grade {percent}%', + values: { percent: slopeRange.gradePercent.toFixed(1) }, + })} + + + {formatMeasurement(slopeRange.min, unit, metricNotation)} →{' '} + {formatMeasurement(slopeRange.max, unit, metricNotation)} + +
+ )} + + {slopeAnchor && ( +
+ + {i18n._({ + id: 'editor.controls.terrainSculptPanel.anchoredAt', + message: 'Anchored at {elevation}', + values: { elevation: formatMeasurement(slopeAnchor[2], unit, metricNotation) }, + })} + + +
+ )} + +

+ {sampling + ? slopePickStart + ? i18n._({ + id: 'editor.controls.terrainSculptPanel.pickEndHint', + message: + 'Click a second point on the ground to match its slope and direction.', + }) + : i18n._({ + id: 'editor.controls.terrainSculptPanel.pickStartHint', + message: 'Click a start point on the ground for the slope.', + }) + : slopeAnchor + ? i18n._({ + id: 'editor.controls.terrainSculptPanel.anchoredBrushHint', + message: + 'Brush strokes grade onto the picked A → B plane. Clear anchor to grade from click height.', + }) + : i18n._({ + id: 'editor.controls.terrainSculptPanel.freeBrushHint', + message: + 'Brush strokes start from the height where you click, or apply this grade across the whole lot.', + })} +

+ + +
+ )} +
setTerrainSlope({ anchor })} + onChange={(anchor: TerrainSlopeAnchor) => { + setTerrainSlopeAnchor(null) + setTerrainSlope({ anchor }) + }} options={[ { value: 'center', @@ -471,7 +477,11 @@ export function TerrainSculptPanel() {