From 14c6a90db1517e47945a17212aa337e3f2f81e6d Mon Sep 17 00:00:00 2001 From: Kumar Anirudha Date: Sun, 15 Nov 2026 13:51:22 +0530 Subject: [PATCH] feat(terrain): add a `shore` prop for a walkable island beach MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `Terrain` takes `shore`, the width in units of a beach around an island (needs `falloff`) - The beach falls 2 units at one slope, from 0.4 above the world ground to wading depth, so `shore: 6` is about 18° - Land near the coast is lowered to meet the beach, and the island grows outward by `shore` - Worlds that don't set `shore` keep every height they had - The workshop's "Island cove" template has a beach, with its dock and sailboat moved in to meet it [CONTRIBUTORS] - New beach branch in `terrainHeight()` in `surfaces/terrain.ts`, the old path is untouched - Tests pin shore-less heights to values recorded from `main` and hold the beach under 25° - `shore` slider range in the workshop's `schema/ranges.ts` - Regenerated `registry/` and the component docs, which also brings `person.md` up to date Refs #76 --- CHANGELOG.md | 12 ++ .../src/content/docs/components/person.md | 4 +- .../src/content/docs/components/terrain.md | 1 + apps/docs/src/workshop/schema/ranges.ts | 1 + apps/docs/src/workshop/templates/index.ts | 5 +- packages/components/src/Terrain.tsx | 21 ++- .../components/src/surfaces/terrain.test.ts | 138 +++++++++++++++++- packages/components/src/surfaces/terrain.ts | 29 +++- registry/components/terrain.json | 4 +- registry/props.json | 6 + registry/world.schema.json | 5 + 11 files changed, 216 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d588550..e2892fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased](https://github.com/nullorder/runek/compare/v0.18.0...HEAD) +### Added + +- `Terrain` gains `shore`: the width, in units, of a beach around an + island (one with `falloff`). Past the land's edge the ground falls 2 + units across it at one slope, from just above the world ground to + wading depth, before it drops to the deep, so an avatar can walk up + out of the sea: `shore: 6` slopes at about 18°, where the coast of a + small island without it runs past 60°. Land near the coast is lowered + to meet the beach. Worlds that don't set `shore` keep every height + they had. The workshop's "Island cove" template has one, and its dock + now starts on the beach. + ### Fixed - `Person`: no clothing layer passes through another. Each garment sits a diff --git a/apps/docs/src/content/docs/components/person.md b/apps/docs/src/content/docs/components/person.md index 70f8998..328dd04 100644 --- a/apps/docs/src/content/docs/components/person.md +++ b/apps/docs/src/content/docs/components/person.md @@ -39,7 +39,7 @@ Or as a node in a world file ([worlds as data](/docs/worlds-as-data)): | `age` | `"child" \| "adult" \| "elder"` | `"adult"` | Head-to-body ratio, stature, and (for `elder`) a stooped spine. | | `body` | `PersonBodySpec` | | The body: `build`, skin `tone`, and `height`. The flat props below are shorthands for the same fields; when both are set, this object wins. | | `face` | `PersonFaceSpec` | | The face, part by part: eye color and size, brow color and weight, nose shape, lip color and fullness, blush. | -| `clothes` | `PersonGarment[]` | | Clothing layers, inner to outer, each with its own type, color, and options. The order decides the fit: a shirt listed before the jeans is tucked in. Replaces `outfit`; `[]` is the bare base body (a smooth mannequin). | +| `clothes` | `PersonGarment[]` | | Clothing layers, inner to outer, each with its own type, color, and options. The order decides the fit: a shirt listed before the jeans is tucked in, and each layer drapes over the ones listed before it. Replaces `outfit`; `[]` is the bare base body (a smooth mannequin). | | `height` | `number` | | Standing height, in units. Every other measurement derives from it. | | `build` | `"slim" \| "average" \| "stocky" \| "athletic" \| "heavy" \| "petite" \| "lanky"` | | Limb thickness and torso depth. Seeded when unset. | | `skinTone` | `color` | | Skin color; seeded from a curated set of tones when unset. | @@ -53,7 +53,7 @@ Or as a node in a world file ([worlds as data](/docs/worlds-as-data)): | `shoeColor` | `color` | | Footwear color; defaults to the palette's `metal`. | | `trimColor` | `color` | | The lit seams and stripes of street clothes (`runner`, `shell`, `rig`, `street`, a hoodie's cords) and a visor's slit. Defaults to a lamp color picked by the seed. They shine on a `punk` figure and are plain color on the others. | | `hat` | `"none" \| "cap" \| "straw" \| "brim" \| "bandana" \| "hood" \| "chef" \| "beanie"` | | | -| `accessories` | `"belt" \| "scarf" \| "cape" \| "bag" \| "glasses" \| "staff" \| "headphones" \| "mask" \| "backpack" \| "visor"[]` | | | +| `accessories` | `"belt" \| "scarf" \| "cape" \| "bag" \| "glasses" \| "staff" \| "headphones" \| "mask" \| "backpack" \| "visor"[]` | | Worn extras. A `belt`, `scarf` or `cape` becomes a clothing layer on the outside of an `outfit`, except a belt under a top that hangs over the waist (a hoodie, a jacket), which goes on the bottoms beneath it. | | `pose` | `"stand" \| "sit" \| "lean" \| "work" \| "wave" \| "type" \| "play" \| "drink" \| "lie"` | `"stand"` | What the figure is doing when it isn't walking. `sit` and `type` need a seat under them (`type` is seated at a desk, fingers tapping); `work` leans over a counter; `play` works controls at waist height; `drink` holds a mug and sips from it now and then; `lie` lies on its back centered on `position`, head toward local -Z, so it takes a `Bed`'s position and rotation at mattress height. | | `patrol` | `[x, y, z][]` | | Walk these waypoints, relative to `position` and turning with `rotation`, in units. Height follows the ground; a waypoint's y lifts the figure above it. | | `wander` | `number` | | Wander a seeded loop of five points within this radius of `position`, in units. `patrol` wins when both are set. | diff --git a/apps/docs/src/content/docs/components/terrain.md b/apps/docs/src/content/docs/components/terrain.md index 1518873..ec9cc94 100644 --- a/apps/docs/src/content/docs/components/terrain.md +++ b/apps/docs/src/content/docs/components/terrain.md @@ -42,6 +42,7 @@ Or as a node in a world file ([worlds as data](/docs/worlds-as-data)): | `frequency` | `number` | `0.04` | Noise frequency. | | `flatRadius` | `number` | `0` | Radius from center kept flat (for a build pad), in units. | | `falloff` | `number` | `0` | Radial island falloff (0 = off). When set, the ground domes up toward the center and sinks below the world ground at its rim, so the mesh reads as a landmass surrounded by water. The value is the fraction of the half-extent that stays land before the coast (e.g. 0.8 = land out to 80% of the radius, then a shoreline into the sea). | +| `shore` | `number` | `0` | Width of a beach around an island, in units (0 = off; needs `falloff`). Past the land's edge the ground falls 2 units across this band at one slope, from 0.4 above the world ground to wading depth, then drops to the deep; land near the coast is lowered to meet it. So the beach is as gentle as it is wide: 6 slopes at about 18°, which an avatar walks up out of the sea, where a small island's bare coast is close to a cliff. It widens the island, so leave room for it inside `size`. | | `collider` | `boolean` | `true` | Register a collider (default true). Set false for distant/backdrop terrain the player never walks, to skip a large trimesh collider. | | `seed` | `number` | `1` | Seed for the deterministic variation: same seed, same result. | diff --git a/apps/docs/src/workshop/schema/ranges.ts b/apps/docs/src/workshop/schema/ranges.ts index 756a285..ff9868e 100644 --- a/apps/docs/src/workshop/schema/ranges.ts +++ b/apps/docs/src/workshop/schema/ranges.ts @@ -9,6 +9,7 @@ export const RANGES: Record> = frequency: [0.005, 0.2, 0.005], flatRadius: [0, 60, 0.5], falloff: [0, 1, 0.01], + shore: [0, 20, 0.5], }, Grass: { count: [0, 6000, 50], sway: [0, 3, 0.05] }, Person: { diff --git a/apps/docs/src/workshop/templates/index.ts b/apps/docs/src/workshop/templates/index.ts index 6472aa5..840cdd5 100644 --- a/apps/docs/src/workshop/templates/index.ts +++ b/apps/docs/src/workshop/templates/index.ts @@ -162,6 +162,7 @@ export const TEMPLATES: Template[] = [ size: [44, 44], relief: 3, falloff: 0.55, + shore: 6, flatRadius: 7, seed: 12, color: '#d8c79a', @@ -174,8 +175,8 @@ export const TEMPLATES: Template[] = [ })), { type: 'Campfire', anchor: 'ground', props: { position: [0, 0, 0], seed: 2 } }, { type: 'Rocks', anchor: 'ground', props: { position: [-4, 0, 3], count: 5, seed: 7 } }, - { type: 'Dock', props: { position: [0, 0, 19], length: 9, seed: 3 } }, - { type: 'Sailboat', props: { position: [4, -0.2, 24], rotation: [0, 0.6, 0], seed: 5 } }, + { type: 'Dock', props: { position: [0, 0, 9.4], length: 9, seed: 3 } }, + { type: 'Sailboat', props: { position: [4, -0.2, 15.5], rotation: [0, 0.6, 0], seed: 5 } }, { type: 'Person', anchor: 'ground', diff --git a/packages/components/src/Terrain.tsx b/packages/components/src/Terrain.tsx index 6a1b863..b5a140f 100644 --- a/packages/components/src/Terrain.tsx +++ b/packages/components/src/Terrain.tsx @@ -30,6 +30,13 @@ export interface TerrainProps { * water. The value is the fraction of the half-extent that stays land before the coast * (e.g. 0.8 = land out to 80% of the radius, then a shoreline into the sea). */ falloff?: number + /** Width of a beach around an island, in units (0 = off; needs `falloff`). Past the land's + * edge the ground falls 2 units across this band at one slope, from 0.4 above the world + * ground to wading depth, then drops to the deep; land near the coast is lowered to meet + * it. So the beach is as gentle as it is wide: 6 slopes at about 18°, which an avatar + * walks up out of the sea, where a small island's bare coast is close to a cliff. It + * widens the island, so leave room for it inside `size`. */ + shore?: number /** Register a collider (default true). Set false for distant/backdrop terrain the player * never walks, to skip a large trimesh collider. */ collider?: boolean @@ -60,6 +67,7 @@ export function Terrain({ frequency = TERRAIN_DEFAULTS.frequency, flatRadius = TERRAIN_DEFAULTS.flatRadius, falloff = TERRAIN_DEFAULTS.falloff, + shore = TERRAIN_DEFAULTS.shore, collider = true, seed = TERRAIN_DEFAULTS.seed, }: TerrainProps) { @@ -78,11 +86,20 @@ export function Terrain({ () => relief > 0 ? terrainGeometry( - { size: [sizeX, sizeZ], relief, resolution, frequency, flatRadius, falloff, seed }, + { + size: [sizeX, sizeZ], + relief, + resolution, + frequency, + flatRadius, + falloff, + shore, + seed, + }, unit, ) : null, - [sizeX, sizeZ, resolution, relief, frequency, flatRadius, falloff, seed, unit], + [sizeX, sizeZ, resolution, relief, frequency, flatRadius, falloff, shore, seed, unit], ) useEffect(() => () => displaced?.dispose(), [displaced]) diff --git a/packages/components/src/surfaces/terrain.test.ts b/packages/components/src/surfaces/terrain.test.ts index d1767dd..6b594ad 100644 --- a/packages/components/src/surfaces/terrain.test.ts +++ b/packages/components/src/surfaces/terrain.test.ts @@ -1,7 +1,10 @@ import * as THREE from 'three' import { describe, expect, it } from 'vitest' import { terrainGeometry } from '../Terrain' -import { type TerrainShape, terrainSurface } from './terrain' +import { type TerrainShape, terrainHeight, terrainSurface } from './terrain' + +// The workshop's "Island cove" terrain, before it had a shore. +const COVE: TerrainShape = { size: [44, 44], relief: 3, falloff: 0.55, flatRadius: 7, seed: 12 } // Golden tests: the query must agree with the rendered mesh (and so the trimesh collider built // from it), not with an idealized noise field. A downward ray against the real geometry is the @@ -19,6 +22,12 @@ const SHAPES: Array<[string, TerrainShape, number]> = [ 1, ], ['scaled unit', { size: [20, 20], relief: 5, resolution: 24, seed: 2 }, 2.5], + ['island with a shore', { ...COVE, shore: 6 }, 1], + [ + 'scaled island with a shore', + { size: [30, 30], relief: 3, falloff: 0.5, shore: 6, seed: 2 }, + 2.5, + ], ] function rayHeight(mesh: THREE.Mesh, x: number, z: number): number | null { @@ -70,3 +79,130 @@ describe('terrainSurface', () => { expect(field(6, 0)).toBeNull() }) }) + +// `[x, z, height]` recorded before `shore` existed: a world that doesn't set it keeps every +// height to the bit. +const PINNED: Array<[string, TerrainShape, number, Array<[number, number, number]>]> = [ + [ + 'rolling', + { size: [40, 40], relief: 3, seed: 7 }, + 1, + [ + [0, 0, -2.5691915560746565], + [3.5, -8.25, -2.422234472320204], + [-17, 12.5, -0.758471265605433], + [19.9, 19.9, 1.2120483001580982], + ], + ], + [ + 'island', + { size: [44, 44], relief: 3, falloff: 0.55, seed: 12 }, + 1, + [ + [0, 0, 1.574648448076914], + [5, -4, 1.3140135499601833], + [-6.5, 6.5, -0.05599064511028096], + [0, 10.25, -3.183853823247618], + [9, 7, -6.301590329062409], + [-15, 2, -7], + ], + ], + [ + 'island with a pad', + COVE, + 1, + [ + [2, 3, 0], + [7.5, 0, 0.010406006693069004], + [-6, 6, 0.11163907046015364], + [0, 9.5, -0.19430265029315943], + [8, -7.25, -2.259145591153959], + [0, 13, -5.90625], + [16, 16, -7], + ], + ], + [ + 'scaled island', + { size: [30, 20], relief: 5, resolution: 24, falloff: 0.8, flatRadius: 2, seed: 2 }, + 2.5, + [ + [4, -3, 0], + [-11, 9.5, 2.9324007804506964], + [0, 17.75, -6.056225105129616], + [20.5, 3, -19.847911112776647], + [30, -20, -22.5], + ], + ], +] + +/** The steepest stretch, in degrees, of the band an avatar wades through: from 0.3 above the + * world ground to 1.5 below it, walked along radii of the collider's own triangles. */ +function steepestShore(shape: TerrainShape, unit: number): number { + const field = terrainSurface.build(shape as Record, { unit, ground: 0 }) + const half = (Math.min(...(shape.size ?? [40, 40])) * unit) / 2 + const step = 0.25 * unit + let steepest = 0 + for (let a = 0; a < 360; a += 5) { + const dx = Math.cos((a * Math.PI) / 180) + const dz = Math.sin((a * Math.PI) / 180) + for (let r = 0; r + step < half; r += step) { + const near = field(dx * r, dz * r) as number + const far = field(dx * (r + step), dz * (r + step)) as number + if (Math.max(near, far) > 0.3 * unit || Math.min(near, far) < -1.5 * unit) continue + steepest = Math.max(steepest, Math.atan(Math.abs(far - near) / step)) + } + } + return (steepest * 180) / Math.PI +} + +describe('terrainHeight', () => { + for (const [name, shape, unit, points] of PINNED) { + it(`keeps its heights without a shore: ${name}`, () => { + const height = terrainHeight(shape, unit) + for (const [x, z, h] of points) expect(height(x, z)).toBe(h) + }) + } + + it('reads a shore only on an island', () => { + const rolling: TerrainShape = { size: [40, 40], relief: 3, seed: 7 } + const plain = terrainHeight(rolling, 1) + const shored = terrainHeight({ ...rolling, shore: 6 }, 1) + const cove = terrainHeight(COVE, 1) + const zeroed = terrainHeight({ ...COVE, shore: 0 }, 1) + for (const [x, z] of [ + [0, 0], + [3.5, -8.25], + [0, 9.5], + [-12, 11], + ]) { + expect(shored(x, z)).toBe(plain(x, z)) + expect(zeroed(x, z)).toBe(cove(x, z)) + } + }) + + describe('shore', () => { + it('turns a coast too steep to walk into a beach', () => { + expect(steepestShore(COVE, 1)).toBeGreaterThan(45) + expect(steepestShore({ ...COVE, shore: 6 }, 1)).toBeLessThan(25) + // No pad, more relief, a scaled unit: the land is cut down to meet the beach. + const hilly: TerrainShape = { size: [60, 60], relief: 6, falloff: 0.5, shore: 6, seed: 4 } + expect(steepestShore(hilly, 1)).toBeLessThan(25) + expect(steepestShore(hilly, 2.5)).toBeLessThan(25) + }) + + it('keeps the build pad flat and still sinks to the deep at the rim', () => { + const height = terrainHeight({ ...COVE, shore: 6 }, 1) + expect(height(0, 0)).toBe(0) + expect(height(-4, 5)).toBe(0) + expect(height(0, 21.9)).toBe(-7) + expect(height(-15.5, 15.5)).toBe(-7) + }) + + it('starts the beach at the edge of a pad wider than the land', () => { + const height = terrainHeight({ ...COVE, flatRadius: 12, shore: 6 }, 1) + expect(height(0, 11.9)).toBe(0) + expect(height(0, 15)).toBeCloseTo(0.4 - 1, 6) + expect(height(0, 18)).toBeCloseTo(-1.6, 6) + }) + }) +}) diff --git a/packages/components/src/surfaces/terrain.ts b/packages/components/src/surfaces/terrain.ts index 5823e4f..bcbabdb 100644 --- a/packages/components/src/surfaces/terrain.ts +++ b/packages/components/src/surfaces/terrain.ts @@ -9,6 +9,7 @@ export interface TerrainShape { frequency?: number flatRadius?: number falloff?: number + shore?: number seed?: number } @@ -19,9 +20,16 @@ export const TERRAIN_DEFAULTS = { frequency: 0.04, flatRadius: 0, falloff: 0, + shore: 0, seed: 1, } +// Fraction of the half-extent an island's coast takes to fall from the land to the deep. +const COAST = 0.18 +// A beach runs from this far above the world ground down to this far below it, in units. +const BEACH_TOP = 0.4 +const BEACH_DEPTH = 1.6 + function valueNoise(seed: number) { const hash = (x: number, y: number) => { let h = (seed ^ Math.imul(x, 374761393) ^ Math.imul(y, 668265263)) >>> 0 @@ -69,19 +77,38 @@ export function terrainHeight(shape: TerrainShape, unit: number): (x: number, z: frequency = TERRAIN_DEFAULTS.frequency, flatRadius = TERRAIN_DEFAULTS.flatRadius, falloff = TERRAIN_DEFAULTS.falloff, + shore = TERRAIN_DEFAULTS.shore, seed = TERRAIN_DEFAULTS.seed, } = shape const noise = valueNoise(seed) const fr = flatRadius * unit const half = (Math.min(size[0], size[1]) * unit) / 2 const sink = (relief + 4) * unit + if (falloff > 0 && shore > 0) { + // Island with a beach: past the land's edge the ground is a cone of one slope down to + // wading depth, then drops to the deep. The land may not rise above that cone, so nothing + // steeper stands behind the beach. The pad flattens the land alone (scaling the sea bed + // would steepen it), and a pad wider than the land pushes the beach out to its edge. + const top = BEACH_TOP * unit + const shelf = BEACH_DEPTH * unit + const width = shore * unit + const start = Math.max((falloff - COAST) * half, fr) + const end = start + width + return (x, z) => { + const r = Math.hypot(x, z) + let land = fbm(noise, x * frequency, z * frequency) * relief * unit + if (fr > 0) land *= smoothstep(r, fr, fr + 8 * unit) + const beach = Math.max(top - ((r - start) / width) * (top + shelf), -shelf) + return Math.min(land, beach) - (sink - shelf) * smoothstep(r, end, end + COAST * half) + } + } return (x, z) => { let h: number if (falloff > 0) { // Island mode: gentle land above the waterline, masked down to the deep at the rim. const land = fbm(noise, x * frequency, z * frequency) * relief * unit const rn = Math.hypot(x, z) / half - const mask = 1 - smoothstep(rn, falloff - 0.18, falloff) + const mask = 1 - smoothstep(rn, falloff - COAST, falloff) h = land * mask - (1 - mask) * sink } else { h = (fbm(noise, x * frequency, z * frequency) - 0.5) * 2 * relief * unit diff --git a/registry/components/terrain.json b/registry/components/terrain.json index ae4434c..d24bad0 100644 --- a/registry/components/terrain.json +++ b/registry/components/terrain.json @@ -12,12 +12,12 @@ "files": [ { "path": "Terrain.tsx", - "content": "import { RigidBody, TrimeshCollider } from '@react-three/rapier'\nimport { useMaterials, useWorld, type Vec3 } from '@runek/core'\nimport { useEffect, useMemo } from 'react'\nimport * as THREE from 'three'\nimport {\n TERRAIN_DEFAULTS,\n type TerrainShape,\n terrainHeight,\n terrainSurface,\n} from './surfaces/terrain'\n\nexport interface TerrainProps {\n position?: Vec3\n rotation?: Vec3\n /** Ground extent `[width, depth]`, in units. */\n size?: [number, number]\n thickness?: number\n /** Defaults to the world palette's `ground` slot. */\n color?: string\n /** Vertical relief amplitude, in units. 0 keeps the ground flat. */\n relief?: number\n /** Grid subdivisions for displaced ground. */\n resolution?: number\n /** Noise frequency. */\n frequency?: number\n /** Radius from center kept flat (for a build pad), in units. */\n flatRadius?: number\n /** Radial island falloff (0 = off). When set, the ground domes up toward the center and\n * sinks below the world ground at its rim, so the mesh reads as a landmass surrounded by\n * water. The value is the fraction of the half-extent that stays land before the coast\n * (e.g. 0.8 = land out to 80% of the radius, then a shoreline into the sea). */\n falloff?: number\n /** Register a collider (default true). Set false for distant/backdrop terrain the player\n * never walks, to skip a large trimesh collider. */\n collider?: boolean\n seed?: number\n}\n\n/** The displaced ground mesh, raised from the same height field the ground query reads. */\nexport function terrainGeometry(shape: TerrainShape, unit: number): THREE.PlaneGeometry {\n const { size = TERRAIN_DEFAULTS.size, resolution = TERRAIN_DEFAULTS.resolution } = shape\n const geo = new THREE.PlaneGeometry(size[0] * unit, size[1] * unit, resolution, resolution)\n geo.rotateX(-Math.PI / 2)\n const height = terrainHeight(shape, unit)\n const pos = geo.attributes.position\n for (let i = 0; i < pos.count; i++) pos.setY(i, height(pos.getX(i), pos.getZ(i)))\n pos.needsUpdate = true\n geo.computeVertexNormals()\n return geo\n}\n\nexport function Terrain({\n position = [0, 0, 0],\n rotation = [0, 0, 0],\n size = TERRAIN_DEFAULTS.size,\n thickness = 0.4,\n color,\n relief = TERRAIN_DEFAULTS.relief,\n resolution = TERRAIN_DEFAULTS.resolution,\n frequency = TERRAIN_DEFAULTS.frequency,\n flatRadius = TERRAIN_DEFAULTS.flatRadius,\n falloff = TERRAIN_DEFAULTS.falloff,\n collider = true,\n seed = TERRAIN_DEFAULTS.seed,\n}: TerrainProps) {\n const { unit, palette } = useWorld()\n const groundColor = color ?? palette.ground\n const m = useMaterials({\n displaced: { slot: 'ground', color: groundColor, flatShading: true },\n flat: { slot: 'ground', color: groundColor },\n })\n const width = size[0] * unit\n const depth = size[1] * unit\n const t = thickness * unit\n\n const [sizeX, sizeZ] = size\n const displaced = useMemo(\n () =>\n relief > 0\n ? terrainGeometry(\n { size: [sizeX, sizeZ], relief, resolution, frequency, flatRadius, falloff, seed },\n unit,\n )\n : null,\n [sizeX, sizeZ, resolution, relief, frequency, flatRadius, falloff, seed, unit],\n )\n useEffect(() => () => displaced?.dispose(), [displaced])\n\n if (displaced) {\n const mesh = \n // The trimesh is built here rather than with colliders=\"trimesh\", which derives it in an\n // effect one commit after mount: a dynamic body spawned over the terrain could fall through.\n return collider ? (\n \n \n {mesh}\n \n ) : (\n \n {mesh}\n \n )\n }\n\n const flat = (\n \n \n \n )\n return collider ? (\n \n {flat}\n \n ) : (\n \n {flat}\n \n )\n}\n\nTerrain.surface = terrainSurface\n", + "content": "import { RigidBody, TrimeshCollider } from '@react-three/rapier'\nimport { useMaterials, useWorld, type Vec3 } from '@runek/core'\nimport { useEffect, useMemo } from 'react'\nimport * as THREE from 'three'\nimport {\n TERRAIN_DEFAULTS,\n type TerrainShape,\n terrainHeight,\n terrainSurface,\n} from './surfaces/terrain'\n\nexport interface TerrainProps {\n position?: Vec3\n rotation?: Vec3\n /** Ground extent `[width, depth]`, in units. */\n size?: [number, number]\n thickness?: number\n /** Defaults to the world palette's `ground` slot. */\n color?: string\n /** Vertical relief amplitude, in units. 0 keeps the ground flat. */\n relief?: number\n /** Grid subdivisions for displaced ground. */\n resolution?: number\n /** Noise frequency. */\n frequency?: number\n /** Radius from center kept flat (for a build pad), in units. */\n flatRadius?: number\n /** Radial island falloff (0 = off). When set, the ground domes up toward the center and\n * sinks below the world ground at its rim, so the mesh reads as a landmass surrounded by\n * water. The value is the fraction of the half-extent that stays land before the coast\n * (e.g. 0.8 = land out to 80% of the radius, then a shoreline into the sea). */\n falloff?: number\n /** Width of a beach around an island, in units (0 = off; needs `falloff`). Past the land's\n * edge the ground falls 2 units across this band at one slope, from 0.4 above the world\n * ground to wading depth, then drops to the deep; land near the coast is lowered to meet\n * it. So the beach is as gentle as it is wide: 6 slopes at about 18°, which an avatar\n * walks up out of the sea, where a small island's bare coast is close to a cliff. It\n * widens the island, so leave room for it inside `size`. */\n shore?: number\n /** Register a collider (default true). Set false for distant/backdrop terrain the player\n * never walks, to skip a large trimesh collider. */\n collider?: boolean\n seed?: number\n}\n\n/** The displaced ground mesh, raised from the same height field the ground query reads. */\nexport function terrainGeometry(shape: TerrainShape, unit: number): THREE.PlaneGeometry {\n const { size = TERRAIN_DEFAULTS.size, resolution = TERRAIN_DEFAULTS.resolution } = shape\n const geo = new THREE.PlaneGeometry(size[0] * unit, size[1] * unit, resolution, resolution)\n geo.rotateX(-Math.PI / 2)\n const height = terrainHeight(shape, unit)\n const pos = geo.attributes.position\n for (let i = 0; i < pos.count; i++) pos.setY(i, height(pos.getX(i), pos.getZ(i)))\n pos.needsUpdate = true\n geo.computeVertexNormals()\n return geo\n}\n\nexport function Terrain({\n position = [0, 0, 0],\n rotation = [0, 0, 0],\n size = TERRAIN_DEFAULTS.size,\n thickness = 0.4,\n color,\n relief = TERRAIN_DEFAULTS.relief,\n resolution = TERRAIN_DEFAULTS.resolution,\n frequency = TERRAIN_DEFAULTS.frequency,\n flatRadius = TERRAIN_DEFAULTS.flatRadius,\n falloff = TERRAIN_DEFAULTS.falloff,\n shore = TERRAIN_DEFAULTS.shore,\n collider = true,\n seed = TERRAIN_DEFAULTS.seed,\n}: TerrainProps) {\n const { unit, palette } = useWorld()\n const groundColor = color ?? palette.ground\n const m = useMaterials({\n displaced: { slot: 'ground', color: groundColor, flatShading: true },\n flat: { slot: 'ground', color: groundColor },\n })\n const width = size[0] * unit\n const depth = size[1] * unit\n const t = thickness * unit\n\n const [sizeX, sizeZ] = size\n const displaced = useMemo(\n () =>\n relief > 0\n ? terrainGeometry(\n {\n size: [sizeX, sizeZ],\n relief,\n resolution,\n frequency,\n flatRadius,\n falloff,\n shore,\n seed,\n },\n unit,\n )\n : null,\n [sizeX, sizeZ, resolution, relief, frequency, flatRadius, falloff, shore, seed, unit],\n )\n useEffect(() => () => displaced?.dispose(), [displaced])\n\n if (displaced) {\n const mesh = \n // The trimesh is built here rather than with colliders=\"trimesh\", which derives it in an\n // effect one commit after mount: a dynamic body spawned over the terrain could fall through.\n return collider ? (\n \n \n {mesh}\n \n ) : (\n \n {mesh}\n \n )\n }\n\n const flat = (\n \n \n \n )\n return collider ? (\n \n {flat}\n \n ) : (\n \n {flat}\n \n )\n}\n\nTerrain.surface = terrainSurface\n", "type": "registry:component" }, { "path": "surfaces/terrain.ts", - "content": "// Terrain's height math, shared by the mesh (Terrain.tsx) and the ground query. Plain TS with\n// no three.js or React, so Node tooling (`runek check-world`) can import it directly.\nimport type { SurfaceDef } from '@runek/core'\n\nexport interface TerrainShape {\n size?: [number, number]\n relief?: number\n resolution?: number\n frequency?: number\n flatRadius?: number\n falloff?: number\n seed?: number\n}\n\nexport const TERRAIN_DEFAULTS = {\n size: [40, 40] as [number, number],\n relief: 0,\n resolution: 64,\n frequency: 0.04,\n flatRadius: 0,\n falloff: 0,\n seed: 1,\n}\n\nfunction valueNoise(seed: number) {\n const hash = (x: number, y: number) => {\n let h = (seed ^ Math.imul(x, 374761393) ^ Math.imul(y, 668265263)) >>> 0\n h = Math.imul(h ^ (h >>> 13), 1274126177)\n return ((h ^ (h >>> 16)) >>> 0) / 4294967296\n }\n return (x: number, y: number) => {\n const x0 = Math.floor(x)\n const y0 = Math.floor(y)\n const fx = x - x0\n const fy = y - y0\n const sx = fx * fx * (3 - 2 * fx)\n const sy = fy * fy * (3 - 2 * fy)\n const top = hash(x0, y0) + (hash(x0 + 1, y0) - hash(x0, y0)) * sx\n const bot = hash(x0, y0 + 1) + (hash(x0 + 1, y0 + 1) - hash(x0, y0 + 1)) * sx\n return top + (bot - top) * sy\n }\n}\n\nfunction fbm(noise: (x: number, y: number) => number, x: number, y: number) {\n let value = 0\n let amp = 0.5\n let freq = 1\n for (let octave = 0; octave < 4; octave++) {\n value += amp * noise(x * freq, y * freq)\n amp *= 0.5\n freq *= 2\n }\n return value\n}\n\n// three's MathUtils.smoothstep, inlined to keep this module three-free.\nfunction smoothstep(x: number, min: number, max: number) {\n if (x <= min) return 0\n if (x >= max) return 1\n const t = (x - min) / (max - min)\n return t * t * (3 - 2 * t)\n}\n\n/** The displaced height field at local (x, z): what each mesh vertex is raised to. */\nexport function terrainHeight(shape: TerrainShape, unit: number): (x: number, z: number) => number {\n const {\n size = TERRAIN_DEFAULTS.size,\n relief = TERRAIN_DEFAULTS.relief,\n frequency = TERRAIN_DEFAULTS.frequency,\n flatRadius = TERRAIN_DEFAULTS.flatRadius,\n falloff = TERRAIN_DEFAULTS.falloff,\n seed = TERRAIN_DEFAULTS.seed,\n } = shape\n const noise = valueNoise(seed)\n const fr = flatRadius * unit\n const half = (Math.min(size[0], size[1]) * unit) / 2\n const sink = (relief + 4) * unit\n return (x, z) => {\n let h: number\n if (falloff > 0) {\n // Island mode: gentle land above the waterline, masked down to the deep at the rim.\n const land = fbm(noise, x * frequency, z * frequency) * relief * unit\n const rn = Math.hypot(x, z) / half\n const mask = 1 - smoothstep(rn, falloff - 0.18, falloff)\n h = land * mask - (1 - mask) * sink\n } else {\n h = (fbm(noise, x * frequency, z * frequency) - 0.5) * 2 * relief * unit\n }\n if (fr > 0) h *= smoothstep(Math.hypot(x, z), fr, fr + 8 * unit)\n return h\n }\n}\n\n/**\n * The walkable top as the mesh actually renders it: flat terrain is a box top; displaced\n * terrain is the PlaneGeometry triangulation of `terrainHeight` (float32 vertices, the\n * `a,b,d` / `b,c,d` diagonal), so queries agree with the trimesh collider, not an idealized\n * noise field.\n */\nexport const terrainSurface: SurfaceDef = {\n kind: 'terrain',\n build(props, { unit }) {\n const shape = props as TerrainShape\n const [sw, sd] = shape.size ?? TERRAIN_DEFAULTS.size\n const w = sw * unit\n const d = sd * unit\n if ((shape.relief ?? TERRAIN_DEFAULTS.relief) <= 0) {\n return (x, z) => (Math.abs(x) <= w / 2 && Math.abs(z) <= d / 2 ? 0 : null)\n }\n const res = shape.resolution ?? TERRAIN_DEFAULTS.resolution\n const height = terrainHeight(shape, unit)\n const segW = w / res\n const segD = d / res\n const vx = (ix: number) => Math.fround(ix * segW - w / 2)\n const vz = (iz: number) => Math.fround(iz * segD - d / 2)\n const vy = (ix: number, iz: number) => Math.fround(height(vx(ix), vz(iz)))\n return (x, z) => {\n if (Math.abs(x) > w / 2 || Math.abs(z) > d / 2) return null\n const ix = Math.min(res - 1, Math.max(0, Math.floor((x + w / 2) / segW)))\n const iz = Math.min(res - 1, Math.max(0, Math.floor((z + d / 2) / segD)))\n const x0 = vx(ix)\n const z0 = vz(iz)\n const u = (x - x0) / (vx(ix + 1) - x0)\n const v = (z - z0) / (vz(iz + 1) - z0)\n const ha = vy(ix, iz)\n const hb = vy(ix, iz + 1)\n const hd = vy(ix + 1, iz)\n if (u + v <= 1) return ha + u * (hd - ha) + v * (hb - ha)\n const hc = vy(ix + 1, iz + 1)\n return hc + (1 - u) * (hb - hc) + (1 - v) * (hd - hc)\n }\n },\n}\n", + "content": "// Terrain's height math, shared by the mesh (Terrain.tsx) and the ground query. Plain TS with\n// no three.js or React, so Node tooling (`runek check-world`) can import it directly.\nimport type { SurfaceDef } from '@runek/core'\n\nexport interface TerrainShape {\n size?: [number, number]\n relief?: number\n resolution?: number\n frequency?: number\n flatRadius?: number\n falloff?: number\n shore?: number\n seed?: number\n}\n\nexport const TERRAIN_DEFAULTS = {\n size: [40, 40] as [number, number],\n relief: 0,\n resolution: 64,\n frequency: 0.04,\n flatRadius: 0,\n falloff: 0,\n shore: 0,\n seed: 1,\n}\n\n// Fraction of the half-extent an island's coast takes to fall from the land to the deep.\nconst COAST = 0.18\n// A beach runs from this far above the world ground down to this far below it, in units.\nconst BEACH_TOP = 0.4\nconst BEACH_DEPTH = 1.6\n\nfunction valueNoise(seed: number) {\n const hash = (x: number, y: number) => {\n let h = (seed ^ Math.imul(x, 374761393) ^ Math.imul(y, 668265263)) >>> 0\n h = Math.imul(h ^ (h >>> 13), 1274126177)\n return ((h ^ (h >>> 16)) >>> 0) / 4294967296\n }\n return (x: number, y: number) => {\n const x0 = Math.floor(x)\n const y0 = Math.floor(y)\n const fx = x - x0\n const fy = y - y0\n const sx = fx * fx * (3 - 2 * fx)\n const sy = fy * fy * (3 - 2 * fy)\n const top = hash(x0, y0) + (hash(x0 + 1, y0) - hash(x0, y0)) * sx\n const bot = hash(x0, y0 + 1) + (hash(x0 + 1, y0 + 1) - hash(x0, y0 + 1)) * sx\n return top + (bot - top) * sy\n }\n}\n\nfunction fbm(noise: (x: number, y: number) => number, x: number, y: number) {\n let value = 0\n let amp = 0.5\n let freq = 1\n for (let octave = 0; octave < 4; octave++) {\n value += amp * noise(x * freq, y * freq)\n amp *= 0.5\n freq *= 2\n }\n return value\n}\n\n// three's MathUtils.smoothstep, inlined to keep this module three-free.\nfunction smoothstep(x: number, min: number, max: number) {\n if (x <= min) return 0\n if (x >= max) return 1\n const t = (x - min) / (max - min)\n return t * t * (3 - 2 * t)\n}\n\n/** The displaced height field at local (x, z): what each mesh vertex is raised to. */\nexport function terrainHeight(shape: TerrainShape, unit: number): (x: number, z: number) => number {\n const {\n size = TERRAIN_DEFAULTS.size,\n relief = TERRAIN_DEFAULTS.relief,\n frequency = TERRAIN_DEFAULTS.frequency,\n flatRadius = TERRAIN_DEFAULTS.flatRadius,\n falloff = TERRAIN_DEFAULTS.falloff,\n shore = TERRAIN_DEFAULTS.shore,\n seed = TERRAIN_DEFAULTS.seed,\n } = shape\n const noise = valueNoise(seed)\n const fr = flatRadius * unit\n const half = (Math.min(size[0], size[1]) * unit) / 2\n const sink = (relief + 4) * unit\n if (falloff > 0 && shore > 0) {\n // Island with a beach: past the land's edge the ground is a cone of one slope down to\n // wading depth, then drops to the deep. The land may not rise above that cone, so nothing\n // steeper stands behind the beach. The pad flattens the land alone (scaling the sea bed\n // would steepen it), and a pad wider than the land pushes the beach out to its edge.\n const top = BEACH_TOP * unit\n const shelf = BEACH_DEPTH * unit\n const width = shore * unit\n const start = Math.max((falloff - COAST) * half, fr)\n const end = start + width\n return (x, z) => {\n const r = Math.hypot(x, z)\n let land = fbm(noise, x * frequency, z * frequency) * relief * unit\n if (fr > 0) land *= smoothstep(r, fr, fr + 8 * unit)\n const beach = Math.max(top - ((r - start) / width) * (top + shelf), -shelf)\n return Math.min(land, beach) - (sink - shelf) * smoothstep(r, end, end + COAST * half)\n }\n }\n return (x, z) => {\n let h: number\n if (falloff > 0) {\n // Island mode: gentle land above the waterline, masked down to the deep at the rim.\n const land = fbm(noise, x * frequency, z * frequency) * relief * unit\n const rn = Math.hypot(x, z) / half\n const mask = 1 - smoothstep(rn, falloff - COAST, falloff)\n h = land * mask - (1 - mask) * sink\n } else {\n h = (fbm(noise, x * frequency, z * frequency) - 0.5) * 2 * relief * unit\n }\n if (fr > 0) h *= smoothstep(Math.hypot(x, z), fr, fr + 8 * unit)\n return h\n }\n}\n\n/**\n * The walkable top as the mesh actually renders it: flat terrain is a box top; displaced\n * terrain is the PlaneGeometry triangulation of `terrainHeight` (float32 vertices, the\n * `a,b,d` / `b,c,d` diagonal), so queries agree with the trimesh collider, not an idealized\n * noise field.\n */\nexport const terrainSurface: SurfaceDef = {\n kind: 'terrain',\n build(props, { unit }) {\n const shape = props as TerrainShape\n const [sw, sd] = shape.size ?? TERRAIN_DEFAULTS.size\n const w = sw * unit\n const d = sd * unit\n if ((shape.relief ?? TERRAIN_DEFAULTS.relief) <= 0) {\n return (x, z) => (Math.abs(x) <= w / 2 && Math.abs(z) <= d / 2 ? 0 : null)\n }\n const res = shape.resolution ?? TERRAIN_DEFAULTS.resolution\n const height = terrainHeight(shape, unit)\n const segW = w / res\n const segD = d / res\n const vx = (ix: number) => Math.fround(ix * segW - w / 2)\n const vz = (iz: number) => Math.fround(iz * segD - d / 2)\n const vy = (ix: number, iz: number) => Math.fround(height(vx(ix), vz(iz)))\n return (x, z) => {\n if (Math.abs(x) > w / 2 || Math.abs(z) > d / 2) return null\n const ix = Math.min(res - 1, Math.max(0, Math.floor((x + w / 2) / segW)))\n const iz = Math.min(res - 1, Math.max(0, Math.floor((z + d / 2) / segD)))\n const x0 = vx(ix)\n const z0 = vz(iz)\n const u = (x - x0) / (vx(ix + 1) - x0)\n const v = (z - z0) / (vz(iz + 1) - z0)\n const ha = vy(ix, iz)\n const hb = vy(ix, iz + 1)\n const hd = vy(ix + 1, iz)\n if (u + v <= 1) return ha + u * (hd - ha) + v * (hb - ha)\n const hc = vy(ix + 1, iz + 1)\n return hc + (1 - u) * (hb - hc) + (1 - v) * (hd - hc)\n }\n },\n}\n", "type": "registry:component" } ] diff --git a/registry/props.json b/registry/props.json index 278728a..2a3bc1a 100644 --- a/registry/props.json +++ b/registry/props.json @@ -9410,6 +9410,12 @@ "optional": true, "default": 0 }, + "shore": { + "type": "number", + "doc": "Width of a beach around an island, in units (0 = off; needs `falloff`). Past the land's\nedge the ground falls 2 units across this band at one slope, from 0.4 above the world\nground to wading depth, then drops to the deep; land near the coast is lowered to meet\nit. So the beach is as gentle as it is wide: 6 slopes at about 18°, which an avatar\nwalks up out of the sea, where a small island's bare coast is close to a cliff. It\nwidens the island, so leave room for it inside `size`.", + "optional": true, + "default": 0 + }, "collider": { "type": "boolean", "doc": "Register a collider (default true). Set false for distant/backdrop terrain the player\nnever walks, to skip a large trimesh collider.", diff --git a/registry/world.schema.json b/registry/world.schema.json index c916519..843aacb 100644 --- a/registry/world.schema.json +++ b/registry/world.schema.json @@ -11760,6 +11760,11 @@ "description": "Radial island falloff (0 = off). When set, the ground domes up toward the center and\nsinks below the world ground at its rim, so the mesh reads as a landmass surrounded by\nwater. The value is the fraction of the half-extent that stays land before the coast\n(e.g. 0.8 = land out to 80% of the radius, then a shoreline into the sea).", "default": 0 }, + "shore": { + "type": "number", + "description": "Width of a beach around an island, in units (0 = off; needs `falloff`). Past the land's\nedge the ground falls 2 units across this band at one slope, from 0.4 above the world\nground to wading depth, then drops to the deep; land near the coast is lowered to meet\nit. So the beach is as gentle as it is wide: 6 slopes at about 18°, which an avatar\nwalks up out of the sea, where a small island's bare coast is close to a cliff. It\nwidens the island, so leave room for it inside `size`.", + "default": 0 + }, "collider": { "type": "boolean", "description": "Register a collider (default true). Set false for distant/backdrop terrain the player\nnever walks, to skip a large trimesh collider.",