10 Commits
Author SHA1 Message Date
claudeandClaude Opus 5.5 21559a637d Devlog: W5, W6, W7 and v0.2.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 12:35:28 -05:00
claudeandClaude Opus 5.5 278b715e0c W7: The drop: sky barge and wing-sail
Simulation.start_drop() plans a seeded straight route across the island at
BARGE_ALTITUDE, through a point near the middle pulled onto land, and puts
every player aboard. Riders move with the barge; jump leaps off with some of
its speed. Freefall steers and tops out at FREEFALL_MAX_SPEED; jump opens
the wing-sail, which also opens by itself WING_AUTO_DEPLOY_HEIGHT above the
ground or water. Gliding sinks slowly and steers at GLIDE_SPEED, and the
sail folds just above the ground or sea so landing does no damage. Anyone
aboard at the end of the route is thrown off. Drop state is hashed.

Every server match now starts with the drop. Bots leap at a time fixed by
their player ID. The carrier's name and look are open in #72.

Closes #14

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 12:34:53 -05:00
claudeandClaude Opus 5.5 be987b6f82 W6: Water and swimming
The simulation has a global sea level (Simulation.sea_level, changed with
set_sea_level and read every tick, so the tide can move it mid-match).
Walkers wade more slowly in water over WADE_DEPTH; in water SWIM_DEPTH deep
they swim: floating head-out, sprint-swimming, diving with crouch, kicking
out with jump, and standing again in the shallows. Falling into deep water
does no fall damage. Water tracks breath, stamina and drowning in whole
ticks: swimming spends stamina, an exhausted swimmer slips under, and with
no breath left the tide phase's drown damage lands once a second. All of
it, plus the sea level, is in the state hash.

WaterView draws the sea surface at the simulation's level with a
procedural shader: depth-tinted colour, foam at the waterline, ripples.

Closes #13

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 12:24:50 -05:00
claudeandClaude Opus 5.5 5db53de4e8 W5: Vegetation and harvestable props
PropSet places about 3,000 pines, scrub, boulders, wrecks and crates per
island from the seed, by elevation band with grove noise, clear of points
of interest. Each prop is one collision box in SimGround with health from
Tuning.PROP_KINDS; destroying it removes the box at once
(SimGround.remove_solid). Prop health is part of the state hash.

PropView draws them as one MultiMesh per kind per 128 m square (about 150
instanced draws), with per-kind visibility ranges, procedural flat-shaded
meshes fitted to the collision boxes, and cheap sync of felled props.

Closes #12

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 12:17:42 -05:00
claudeandClaude Opus 5.5 283d0e966e Devlog: W2, W3 and W4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 14:47:41 -05:00
claudeandClaude Opus 5.5 5021d13686 W4: Points of interest
PoiSet.generate(island) places 10 to 16 points of interest per island from
the seed's "poi" stream: hilltop shrines, lighthouses, docks, salt works,
quarries and fishing hamlets, at least 85 m apart. Each kind has a siting
rule (height band, flatness, coast or summit) that loosens step by step
until its minimum is placed. Piers are sited so their deck clears the
ground all the way out to water 1.5 m deep.

Poi assembles each from modular parts in a local frame turned in quarter
turns, so every solid stays an axis-aligned box: walls with a door and
lintel, plinths, steps down to the ground, roofs, a stair to a loft. Each
POI carries loot spawn markers, exposed through PoiSet.loot_markers(),
and walking routes from open ground into its interiors.

- Simulation adds every POI solid to its ground and never spawns players
  inside one.
- SimGround indexes solids in 8 m cells, so collision queries only test
  nearby boxes. Smoke p95 tick is 0.47 ms with about 300 solids.
- Movement tests the body where it will stand after stepping up, so
  stairs with treads narrower than the body can be climbed. The
  traversal test found the lighthouse stair impassable without it.
- PoiView draws parts as one MultiMesh per look, in the seafaring
  palette. Capture scenarios poi_<kind> frame each kind.
- Summit stone is darker so it no longer reads as snow.

Tests: 30 seeds get every kind within its limits, 10 to 16 in total,
spaced and sited; placement is deterministic; loot markers stand on
floors and are not inside solids; a player walks every route of every
POI on 4 seeds through doors, up steps and the lighthouse stair; stairs
with 0.45 m treads are climbed and a step doesn't carry the body into a
wall; the solid index matches a full scan on 500 queries.

Closes #11

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 14:47:10 -05:00
claudeandClaude Opus 5.5 8b74485168 W3: Chunked terrain mesh, collision and LOD
TerrainView draws the island as 16 x 16 chunks of 64 m, each at one of
four detail levels (2, 4, 8 and 16 m spacing) chosen by distance to the
camera. TerrainChunkBuilder builds chunk geometry on WorkerThreadPool
threads; the main thread only uploads finished meshes, within a 2 ms
per-frame budget, nearest chunks first.

- Seams: every chunk hangs skirts deeper than twice the most any level
  strays from the full-resolution edge, so neighbours at any two levels
  meet without a crack. Normals come from the full-resolution heightfield
  at every level, and back faces light like the ground above them.
- Splat material: a procedural shader blends sand, marsh, grass and rock
  with weights from the island's bands, averaged over 4 m so borders
  blend. Steep ground turns to rock and summits weather pale.
- Collision stays SimGround's heightfield, with no renderer involved.
- Capture scenarios terrain, terrain_lod (tinted by level) and
  terrain_cracks (magenta sky). tools/crack_check.gd counts sky pixels
  seen through the ground; make terrain-capture requires cracks in a
  skirtless control and none in the real terrain.

Tests: chunk vertices sit on the heightfield; skirts cover every pairing
of levels on sampled shared edges; detail falls with distance; flying
across the island at 30 m/s for 2,037 frames streams 661 chunk rebuilds
with the worst main-thread frame at 0.8 to 1.4 ms (headless, CPU only);
24 players over 900 ticks on two generated islands never sink into the
ground, and a player sprints up towards a summit unharmed.
make terrain-capture: control 437 crack pixels, terrain 0.

Closes #10

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 14:28:30 -05:00
claudeandClaude Opus 5.5 c70d0c1c4f W2: Procedural island generator
Island.generate(seed) builds a 513 x 513 heightfield (2 m spacing, the whole
1,024 m world) from the match seed's "worldgen" stream: a warped coastline,
a coastal shelf and interior dome, two to four summits joined by ridges,
rolling and rocky detail, and flattened marsh in wet lowland. Land is scaled
so the tallest summit lands between ISLAND_PEAK_MIN and ISLAND_PEAK_MAX,
under the last tide. Each sample gets an elevation band (sea, beach, marsh,
forest, highland, summit) for terrain materials.

- Simulation generates the island unless a test supplies its own ground,
  and spawns players on dry land until the drop arrives.
- The headless server logs world_hash in its start line.
- Island.heightmap_hash() is SHA-256 over millimetre heights and bands.
- tools/island_map.gd draws a top-down map with tide contours.
- New island constants in tuning.gd; GDD gains an island section.

Tests: a 100-seed sweep checks generation time (slowest 617 ms against
5 s), land area, at least two distinct high points, walkable land, bands,
and that no more than 3% of dry land is cut off at sea levels 0 and 8 m
(worst seen 0.87%). A separate server process given only the seed must
log the same heightmap hash.

Closes #9

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 14:15:59 -05:00
claudeandClaude Opus 5.5 f1ce780474 Devlog: F6, F7, W1 and v0.1.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:24:37 -05:00
claudeandClaude Opus 5.5 70e88cec8a W1: Third-person character controller and camera
Simulation (src/sim/):
- SimGround holds the terrain heightfield (bilinear heights, normals)
  and axis-aligned box solids, with support, body-overlap, point and
  ray queries. The island generator and building will fill it.
- Movement steps a player per tick: walk, sprint (forward only),
  crouch (lower body, slower, no jump), jump with exact constant-gravity
  integration, air control, step-up onto ledges up to STEP_HEIGHT,
  ground snapping on downhill walks, slopes over MAX_SLOPE_DEGREES that
  block walking and jumping uphill and make players slide (speed capped),
  ceiling bumps, sliding along walls, and fall damage from impact speed.
- Gravity now applies on ticks with no command. on_ground and crouching
  are part of the state hash. New movement numbers are in Tuning.
- Fixed the strafe direction: right is forward x up in Godot's frame,
  (-cos yaw, 0, sin yaw). Documented the look convention.

Client (src/client/):
- CameraRig places an over-the-shoulder camera with an eased
  aim-down-sights blend (closer, narrower FOV), casting against the same
  SimGround: pivot to shoulder, shoulder back, then a straight line from
  the pivot, with a final clearance pull-in so the near plane never
  enters geometry.
- InputSettings: mouse sensitivity, aim sensitivity scale and invert-Y,
  clamped and saved to user://settings.cfg. PlayerCamera applies both.

Tests: 46 new across movement, ground queries, camera and settings,
including a 24,480-view scripted camera sweep through five arenas (wall,
corridor, low roof, corner, steep bank) that checks the eye and every
near-plane corner stay out of geometry with a clear line to the pivot.
The hash test now flips a high stick bit, because a 1/127 nudge to an
airborne player moves them less than the hash's millimetre.
Capture scenarios camera, camera_wall and camera_aim.

Closes #8

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:24:02 -05:00
108 changed files with 6060 additions and 34 deletions
+2
View File
@@ -24,6 +24,8 @@ continuity.
| `tools/godot.sh -- --server --seed=N --bots=N --ticks=N` | Runs a headless dedicated server. See `src/server/server_config.gd` for every option. Logs are JSON lines carrying the seed. Exit codes: 0 clean, 1 script error, 2 bad command line. |
| `tools/godot.sh ...` | Runs the pinned engine. Headless by default. |
| `tools/capture.sh <scene-or-scenario> <out.png>` | Renders the real client offscreen in a throwaway `tidewall-capture-*` Docker container (Xvfb, Mesa software rendering) and saves a PNG. Fails on a blank frame or a renderer fallback. |
| `tools/godot.sh --script res://tools/island_map.gd -- --seed=N --out=res://captures/island.png` | Draws a top-down map of a seed's island, with a contour at each tide level. |
| `make terrain-capture` | Renders the terrain crack check and a skirtless control in the capture container. The control must crack and the real terrain must not. Needs Docker. |
| `make capture-test` | Proves the capture harness works and rejects a blank frame. Needs Docker, so it isn't part of `make check`. |
Run one group of tests with `tools/run_tests.sh --root=res://test/sim` or
+5 -1
View File
@@ -1,7 +1,7 @@
# Tidewall build entry points. Everything runs headless with the repo-local engine.
GODOT := tools/godot.sh
.PHONY: check import parse test test-selfcheck smoke capture-test binaries verify-engine
.PHONY: check import parse test test-selfcheck smoke capture-test terrain-capture binaries verify-engine
## Everything that must pass before a push.
check: verify-engine binaries parse test test-selfcheck smoke
@@ -33,3 +33,7 @@ smoke: import
## Renders the capture test scenes in the offscreen container. Needs Docker.
capture-test: import
@tools/capture_selfcheck.sh
## Renders the terrain crack check and its control in the offscreen container. Needs Docker.
terrain-capture: import
@tools/terrain_capture_check.sh
+21
View File
@@ -55,6 +55,12 @@ Clients stamp commands for the tick they predict, and each packet repeats recent
commands to survive loss. The server applies the command for each tick, or a neutral
command with the player's last look direction if none has arrived.
**Look convention.** At yaw 0 the player faces +z; forward is `(sin yaw, 0, cos yaw)`.
Right is forward × up, `(-cos yaw, 0, sin yaw)`, matching Godot's right-handed, y-up
frame, so turning right *decreases* yaw. Positive pitch looks up. `Movement` and the
client's `CameraRig` both follow this, and a test checks that strafing right moves
towards the camera's screen-right.
The binary encoding is a fixed 14 bytes per command, little-endian, in the order of
the table above. See `src/sim/player_command.gd`. Decoding a truncated buffer returns
nothing, and out-of-range values are clamped, so bad input can't reach the simulation.
@@ -114,11 +120,26 @@ sent on a reliable ordered event stream, since a dropped wall is a gameplay lie.
| `src/audio/` | Sound playback, music | `src/sim/` (read only) |
| `src/app/` | Startup and mode selection | Everything |
## Terrain
The island's heightfield (`Island`, in `src/sim/`) is the only terrain collision, on
the server and in client prediction. Nothing in the renderer is ever used for collision.
The client draws it with `TerrainView` (`src/client/terrain/`): 64 m chunks at four
levels of detail chosen by distance to the camera. `TerrainChunkBuilder` builds chunk
geometry on `WorkerThreadPool` threads, and the main thread only uploads finished meshes,
within a per-frame budget. Each chunk hangs skirts from its edges deeper than any two
levels can disagree, so a level boundary never opens a crack. Normals come from the
full-resolution heightfield at every level, so lighting doesn't change across a boundary.
The terrain shader blends procedural sand, marsh, grass and rock layers using splat
weights from the island's elevation bands, with rock on steep ground.
## Performance budgets
| Budget | Target |
|---|---|
| Server tick | Under **12 ms** with 24 players |
| Client | **60 fps** on a GTX 1060-class GPU at medium settings |
| Terrain streaming | Under **8 ms** of main-thread work in any frame (measured headless; GPU upload unmeasured) |
Software rendering in CI can't verify the client budget. It needs a real GPU playtest.
+142
View File
@@ -30,3 +30,145 @@ players over 10,000 ticks.
**Known gaps:** the LFS push path hasn't been exercised, as nothing is in LFS yet.
**Next:** F6 headless server and `make smoke`, then F7 capture harness.
## 2026-11-09 (evening): F6, F7, W1 and v0.1.0
**Done:**
- F6 (#6): headless dedicated server (`tools/godot.sh -- --server ...`), JSON-line logs
that all carry the seed, exit codes 0, 1 and 2, and `make smoke`, which is now part of
`make check`.
- F7 (#7): `tools/capture.sh`, which renders in a throwaway `tidewall-capture-*` container
(debian:13, Xvfb, Mesa) with no network, plus `make capture-test`.
- v0.1 Foundations milestone closed and tagged `v0.1.0`, on its due date.
- W1 (#8): `SimGround`, `Movement`, `CameraRig`, `InputSettings` and `PlayerCamera`.
- Opened #70 (H7), graceful shutdown on SIGTERM, as a low-priority hardening follow-up.
**Tests:** `make check` passes: 39 scripts parsed, 97 tests, 8 self-check fixtures,
and the smoke run. Smoke with 24 wander bots: p95 tick about 0.4 ms against the 12 ms
budget. `make capture-test` passes. Captures checked by eye: smoke, camera, camera_wall,
camera_aim.
**Decisions:**
- Captures default to Forward+ through Lavapipe, the game's renderer. Debian 13's ICD is
`lvp_icd.json`. Godot silently falls back to OpenGL when Vulkan fails, so `capture.sh`
fails when the renderer it got isn't the one it asked for. Compatibility renders
brighter than Forward+, so compare captures only within one renderer.
- `capture.sh` refreshes the class cache headless on the host before rendering, and
`captures/` has a `.gdignore`.
- **Look convention fixed:** right is forward x up, `(-cos yaw, 0, sin yaw)`, and turning
right decreases yaw. F5 had it mirrored. See ARCHITECTURE.md.
- Fall damage comes from landing speed, not drop height, so a capped slide down a steep
bank is harmless but a cliff fall isn't.
- The camera casts pivot to shoulder, then backward, then straight from the pivot, and
finishes with a clearance pull-in. The 24,480-view sweep found both a steep-slope
near-plane clip and over-the-wall occlusion before they shipped.
- The hash-sensitivity test now flips a high stick bit, because a 1/127 nudge to an
airborne player is below the hash's millimetre rounding.
- `WanderBot` is a placeholder until the bots in v0.4.
**Known gaps:** SIGTERM kills the server without a stop line (#70). Mouse feel and frame
rates can't be verified without a GPU playtest.
**Next:** W2, the procedural island generator (#9), then W3 chunked terrain (#10). v0.2 is
due at the end of 2026-11-10, with 6 issues left.
## 2026-11-10 (afternoon): W2, W3 and W4
**Done:**
- W2 (#9): `Island.generate(seed)`, a 513 × 513 heightfield at 2 m over the 1,024 m world,
with a warped coast, a shelf and interior dome, 2 to 4 summits on ridges, marsh, and
elevation bands. `Simulation` generates it; the server logs `world_hash`.
`tools/island_map.gd` draws top-down maps.
- W3 (#10): `TerrainView` and `TerrainChunkBuilder`, 64 m chunks at four detail levels,
built on worker threads, with skirts at the seams and a procedural splat shader.
`make terrain-capture` proves no cracks against a skirtless control.
- W4 (#11): `PoiSet` and `Poi`, six original POI kinds from modular parts, 10 to 16 per
island, with loot markers and walk routes. `PoiView` draws them as MultiMeshes.
`SimGround` now indexes solids in 8 m cells.
- Opened #71 (H8) to watch a one-off 238 ms streaming frame seen under host load.
**Tests:** `make check` passes: 120 tests, self-check and smoke (p95 tick 0.47 ms with
24 bots and about 300 POI solids). `make check` now takes about 2.5 minutes, mostly the
100-seed island sweep. `make terrain-capture` passes (control 437 crack pixels, real 0).
Captures checked by eye: island maps of seeds 1 to 4, terrain, terrain_lod,
terrain_cracks, and poi_* for all six kinds.
**Decisions:**
- The island is about 1 km across, not the 2 km in W2's text, because the world and the
snapshot position range are 1,024 m. Reasoning is on #9.
- Worldgen and POI placement each use their own `SimRng(seed)` copy, so generating them
on a client never shifts the match's gameplay streams.
- `Simulation.new(seed)` generates the island; tests that don't care pass
`SimGround.flat()` as the second argument to skip worldgen.
- Terrain seams use skirts, not edge stitching, so chunks never need to know their
neighbours' levels. Skirt depth is computed per chunk from the actual edge error.
- The streaming budget is measured as main-thread wall time in `TerrainView._process`,
headless. It can't see GPU upload cost.
- **Movement change:** step-up tests the body at the height it will step up to. The W4
traversal test showed the lighthouse stair was impassable without it. Treads must be
at least the player radius (0.4 m) deep; the POI stairs use 0.5 m.
- POI solids are axis-aligned boxes, rotated only in quarter turns.
- Summit stone was darkened after the shrine capture read as snow.
**Known gaps:** no water yet, so piers and coasts show bare sea floor (W6). POIs and
lowland are blockout visuals until W5 vegetation and the v0.6 art pass. Frame times
and feel still need a real GPU.
**Pace:** v0.2 is due at the end of today and W5, W6 and W7 remain, so it will finish
about a day late. Next by the work order is W5 (#12, no priority label), then W6 (#13,
water, core) and W7 (#14, the drop). If the next run finds v0.2 more than a day behind,
defer W5 per the pacing rule and do W6 and W7 first.
## 2026-11-11 (midday): W5, W6, W7 and v0.2.0
**Start of run:** the tree held an unfinished W5 from the previous run: the prop
simulation, `SimGround.remove_solid` and tests, but no view. Two of its tests had bugs.
`_first_open` always returned -1 because its clearance scan touched the trunk itself, and
the damage loop then spun forever, which hung the test run. Boulders on slopes were also
buried on their uphill side. I fixed both, finished the work and committed it rather than
stashing it. The Agents category held nothing for this task.
**Done:**
- W5 (#12): `PropSet`, about 3,000 pines, scrub, boulders, wrecks and crates per island,
each with one collision box and health. A destroyed prop's box is removed at once.
`PropView` draws one MultiMesh per kind per 128 m square, about 150 draws, with
per-kind visibility ranges and procedural flat-shaded meshes.
- W6 (#13): a global sea level, changeable at runtime; wading; swimming (float, sprint,
dive, kick out, stand up in the shallows); stamina, breath and drown damage, counted in
ticks; no fall damage into deep water. `WaterView` is a procedural sea shader with
depth tint, foam at the waterline and ripples that fade with distance.
- W7 (#14): `Drop`, a seeded route that always crosses land, riding, leaping,
freefall, the wing-sail (by hand or automatic at 40 m), steering, a safe handoff to
landing or swimming, and ejection at the route's end. Every server match starts with
the drop, and bots leap at a time fixed by their ID.
- Closed milestone v0.2 and tagged `v0.2.0`.
- Opened #72 (`needs-eric`, v0.6): the GDD's core loop describes the launch as a packet
ship, a lifeline mortar and a gull-kite, while W7 says sky barge and wing-sail. Only
names and visuals depend on it.
**Tests:** `make check` passes: 151 tests, self-check and smoke (p95 tick 0.53 ms with
24 bots, who now leap from the barge). Captures checked by eye: props_forest,
props_felled, props_overview, props_beach, props_crate, props_highland, water_shore
and water_flood.
**Decisions:**
- Vertex colours in generated meshes are sRGB (`vertex_color_is_srgb`). Without it the
palette came out washed out.
- Prop materials are matte, because a bright sky highlight on pine tips read as snow.
- Swimming starts at 1.35 m of water and ends below 1.2 m. The gap stops players
flickering between swimming and walking at the edge.
- An exhausted swimmer sinks until the head is under, so stamina feeds into drowning.
There's no separate "exhausted" damage.
- The drop's route passes near the island's middle, pulled onto land, so every route
crosses at least 250 m of dry land.
- Gameplay timers (breath, stamina, drowning) are whole ticks, for exact replay.
**Known gaps:** no client scene yet puts terrain, props, water and a player together.
That comes with the client and HUD work. There are no barge or sail visuals, pending #72.
A swimmer can't climb onto pier decks yet. GPU frame times are unverified.
**Pace:** v0.2 finished about half a day late. v0.3 (9 issues) is due at the end of
today, so the next run starts about a day behind. Next is B1 (#15, harvesting, which
can use `PropSet.damage` and `material_of`), then B2 and B3. If the next run is more
than a day behind, defer B4 (#18, priority/low) and then B8 (#22, no priority) as the
pacing rule says.
+79 -1
View File
@@ -43,6 +43,80 @@ name, so it can't drift from the game. To change a number, edit that file.
Bots fill empty slots. Offline play is a local server filled with bots, the same game
code as online play. A downed duo partner can be revived, within `REVIVE_SECONDS`.
## The island
Every match is a new island, generated from the match seed by
[`src/sim/island.gd`](../src/sim/island.gd). The server and every client build it from the
seed alone, and compare `Island.heightmap_hash()`, so terrain is never sent.
- About a kilometre across (`ISLAND_RADIUS_METRES`), in the `WORLD_SIZE_METRES` square,
with open sea all round for the packet ship's approach.
- Elevation bands suit the tide: beach up to `ISLAND_BEACH_TOP`, wet flat marsh up to
`ISLAND_MARSH_TOP`, forest up to `ISLAND_FOREST_TOP`, then highland, and summit ground
from `ISLAND_SUMMIT_BAND`.
- Land rises from the coast over a broad dome, so each tide phase takes a ring of the
island rather than all the low ground at once.
- Two to four summits (`ISLAND_MIN_SUMMITS`, `ISLAND_MAX_SUMMITS`), at least
`ISLAND_SUMMIT_SPACING_METRES` apart and joined by lower ridges. The tallest stands
between `ISLAND_PEAK_MIN` and `ISLAND_PEAK_MAX`, always below `ISLAND_MAX_HEIGHT`, so the
last tide covers it. Late fights happen on several hills, not one.
- The worldgen test sweeps 100 seeds: land covers 30 to 70% of the world, at least two
distinct high points, 85% of land walkable, and no more than 3% of dry land cut off
from the main landmass at the first two sea levels.
`tools/island_map.gd` draws a top-down map of any seed, with a contour at each tide level.
### Points of interest
Every island gets 10 to 16 places worth landing at (`POI_KINDS`, `POI_MIN_TOTAL`,
`POI_MAX_TOTAL`), at least `POI_SPACING_METRES` apart, placed from the seed by
[`src/sim/poi_set.gd`](../src/sim/poi_set.gd):
| Kind | Sited | Built from |
|---|---|---|
| Hilltop shrine | On a summit | Open-fronted stone shrine with a painted roof, cairns |
| Lighthouse | Near the coast, raised ground | Stone tower, keeper's room, stair to a loft, light chamber |
| Dock | On the shore, facing open water | Plank pier on posts reaching deep water, net shed |
| Salt works | Flat beach or marsh | Evaporation pans behind low walls, boiling house |
| Quarry | Highland | Cut stone blocks, lifting frame, tool shed |
| Fishing hamlet | Forest band | Three or four huts round a yard, net-drying rack |
Each is assembled from modular parts (walls with doors, plinths, steps, roofs, stairs).
Loot spawn markers sit on their floors, for the loot system, and a test walks a player
from open ground into every interior.
### Props
About 3,000 props cover each island, placed from the seed by
[`src/sim/prop_set.gd`](../src/sim/prop_set.gd) at a density set per elevation band in
`PROP_DENSITY`, with groves and clearings in the forest. They keep
`PROP_POI_CLEARANCE` from every point of interest, its loot markers and its walking
routes.
| Prop | Found | Harvests |
|---|---|---|
| Pine | Forest and highland | Driftwood |
| Scrub | Marsh, forest, everywhere a little | Driftwood |
| Boulder | Highland and summits | Stone |
| Wreck | Beached hulls on the shore | Salvage iron |
| Crate | Washed up on beaches | Driftwood |
Each prop has the health in `PROP_KINDS` and blocks players with one box. When it is
destroyed its box goes at once. Both server and client place the same props from the
seed, so only damage is match state.
### The drop
Every match starts with the drop, simulated in [`src/sim/drop.gd`](../src/sim/drop.gd).
A carrier crosses the island at `BARGE_ALTITUDE` on a straight route drawn from the seed.
The route passes within `BARGE_CENTRE_JITTER` of the middle and always crosses at least
`BARGE_MIN_LAND_METRES` of dry land. Players ride it until they press jump, then fall,
steering at `FREEFALL_STEER_SPEED`, up to `FREEFALL_MAX_SPEED`. Jump opens the sail, and
it opens by itself `WING_AUTO_DEPLOY_HEIGHT` above the ground or water. Under the sail
they sink at `GLIDE_FALL_SPEED` and steer at `GLIDE_SPEED`, and touch down without damage.
Anyone still aboard at the end of the route is thrown off. The carrier's name and look,
sky barge or the packet ship and mortar of the core loop above, are open in #72.
## Tide phases
`TIDE_PHASES` is an ordered list of phases. Each one sets:
@@ -55,7 +129,11 @@ code as online play. A downed duo partner can be revived, within `REVIVE_SECONDS
The last phase raises the sea above the highest ground, so every match ends. Players
standing in shallow water wade and slow down. Underwater, they lose breath over
`BREATH_SECONDS`, and then take the phase's `drown_dps`. Swimming is slow and leaves a
player unable to build or fire. Water flows along the terrain, so low ground that is
player unable to build or fire. Players swim where the water over the floor is at least
`SWIM_DEPTH`, floating head-out at `SWIM_FLOAT_DEPTH`; crouch dives and jump kicks out of
the water. Swimming spends stamina (`SWIM_STAMINA_SECONDS`, faster when sprint-swimming),
which comes back on land. A swimmer with no stamina slips under and starts losing breath,
so a long swim out to sea can drown. Landing in deep water does no fall damage. Water flows along the terrain, so low ground that is
cut off from the sea stays dry until something opens a path.
## Building
+6
View File
@@ -24,4 +24,10 @@ func think(sim: Simulation) -> PlayerCommand:
_yaw = rng.randf() * TAU
_sprint = rng.randf() < 0.3
var buttons: int = PlayerCommand.BUTTON_SPRINT if _sprint else 0
# Leap from the barge at a time fixed by the player ID, between 2 and 22 seconds in.
var player: SimEntity = sim.entities.find(player_id)
if player != null and player.drop_state == Drop.ABOARD and sim.drop != null:
var leap_tick: int = sim.drop.began_tick + Tuning.TICK_RATE_HZ * 2 + (player_id * 53) % (Tuning.TICK_RATE_HZ * 20)
if sim.tick >= leap_tick:
buttons = PlayerCommand.BUTTON_JUMP
return PlayerCommand.from_input(sim.tick, Vector2(0.0, 1.0), _yaw, 0.0, buttons)
+92
View File
@@ -0,0 +1,92 @@
## Over-the-shoulder third-person camera placement, with collision and aim-down-sights.
## Pure logic: it reads the same SimGround the simulation uses, so the camera can't see
## through anything the player can't walk through. PlayerCamera applies the result.
class_name CameraRig
extends RefCounted
const PIVOT_HEIGHT: float = 1.6
const CROUCH_PIVOT_HEIGHT: float = 1.05
const SHOULDER: float = 0.6
const AIM_SHOULDER: float = 0.8
const DISTANCE: float = 3.4
const AIM_DISTANCE: float = 1.8
const FOV: float = 72.0
const AIM_FOV: float = 48.0
## Clearance kept between the camera and any surface, larger than the near plane's
## half-extent so the near plane never cuts into geometry.
const MARGIN: float = 0.25
const NEAR: float = 0.05
## Minimum distance from any surface, enough to keep the whole near plane outside it.
const CLEARANCE: float = 0.1
const CLEAR_STEPS: int = 16
## Seconds to move most of the way between hip and aim.
const AIM_BLEND_SECONDS: float = 0.12
## 0 at the hip, 1 fully aimed. Advanced by `update_aim`.
var aim_blend: float = 0.0
## Eases aim_blend towards aiming or not over `delta` seconds.
func update_aim(aiming: bool, delta: float) -> void:
var target: float = 1.0 if aiming else 0.0
var rate: float = 1.0 - exp(-delta * 3.0 / AIM_BLEND_SECONDS)
aim_blend = lerpf(aim_blend, target, rate)
if absf(aim_blend - target) < 0.001:
aim_blend = target
## The look direction for a yaw and pitch, matching the simulation's convention that
## forward at yaw 0 is +z and positive pitch looks up.
static func look_direction(yaw: float, pitch: float) -> Vector3:
return Vector3(sin(yaw) * cos(pitch), sin(pitch), cos(yaw) * cos(pitch))
## The point the camera orbits, above the player's feet.
static func pivot(feet: Vector3, crouching: bool) -> Vector3:
return feet + Vector3.UP * (CROUCH_PIVOT_HEIGHT if crouching else PIVOT_HEIGHT)
## Solves the camera transform for a player. The camera looks along the aim direction
## from behind and to the right of the pivot, pulled in where geometry is in the way.
func solve(feet: Vector3, yaw: float, pitch: float, crouching: bool, ground: SimGround) -> Transform3D:
var look: Vector3 = look_direction(yaw, pitch)
var right: Vector3 = Vector3(-cos(yaw), 0.0, sin(yaw))
var shoulder: float = lerpf(SHOULDER, AIM_SHOULDER, aim_blend)
var distance: float = lerpf(DISTANCE, AIM_DISTANCE, aim_blend)
var origin: Vector3 = pivot(feet, crouching)
var beside: Vector3 = _cast(ground, origin, origin + right * shoulder)
var eye: Vector3 = _cast(ground, beside, beside - look * distance)
# The two legs can each be clear while the camera ends up over a wall top, where the
# wall hides the player. Keep a clear straight line back to the pivot as well.
eye = _cast(ground, origin, eye)
eye = _clear(ground, eye, origin)
var basis: Basis = Basis.looking_at(look, Vector3.UP if absf(look.y) < 0.999 else Vector3.FORWARD)
return Transform3D(basis, eye)
func fov() -> float:
return lerpf(FOV, AIM_FOV, aim_blend)
## Moves from `from` towards `to`, stopping MARGIN short of the first surface.
static func _cast(ground: SimGround, from: Vector3, to: Vector3) -> Vector3:
var length: float = from.distance_to(to)
if length <= 0.0:
return from
var direction: Vector3 = (to - from) / length
# Cast MARGIN past the end, so an end point just short of a wall is pulled in too.
var reach: float = length + MARGIN
var hit: float = ground.raycast(from, from + direction * reach)
return from + direction * clampf(hit * reach - MARGIN, 0.0, length)
## A ray can graze a surface it never hits. If the eye ended up within the near plane's
## clearance of anything, slide it back towards `safe` until it's clear.
static func _clear(ground: SimGround, eye: Vector3, safe: Vector3) -> Vector3:
var point: Vector3 = eye
for step: int in CLEAR_STEPS:
if not ground.point_inside(point, CLEARANCE):
return point
point = eye.lerp(safe, float(step + 1) / CLEAR_STEPS)
return safe
+1
View File
@@ -0,0 +1 @@
uid://bffma7fh66ygi
+60
View File
@@ -0,0 +1,60 @@
## Player-adjustable look settings, saved in the user's config file.
class_name InputSettings
extends RefCounted
const DEFAULT_PATH: String = "user://settings.cfg"
const SECTION: String = "input"
## Radians of turn per pixel of mouse motion at sensitivity 1.0.
const RADIANS_PER_PIXEL: float = 0.0025
const MIN_SENSITIVITY: float = 0.05
const MAX_SENSITIVITY: float = 10.0
## Looking straight up or down flips the camera basis, so stop just short.
const PITCH_LIMIT: float = deg_to_rad(85.0)
var mouse_sensitivity: float = 1.0:
set(value):
mouse_sensitivity = clampf(value, MIN_SENSITIVITY, MAX_SENSITIVITY)
## Multiplies the sensitivity while aiming down sights.
var aim_sensitivity_scale: float = 0.6:
set(value):
aim_sensitivity_scale = clampf(value, 0.1, 2.0)
var invert_y: bool = false
## Applies a mouse motion to a look direction. Returns Vector2(yaw, pitch) in radians.
## Moving the mouse right turns right; moving it up looks up, unless invert_y is set.
func apply_mouse(relative: Vector2, yaw: float, pitch: float, aiming: bool) -> Vector2:
var scale: float = RADIANS_PER_PIXEL * mouse_sensitivity
if aiming:
scale *= aim_sensitivity_scale
var vertical: float = relative.y if invert_y else -relative.y
var new_yaw: float = fposmod(yaw - relative.x * scale, TAU)
var new_pitch: float = clampf(pitch + vertical * scale, -PITCH_LIMIT, PITCH_LIMIT)
return Vector2(new_yaw, new_pitch)
func save(path: String = DEFAULT_PATH) -> Error:
var config: ConfigFile = ConfigFile.new()
config.load(path) # Keep other sections; a missing file is fine.
config.set_value(SECTION, "mouse_sensitivity", mouse_sensitivity)
config.set_value(SECTION, "aim_sensitivity_scale", aim_sensitivity_scale)
config.set_value(SECTION, "invert_y", invert_y)
return config.save(path)
## Loads saved settings. Missing or malformed values keep their defaults.
static func load_from(path: String = DEFAULT_PATH) -> InputSettings:
var settings: InputSettings = InputSettings.new()
var config: ConfigFile = ConfigFile.new()
if config.load(path) != OK:
return settings
var sensitivity: Variant = config.get_value(SECTION, "mouse_sensitivity", 1.0)
if sensitivity is float or sensitivity is int:
settings.mouse_sensitivity = float(sensitivity)
var aim_scale: Variant = config.get_value(SECTION, "aim_sensitivity_scale", 0.6)
if aim_scale is float or aim_scale is int:
settings.aim_sensitivity_scale = float(aim_scale)
var invert: Variant = config.get_value(SECTION, "invert_y", false)
if invert is bool:
settings.invert_y = invert
return settings
+1
View File
@@ -0,0 +1 @@
uid://bn4kidspsub2m
+42
View File
@@ -0,0 +1,42 @@
## The local player's third-person camera. Turns mouse motion into a look direction using
## InputSettings, and places itself each frame with CameraRig, so it never clips through
## terrain or structures. The input layer reads `yaw` and `pitch` when it builds the
## player's commands.
class_name PlayerCamera
extends Camera3D
var settings: InputSettings = InputSettings.new()
var rig: CameraRig = CameraRig.new()
var ground: SimGround = SimGround.flat()
## Radians, in the simulation's convention (see docs/ARCHITECTURE.md).
var yaw: float = 0.0
var pitch: float = 0.0
var aiming: bool = false
## Where the followed player's feet are, and whether they're crouching. Set by whoever
## owns the player's presentation, from interpolated snapshots.
var target_feet: Vector3 = Vector3.ZERO
var target_crouching: bool = false
func _ready() -> void:
near = CameraRig.NEAR
fov = CameraRig.FOV
func _unhandled_input(event: InputEvent) -> void:
var motion: InputEventMouseMotion = event as InputEventMouseMotion
if motion != null and Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
var look: Vector2 = settings.apply_mouse(motion.relative, yaw, pitch, aiming)
yaw = look.x
pitch = look.y
func _process(delta: float) -> void:
rig.update_aim(aiming, delta)
snap()
## Places the camera for the current target and look direction immediately.
func snap() -> void:
global_transform = rig.solve(target_feet, yaw, pitch, target_crouching, ground)
fov = rig.fov()
+1
View File
@@ -0,0 +1 @@
uid://bkvavm0kwaxr5
+54
View File
@@ -0,0 +1,54 @@
## Draws an island's points of interest from their parts: one MultiMesh of boxes per
## look, so the whole set costs a handful of draw calls. Colours follow the weathered
## seafaring palette in docs/ORIGINALITY.md: tarred wood, grey planks, stone, faded red
## roofs, salt-faded paint and white salt. No textures; the art pass replaces these.
class_name PoiView
extends Node3D
const LOOKS: Dictionary = {
Poi.LOOK_TARRED_WOOD: {"colour": Color(0.19, 0.16, 0.13), "roughness": 0.7},
Poi.LOOK_PLANK: {"colour": Color(0.50, 0.45, 0.37), "roughness": 0.9},
Poi.LOOK_STONE: {"colour": Color(0.56, 0.54, 0.49), "roughness": 0.95},
Poi.LOOK_ROOF: {"colour": Color(0.56, 0.27, 0.20), "roughness": 0.85},
Poi.LOOK_PAINT: {"colour": Color(0.33, 0.55, 0.56), "roughness": 0.8},
Poi.LOOK_SALT: {"colour": Color(0.90, 0.90, 0.86), "roughness": 0.6},
Poi.LOOK_LAMP: {"colour": Color(0.98, 0.86, 0.55), "roughness": 0.3, "glow": 1.6},
}
func setup(placed: PoiSet) -> void:
var by_look: Dictionary = {}
for poi: Poi in placed.pois:
for part: Dictionary in poi.parts:
var look: String = part["look"]
if not by_look.has(look):
by_look[look] = []
(by_look[look] as Array).append(part["box"])
for look: String in by_look:
var boxes: Array = by_look[look]
var mesh: BoxMesh = BoxMesh.new()
mesh.size = Vector3.ONE
mesh.material = _material(look)
var multimesh: MultiMesh = MultiMesh.new()
multimesh.transform_format = MultiMesh.TRANSFORM_3D
multimesh.mesh = mesh
multimesh.instance_count = boxes.size()
for index: int in boxes.size():
var box: AABB = boxes[index]
multimesh.set_instance_transform(index, Transform3D(Basis.from_scale(box.size), box.get_center()))
var instance: MultiMeshInstance3D = MultiMeshInstance3D.new()
instance.name = look
instance.multimesh = multimesh
add_child(instance)
func _material(look: String) -> StandardMaterial3D:
var spec: Dictionary = LOOKS.get(look, LOOKS[Poi.LOOK_PLANK])
var material: StandardMaterial3D = StandardMaterial3D.new()
material.albedo_color = spec["colour"]
material.roughness = spec["roughness"]
if spec.has("glow"):
material.emission_enabled = true
material.emission = spec["colour"]
material.emission_energy_multiplier = spec["glow"]
return material
+1
View File
@@ -0,0 +1 @@
uid://dvntokn6rpcxs
+350
View File
@@ -0,0 +1,350 @@
## Draws the island's props: pines, scrub, boulders, wrecks and crates.
##
## The island is cut into CHUNK-metre squares, and each square gets one MultiMesh per
## kind, so the GPU draws thousands of props in a few hundred instanced calls, culls
## whole squares outside the view, and drops each kind beyond its own visibility range
## (small things vanish first). Meshes are built here from code, low-poly, flat-shaded,
## and coloured per vertex in the weathered palette from docs/ORIGINALITY.md. Each
## instance gets a slight colour shift so a stand of pines isn't one flat green.
##
## Destruction comes from the simulation: `sync()` reads new entries in
## PropSet.destroyed and collapses those instances to nothing. Collision never comes from
## here; SimGround holds the props' boxes on the server and in client prediction alike.
class_name PropView
extends Node3D
## Side of the culling squares, in metres.
const CHUNK: float = 128.0
## Beyond this distance from the camera a kind isn't drawn, in metres. Pines and wrecks
## carry the skyline; scrub and crates are only worth drawing close up.
const RANGES: Dictionary = {"pine": 520.0, "scrub": 170.0, "boulder": 380.0, "wreck": 420.0, "crate": 140.0}
## Fade band at the end of each range, in metres.
const FADE: float = 30.0
## How far an instance's colour may stray from white, per channel.
const TINT: float = 0.12
const BARK: Color = Color(0.40, 0.30, 0.22)
const NEEDLES: Array[Color] = [Color(0.22, 0.36, 0.28), Color(0.26, 0.40, 0.30), Color(0.31, 0.44, 0.32)]
const SCRUB: Array[Color] = [Color(0.45, 0.48, 0.30), Color(0.53, 0.53, 0.34)]
const STONE: Color = Color(0.56, 0.55, 0.51)
const LICHEN: Color = Color(0.62, 0.61, 0.45)
const TAR: Color = Color(0.31, 0.26, 0.22)
const PLANK: Color = Color(0.64, 0.60, 0.52)
const CRATE: Color = Color(0.68, 0.55, 0.38)
## Props drawn and props hidden since setup.
var drawn: int = 0
var hidden_count: int = 0
## Main-thread microseconds the most recent `sync()` took.
var last_sync_usec: int = 0
var _props: PropSet
## Per prop: the instance node index and the instance index within it.
var _node_of: PackedInt32Array = PackedInt32Array()
var _index_of: PackedInt32Array = PackedInt32Array()
var _nodes: Array[MultiMeshInstance3D] = []
var _hidden: PackedByteArray = PackedByteArray()
## How many entries of PropSet.destroyed have been applied.
var _cursor: int = 0
## Builds every instance for `props`. Call once, before or after adding to the tree.
func setup(props: PropSet) -> void:
_props = props
var count: int = props.count()
_node_of.resize(count)
_index_of.resize(count)
_hidden.resize(count)
_hidden.fill(0)
var meshes: Array[ArrayMesh] = []
for kind: String in PropSet.KINDS:
meshes.append(build_mesh(kind))
# (chunk key, kind code) -> prop IDs, in prop order so the layout is deterministic.
var groups: Dictionary = {}
var keys: Array[Vector3i] = []
for prop: int in count:
var centre: Vector3 = props.boxes[prop].get_center()
var key: Vector3i = Vector3i(floori(centre.x / CHUNK), floori(centre.z / CHUNK), props.kinds[prop])
if not groups.has(key):
groups[key] = PackedInt32Array()
keys.append(key)
var members: PackedInt32Array = groups[key]
members.append(prop)
groups[key] = members
for key: Vector3i in keys:
var members: PackedInt32Array = groups[key]
var kind: String = PropSet.KINDS[key.z]
var multimesh: MultiMesh = MultiMesh.new()
multimesh.transform_format = MultiMesh.TRANSFORM_3D
multimesh.use_colors = true
multimesh.mesh = meshes[key.z]
multimesh.instance_count = members.size()
for index: int in members.size():
var prop: int = members[index]
multimesh.set_instance_transform(index, instance_transform(props, prop))
multimesh.set_instance_color(index, _tint(prop))
_node_of[prop] = _nodes.size()
_index_of[prop] = index
var instance: MultiMeshInstance3D = MultiMeshInstance3D.new()
instance.name = "%s_%d_%d" % [kind, key.x, key.y]
instance.multimesh = multimesh
instance.visibility_range_end = RANGES[kind]
instance.visibility_range_end_margin = FADE
instance.visibility_range_fade_mode = GeometryInstance3D.VISIBILITY_RANGE_FADE_SELF
# Scrub and crates are too small to cast shadows worth their cost.
if kind == "scrub" or kind == "crate":
instance.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
_nodes.append(instance)
add_child(instance)
drawn = count
_cursor = 0
sync()
## Applies destructions the simulation recorded since the last call. Cheap: it touches
## only the new entries. Returns how many props it hid.
func sync() -> int:
var started: int = Time.get_ticks_usec()
var applied: int = 0
while _cursor < _props.destroyed.size():
var prop: int = _props.destroyed[_cursor]
_cursor += 1
if _hidden[prop] != 0:
continue
_hidden[prop] = 1
_nodes[_node_of[prop]].multimesh.set_instance_transform(_index_of[prop], Transform3D(Basis.from_scale(Vector3.ZERO), Vector3.ZERO))
drawn -= 1
hidden_count += 1
applied += 1
last_sync_usec = Time.get_ticks_usec() - started
return applied
func _process(_delta: float) -> void:
if _props != null:
sync()
func is_drawn(prop: int) -> bool:
return _hidden[prop] == 0
func node_count() -> int:
return _nodes.size()
## The MultiMeshInstance3D drawing `prop`, and its index there.
func node_for(prop: int) -> MultiMeshInstance3D:
return _nodes[_node_of[prop]]
func instance_index(prop: int) -> int:
return _index_of[prop]
## The transform that fits a kind's unit mesh to the prop's collision box. Meshes span
## -0.5 .. 0.5 across and 0 .. 1 up, so the visible prop matches what blocks players.
## Wrecks lie along the long side of their box; crates turn only a little, so their
## corners stay close to the box.
static func instance_transform(props: PropSet, prop: int) -> Transform3D:
var box: AABB = props.boxes[prop]
var kind: String = props.kind_name(prop)
var yaw: float = props.yaws[prop]
var scale: Vector3 = box.size
if kind == "wreck":
var along_x: bool = box.size.x >= box.size.z
scale = Vector3(maxf(box.size.x, box.size.z), box.size.y, minf(box.size.x, box.size.z))
yaw = (0.0 if along_x else PI * 0.5) + (PI if yaw > PI else 0.0)
elif kind == "crate":
yaw = (yaw / TAU - 0.5) * deg_to_rad(16.0)
scale = Vector3(box.size.x * 0.92, box.size.y, box.size.z * 0.92)
var basis: Basis = Basis(Vector3.UP, yaw).scaled_local(scale)
var base: Vector3 = Vector3(box.get_center().x, box.position.y, box.get_center().z)
return Transform3D(basis, base)
func _tint(prop: int) -> Color:
# A hash of the ID, not a random stream, so the view never touches simulation RNG.
var h: int = hash(prop * 2654435761)
var shift: float = (float(h & 0xff) / 255.0 - 0.5) * 2.0 * TINT
var warm: float = (float((h >> 8) & 0xff) / 255.0 - 0.5) * TINT
return Color(1.0 + shift + warm, 1.0 + shift, 1.0 + shift - warm)
## The unit mesh for a kind: footprint -0.5 .. 0.5, height 0 .. 1. Pines' canopies
## spread well past their trunk footprint, since only the trunk blocks players.
static func build_mesh(kind: String) -> ArrayMesh:
var tool: SurfaceTool = SurfaceTool.new()
tool.begin(Mesh.PRIMITIVE_TRIANGLES)
match kind:
"pine":
_prism(tool, 6, 0.5, 0.35, 0.0, 0.42, BARK)
_cone(tool, 9, 3.9, 0.20, 0.42, NEEDLES[0], 0.0)
_cone(tool, 9, 3.0, 0.42, 0.36, NEEDLES[1], 0.35)
_cone(tool, 8, 2.0, 0.63, 0.37, NEEDLES[2], 0.7)
"scrub":
_lump(tool, Vector3(0.0, 0.0, 0.0), Vector3(0.5, 1.0, 0.5), 7, 3, SCRUB[0], 11)
_lump(tool, Vector3(0.18, 0.0, -0.12), Vector3(0.28, 0.7, 0.28), 6, 3, SCRUB[1], 23)
_lump(tool, Vector3(-0.2, 0.0, 0.18), Vector3(0.28, 0.6, 0.28), 6, 3, SCRUB[1], 37)
"boulder":
_lump(tool, Vector3(0.0, 0.0, 0.0), Vector3(0.5, 1.0, 0.5), 8, 5, STONE, 5, 0.18, LICHEN)
"wreck":
_hull(tool)
"crate":
_crate(tool)
tool.generate_normals()
var material: StandardMaterial3D = StandardMaterial3D.new()
material.vertex_color_use_as_albedo = true
# The palette is written in sRGB, like every other colour in the project.
material.vertex_color_is_srgb = true
material.roughness = 1.0
# Matte: a shiny sky highlight on needle tips reads as snow.
material.metallic_specular = 0.15
if kind == "wreck":
material.cull_mode = BaseMaterial3D.CULL_DISABLED
tool.set_material(material)
return tool.commit()
## A vertical prism of `sides`, radius `radius` at the bottom and `top_radius` at the
## top, from y `from` to `to`. No smoothing: every face its own vertices.
static func _prism(tool: SurfaceTool, sides: int, radius: float, top_radius: float, from: float, to: float, colour: Color) -> void:
for side: int in sides:
var a: float = TAU * side / sides
var b: float = TAU * (side + 1) / sides
var p0: Vector3 = Vector3(cos(a) * radius, from, sin(a) * radius)
var p1: Vector3 = Vector3(cos(b) * radius, from, sin(b) * radius)
var p2: Vector3 = Vector3(cos(b) * top_radius, to, sin(b) * top_radius)
var p3: Vector3 = Vector3(cos(a) * top_radius, to, sin(a) * top_radius)
_quad(tool, p0, p1, p2, p3, colour)
## A cone tier for a pine: a skirt from `radius` at `base` to a point `height` above,
## with a flat underside. `twist` turns the tier so tiers don't line up.
static func _cone(tool: SurfaceTool, sides: int, radius: float, base: float, height: float, colour: Color, twist: float) -> void:
var tip: Vector3 = Vector3(0.0, base + height, 0.0)
var under: Vector3 = Vector3(0.0, base + height * 0.12, 0.0)
for side: int in sides:
var a: float = TAU * side / sides + twist
var b: float = TAU * (side + 1) / sides + twist
# Alternate rim heights give the tier a ragged, wind-cut edge.
var drop_a: float = 0.03 if side % 2 == 0 else -0.02
var drop_b: float = 0.03 if (side + 1) % 2 == 0 else -0.02
if side + 1 == sides:
drop_b = 0.03
var p0: Vector3 = Vector3(cos(a) * radius, base - drop_a, sin(a) * radius)
var p1: Vector3 = Vector3(cos(b) * radius, base - drop_b, sin(b) * radius)
_tri(tool, p1, p0, tip, colour)
_tri(tool, p0, p1, under, colour.darkened(0.35))
## A lumpy dome or rock: latitude rings over a half-ellipsoid of `extent` standing on
## y = 0 at `centre`, with radii jittered by a fixed hash of `salt`. With `speckle`,
## upward faces take `top_colour` the way lichen does.
static func _lump(tool: SurfaceTool, centre: Vector3, extent: Vector3, sides: int, rings: int, colour: Color, salt: int,
jitter: float = 0.14, top_colour: Color = Color.TRANSPARENT) -> void:
var grid: Array[PackedVector3Array] = []
for ring: int in rings + 1:
var row: PackedVector3Array = PackedVector3Array()
var lat: float = PI * 0.5 * ring / rings
for side: int in sides:
var lon: float = TAU * side / sides
# Never wider than 1, so the lump stays inside its footprint.
var wobble: float = 1.0 - jitter * 2.0 * _hash01(salt, ring * 31 + side)
if ring == rings:
wobble = 1.0
var radial: float = cos(lat) * wobble
var up: float = sin(lat) * (0.85 + 0.15 * wobble)
row.append(centre + Vector3(cos(lon) * radial * extent.x, up * extent.y, sin(lon) * radial * extent.z))
grid.append(row)
for ring: int in rings:
for side: int in sides:
var next: int = (side + 1) % sides
var a: Vector3 = grid[ring][side]
var b: Vector3 = grid[ring][next]
var c: Vector3 = grid[ring + 1][next]
var d: Vector3 = grid[ring + 1][side]
var shade: Color = colour
if top_colour.a > 0.0 and ring >= rings - 2 and _hash01(salt + 7, ring * 31 + side) > 0.45:
shade = top_colour
# Lower rings sit in shadow and grime.
shade = shade.darkened(0.18 * (1.0 - float(ring) / rings))
_quad(tool, a, d, c, b, shade)
## A beached hull, long along x: tarred planks tapering to a stem at +x and a transom
## at -x, open on top, with grey ribs standing out of it.
static func _hull(tool: SurfaceTool) -> void:
# Cross-sections along x: (x, half beam scale, depth scale).
var stations: Array[Vector3] = [
Vector3(-0.5, 0.78, 0.82), Vector3(-0.25, 1.0, 1.0), Vector3(0.1, 0.96, 1.0),
Vector3(0.32, 0.7, 0.92), Vector3(0.5, 0.0, 0.8),
]
# Section profile from port gunwale through the keel to starboard: (z, y).
var profile: Array[Vector2] = [
Vector2(-0.5, 0.62), Vector2(-0.44, 0.3), Vector2(-0.24, 0.08), Vector2(0.0, 0.0),
Vector2(0.24, 0.08), Vector2(0.44, 0.3), Vector2(0.5, 0.62),
]
var sections: Array[PackedVector3Array] = []
for station: Vector3 in stations:
var row: PackedVector3Array = PackedVector3Array()
for point: Vector2 in profile:
var y: float = 0.62 - (0.62 - point.y) * station.z
row.append(Vector3(station.x, y, point.x * station.y))
sections.append(row)
for s: int in stations.size() - 1:
for p: int in profile.size() - 1:
var shade: Color = TAR if p % 2 == 0 else TAR.lightened(0.12)
_quad(tool, sections[s][p], sections[s + 1][p], sections[s + 1][p + 1], sections[s][p + 1], shade)
# Transom.
var stern: PackedVector3Array = sections[0]
for p: int in range(1, profile.size() - 1):
_tri(tool, stern[0], stern[p + 1], stern[p], TAR.lightened(0.05))
# Ribs: thin frames rising above the gunwale, bleached grey.
for x: float in [-0.3, -0.08, 0.14]:
for z: float in [-0.46, 0.46]:
_box(tool, Vector3(x, 0.4, z * 0.98), Vector3(0.025, 0.6, 0.06), PLANK)
# A plank thwart across the middle.
_box(tool, Vector3(-0.15, 0.5, 0.0), Vector3(0.05, 0.03, 0.92), PLANK)
## A plank crate with darker corner battens.
static func _crate(tool: SurfaceTool) -> void:
_box(tool, Vector3(0.0, 0.5, 0.0), Vector3(0.96, 0.96, 0.96), CRATE)
var batten: Color = CRATE.darkened(0.45)
for x: float in [-0.46, 0.46]:
for z: float in [-0.46, 0.46]:
_box(tool, Vector3(x, 0.5, z), Vector3(0.08, 1.0, 0.08), batten)
for y: float in [0.06, 0.94]:
_box(tool, Vector3(0.0, y, 0.0), Vector3(1.0, 0.08, 1.0), batten)
static func _box(tool: SurfaceTool, centre: Vector3, size: Vector3, colour: Color) -> void:
var h: Vector3 = size * 0.5
var c: Array[Vector3] = []
for i: int in 8:
c.append(centre + Vector3(h.x if i & 1 else -h.x, h.y if i & 2 else -h.y, h.z if i & 4 else -h.z))
_quad(tool, c[2], c[3], c[1], c[0], colour) # -z
_quad(tool, c[7], c[6], c[4], c[5], colour) # +z
_quad(tool, c[6], c[2], c[0], c[4], colour) # -x
_quad(tool, c[3], c[7], c[5], c[1], colour) # +x
_quad(tool, c[6], c[7], c[3], c[2], colour) # +y
_quad(tool, c[0], c[1], c[5], c[4], colour) # -y
## Two triangles a-b-c and a-c-d, counter-clockwise seen from outside.
static func _quad(tool: SurfaceTool, a: Vector3, b: Vector3, c: Vector3, d: Vector3, colour: Color) -> void:
_tri(tool, a, b, c, colour)
_tri(tool, a, c, d, colour)
static func _tri(tool: SurfaceTool, a: Vector3, b: Vector3, c: Vector3, colour: Color) -> void:
tool.set_color(colour)
# Godot's front faces wind clockwise, so emit in reverse.
tool.add_vertex(a)
tool.add_vertex(c)
tool.add_vertex(b)
static func _hash01(salt: int, index: int) -> float:
return float(hash(salt * 7919 + index * 104729) & 0xffff) / 65535.0
+1
View File
@@ -0,0 +1 @@
uid://c4qtatighmhh7
+81
View File
@@ -0,0 +1,81 @@
// Tidewall terrain: four procedural layers (sand, marsh, grass, rock) blended by the
// splat weights in the vertex colour, with rock taking over on steep ground and weathered
// pale stone on the summits. No textures: every pattern is generated here.
shader_type spatial;
render_mode cull_disabled;
uniform float summit_height = 50.0;
uniform float max_slope_cos = 0.69;
uniform vec3 sand_colour : source_color = vec3(0.80, 0.71, 0.52);
uniform vec3 marsh_colour : source_color = vec3(0.37, 0.39, 0.25);
uniform vec3 grass_colour : source_color = vec3(0.31, 0.42, 0.22);
uniform vec3 rock_colour : source_color = vec3(0.47, 0.44, 0.39);
uniform vec3 summit_colour : source_color = vec3(0.60, 0.58, 0.53);
// Debug: tint each chunk by its level of detail (set per instance by TerrainView).
instance uniform float lod_tint = -1.0;
varying vec3 world_position;
varying vec3 world_normal;
float hash(vec2 p) {
p = fract(p * vec2(123.34, 456.21));
p += dot(p, p + 45.32);
return fract(p.x * p.y);
}
float value_noise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
vec2 u = f * f * (3.0 - 2.0 * f);
return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), u.x),
mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x), u.y);
}
float fbm(vec2 p) {
float total = 0.0;
float amplitude = 0.5;
for (int octave = 0; octave < 4; octave++) {
total += amplitude * value_noise(p);
p *= 2.03;
amplitude *= 0.5;
}
return total;
}
void vertex() {
world_position = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
world_normal = normalize((MODEL_MATRIX * vec4(NORMAL, 0.0)).xyz);
}
void fragment() {
vec2 p = world_position.xz;
float broad = fbm(p * 0.035);
float fine = fbm(p * 0.6);
float ripple = 0.5 + 0.5 * sin(dot(p, vec2(0.55, 0.32)) + broad * 9.0);
vec3 sand = sand_colour * (0.9 + 0.12 * fine) * (0.97 + 0.04 * ripple);
vec3 marsh = mix(marsh_colour * 0.75, marsh_colour * 1.1, smoothstep(0.35, 0.65, broad + 0.2 * fine));
vec3 grass = grass_colour * (0.78 + 0.35 * broad) * (0.9 + 0.15 * fine);
grass = mix(grass, grass * vec3(1.15, 1.05, 0.7), smoothstep(0.55, 0.75, broad));
float strata = 0.5 + 0.5 * sin(world_position.y * 2.1 + broad * 5.0);
vec3 rock = rock_colour * (0.82 + 0.22 * fine + 0.1 * strata);
vec3 summit = summit_colour * (0.88 + 0.14 * fine);
rock = mix(rock, summit, 0.8 * smoothstep(summit_height - 2.0, summit_height + 6.0, world_position.y + 3.0 * broad));
vec4 weights = max(COLOR, vec4(0.0));
float steep = 1.0 - smoothstep(max_slope_cos - 0.08, max_slope_cos + 0.12, world_normal.y);
weights = mix(weights, vec4(0.0, 0.0, 0.0, 1.0), steep);
weights /= max(weights.r + weights.g + weights.b + weights.a, 0.0001);
vec3 albedo = sand * weights.r + marsh * weights.g + grass * weights.b + rock * weights.a;
if (lod_tint >= 0.0) {
vec3 tints[4] = vec3[](vec3(1.0, 0.5, 0.5), vec3(0.5, 1.0, 0.5), vec3(0.5, 0.6, 1.0), vec3(1.0, 1.0, 0.4));
albedo *= tints[int(lod_tint) % 4];
}
ALBEDO = albedo;
// Skirts and any face seen from below must light like the ground above them, so
// use the terrain normal for both faces instead of the flipped back-face normal.
NORMAL = normalize((VIEW_MATRIX * vec4(world_normal, 0.0)).xyz);
ROUGHNESS = mix(0.95, 0.6, weights.g);
SPECULAR = 0.2;
}
+1
View File
@@ -0,0 +1 @@
uid://c7ee5h5pe6qjq
+178
View File
@@ -0,0 +1,178 @@
## Builds render-mesh arrays for one square chunk of the island's heightfield at one
## level of detail. Pure and thread-safe: it only reads the heightfield and bands, so
## TerrainView runs it on worker threads and only uploads meshes on the main thread.
##
## Seams: every chunk hangs a skirt, a vertical strip of triangles, from each edge down
## by more than any level of detail can disagree with any other along that edge. A
## neighbour at a different detail level then meets a wall instead of a gap, so there
## are never cracks to see through. Normals come from the full-resolution heightfield at
## every level, so lighting matches across a level boundary.
##
## Splat weights go in the vertex colour: r sand, g marsh, b grass, a rock. The terrain
## shader blends procedural layers with them.
class_name TerrainChunkBuilder
extends RefCounted
## Heightfield cells along a chunk's side. 32 cells of 2 m make 64 m chunks.
const CHUNK_CELLS: int = 32
## Sample step at each level of detail. Level 0 is full resolution.
const LOD_STEPS: Array[int] = [1, 2, 4, 8]
const SKIRT_MARGIN: float = 0.5
## Samples either side that splat weights are averaged over.
const WEIGHT_RADIUS: int = 2
const _BAND_WEIGHTS: Dictionary = {
Island.Band.SEA: Color(1.0, 0.0, 0.0, 0.0),
Island.Band.BEACH: Color(1.0, 0.0, 0.0, 0.0),
Island.Band.MARSH: Color(0.0, 1.0, 0.0, 0.0),
Island.Band.FOREST: Color(0.0, 0.0, 1.0, 0.0),
Island.Band.HIGHLAND: Color(0.0, 0.0, 0.0, 1.0),
Island.Band.SUMMIT: Color(0.0, 0.0, 0.0, 1.0),
}
## Chunks along each side of the world.
static func chunks_per_side(ground: SimGround) -> int:
return (ground.samples - 1) / CHUNK_CELLS
## World-space bounds of a chunk's footprint, as (min x, min z, size).
static func chunk_rect(ground: SimGround, chunk: Vector2i) -> Rect2:
var size: float = CHUNK_CELLS * ground.cell
return Rect2(chunk.x * size, chunk.y * size, size, size)
## Mesh arrays for `chunk` at level `lod`, ready for ArrayMesh.add_surface_from_arrays.
## Vertices are in world space. `skirts` is false only for the capture that proves the
## crack check can see cracks.
static func build(ground: SimGround, bands: PackedByteArray, chunk: Vector2i, lod: int, skirts: bool = true) -> Array:
var step: int = LOD_STEPS[lod]
var per_side: int = CHUNK_CELLS / step + 1
var origin: Vector2i = chunk * CHUNK_CELLS
var samples: int = ground.samples
var heights: PackedFloat32Array = ground.heights
var cell: float = ground.cell
var vertices: PackedVector3Array = PackedVector3Array()
var normals: PackedVector3Array = PackedVector3Array()
var colours: PackedColorArray = PackedColorArray()
var uvs: PackedVector2Array = PackedVector2Array()
var total: int = per_side * per_side + 4 * per_side
vertices.resize(total)
normals.resize(total)
colours.resize(total)
uvs.resize(total)
for row: int in per_side:
for column: int in per_side:
var gx: int = origin.x + column * step
var gz: int = origin.y + row * step
var index: int = row * per_side + column
var at: int = gz * samples + gx
vertices[index] = Vector3(gx * cell, heights[at], gz * cell)
normals[index] = _normal(heights, samples, cell, gx, gz)
colours[index] = _weights(bands, samples, gx, gz)
uvs[index] = Vector2(gx, gz) * cell
var indices: PackedInt32Array = PackedInt32Array()
for row: int in per_side - 1:
for column: int in per_side - 1:
var a: int = row * per_side + column
var b: int = a + 1
var c: int = a + per_side
var d: int = c + 1
indices.append_array(PackedInt32Array([a, b, c, b, d, c]))
var depth: float = skirt_depth(ground, chunk) if skirts else 0.0
var skirt_start: int = per_side * per_side
# Edges in order: north (row 0), south (last row), west (column 0), east (last column).
for edge: int in 4:
for position: int in per_side:
var top: int = _edge_vertex(edge, position, per_side)
var index: int = skirt_start + edge * per_side + position
vertices[index] = vertices[top] - Vector3(0.0, depth, 0.0)
normals[index] = normals[top]
colours[index] = colours[top]
uvs[index] = uvs[top]
for position: int in per_side - 1:
var top_a: int = _edge_vertex(edge, position, per_side)
var top_b: int = _edge_vertex(edge, position + 1, per_side)
var low_a: int = skirt_start + edge * per_side + position
var low_b: int = low_a + 1
indices.append_array(PackedInt32Array([top_a, top_b, low_a, top_b, low_b, low_a]))
var arrays: Array = []
arrays.resize(Mesh.ARRAY_MAX)
arrays[Mesh.ARRAY_VERTEX] = vertices
arrays[Mesh.ARRAY_NORMAL] = normals
arrays[Mesh.ARRAY_COLOR] = colours
arrays[Mesh.ARRAY_TEX_UV] = uvs
arrays[Mesh.ARRAY_INDEX] = indices
return arrays
## How far the skirts hang below a chunk's edges: twice the most that any level of
## detail strays from the full-resolution edge, plus a margin. Two neighbours share
## each edge, so this covers any pairing of levels.
static func skirt_depth(ground: SimGround, chunk: Vector2i) -> float:
var worst: float = 0.0
var origin: Vector2i = chunk * CHUNK_CELLS
for edge: int in 4:
for step: int in LOD_STEPS:
for position: int in CHUNK_CELLS + 1:
var low: int = (position / step) * step
var high: int = mini(low + step, CHUNK_CELLS)
var t: float = 0.0 if high == low else float(position - low) / float(high - low)
var exact: float = _edge_height(ground, origin, edge, position)
var coarse: float = lerpf(_edge_height(ground, origin, edge, low), _edge_height(ground, origin, edge, high), t)
worst = maxf(worst, absf(exact - coarse))
return 2.0 * worst + SKIRT_MARGIN
## Splat weights averaged over the samples within WEIGHT_RADIUS, so layer borders blend
## over a few metres instead of stepping from sample to sample.
static func _weights(bands: PackedByteArray, samples: int, gx: int, gz: int) -> Color:
var total: Color = Color(0.0, 0.0, 0.0, 0.0)
var count: int = 0
for z: int in range(maxi(gz - WEIGHT_RADIUS, 0), mini(gz + WEIGHT_RADIUS, samples - 1) + 1):
for x: int in range(maxi(gx - WEIGHT_RADIUS, 0), mini(gx + WEIGHT_RADIUS, samples - 1) + 1):
total += _BAND_WEIGHTS[bands[z * samples + x]]
count += 1
return total / float(count)
static func _edge_height(ground: SimGround, origin: Vector2i, edge: int, position: int) -> float:
var gx: int = origin.x
var gz: int = origin.y
match edge:
0:
gx += position
1:
gx += position
gz += CHUNK_CELLS
2:
gz += position
_:
gx += CHUNK_CELLS
gz += position
return ground.heights[gz * ground.samples + gx]
static func _edge_vertex(edge: int, position: int, per_side: int) -> int:
match edge:
0:
return position
1:
return (per_side - 1) * per_side + position
2:
return position * per_side
_:
return position * per_side + per_side - 1
static func _normal(heights: PackedFloat32Array, samples: int, cell: float, gx: int, gz: int) -> Vector3:
var left: float = heights[gz * samples + maxi(gx - 1, 0)]
var right: float = heights[gz * samples + mini(gx + 1, samples - 1)]
var up: float = heights[maxi(gz - 1, 0) * samples + gx]
var down: float = heights[mini(gz + 1, samples - 1) * samples + gx]
return Vector3(left - right, 2.0 * cell, up - down).normalized()
@@ -0,0 +1 @@
uid://ccwnw5e74lpwj
+176
View File
@@ -0,0 +1,176 @@
## Draws the island's terrain as streamed chunks with distance-based levels of detail.
##
## Each frame it picks the wanted detail level for every chunk from its distance to
## `focus` (normally the camera). Chunks whose level changed are rebuilt by
## TerrainChunkBuilder on WorkerThreadPool threads; the main thread only turns finished
## arrays into meshes, and stops for the frame once it has spent UPLOAD_BUDGET_USEC.
## So streaming never builds geometry on the main thread.
##
## Collision never comes from here. The simulation's SimGround is the one solid shape,
## on the server and in client prediction alike.
class_name TerrainView
extends Node3D
const SHADER: Shader = preload("res://src/client/terrain/terrain.gdshader")
## Distance from the focus to a chunk's nearest point at which each coarser level takes
## over. Index i is where level i + 1 begins.
const LOD_DISTANCES: Array[float] = [90.0, 200.0, 420.0]
## Main-thread time allowed per frame for turning finished builds into meshes.
const UPLOAD_BUDGET_USEC: int = 2_000
## Builds allowed in flight at once, so a fast camera can't queue the whole island.
const MAX_IN_FLIGHT: int = 6
## Where detail is centred, in world space.
var focus: Vector3 = Vector3.ZERO
## Tint chunks by detail level, for captures that check seams.
var show_lod: bool = false
## False only to prove that seams would crack without skirts. Never off in the game.
var skirts: bool = true
## Main-thread microseconds spent in the most recent `_process`, and the most ever.
var last_frame_usec: int = 0
var max_frame_usec: int = 0
var uploads: int = 0
var _island: Island
var _material: ShaderMaterial
var _per_side: int = 0
## Chunk -> MeshInstance3D
var _instances: Dictionary = {}
## Chunk -> level currently shown
var _shown: Dictionary = {}
## Chunk -> level being built
var _building: Dictionary = {}
var _finished: Array[Dictionary] = []
var _mutex: Mutex = Mutex.new()
var _tasks: Array[int] = []
## Prepares the view for `island`. Call before adding to the tree, or right after.
func setup(island: Island) -> void:
_island = island
_per_side = TerrainChunkBuilder.chunks_per_side(island.ground)
_material = ShaderMaterial.new()
_material.shader = SHADER
_material.set_shader_parameter("summit_height", Tuning.ISLAND_SUMMIT_BAND)
_material.set_shader_parameter("max_slope_cos", cos(deg_to_rad(Tuning.MAX_SLOPE_DEGREES)))
## Builds every chunk at its wanted level right now, on the calling thread. For loading
## screens, tests and captures, where a hitch doesn't matter.
func build_all_now() -> void:
for chunk: Vector2i in _all_chunks():
var lod: int = wanted_lod(chunk)
_apply(chunk, lod, TerrainChunkBuilder.build(_island.ground, _island.bands, chunk, lod, skirts))
## The detail level `chunk` should be shown at for the current focus.
func wanted_lod(chunk: Vector2i) -> int:
var rect: Rect2 = TerrainChunkBuilder.chunk_rect(_island.ground, chunk)
var nearest: Vector2 = Vector2(
clampf(focus.x, rect.position.x, rect.end.x), clampf(focus.z, rect.position.y, rect.end.y))
var distance: float = nearest.distance_to(Vector2(focus.x, focus.z))
for index: int in LOD_DISTANCES.size():
if distance < LOD_DISTANCES[index]:
return index
return LOD_DISTANCES.size()
## The level a chunk is shown at, or -1 if it isn't built yet.
func shown_lod(chunk: Vector2i) -> int:
return _shown.get(chunk, -1)
## True when every chunk is shown at its wanted level and nothing is building.
func settled() -> bool:
if not _building.is_empty():
return false
for chunk: Vector2i in _all_chunks():
if shown_lod(chunk) != wanted_lod(chunk):
return false
return true
func _process(_delta: float) -> void:
if _island == null:
return
var started: int = Time.get_ticks_usec()
_upload_finished(started)
_queue_changes()
last_frame_usec = Time.get_ticks_usec() - started
max_frame_usec = maxi(max_frame_usec, last_frame_usec)
func _exit_tree() -> void:
for task: int in _tasks:
WorkerThreadPool.wait_for_task_completion(task)
_tasks.clear()
func _queue_changes() -> void:
# Nearest chunks first, so detail arrives where the player is looking from.
var pending: Array[Vector2i] = []
for chunk: Vector2i in _all_chunks():
if not _building.has(chunk) and shown_lod(chunk) != wanted_lod(chunk):
pending.append(chunk)
var centre: Vector2 = Vector2(focus.x, focus.z)
var ground: SimGround = _island.ground
pending.sort_custom(func(a: Vector2i, b: Vector2i) -> bool:
return TerrainChunkBuilder.chunk_rect(ground, a).get_center().distance_squared_to(centre) \
< TerrainChunkBuilder.chunk_rect(ground, b).get_center().distance_squared_to(centre))
for chunk: Vector2i in pending:
if _building.size() >= MAX_IN_FLIGHT:
break
var lod: int = wanted_lod(chunk)
_building[chunk] = lod
_tasks.append(WorkerThreadPool.add_task(_build_on_worker.bind(chunk, lod)))
func _build_on_worker(chunk: Vector2i, lod: int) -> void:
var arrays: Array = TerrainChunkBuilder.build(_island.ground, _island.bands, chunk, lod, skirts)
_mutex.lock()
_finished.append({"chunk": chunk, "lod": lod, "arrays": arrays})
_mutex.unlock()
func _upload_finished(started: int) -> void:
# Reap completed tasks so the pool doesn't keep their records.
var running: Array[int] = []
for task: int in _tasks:
if WorkerThreadPool.is_task_completed(task):
WorkerThreadPool.wait_for_task_completion(task)
else:
running.append(task)
_tasks = running
while Time.get_ticks_usec() - started < UPLOAD_BUDGET_USEC:
_mutex.lock()
var result: Dictionary = {} if _finished.is_empty() else _finished.pop_front()
_mutex.unlock()
if result.is_empty():
return
var chunk: Vector2i = result["chunk"]
_building.erase(chunk)
_apply(chunk, result["lod"], result["arrays"])
func _apply(chunk: Vector2i, lod: int, arrays: Array) -> void:
var mesh: ArrayMesh = ArrayMesh.new()
mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
mesh.surface_set_material(0, _material)
var instance: MeshInstance3D = _instances.get(chunk)
if instance == null:
instance = MeshInstance3D.new()
instance.name = "Chunk_%d_%d" % [chunk.x, chunk.y]
add_child(instance)
_instances[chunk] = instance
instance.mesh = mesh
instance.set_instance_shader_parameter("lod_tint", float(lod) if show_lod else -1.0)
_shown[chunk] = lod
uploads += 1
func _all_chunks() -> Array[Vector2i]:
var chunks: Array[Vector2i] = []
for z: int in _per_side:
for x: int in _per_side:
chunks.append(Vector2i(x, z))
return chunks
+1
View File
@@ -0,0 +1 @@
uid://dl7o5bhcs733r
+74
View File
@@ -0,0 +1,74 @@
// Tidewall sea: one transparent surface at the simulation's sea level. Colour deepens
// with the water's thickness, read from the depth buffer, so shallows over sand show
// green-grey and open water turns slate blue. A pale band of foam marks the waterline,
// where the tide is about to reach. Small procedural ripples move the normals. No
// textures: every pattern is generated here.
shader_type spatial;
render_mode blend_mix, depth_draw_always, cull_disabled, specular_schlick_ggx;
uniform sampler2D depth_texture : hint_depth_texture, filter_linear;
uniform vec3 shallow_colour : source_color = vec3(0.42, 0.55, 0.50);
uniform vec3 deep_colour : source_color = vec3(0.10, 0.22, 0.30);
uniform vec3 foam_colour : source_color = vec3(0.86, 0.88, 0.84);
// Metres of water over which the colour goes from shallow to deep.
uniform float depth_scale = 7.0;
// Width of the foam at the waterline, in metres of water thickness.
uniform float foam_width = 0.6;
uniform float ripple_strength = 0.25;
varying vec3 world_position;
float hash(vec2 p) {
p = fract(p * vec2(123.34, 456.21));
p += dot(p, p + 45.32);
return fract(p.x * p.y);
}
float value_noise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
vec2 u = f * f * (3.0 - 2.0 * f);
return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), u.x),
mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x), u.y);
}
float waves(vec2 p, float t) {
return value_noise(p * 0.45 + vec2(t * 0.11, t * 0.07)) * 0.6
+ value_noise(p * 1.3 - vec2(t * 0.19, -t * 0.05)) * 0.4;
}
void vertex() {
world_position = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
}
void fragment() {
vec2 p = world_position.xz;
float t = TIME;
// Thickness of water between this surface and whatever is behind it.
float scene_depth = texture(depth_texture, SCREEN_UV).r;
vec4 behind = INV_PROJECTION_MATRIX * vec4(SCREEN_UV * 2.0 - 1.0, scene_depth, 1.0);
behind.xyz /= behind.w;
float thickness = max(-behind.z - (-VERTEX.z), 0.0);
// Convert view distance to roughly vertical metres using the view angle.
float vertical = thickness * clamp(abs(normalize(VERTEX).y) + 0.25, 0.25, 1.0);
float deep = 1.0 - exp(-vertical / depth_scale);
vec3 water = mix(shallow_colour, deep_colour, deep);
float e = 0.35;
float h = waves(p, t);
float hx = waves(p + vec2(e, 0.0), t) - h;
float hz = waves(p + vec2(0.0, e), t) - h;
// Ripples fade with distance, so the far sea doesn't shimmer into noise.
float ripple = ripple_strength * exp(-length(VERTEX) / 140.0);
vec3 n = normalize(vec3(-hx * ripple / e, 1.0, -hz * ripple / e));
NORMAL = normalize((VIEW_MATRIX * vec4(n, 0.0)).xyz);
float foam_edge = 1.0 - smoothstep(0.0, foam_width, vertical + (h - 0.5) * 0.4);
ALBEDO = mix(water, foam_colour, foam_edge * 0.85);
ROUGHNESS = mix(0.12, 0.6, foam_edge);
METALLIC = 0.0;
SPECULAR = 0.5;
ALPHA = clamp(mix(0.55, 0.96, deep) + foam_edge * 0.3, 0.0, 1.0);
}
+1
View File
@@ -0,0 +1 @@
uid://b7qhmjym78vlr
+58
View File
@@ -0,0 +1,58 @@
## Draws the sea: one flat surface at the simulation's sea level, wide enough to reach
## past the horizon from anywhere on the island. `follow(sim)` moves it whenever the
## tide changes the level, so what players see is always the level the server uses.
## The surface is the only thing here; drowning and swimming live in the simulation.
class_name WaterView
extends Node3D
const SHADER: Shader = preload("res://src/client/water/water.gdshader")
## Side of the surface, in metres, centred on the world.
const SIZE: float = 6000.0
## Grid steps across the surface. It is flat, so few are needed.
const SUBDIVISIONS: int = 32
var level: float = 0.0
var _surface: MeshInstance3D
func _ready() -> void:
if _surface == null:
_build()
## Places the surface at `sea_level`. Cheap; safe to call every frame.
func set_level(sea_level: float) -> void:
if _surface == null:
_build()
level = sea_level
_surface.position.y = sea_level
## Matches the surface to the simulation's current sea level.
func follow(sim: Simulation) -> void:
if not is_equal_approx(sim.sea_level, level) or _surface == null:
set_level(sim.sea_level)
func surface() -> MeshInstance3D:
if _surface == null:
_build()
return _surface
func _build() -> void:
var mesh: PlaneMesh = PlaneMesh.new()
mesh.size = Vector2(SIZE, SIZE)
mesh.subdivide_width = SUBDIVISIONS
mesh.subdivide_depth = SUBDIVISIONS
var material: ShaderMaterial = ShaderMaterial.new()
material.shader = SHADER
mesh.material = material
_surface = MeshInstance3D.new()
_surface.name = "Sea"
_surface.mesh = mesh
_surface.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
var centre: float = Tuning.WORLD_SIZE_METRES * 0.5
_surface.position = Vector3(centre, level, centre)
add_child(_surface)
+1
View File
@@ -0,0 +1 @@
uid://fkpqxmr813lf
+1
View File
@@ -43,6 +43,7 @@ func _ready() -> void:
var started: Dictionary = config.to_dictionary()
started["engine"] = Engine.get_version_info()["string"]
started["tick_rate_hz"] = Tuning.TICK_RATE_HZ
started["world_hash"] = loop.sim.island.heightmap_hash()
started["listening"] = false
started["note"] = "networking arrives in v0.5; players join as idle slots until then"
_log("start", started)
+2
View File
@@ -22,6 +22,8 @@ func _init(match_seed: int, human_players: int, bot_count: int) -> void:
var id: int = sim.add_player()
player_ids.append(id)
bots.append(WanderBot.new(id))
# Every match starts on the sky barge.
sim.start_drop()
## Runs one tick and records how long it took.
+113
View File
@@ -0,0 +1,113 @@
## The start of a match: a sky barge drifts across the island on a seeded straight route,
## carrying every player. Each one leaps when they choose, falls, opens a wing-sail
## (by hand, or automatically near the ground) and steers down. Anyone still aboard
## when the barge reaches the end of its route is thrown off.
##
## The route is drawn from the "drop" stream: a heading, and a point near the island's
## middle that the route passes through, so it always crosses land. Movement handles
## falling and gliding; this owns the barge, boarding and leaping.
class_name Drop
extends RefCounted
## Player drop states, in SimEntity.drop_state.
const NONE: int = 0
const ABOARD: int = 1
const FREEFALL: int = 2
const GLIDING: int = 3
## Where the route starts and ends, at barge altitude.
var start: Vector3 = Vector3.ZERO
var finish: Vector3 = Vector3.ZERO
## Ticks the barge takes from start to finish.
var duration_ticks: int = 0
## Simulation tick the drop began on.
var began_tick: int = 0
## True once the barge has reached the end and thrown everyone off.
var finished: bool = false
## Plans the route for `island` from the simulation's "drop" stream.
static func plan(island_ground: SimGround, rng: SimRng, tick: int) -> Drop:
var drop: Drop = Drop.new()
var stream: RandomNumberGenerator = rng.stream("drop")
var size: float = Tuning.WORLD_SIZE_METRES
var centre: Vector2 = Vector2(size, size) * 0.5
var heading: float = stream.randf() * TAU
var jitter_angle: float = stream.randf() * TAU
var jitter: float = sqrt(stream.randf()) * Tuning.BARGE_CENTRE_JITTER
var through: Vector2 = centre + Vector2(cos(jitter_angle), sin(jitter_angle)) * jitter
# Pull the crossing point onto land if the jitter put it over water.
var tries: int = 0
while island_ground.terrain_height(through.x, through.y) <= Tuning.ISLAND_BEACH_TOP and tries < 16:
through = through.lerp(centre, 0.5)
tries += 1
var direction: Vector2 = Vector2(cos(heading), sin(heading))
var margin: float = Tuning.BARGE_ROUTE_MARGIN
var back: float = _distance_to_edge(through, -direction, margin, size)
var ahead: float = _distance_to_edge(through, direction, margin, size)
var a: Vector2 = through - direction * back
var b: Vector2 = through + direction * ahead
drop.start = Vector3(a.x, Tuning.BARGE_ALTITUDE, a.y)
drop.finish = Vector3(b.x, Tuning.BARGE_ALTITUDE, b.y)
drop.duration_ticks = maxi(ceili(a.distance_to(b) / Tuning.BARGE_SPEED * Tuning.TICK_RATE_HZ), 1)
drop.began_tick = tick
return drop
## How far along the route the barge is at `tick`, from 0 to 1.
func progress(tick: int) -> float:
return clampf(float(tick - began_tick) / duration_ticks, 0.0, 1.0)
func barge_position(tick: int) -> Vector3:
return start.lerp(finish, progress(tick))
func barge_velocity() -> Vector3:
return (finish - start) / (float(duration_ticks) / Tuning.TICK_RATE_HZ)
## True once the barge is at the end of its route.
func is_over(tick: int) -> bool:
return tick - began_tick >= duration_ticks
## Points along the route every `step` metres, at ground level, for tests and maps.
func route_samples(step: float) -> PackedVector2Array:
var points: PackedVector2Array = PackedVector2Array()
var a: Vector2 = Vector2(start.x, start.z)
var b: Vector2 = Vector2(finish.x, finish.z)
var count: int = maxi(ceili(a.distance_to(b) / step), 1)
for index: int in count + 1:
points.append(a.lerp(b, float(index) / count))
return points
## Puts a player aboard: carried with the barge, not moving on their own.
static func board(player: SimEntity, at: Vector3) -> void:
player.drop_state = ABOARD
player.position = at
player.velocity = Vector3.ZERO
player.on_ground = false
player.swimming = false
## Throws a player off the barge into freefall, keeping some of the barge's speed.
func leap(player: SimEntity, tick: int) -> void:
player.drop_state = FREEFALL
player.position = barge_position(tick)
var carried: Vector3 = barge_velocity() * Tuning.LEAP_CARRY
player.velocity = Vector3(carried.x, 0.0, carried.z)
player.on_ground = false
## Distance from `from` along unit `direction` to the square [margin, size - margin].
static func _distance_to_edge(from: Vector2, direction: Vector2, margin: float, size: float) -> float:
var best: float = INF
for axis: int in 2:
var d: float = direction[axis]
if absf(d) < 0.000001:
continue
var edge: float = (size - margin) if d > 0.0 else margin
best = minf(best, (edge - from[axis]) / d)
return maxf(best, 0.0)
+1
View File
@@ -0,0 +1 @@
uid://1jnfkm281f0h
+250
View File
@@ -0,0 +1,250 @@
## The procedural island. One seed gives one island, on the server and on every client,
## so terrain is never sent over the network: both ends call `Island.generate(seed)`.
##
## The island is built in layers, each a pure function of the seed:
## 1. a warped coastline around the world centre, falling to the sea floor outside it;
## 2. a raised interior plateau that keeps land joined through the early tide;
## 3. two to four summits, joined by ridges, which become the last dry ground;
## 4. rolling detail, rocky highland detail, and flattened marsh in wet lowland.
## Then the land is scaled so the tallest summit lands in the tuned peak range.
##
## All randomness comes from the match seed's "worldgen" stream. FastNoiseLite is a
## seeded, pure function in the engine core with no rendering dependency.
class_name Island
extends RefCounted
enum Band { SEA, BEACH, MARSH, FOREST, HIGHLAND, SUMMIT }
## Height of the coastal shelf the land rises to, before detail and summits, in metres.
const PLATEAU_HEIGHT: float = 11.0
## Extra height of a broad dome over the interior, so each tide phase takes a ring of
## land rather than the whole plateau at once.
const DOME_HEIGHT: float = 16.0
## Fraction of the radius, measured inward from the coast, over which land rises to the plateau.
const COAST_RISE: float = 0.32
## How far the coastline is pushed in or out, as a fraction of the radius.
const COAST_WARP: float = 0.22
const DETAIL_METRES: float = 6.5
const ROCK_METRES: float = 7.0
const RIDGE_FRACTION: float = 0.55
const MARSH_LEVEL: float = 3.6
## Moisture above this turns wet lowland into marsh.
const MARSH_MOISTURE: float = 0.05
var match_seed: int = 0
var ground: SimGround
## Elevation band per heightfield sample, same layout as `ground.heights`.
var bands: PackedByteArray = PackedByteArray()
## The summit centres the generator placed, as (x, height, z), tallest first.
var summits: Array[Vector3] = []
## Wall-clock generation time is measured by callers; the island never reads a clock.
## Builds the island for `seed_value`.
static func generate(seed_value: int) -> Island:
var island: Island = Island.new()
island.match_seed = seed_value
island._build()
return island
## SHA-256 hex digest of the heightfield, heights rounded to millimetres. Two machines
## that agree on this agree on every walkable surface.
func heightmap_hash() -> String:
var buffer: StreamPeerBuffer = StreamPeerBuffer.new()
buffer.big_endian = false
buffer.put_32(ground.samples)
buffer.put_32(roundi(ground.cell * 1000.0))
for value: float in ground.heights:
buffer.put_32(roundi(value * 1000.0))
buffer.put_data(bands)
var hasher: HashingContext = HashingContext.new()
hasher.start(HashingContext.HASH_SHA256)
hasher.update(buffer.data_array)
return hasher.finish().hex_encode()
## The elevation band at world position (x, z), from the nearest sample.
func band_at(x: float, z: float) -> Band:
var limit: int = ground.samples - 1
var gx: int = clampi(roundi(x / ground.cell), 0, limit)
var gz: int = clampi(roundi(z / ground.cell), 0, limit)
return bands[gz * ground.samples + gx] as Band
## The highest terrain sample, in metres.
func max_height() -> float:
var best: float = -INF
for value: float in ground.heights:
best = maxf(best, value)
return best
func _build() -> void:
var rng: RandomNumberGenerator = SimRng.new(match_seed).stream("worldgen")
var size: float = Tuning.WORLD_SIZE_METRES
var cell: float = Tuning.ISLAND_GRID_METRES
var side: int = roundi(size / cell) + 1
var centre: Vector2 = Vector2(size, size) * 0.5
var radius: float = Tuning.ISLAND_RADIUS_METRES
var coast: FastNoiseLite = _noise(rng.randi(), 1.0 / 260.0, 3)
var detail: FastNoiseLite = _noise(rng.randi(), 1.0 / 170.0, 4)
var rock: FastNoiseLite = _noise(rng.randi(), 1.0 / 60.0, 3)
rock.fractal_type = FastNoiseLite.FRACTAL_RIDGED
var moisture: FastNoiseLite = _noise(rng.randi(), 1.0 / 200.0, 2)
var peaks: Array[Dictionary] = _place_summits(rng, centre, radius)
var ridges: Array[Dictionary] = _link_summits(peaks)
var heights: PackedFloat32Array = PackedFloat32Array()
heights.resize(side * side)
var wet: PackedFloat32Array = PackedFloat32Array()
wet.resize(side * side)
for gz: int in side:
var z: float = gz * cell
for gx: int in side:
var x: float = gx * cell
var index: int = gz * side + gx
var offset: Vector2 = Vector2(x, z) - centre
# Inland is 0 at the coast, 1 at the centre, negative out to sea.
var inland: float = 1.0 - offset.length() / radius + COAST_WARP * coast.get_noise_2d(x, z)
if inland <= 0.0:
heights[index] = -Tuning.ISLAND_SEA_DEPTH * clampf(-inland / 0.12, 0.0, 1.0) - 0.4
continue
var rise: float = _smooth(0.0, COAST_RISE, inland)
var height: float = PLATEAU_HEIGHT * rise + DOME_HEIGHT * _smooth(0.15, 1.1, inland) + 0.6
var raise: float = 0.0
for peak: Dictionary in peaks:
var reach: float = Vector2(x, z).distance_squared_to(peak["at"]) / pow(peak["radius"], 2.0)
raise = maxf(raise, peak["height"] * exp(-1.6 * reach))
for ridge: Dictionary in ridges:
var gap: float = _distance_to_segment(Vector2(x, z), ridge["from"], ridge["to"])
raise = maxf(raise, ridge["height"] * exp(-pow(gap / ridge["width"], 2.0)))
var inner: float = _smooth(0.08, 0.45, inland)
height += raise * inner
height += DETAIL_METRES * detail.get_noise_2d(x, z) * rise
# Rock grows with altitude, so highlands are craggy and lowlands rolling.
var altitude: float = clampf((height - PLATEAU_HEIGHT - DOME_HEIGHT) / 28.0, 0.0, 1.0)
height += ROCK_METRES * (rock.get_noise_2d(x, z) + 0.3) * altitude
heights[index] = height
wet[index] = moisture.get_noise_2d(x, z)
_scale_to_peak(heights, rng)
var band_data: PackedByteArray = PackedByteArray()
band_data.resize(side * side)
for index: int in heights.size():
var height: float = heights[index]
if height > 0.0 and height < Tuning.ISLAND_MARSH_TOP + 1.5 and wet[index] > MARSH_MOISTURE:
# Flatten wet lowland towards a marsh level just above the beach.
var weight: float = _smooth(MARSH_MOISTURE, MARSH_MOISTURE + 0.25, wet[index])
weight *= 1.0 - _smooth(Tuning.ISLAND_MARSH_TOP - 1.0, Tuning.ISLAND_MARSH_TOP + 1.5, height)
height = lerpf(height, maxf(MARSH_LEVEL, Tuning.ISLAND_BEACH_TOP + 0.3), weight)
heights[index] = height
band_data[index] = _classify(height, wet[index])
ground = SimGround.from_heights(heights, side, cell)
bands = band_data
for peak: Dictionary in peaks:
var at: Vector2 = peak["at"]
summits.append(Vector3(at.x, ground.terrain_height(at.x, at.y), at.y))
summits.sort_custom(func(a: Vector3, b: Vector3) -> bool: return a.y > b.y)
func _noise(noise_seed: int, frequency: float, octaves: int) -> FastNoiseLite:
var noise: FastNoiseLite = FastNoiseLite.new()
noise.noise_type = FastNoiseLite.TYPE_SIMPLEX_SMOOTH
noise.seed = noise_seed & 0x7FFFFFFF
noise.frequency = frequency
noise.fractal_type = FastNoiseLite.FRACTAL_FBM
noise.fractal_octaves = octaves
return noise
## Picks summit centres well inside the coast and far enough apart. The first is the
## tallest. Heights here are before scaling to the peak range.
func _place_summits(rng: RandomNumberGenerator, centre: Vector2, radius: float) -> Array[Dictionary]:
var count: int = rng.randi_range(Tuning.ISLAND_MIN_SUMMITS, Tuning.ISLAND_MAX_SUMMITS)
var peaks: Array[Dictionary] = []
var spacing: float = Tuning.ISLAND_SUMMIT_SPACING_METRES
var attempts: int = 0
while peaks.size() < count and attempts < 400:
attempts += 1
# Relax the spacing slowly if the island can't fit them all.
var needed: float = spacing * (1.0 - 0.3 * attempts / 400.0)
var angle: float = rng.randf() * TAU
var distance: float = radius * rng.randf_range(0.12, 0.55)
var at: Vector2 = centre + Vector2(cos(angle), sin(angle)) * distance
var clear: bool = true
for peak: Dictionary in peaks:
if at.distance_to(peak["at"]) < needed:
clear = false
break
if not clear:
continue
var height: float = 46.0 if peaks.is_empty() else rng.randf_range(30.0, 42.0)
peaks.append({"at": at, "height": height, "radius": rng.randf_range(95.0, 145.0)})
return peaks
## Joins each summit to its nearest neighbour with a lower ridge, giving highland spines.
func _link_summits(peaks: Array[Dictionary]) -> Array[Dictionary]:
var ridges: Array[Dictionary] = []
var linked: Dictionary = {}
for index: int in peaks.size():
var nearest: int = -1
var best: float = INF
for other: int in peaks.size():
var gap: float = (peaks[index]["at"] as Vector2).distance_to(peaks[other]["at"])
if other != index and gap < best:
best = gap
nearest = other
if nearest < 0:
continue
var key: Vector2i = Vector2i(mini(index, nearest), maxi(index, nearest))
if linked.has(key):
continue
linked[key] = true
var low: float = minf(peaks[index]["height"], peaks[nearest]["height"])
ridges.append({
"from": peaks[index]["at"], "to": peaks[nearest]["at"],
"height": low * RIDGE_FRACTION, "width": 50.0,
})
return ridges
## Scales land heights so the tallest point lands in the tuned peak range. The sea
## floor is left alone, so the coastline doesn't move.
func _scale_to_peak(heights: PackedFloat32Array, rng: RandomNumberGenerator) -> void:
var highest: float = 0.0
for value: float in heights:
highest = maxf(highest, value)
var target: float = rng.randf_range(Tuning.ISLAND_PEAK_MIN, Tuning.ISLAND_PEAK_MAX)
var factor: float = target / highest
for index: int in heights.size():
if heights[index] > 0.0:
heights[index] *= factor
func _classify(height: float, wetness: float) -> int:
if height <= 0.0:
return Band.SEA
if height < Tuning.ISLAND_BEACH_TOP:
return Band.BEACH
if height < Tuning.ISLAND_MARSH_TOP and wetness > MARSH_MOISTURE:
return Band.MARSH
if height < Tuning.ISLAND_FOREST_TOP:
return Band.FOREST
if height < Tuning.ISLAND_SUMMIT_BAND:
return Band.HIGHLAND
return Band.SUMMIT
static func _smooth(from: float, to: float, value: float) -> float:
return smoothstep(from, to, value)
static func _distance_to_segment(point: Vector2, from: Vector2, to: Vector2) -> float:
var span: Vector2 = to - from
var t: float = clampf((point - from).dot(span) / maxf(span.length_squared(), 0.0001), 0.0, 1.0)
return point.distance_to(from + span * t)
+1
View File
@@ -0,0 +1 @@
uid://kdm40yq5wyhl
+311
View File
@@ -0,0 +1,311 @@
## Command-driven player movement: walk, sprint, crouch, jump, gravity, slopes,
## step-up, sliding, fall damage, wading and swimming. Deterministic: it depends only on
## the entity, the command, the ground and the sea level.
class_name Movement
extends RefCounted
const DT: float = 1.0 / Tuning.TICK_RATE_HZ
## Advances one player by one tick. `command` may be null, meaning no input this tick:
## the player keeps looking the same way and stops trying to move, but still falls.
## `sea_level` is the water surface; the default means no water at all. Breath, stamina
## and drowning are Water's job, after this.
static func step(player: SimEntity, command: PlayerCommand, ground: SimGround, sea_level: float = -INF) -> void:
var wish: Vector3 = Vector3.ZERO
var wants_jump: bool = false
player.crouching = false
if command != null:
player.yaw = command.yaw
player.pitch = command.pitch
player.crouching = command.is_pressed(PlayerCommand.BUTTON_CROUCH)
wants_jump = command.is_pressed(PlayerCommand.BUTTON_JUMP) and not player.crouching
wish = _wish_velocity(command, player.crouching)
if player.drop_state == Drop.ABOARD:
# Riders move with the barge; Simulation places them.
return
if player.drop_state != Drop.NONE:
_fall_from_barge(player, command, ground, sea_level)
return
if player.swimming:
if wants_jump and player.stamina_ticks > 0 and _at_surface(player, sea_level):
# Kick up out of the water. Airborne from here; back in if it lands in deep water.
player.swimming = false
player.on_ground = false
player.velocity.y = Tuning.JUMP_VELOCITY
else:
_swim(player, command, ground, sea_level)
return
# Wading: water over the feet slows walkers and stops sprinting.
if player.on_ground and sea_level - player.position.y > Tuning.WADE_DEPTH:
wish = wish.limit_length(Tuning.WADE_SPEED)
var velocity: Vector3 = player.velocity
if player.on_ground:
velocity.x = wish.x
velocity.z = wish.z
velocity.y = 0.0
if wants_jump:
velocity.y = Tuning.JUMP_VELOCITY
player.on_ground = false
else:
velocity.x += (wish.x - velocity.x) * Tuning.AIR_CONTROL
velocity.z += (wish.z - velocity.z) * Tuning.AIR_CONTROL
velocity = _move_horizontally(player, velocity, ground)
_move_vertically(player, velocity, ground, sea_level)
# Walked, or the tide rose, into water deep enough to swim.
if not player.swimming and player.on_ground and Water.is_deep(sea_level, player.position.y):
_enter_water(player)
## Height of the player's body, which shrinks while crouching.
static func body_height(player: SimEntity) -> float:
return Tuning.CROUCH_HEIGHT if player.crouching else Tuning.PLAYER_HEIGHT
static func _wish_velocity(command: PlayerCommand, crouching: bool) -> Vector3:
var move: Vector2 = command.move_vector()
if move.length() > 1.0:
move = move.normalized()
var angle: float = command.yaw_radians()
var forward: Vector3 = Vector3(sin(angle), 0.0, cos(angle))
# Right is forward x up in Godot's right-handed, y-up frame.
var right: Vector3 = Vector3(-cos(angle), 0.0, sin(angle))
var speed: float = Tuning.WALK_SPEED
if crouching:
speed = Tuning.CROUCH_SPEED
elif command.is_pressed(PlayerCommand.BUTTON_SPRINT) and move.y > 0.0:
speed = Tuning.SPRINT_SPEED
return (right * move.x + forward * move.y) * speed
## Moves along x and z, sliding along whatever blocks the way. Returns the velocity with
## blocked components removed.
static func _move_horizontally(player: SimEntity, velocity: Vector3, ground: SimGround) -> Vector3:
var delta: Vector3 = Vector3(velocity.x, 0.0, velocity.z) * DT
if delta.is_zero_approx():
return velocity
var result: Vector3 = velocity
if _can_move_to(player, player.position + delta, ground):
player.position += delta
elif _can_move_to(player, player.position + Vector3(delta.x, 0.0, 0.0), ground):
player.position.x += delta.x
result.z = 0.0
elif _can_move_to(player, player.position + Vector3(0.0, 0.0, delta.z), ground):
player.position.z += delta.z
result.x = 0.0
else:
result.x = 0.0
result.z = 0.0
var size: float = Tuning.WORLD_SIZE_METRES
player.position.x = clampf(player.position.x, 0.0, size)
player.position.z = clampf(player.position.z, 0.0, size)
return result
static func _can_move_to(player: SimEntity, target: Vector3, ground: SimGround) -> bool:
var supported: bool = player.on_ground or player.swimming
var step: float = Tuning.STEP_HEIGHT if supported else 0.0
# On foot, the body is tested where it will stand: on whatever it steps up onto at
# the target. Otherwise the next riser of a stair narrower than the body would block
# a player who hasn't been lifted onto the current one yet.
var body: Vector3 = target
if supported:
body.y = maxf(target.y, ground.support_height(target.x, target.z, target.y + step))
if ground.body_blocked(body, Tuning.PLAYER_RADIUS, body_height(player), step):
return false
# Moving uphill into terrain that's too steep is blocked, on foot or in the air, so
# nobody can climb a cliff by pushing into it. Downhill is always allowed.
var rise: float = ground.terrain_height(target.x, target.z) - player.position.y
if rise > 0.0 and not ground.walkable_terrain(target.x, target.z):
if not ground.support_is_solid(target.x, target.z, player.position.y + step):
return false
return true
static func _move_vertically(player: SimEntity, velocity: Vector3, ground: SimGround, sea_level: float) -> void:
var feet: Vector3 = player.position
if player.on_ground:
var reach: float = feet.y + Tuning.STEP_HEIGHT
var support: float = ground.support_height(feet.x, feet.z, reach)
if support >= feet.y - Tuning.GROUND_SNAP:
player.position.y = support
player.velocity = Vector3(velocity.x, 0.0, velocity.z)
if not _walkable_support(ground, player.position):
player.on_ground = false
return
# Walked off a ledge: start falling from here.
player.on_ground = false
# Airborne. Exact integration under constant gravity.
var new_y: float = feet.y + velocity.y * DT - 0.5 * Tuning.GRAVITY * DT * DT
velocity.y -= Tuning.GRAVITY * DT
var head_room: Vector3 = Vector3(feet.x, new_y, feet.z)
if velocity.y > 0.0 and ground.body_blocked(head_room, Tuning.PLAYER_RADIUS, body_height(player), 0.0):
# Bumped a ceiling.
new_y = feet.y
velocity.y = 0.0
player.position.y = new_y
var support: float = ground.support_height(feet.x, feet.z, maxf(feet.y, new_y))
# Falling into deep water: the water catches the player, with no fall damage.
if velocity.y <= 0.0 and Water.is_deep(sea_level, support) and new_y <= sea_level - Tuning.SWIM_DEPTH:
player.position.y = maxf(new_y, support)
player.velocity = velocity
_enter_water(player)
return
if new_y > support:
player.velocity = velocity
return
player.position.y = support
if _walkable_support(ground, player.position):
_land(player, -velocity.y)
velocity.y = 0.0
player.on_ground = true
else:
# Too steep to stand on: keep only the motion along the slope.
var normal: Vector3 = ground.terrain_normal(feet.x, feet.z)
var into: float = velocity.dot(normal)
if into < 0.0:
velocity -= normal * into
velocity = velocity.limit_length(Tuning.SLIDE_MAX_SPEED)
player.velocity = velocity
static func _walkable_support(ground: SimGround, feet: Vector3) -> bool:
if ground.support_is_solid(feet.x, feet.z, feet.y + 0.001):
return true
return ground.walkable_terrain(feet.x, feet.z)
## Applies fall damage for landing at `impact_speed` metres per second, downward.
static func _land(player: SimEntity, impact_speed: float) -> void:
if impact_speed <= 0.0:
return
var drop: float = impact_speed * impact_speed / (2.0 * Tuning.GRAVITY)
var excess: float = drop - Tuning.FALL_DAMAGE_SAFE_METRES
if excess > 0.0:
player.health = maxi(player.health - roundi(excess * Tuning.FALL_DAMAGE_PER_METRE), 0)
static func _enter_water(player: SimEntity) -> void:
player.swimming = true
player.on_ground = false
player.velocity.y *= Tuning.WATER_ENTRY_DAMP
## True when a swimmer is up at the surface, head out, and so can kick out of the water.
static func _at_surface(player: SimEntity, sea_level: float) -> bool:
return player.position.y >= sea_level - Tuning.SWIM_FLOAT_DEPTH - 0.2
## One tick in deep water. Swimmers move at SWIM_SPEED (faster sprinting while stamina
## lasts), float with the head out, dive while crouch is held, and rest on the sea floor
## rather than sinking through it. Out of stamina, they slip under. Where the water
## over the floor gets shallow they stand up and walk.
static func _swim(player: SimEntity, command: PlayerCommand, ground: SimGround, sea_level: float) -> void:
var has_stamina: bool = player.stamina_ticks > 0
var speed: float = Tuning.SWIM_SPEED
var diving: bool = false
var move: Vector3 = Vector3.ZERO
if command != null:
var input: Vector2 = command.move_vector()
if input.length() > 1.0:
input = input.normalized()
var angle: float = command.yaw_radians()
var forward: Vector3 = Vector3(sin(angle), 0.0, cos(angle))
var right: Vector3 = Vector3(-cos(angle), 0.0, sin(angle))
move = right * input.x + forward * input.y
diving = command.is_pressed(PlayerCommand.BUTTON_CROUCH)
if command.is_pressed(PlayerCommand.BUTTON_SPRINT) and has_stamina and input.y > 0.0:
speed = Tuning.SWIM_SPRINT_SPEED
if not has_stamina:
speed *= Tuning.SWIM_EXHAUSTED_FACTOR
var velocity: Vector3 = move * speed
var float_depth: float = Tuning.SWIM_FLOAT_DEPTH if has_stamina else Tuning.SWIM_EXHAUSTED_DEPTH
var wanted: float = -Tuning.SWIM_VERTICAL_SPEED
if not diving:
wanted = clampf((sea_level - float_depth - player.position.y) * 4.0, -Tuning.SWIM_VERTICAL_SPEED, Tuning.SWIM_VERTICAL_SPEED)
velocity.y = move_toward(player.velocity.y, wanted, Tuning.SWIM_VERTICAL_ACCEL * DT)
velocity = _move_horizontally(player, velocity, ground)
var new_y: float = player.position.y + velocity.y * DT
var floor_y: float = ground.support_height(player.position.x, player.position.z, maxf(player.position.y, new_y) + Tuning.STEP_HEIGHT)
if new_y <= floor_y:
new_y = floor_y
velocity.y = maxf(velocity.y, 0.0)
if velocity.y > 0.0 and ground.body_blocked(Vector3(player.position.x, new_y, player.position.z), Tuning.PLAYER_RADIUS, body_height(player), 0.0):
new_y = player.position.y
velocity.y = 0.0
player.position.y = new_y
player.velocity = velocity
# Shallow enough to stand: back on foot, without fall damage.
if sea_level - floor_y < Tuning.SWIM_EXIT_DEPTH:
player.swimming = false
if floor_y >= player.position.y - Tuning.GROUND_SNAP:
player.position.y = floor_y
player.velocity.y = 0.0
player.on_ground = _walkable_support(ground, player.position)
else:
player.on_ground = false
## One tick of the drop after leaping: freefall, then the wing-sail. Players steer with
## the move keys relative to where they look; jump opens the sail, and it opens by itself
## WING_AUTO_DEPLOY_HEIGHT above the ground or water. Near the bottom the sail folds and
## ordinary falling (or the water) takes over, slow enough to do no damage.
static func _fall_from_barge(player: SimEntity, command: PlayerCommand, ground: SimGround, sea_level: float) -> void:
var below: float = _drop_floor(player, ground, sea_level, player.position.y)
if player.drop_state == Drop.FREEFALL:
var opens: bool = command != null and command.is_pressed(PlayerCommand.BUTTON_JUMP)
if opens or player.position.y - below <= Tuning.WING_AUTO_DEPLOY_HEIGHT:
player.drop_state = Drop.GLIDING
var gliding: bool = player.drop_state == Drop.GLIDING
var wish: Vector3 = Vector3.ZERO
if command != null:
var input: Vector2 = command.move_vector()
if input.length() > 1.0:
input = input.normalized()
var angle: float = command.yaw_radians()
var forward: Vector3 = Vector3(sin(angle), 0.0, cos(angle))
var right: Vector3 = Vector3(-cos(angle), 0.0, sin(angle))
wish = (right * input.x + forward * input.y) * (Tuning.GLIDE_SPEED if gliding else Tuning.FREEFALL_STEER_SPEED)
var velocity: Vector3 = player.velocity
var flat: Vector3 = Vector3(velocity.x, 0.0, velocity.z).move_toward(wish, Tuning.DROP_STEER_ACCEL * DT)
velocity.x = flat.x
velocity.z = flat.z
if gliding:
velocity.y = move_toward(velocity.y, -Tuning.GLIDE_FALL_SPEED, Tuning.GLIDE_BRAKE * DT)
else:
velocity.y = maxf(velocity.y - Tuning.GRAVITY * DT, -Tuning.FREEFALL_MAX_SPEED)
velocity = _move_horizontally(player, velocity, ground)
var new_y: float = player.position.y + velocity.y * DT
var support: float = ground.support_height(player.position.x, player.position.z, maxf(player.position.y, new_y))
below = maxf(support, sea_level if Water.is_deep(sea_level, support) else support)
player.velocity = velocity
if new_y <= support:
# Came down on something in a single tick: set down gently.
player.position.y = support
player.velocity.y = 0.0
player.drop_state = Drop.NONE
player.on_ground = _walkable_support(ground, player.position)
return
player.position.y = new_y
if new_y - below <= Tuning.DROP_LAND_HANDOFF:
player.drop_state = Drop.NONE
player.on_ground = false
player.velocity.y = maxf(velocity.y, -Tuning.GLIDE_FALL_SPEED)
## The ground or deep water under a falling player.
static func _drop_floor(player: SimEntity, ground: SimGround, sea_level: float, from_y: float) -> float:
var support: float = ground.support_height(player.position.x, player.position.z, from_y)
return maxf(support, sea_level) if Water.is_deep(sea_level, support) else support
+1
View File
@@ -0,0 +1 @@
uid://b4wtn2is3k3td
+174
View File
@@ -0,0 +1,174 @@
## One placed point of interest: its solid parts, how each part looks, where loot can
## spawn, and walking routes that reach its interiors.
##
## Parts are built in a local frame (x right, z forward out of the front door, y up from
## `floor_y` at the origin) and turned in quarter turns, so every solid stays an
## axis-aligned box that SimGround can collide with.
class_name Poi
extends RefCounted
## Part looks, for the renderer. The simulation only cares about the boxes.
const LOOK_TARRED_WOOD: String = "tarred_wood"
const LOOK_PLANK: String = "plank"
const LOOK_STONE: String = "stone"
const LOOK_ROOF: String = "roof"
const LOOK_PAINT: String = "paint"
const LOOK_SALT: String = "salt"
const LOOK_LAMP: String = "lamp"
const WALL: float = 0.3
const DOOR_WIDTH: float = 1.4
const DOOR_HEIGHT: float = 2.2
const STEP_RISE: float = 0.35
const STEP_DEPTH: float = 0.6
var kind: String = ""
## World-space origin of the local frame, and its facing in quarter turns.
var origin: Vector3 = Vector3.ZERO
var facing: int = 0
## Every solid box, in world space.
var solids: Array[AABB] = []
## Render parts: {"box": AABB, "look": String}, in world space.
var parts: Array[Dictionary] = []
## Loot spawn markers, in world space, standing on a floor.
var loot: Array[Vector3] = []
## Walking routes, each a list of world points from open ground outside to somewhere
## inside. The traversal test walks every one.
var routes: Array[Array] = []
var _ground: SimGround
func _init(poi_kind: String, at: Vector3, quarter_turns: int, ground: SimGround) -> void:
kind = poi_kind
origin = at
facing = posmod(quarter_turns, 4)
_ground = ground
## Turns a local point into world space.
func to_world(local: Vector3) -> Vector3:
var x: float = local.x
var z: float = local.z
match facing:
1:
var turned: float = x
x = z
z = -turned
2:
x = -x
z = -z
3:
var turned: float = x
x = -z
z = turned
return origin + Vector3(x, local.y, z)
## Adds a box given by its local minimum corner and size.
func box(local_min: Vector3, size: Vector3, look: String, solid: bool = true) -> AABB:
var a: Vector3 = to_world(local_min)
var b: Vector3 = to_world(local_min + size)
var world: AABB = AABB(a, b - a).abs()
parts.append({"box": world, "look": look})
if solid:
solids.append(world)
return world
## Lowest and highest terrain under a local rectangle, sampled every metre.
func terrain_range(local_min: Vector2, local_size: Vector2) -> Vector2:
var low: float = INF
var high: float = -INF
var steps_x: int = maxi(ceili(local_size.x), 1)
var steps_z: int = maxi(ceili(local_size.y), 1)
for iz: int in steps_z + 1:
for ix: int in steps_x + 1:
var local: Vector3 = Vector3(local_min.x + local_size.x * ix / steps_x, 0.0, local_min.y + local_size.y * iz / steps_z)
var world: Vector3 = to_world(local)
var height: float = _ground.terrain_height(world.x, world.z)
low = minf(low, height)
high = maxf(high, height)
return Vector2(low, high)
## Terrain height under a local point.
func ground_at(local: Vector3) -> float:
var world: Vector3 = to_world(local)
return _ground.terrain_height(world.x, world.z)
## A plinth whose top is `top` (local height), filling down into the ground under it.
func plinth(local_min: Vector2, local_size: Vector2, top: float, look: String) -> void:
var under: Vector2 = terrain_range(local_min, local_size)
var bottom: float = minf(under.x - origin.y - 0.6, top - 0.3)
box(Vector3(local_min.x, bottom, local_min.y), Vector3(local_size.x, top - bottom, local_size.y), look)
## Steps leading down from a platform edge at local `from` (its height is the platform
## top), heading along local `direction` (a unit axis), `width` wide, until they meet the
## ground. Returns the local point on open ground at the foot of the steps.
func steps_down(from: Vector3, direction: Vector3, width: float, look: String) -> Vector3:
var top: float = from.y
var at: Vector3 = from
var side: Vector3 = Vector3(direction.z, 0.0, -direction.x).abs() * width
var guard: int = 0
while top - (ground_at(at + direction * STEP_DEPTH) - origin.y) > STEP_RISE * 1.1 and guard < 40:
guard += 1
top -= STEP_RISE
var corner_a: Vector3 = at - side * 0.5
var corner_b: Vector3 = at + direction * STEP_DEPTH + side * 0.5
var low: Vector3 = Vector3(minf(corner_a.x, corner_b.x), 0.0, minf(corner_a.z, corner_b.z))
var size: Vector3 = Vector3(absf(corner_b.x - corner_a.x), 0.0, absf(corner_b.z - corner_a.z))
var ground_low: float = minf(ground_at(at), ground_at(at + direction * STEP_DEPTH)) - origin.y - 0.5
box(Vector3(low.x, ground_low, low.z), Vector3(size.x, top - ground_low, size.z), look)
at += direction * STEP_DEPTH
var foot: Vector3 = at + direction * 1.2
foot.y = ground_at(foot) - origin.y
return foot
## A hut: four walls with a door in the front (+z) wall, a floor on a plinth, a roof,
## steps down from the door, one loot marker inside, and a route from outside to it.
## `centre` is local; the floor height is chosen from the ground under the footprint.
func hut(centre: Vector3, width: float, depth: float, height: float, wall_look: String, roof_look: String) -> void:
var min_corner: Vector2 = Vector2(centre.x - width * 0.5, centre.z - depth * 0.5)
var under: Vector2 = terrain_range(min_corner, Vector2(width, depth))
var floor_y: float = under.y - origin.y + 0.15
plinth(min_corner, Vector2(width, depth), floor_y, LOOK_STONE)
var x0: float = min_corner.x
var z0: float = min_corner.y
var top: float = floor_y + height
# Back, left and right walls.
box(Vector3(x0, floor_y, z0), Vector3(width, height, WALL), wall_look)
box(Vector3(x0, floor_y, z0), Vector3(WALL, height, depth), wall_look)
box(Vector3(x0 + width - WALL, floor_y, z0), Vector3(WALL, height, depth), wall_look)
# Front wall, either side of the door, and the lintel over it.
var front_z: float = z0 + depth - WALL
var side_width: float = (width - DOOR_WIDTH) * 0.5
box(Vector3(x0, floor_y, front_z), Vector3(side_width, height, WALL), wall_look)
box(Vector3(x0 + side_width + DOOR_WIDTH, floor_y, front_z), Vector3(side_width, height, WALL), wall_look)
box(Vector3(x0 + side_width, floor_y + DOOR_HEIGHT, front_z), Vector3(DOOR_WIDTH, height - DOOR_HEIGHT, WALL), wall_look)
# Roof with an overhang, and a painted door frame for the folk-art look.
box(Vector3(x0 - 0.4, top, z0 - 0.4), Vector3(width + 0.8, 0.3, depth + 0.8), roof_look)
box(Vector3(x0 + side_width - 0.12, floor_y, z0 + depth), Vector3(0.12, DOOR_HEIGHT, 0.06), LOOK_PAINT, false)
box(Vector3(x0 + side_width + DOOR_WIDTH, floor_y, z0 + depth), Vector3(0.12, DOOR_HEIGHT, 0.06), LOOK_PAINT, false)
var door: Vector3 = Vector3(centre.x, floor_y, z0 + depth)
var foot: Vector3 = steps_down(door, Vector3(0.0, 0.0, 1.0), DOOR_WIDTH + 0.4, LOOK_STONE)
var inside: Vector3 = Vector3(centre.x, floor_y, z0 + depth - 1.2)
var marker: Vector3 = Vector3(centre.x, floor_y, z0 + 1.2)
add_loot(marker)
add_route([foot + Vector3(0.0, 0.0, 1.5), foot, door, inside, marker])
func add_loot(local: Vector3) -> void:
loot.append(to_world(local))
## A route through local points, stored in world space.
func add_route(points: Array[Vector3]) -> void:
var world: Array = []
for point: Vector3 in points:
world.append(to_world(point))
routes.append(world)
+1
View File
@@ -0,0 +1 @@
uid://cany76y8w47r
+378
View File
@@ -0,0 +1,378 @@
## Places an island's points of interest from the match seed. Like the island itself,
## both ends build the same set from the seed alone.
##
## Kinds, all original to Tidewall: fishing hamlets, docks, lighthouses, a quarry, salt
## works and hilltop shrines. Each kind has a siting rule (a band of height, how flat,
## near the coast or a summit) and is assembled from Poi's modular parts.
class_name PoiSet
extends RefCounted
## Kinds in placing order: the most particular sites are claimed first.
const ORDER: Array[String] = ["shrine", "lighthouse", "dock", "salt_works", "quarry", "hamlet"]
const CANDIDATES: int = 260
const RELAX_STEPS: Array[float] = [1.0, 1.5, 2.2, 3.2]
const STRICT_ONLY: Array[float] = [1.0]
const PIER_DECK_MIN: float = 1.4
const PIER_WATER_DEPTH: float = 1.5
const PIER_PAST_WATER: float = 6.0
const PIER_MAX_METRES: float = 36.0
## Radius around a site whose terrain must lie within a kind's flatness, in metres.
const SITE_RADIUS: Dictionary = {
"shrine": 6.0, "lighthouse": 6.0, "dock": 5.0, "salt_works": 12.0, "quarry": 10.0, "hamlet": 14.0,
}
var pois: Array[Poi] = []
var _island: Island
var _ground: SimGround
static func generate(island: Island) -> PoiSet:
var placed: PoiSet = PoiSet.new()
placed._island = island
placed._ground = island.ground
placed._place_all(SimRng.new(island.match_seed).stream("poi"))
return placed
## Every loot spawn marker, for the loot system: {"position": Vector3, "poi": index,
## "kind": String}, in placing order.
func loot_markers() -> Array[Dictionary]:
var markers: Array[Dictionary] = []
for index: int in pois.size():
for at: Vector3 in pois[index].loot:
markers.append({"position": at, "poi": index, "kind": pois[index].kind})
return markers
## Adds every POI's solids to `ground`.
func add_solids_to(ground: SimGround) -> void:
for poi: Poi in pois:
for solid: AABB in poi.solids:
ground.add_solid(solid)
func count_of(kind: String) -> int:
var count: int = 0
for poi: Poi in pois:
if poi.kind == kind:
count += 1
return count
func _place_all(rng: RandomNumberGenerator) -> void:
var wanted: Dictionary = {}
var total: int = 0
for kind: String in ORDER:
var limits: Dictionary = Tuning.POI_KINDS[kind]
wanted[kind] = rng.randi_range(limits["min"], limits["max"])
total += wanted[kind]
while total > Tuning.POI_MAX_TOTAL:
for kind: String in ORDER:
if total > Tuning.POI_MAX_TOTAL and wanted[kind] > Tuning.POI_KINDS[kind]["min"]:
wanted[kind] -= 1
total -= 1
for kind: String in ORDER:
for index: int in wanted[kind]:
# Every kind's minimum must be placed, so loosen its siting rules step by step
# when the island is awkward. Extras only go on good sites.
var steps: Array[float] = RELAX_STEPS if index < Tuning.POI_KINDS[kind]["min"] else STRICT_ONLY
for relax: float in steps:
if _place_one(kind, rng, relax):
break
# If a strict siting rule left the island short, relax and top up with hamlets.
var relax: float = 1.5
while pois.size() < Tuning.POI_MIN_TOTAL and relax < 4.0:
_place_one("hamlet", rng, relax)
relax += 0.25
## Tries candidate sites for `kind` and builds the best. `relax` widens the siting rules.
func _place_one(kind: String, rng: RandomNumberGenerator, relax: float) -> bool:
var best: Vector2 = Vector2.ZERO
var best_score: float = INF
var size: float = Tuning.WORLD_SIZE_METRES
for _attempt: int in CANDIDATES:
var site: Vector2
if kind == "shrine" and count_of("shrine") < _island.summits.size():
var summit: Vector3 = _island.summits[count_of("shrine")]
site = Vector2(summit.x, summit.z) + Vector2(rng.randf_range(-25.0, 25.0), rng.randf_range(-25.0, 25.0))
else:
site = Vector2(rng.randf_range(0.08, 0.92) * size, rng.randf_range(0.08, 0.92) * size)
var score: float = _site_score(kind, site, relax)
if score < best_score:
best_score = score
best = site
if best_score == INF:
return false
var height: float = _ground.terrain_height(best.x, best.y)
var poi: Poi = Poi.new(kind, Vector3(best.x, height, best.y), _facing_for(kind, best, rng), _ground)
call("_build_" + kind, poi, rng)
pois.append(poi)
return true
## Lower is better; INF means unsuitable.
func _site_score(kind: String, site: Vector2, relax: float) -> float:
for poi: Poi in pois:
if Vector2(poi.origin.x, poi.origin.z).distance_to(site) < Tuning.POI_SPACING_METRES:
return INF
var height: float = _ground.terrain_height(site.x, site.y)
var spread: float = _spread(site, SITE_RADIUS[kind])
match kind:
"shrine":
if height < Tuning.ISLAND_FOREST_TOP or spread > 4.0 * relax:
return INF
return spread - height * 0.2
"lighthouse":
var sea: float = _distance_to_sea(site, 80.0)
if height < 6.0 or height > 30.0 * relax or sea > 60.0 * relax or spread > 3.0 * relax:
return INF
return spread + sea * 0.05 - height * 0.05
"dock":
if height < 0.4 or height > 2.4 * relax or spread > 2.5 * relax:
return INF
var turn: int = _seaward(site)
if turn < 0 or _pier_length(site, turn) == 0.0:
return INF
return spread + _pier_length(site, turn) * 0.05
"salt_works":
if height < Tuning.ISLAND_BEACH_TOP * 0.5 or height > Tuning.ISLAND_MARSH_TOP * relax or spread > 2.0 * relax:
return INF
return spread
"quarry":
if height < Tuning.ISLAND_FOREST_TOP - 6.0 or height > Tuning.ISLAND_SUMMIT_BAND * relax or spread > 4.0 * relax:
return INF
return spread
_:
if height < Tuning.ISLAND_MARSH_TOP or height > Tuning.ISLAND_FOREST_TOP * relax or spread > 2.5 * relax:
return INF
return spread
return INF
## Highest minus lowest terrain within `radius` of `site`.
func _spread(site: Vector2, radius: float) -> float:
var low: float = INF
var high: float = -INF
for ring: float in [0.0, radius * 0.5, radius]:
for index: int in 8:
var angle: float = TAU * index / 8.0
var at: Vector2 = site + Vector2(cos(angle), sin(angle)) * ring
var height: float = _ground.terrain_height(at.x, at.y)
low = minf(low, height)
high = maxf(high, height)
return high - low
func _distance_to_sea(site: Vector2, limit: float) -> float:
for distance: float in range(0, int(limit) + 1, 5):
for index: int in 8:
var angle: float = TAU * index / 8.0
var at: Vector2 = site + Vector2(cos(angle), sin(angle)) * distance
if _ground.terrain_height(at.x, at.y) <= 0.0:
return distance
return INF
## The quarter turn whose front faces open sea within 30 m, or -1.
func _seaward(site: Vector2) -> int:
var directions: Array[Vector2] = [Vector2(0.0, 1.0), Vector2(1.0, 0.0), Vector2(0.0, -1.0), Vector2(-1.0, 0.0)]
var best: int = -1
var deepest: float = -0.5
for turn: int in 4:
var far: Vector2 = site + directions[turn] * 30.0
var depth: float = _ground.terrain_height(far.x, far.y)
if depth < deepest:
deepest = depth
best = turn
return best
## Deck height for a pier at `site`, in world metres: a little above the shore, and
## always clear of the starting sea.
func _deck_top(site: Vector2) -> float:
return maxf(_ground.terrain_height(site.x, site.y) + 0.3, PIER_DECK_MIN)
## How long a pier from `site` facing quarter turn `turn` must be to reach water at
## least PIER_WATER_DEPTH deep, plus PIER_PAST_WATER. 0 if it can't: the sea is too far
## away, or the ground rises under the deck on the way.
func _pier_length(site: Vector2, turn: int) -> float:
var directions: Array[Vector2] = [Vector2(0.0, 1.0), Vector2(1.0, 0.0), Vector2(0.0, -1.0), Vector2(-1.0, 0.0)]
var deck: float = _deck_top(site)
for distance: float in range(4, int(PIER_MAX_METRES) + 1, 2):
var at: Vector2 = site + directions[turn] * distance
var height: float = _ground.terrain_height(at.x, at.y)
if height > deck - 0.4:
return 0.0
if height < -PIER_WATER_DEPTH:
return minf(distance + PIER_PAST_WATER, PIER_MAX_METRES)
return 0.0
func _facing_for(kind: String, site: Vector2, rng: RandomNumberGenerator) -> int:
if kind == "dock":
return _seaward(site)
return rng.randi_range(0, 3)
func _build_hamlet(poi: Poi, rng: RandomNumberGenerator) -> void:
# Huts around a yard, doors facing in, and a net-drying rack in the middle.
var huts: int = rng.randi_range(3, 4)
var spots: Array[Vector3] = [Vector3(0.0, 0.0, -9.0), Vector3(-9.0, 0.0, 0.0), Vector3(9.0, 0.0, 0.0), Vector3(0.0, 0.0, 9.0)]
for index: int in huts:
var hut: Poi = _child(poi, spots[index], index)
hut.hut(Vector3.ZERO, rng.randf_range(5.0, 6.5), rng.randf_range(4.5, 5.5), 2.8, Poi.LOOK_TARRED_WOOD, Poi.LOOK_ROOF)
_adopt(poi, hut)
for x: float in [-2.0, 2.0]:
poi.box(Vector3(x - 0.1, -0.5, -0.1), Vector3(0.2, 2.6, 0.2), Poi.LOOK_PLANK)
poi.box(Vector3(-2.2, 2.0, -0.08), Vector3(4.4, 0.12, 0.16), Poi.LOOK_PLANK)
poi.add_loot(Vector3(0.0, poi.ground_at(Vector3(0.0, 0.0, 1.5)) - poi.origin.y, 1.5))
func _build_dock(poi: Poi, _rng: RandomNumberGenerator) -> void:
# A plank pier running out to sea on posts, with a net shed on the shore behind it.
var site: Vector2 = Vector2(poi.origin.x, poi.origin.z)
var deck_top: float = _deck_top(site) - poi.origin.y
var length: float = _pier_length(site, poi.facing)
poi.box(Vector3(-1.5, deck_top - 0.25, 0.0), Vector3(3.0, 0.25, length), Poi.LOOK_PLANK)
for z: float in range(2, int(length), 4):
for x: float in [-1.4, 1.2]:
poi.box(Vector3(x, -Tuning.ISLAND_SEA_DEPTH - poi.origin.y, z), Vector3(0.2, deck_top + Tuning.ISLAND_SEA_DEPTH + poi.origin.y + 0.9, 0.2), Poi.LOOK_TARRED_WOOD, false)
poi.box(Vector3(-1.6, deck_top, length - 0.2), Vector3(3.2, 0.9, 0.2), Poi.LOOK_PAINT)
var shed: Poi = _child(poi, Vector3(0.0, 0.0, -8.0), 0)
shed.hut(Vector3.ZERO, 5.0, 4.5, 2.6, Poi.LOOK_TARRED_WOOD, Poi.LOOK_ROOF)
_adopt(poi, shed)
# Steps down from the landward end of the deck to the shore.
var landing: Vector3 = poi.steps_down(Vector3(0.0, deck_top, 0.0), Vector3(0.0, 0.0, -1.0), 2.4, Poi.LOOK_PLANK)
var on_deck: Vector3 = Vector3(0.0, deck_top, 1.0)
var end: Vector3 = Vector3(0.0, deck_top, length - 1.5)
poi.add_loot(end)
poi.add_route([landing, on_deck, end])
func _build_lighthouse(poi: Poi, _rng: RandomNumberGenerator) -> void:
# A square stone tower: a keeper's room, a stair along the back wall up to a loft,
# and the light chamber above. The loot is in the loft.
var side: float = 7.0
var half: float = side * 0.5
var under: Vector2 = poi.terrain_range(Vector2(-half, -half), Vector2(side, side))
var floor_y: float = under.y - poi.origin.y + 0.15
poi.plinth(Vector2(-half, -half), Vector2(side, side), floor_y, Poi.LOOK_STONE)
var loft: float = floor_y + 3.5
var top: float = floor_y + 13.0
var inner: float = side - 2.0 * Poi.WALL
var x0: float = -half
var z0: float = -half
poi.box(Vector3(x0, floor_y, z0), Vector3(side, top - floor_y, Poi.WALL), Poi.LOOK_STONE)
poi.box(Vector3(x0, floor_y, z0), Vector3(Poi.WALL, top - floor_y, side), Poi.LOOK_STONE)
poi.box(Vector3(half - Poi.WALL, floor_y, z0), Vector3(Poi.WALL, top - floor_y, side), Poi.LOOK_STONE)
var side_width: float = (side - Poi.DOOR_WIDTH) * 0.5
poi.box(Vector3(x0, floor_y, half - Poi.WALL), Vector3(side_width, top - floor_y, Poi.WALL), Poi.LOOK_STONE)
poi.box(Vector3(x0 + side_width + Poi.DOOR_WIDTH, floor_y, half - Poi.WALL), Vector3(side_width, top - floor_y, Poi.WALL), Poi.LOOK_STONE)
poi.box(Vector3(x0 + side_width, floor_y + Poi.DOOR_HEIGHT, half - Poi.WALL), Vector3(Poi.DOOR_WIDTH, top - floor_y - Poi.DOOR_HEIGHT, Poi.WALL), Poi.LOOK_STONE)
# Painted bands, the light chamber and its cap.
for band: float in [4.5, 8.5]:
poi.box(Vector3(x0 - 0.05, floor_y + band, z0 - 0.05), Vector3(side + 0.1, 1.2, side + 0.1), Poi.LOOK_PAINT, false)
poi.box(Vector3(-2.0, top, -2.0), Vector3(4.0, 2.4, 4.0), Poi.LOOK_LAMP)
poi.box(Vector3(-2.5, top + 2.4, -2.5), Vector3(5.0, 0.4, 5.0), Poi.LOOK_ROOF)
# Stair along the back wall, rising towards -x, ten steps up to the loft.
var stair_width: float = 1.1
var steps: int = ceili((loft - floor_y) / Poi.STEP_RISE)
var rise: float = (loft - floor_y) / steps
var tread: float = 0.5
var stair_z: float = z0 + Poi.WALL
var start_x: float = half - Poi.WALL - 1.0
for index: int in steps:
var step_top: float = floor_y + rise * (index + 1)
var x: float = start_x - tread * (index + 1)
poi.box(Vector3(x, floor_y, stair_z), Vector3(tread, step_top - floor_y, stair_width), Poi.LOOK_PLANK)
var stair_end_x: float = start_x - tread * steps
# The loft covers the room except the stair well above the flight.
var well_end: float = start_x + 0.2
poi.box(Vector3(x0 + Poi.WALL, loft - 0.3, stair_z + stair_width), Vector3(inner, 0.3, inner - stair_width), Poi.LOOK_PLANK)
poi.box(Vector3(x0 + Poi.WALL, loft - 0.3, stair_z), Vector3(stair_end_x - x0 - Poi.WALL, 0.3, stair_width), Poi.LOOK_PLANK)
poi.box(Vector3(well_end, loft - 0.3, stair_z), Vector3(half - Poi.WALL - well_end, 0.3, stair_width), Poi.LOOK_PLANK)
var door: Vector3 = Vector3(0.0, floor_y, half)
var foot: Vector3 = poi.steps_down(door, Vector3(0.0, 0.0, 1.0), Poi.DOOR_WIDTH + 0.4, Poi.LOOK_STONE)
var room: Vector3 = Vector3(0.0, floor_y, half - 1.5)
var stair_foot: Vector3 = Vector3(start_x + 0.4, floor_y, stair_z + stair_width * 0.5)
var stair_top: Vector3 = Vector3(stair_end_x + 0.25, loft, stair_z + stair_width * 0.5)
var loft_spot: Vector3 = Vector3(stair_end_x + 0.6, loft, z0 + Poi.WALL + stair_width + 1.6)
poi.add_loot(Vector3(1.5, floor_y, half - 2.0))
poi.add_loot(loft_spot)
poi.add_route([foot + Vector3(0.0, 0.0, 1.5), foot, door, room, stair_foot, stair_top, loft_spot])
func _build_quarry(poi: Poi, rng: RandomNumberGenerator) -> void:
# Cut stone blocks, a lifting frame and a tool shed.
var shed: Poi = _child(poi, Vector3(0.0, 0.0, -6.0), rng.randi_range(0, 3))
shed.hut(Vector3.ZERO, 5.0, 4.0, 2.6, Poi.LOOK_PLANK, Poi.LOOK_ROOF)
_adopt(poi, shed)
for index: int in rng.randi_range(5, 8):
var at: Vector3 = Vector3(rng.randf_range(-9.0, 9.0), 0.0, rng.randf_range(1.0, 10.0))
var size: Vector3 = Vector3(rng.randf_range(1.2, 2.4), rng.randf_range(0.8, 1.8), rng.randf_range(1.2, 2.4))
var base: float = poi.ground_at(at) - poi.origin.y - 0.3
poi.box(Vector3(at.x, base, at.z), size + Vector3(0.0, 0.3, 0.0), Poi.LOOK_STONE)
var frame_z: float = 5.0
for x: float in [-3.0, 3.0]:
var base: float = poi.ground_at(Vector3(x, 0.0, frame_z)) - poi.origin.y - 0.3
poi.box(Vector3(x - 0.15, base, frame_z - 0.15), Vector3(0.3, 5.3, 0.3), Poi.LOOK_TARRED_WOOD)
poi.box(Vector3(-3.3, poi.ground_at(Vector3(0.0, 0.0, frame_z)) - poi.origin.y + 4.8, frame_z - 0.2), Vector3(6.6, 0.4, 0.4), Poi.LOOK_TARRED_WOOD)
poi.add_loot(Vector3(0.0, poi.ground_at(Vector3(0.0, 0.0, 12.0)) - poi.origin.y, 12.0))
func _build_salt_works(poi: Poi, rng: RandomNumberGenerator) -> void:
# Shallow evaporation pans behind low walls you can step over, and a boiling house.
var house: Poi = _child(poi, Vector3(0.0, 0.0, -9.0), 0)
house.hut(Vector3.ZERO, 8.0, 6.0, 3.2, Poi.LOOK_TARRED_WOOD, Poi.LOOK_ROOF)
_adopt(poi, house)
poi.box(Vector3(2.4, house.origin.y - poi.origin.y - 0.5, -12.8), Vector3(0.8, 6.5, 0.8), Poi.LOOK_STONE)
for row: int in 2:
for column: int in 3:
var x0: float = -10.5 + column * 7.0
var z0: float = 1.0 + row * 6.0
var base: float = poi.ground_at(Vector3(x0 + 3.0, 0.0, z0 + 2.5)) - poi.origin.y
poi.box(Vector3(x0, base - 0.3, z0), Vector3(6.0, 0.35, 5.0), Poi.LOOK_SALT, false)
for wall: Array in [[Vector3(x0, 0, z0), Vector3(6.0, 0, 0.25)], [Vector3(x0, 0, z0 + 4.75), Vector3(6.0, 0, 0.25)],
[Vector3(x0, 0, z0), Vector3(0.25, 0, 5.0)], [Vector3(x0 + 5.75, 0, z0), Vector3(0.25, 0, 5.0)]]:
var at: Vector3 = wall[0]
var size: Vector3 = wall[1]
poi.box(Vector3(at.x, base - 0.3, at.z), Vector3(size.x, 0.6, size.z), Poi.LOOK_STONE)
poi.add_loot(Vector3(-7.5, poi.ground_at(Vector3(-7.5, 0.0, 3.5)) - poi.origin.y, 3.5))
if rng.randf() < 0.5:
poi.add_loot(Vector3(6.5, poi.ground_at(Vector3(6.5, 0.0, 9.5)) - poi.origin.y, 9.5))
func _build_shrine(poi: Poi, rng: RandomNumberGenerator) -> void:
# A small open-fronted stone shrine with a painted lintel, and cairns around it.
poi.hut(Vector3.ZERO, 4.0, 3.6, 2.6, Poi.LOOK_STONE, Poi.LOOK_PAINT)
for index: int in rng.randi_range(3, 5):
var angle: float = TAU * index / 5.0 + rng.randf() * 0.4
var at: Vector3 = Vector3(cos(angle), 0.0, sin(angle)) * rng.randf_range(6.0, 9.0)
if at.z > 2.0 and absf(at.x) < 2.5:
continue # Keep the approach to the door clear.
var base: float = poi.ground_at(at) - poi.origin.y - 0.2
for layer: int in 3:
var size: float = 1.2 - layer * 0.3
poi.box(Vector3(at.x - size * 0.5, base + layer * 0.5, at.z - size * 0.5), Vector3(size, 0.5, size), Poi.LOOK_STONE)
## A sub-part with its own local frame at `offset` in the parent's frame, turned by a
## further `turns` quarter turns.
func _child(parent: Poi, offset: Vector3, turns: int) -> Poi:
var at: Vector3 = parent.to_world(offset)
at.y = _ground.terrain_height(at.x, at.z)
var facing: int = parent.facing + turns
if parent.kind == "hamlet":
# Spots around the yard: back, left, right, front. Turn each door to the yard.
facing = parent.facing + [0, 1, 3, 2][turns]
return Poi.new(parent.kind, at, facing, _ground)
func _adopt(parent: Poi, child: Poi) -> void:
parent.solids.append_array(child.solids)
parent.parts.append_array(child.parts)
parent.loot.append_array(child.loot)
parent.routes.append_array(child.routes)
+1
View File
@@ -0,0 +1 @@
uid://dbhv43jwkephj
+262
View File
@@ -0,0 +1,262 @@
## The island's scattered props: pines, scrub, boulders, wrecks and crates. Like the
## island and its points of interest, both ends build the same set from the seed alone,
## so props are never sent over the network. Only damage to them is match state.
##
## Placement walks a jittered grid of CELL-metre squares. Every square draws the same
## number of random values whatever it ends up holding, so a change in one square's
## outcome never shifts the next. A kind's chance in a square comes from its density in
## the square's elevation band (Tuning.PROP_DENSITY), scaled by a grove noise for pines
## and scrub, so forests have thickets and clearings.
##
## Each prop is one axis-aligned collision box in SimGround. Destroying a prop removes
## its box, so players can walk where it stood. Props are stored in packed arrays,
## because there are thousands of them.
class_name PropSet
extends RefCounted
## Side of the placement squares, in metres. At most one prop per square.
const CELL: float = 4.0
## Random values drawn per square: pick, jitter x, jitter z, size, height, length, turn.
const DRAWS: int = 7
## Kind codes, in the order kinds are tried within a square.
const KINDS: Array[String] = ["pine", "scrub", "boulder", "wreck", "crate"]
## Band names, indexed by Island.Band.
const BAND_NAMES: Array[String] = ["sea", "beach", "marsh", "forest", "highland", "summit"]
## Grove noise scale, in metres, and how strongly it thins or thickens growth.
const GROVE_METRES: float = 70.0
const GROVE_STRENGTH: float = 1.6
## Lowest ground props stand on, in metres above the starting sea. Wrecks lie lower.
const MIN_HEIGHT: float = 0.4
const WRECK_MIN_HEIGHT: float = 0.1
## Most ground rise across a footprint each kind accepts, in metres.
const TILT_LIMITS: Dictionary = {"pine": 1.6, "boulder": 2.0, "wreck": 1.2, "scrub": 0.6, "crate": 0.6}
## Boxes sink this far into the ground at their lowest corner, so none float on slopes.
const SINK: float = 0.25
## Per prop, indexed by prop ID (0 .. count() - 1).
var kinds: PackedByteArray = PackedByteArray()
## Where the prop meets the ground, at its footprint centre.
var positions: PackedVector3Array = PackedVector3Array()
## Visual yaw in radians. Collision is the box in `boxes` whatever the yaw.
var yaws: PackedFloat32Array = PackedFloat32Array()
var boxes: Array[AABB] = []
var health: PackedInt32Array = PackedInt32Array()
## The SimGround solid ID of each prop's box, or -1 when it isn't in a ground.
var solid_ids: PackedInt32Array = PackedInt32Array()
## Prop IDs in the order they were destroyed, for views to catch up on.
var destroyed: PackedInt32Array = PackedInt32Array()
var _ground: SimGround
## Places props for `island`, clear of `placed` points of interest.
static func generate(island: Island, placed: PoiSet) -> PropSet:
var props: PropSet = PropSet.new()
props._place(island, placed)
return props
func count() -> int:
return kinds.size()
func kind_name(prop: int) -> String:
return KINDS[kinds[prop]]
func material_of(prop: int) -> String:
return Tuning.PROP_KINDS[kind_name(prop)]["material"]
func is_standing(prop: int) -> bool:
return health[prop] > 0
func count_of(kind: String) -> int:
var code: int = KINDS.find(kind)
var total: int = 0
for value: int in kinds:
if value == code:
total += 1
return total
## Adds every prop's box to `ground` and remembers the solid IDs, so destroying a prop
## removes its collision. Call once.
func add_solids_to(ground: SimGround) -> void:
_ground = ground
solid_ids.resize(count())
for prop: int in count():
solid_ids[prop] = ground.add_solid(boxes[prop]) if is_standing(prop) else -1
## Takes `amount` health from a standing prop. Returns true if this destroyed it, which
## also removes its collision. Damage to an already destroyed prop does nothing.
func damage(prop: int, amount: int) -> bool:
if prop < 0 or prop >= count() or not is_standing(prop) or amount <= 0:
return false
health[prop] = maxi(health[prop] - amount, 0)
if health[prop] > 0:
return false
destroyed.append(prop)
if _ground != null and solid_ids[prop] >= 0:
_ground.remove_solid(solid_ids[prop])
solid_ids[prop] = -1
return true
## Standing props whose boxes come within `radius` of `point`, nearest first.
func near(point: Vector3, radius: float) -> PackedInt32Array:
var found: Array[Vector2] = []
for prop: int in count():
if not is_standing(prop):
continue
var gap: float = _distance_to_box(boxes[prop], point)
if gap <= radius:
found.append(Vector2(gap, prop))
found.sort()
var ids: PackedInt32Array = PackedInt32Array()
for entry: Vector2 in found:
ids.append(int(entry.y))
return ids
## SHA-256 hex digest of every prop's kind and box, millimetre-rounded. Two machines
## that agree on this see the same props in the same places.
func layout_hash() -> String:
var buffer: StreamPeerBuffer = StreamPeerBuffer.new()
buffer.big_endian = false
buffer.put_32(count())
buffer.put_data(kinds)
for box: AABB in boxes:
for value: float in [box.position.x, box.position.y, box.position.z, box.size.x, box.size.y, box.size.z]:
buffer.put_32(roundi(value * 1000.0))
for yaw: float in yaws:
buffer.put_32(roundi(yaw * 1000.0))
var hasher: HashingContext = HashingContext.new()
hasher.start(HashingContext.HASH_SHA256)
hasher.update(buffer.data_array)
return hasher.finish().hex_encode()
func _place(island: Island, placed: PoiSet) -> void:
var ground: SimGround = island.ground
var rng: RandomNumberGenerator = SimRng.new(island.match_seed).stream("props")
var grove: FastNoiseLite = FastNoiseLite.new()
grove.noise_type = FastNoiseLite.TYPE_SIMPLEX_SMOOTH
grove.seed = rng.randi()
grove.frequency = 1.0 / GROVE_METRES
var blocked: SimGround = _poi_keep_out(placed)
var mine: SimGround = SimGround.flat()
var per_side: int = floori(Tuning.WORLD_SIZE_METRES / CELL)
var cell_area_hectares: float = CELL * CELL / 10000.0
var values: PackedFloat32Array = PackedFloat32Array()
values.resize(DRAWS)
for gz: int in per_side:
for gx: int in per_side:
for draw: int in DRAWS:
values[draw] = rng.randf()
var x: float = (gx + 0.15 + 0.7 * values[1]) * CELL
var z: float = (gz + 0.15 + 0.7 * values[2]) * CELL
var band: int = island.band_at(x, z)
if band == Island.Band.SEA:
continue
var densities: Dictionary = Tuning.PROP_DENSITY[BAND_NAMES[band]]
var growth: float = clampf(1.0 + grove.get_noise_2d(x, z) * GROVE_STRENGTH, 0.0, 2.2)
var pick: float = values[0]
var chosen: int = -1
for code: int in KINDS.size():
var kind: String = KINDS[code]
var chance: float = float(densities.get(kind, 0.0)) * cell_area_hectares
if kind == "pine" or kind == "scrub":
chance *= growth
if pick < chance:
chosen = code
break
pick -= chance
if chosen < 0:
continue
var box: AABB = _box_for(chosen, Vector2(x, z), values, ground)
if box.size == Vector3.ZERO:
continue
if _overlaps(blocked, box, Tuning.PROP_POI_CLEARANCE) or _overlaps(mine, box, 0.3):
continue
mine.add_solid(box)
kinds.append(chosen)
positions.append(Vector3(x, ground.terrain_height(x, z), z))
yaws.append(values[6] * TAU)
boxes.append(box)
health.append(Tuning.PROP_KINDS[KINDS[chosen]]["health"])
## The prop's collision box, or an empty box if the spot doesn't suit the kind.
func _box_for(code: int, at: Vector2, values: PackedFloat32Array, ground: SimGround) -> AABB:
var kind: String = KINDS[code]
var spec: Dictionary = Tuning.PROP_KINDS[kind]
var width: float = lerpf(spec["width"][0], spec["width"][1], values[3])
var height: float = lerpf(spec["height"][0], spec["height"][1], values[4])
var size: Vector3 = Vector3(width, height, width)
if kind == "wreck":
var length: float = lerpf(spec["length"][0], spec["length"][1], values[5])
# Wrecks lie along x or z, so the box stays axis-aligned.
size = Vector3(length, height, width) if values[6] < 0.5 else Vector3(width, height, length)
var half: Vector2 = Vector2(size.x, size.z) * 0.5
var lowest: float = INF
var highest: float = -INF
for corner: Vector2 in [Vector2(-1, -1), Vector2(1, -1), Vector2(-1, 1), Vector2(1, 1), Vector2.ZERO]:
var h: float = ground.terrain_height(at.x + corner.x * half.x, at.y + corner.y * half.y)
lowest = minf(lowest, h)
highest = maxf(highest, h)
var floor_min: float = WRECK_MIN_HEIGHT if kind == "wreck" else MIN_HEIGHT
if lowest < floor_min:
return AABB()
# Boulders and pines take slopes; the rest need somewhere flattish.
var tilt: float = highest - lowest
var max_tilt: float = TILT_LIMITS.get(kind, 0.6)
if tilt > max_tilt:
return AABB()
var base: float = lowest - SINK
# The box grows by the tilt, so its top stands `height - SINK` above the uphill
# corner too. Boulders sink deeper on slopes, so the uphill side isn't a wall.
if kind == "boulder":
base -= tilt * 0.4
size.y += tilt * 0.4
size.y += tilt if kind != "pine" else 0.0
return AABB(Vector3(at.x - half.x, base, at.y - half.y), size)
## A ground holding every POI solid, plus small boxes at loot markers and along walking
## routes, for keeping props out of the way.
func _poi_keep_out(placed: PoiSet) -> SimGround:
var keep_out: SimGround = SimGround.flat()
for poi: Poi in placed.pois:
for solid: AABB in poi.solids:
keep_out.add_solid(solid)
for at: Vector3 in poi.loot:
keep_out.add_solid(AABB(at - Vector3(0.5, 0.0, 0.5), Vector3(1.0, 2.0, 1.0)))
for route: Array in poi.routes:
for index: int in range(1, route.size()):
var a: Vector3 = route[index - 1]
var b: Vector3 = route[index]
var steps: int = maxi(ceili(a.distance_to(b) / 1.0), 1)
for step: int in steps + 1:
var at: Vector3 = a.lerp(b, float(step) / steps)
keep_out.add_solid(AABB(at - Vector3(0.5, 0.0, 0.5), Vector3(1.0, 2.0, 1.0)))
return keep_out
## True if `box`, grown sideways by `margin`, overlaps any solid in `ground`. Height is
## ignored: a prop under a pier deck still blocks the way to it.
func _overlaps(ground: SimGround, box: AABB, margin: float) -> bool:
var low: Vector2 = Vector2(box.position.x - margin, box.position.z - margin)
var high: Vector2 = Vector2(box.end.x + margin, box.end.z + margin)
for id: int in ground.solids_near(low.x, low.y, high.x, high.y):
var other: AABB = ground.solids[id]
if other.position.x < high.x and other.end.x > low.x and other.position.z < high.y and other.end.z > low.y:
return true
return false
static func _distance_to_box(box: AABB, point: Vector3) -> float:
var closest: Vector3 = point.clamp(box.position, box.end)
return closest.distance_to(point)
+1
View File
@@ -0,0 +1 @@
uid://mdvwhfhnp6nk
+11
View File
@@ -11,6 +11,17 @@ var velocity: Vector3 = Vector3.ZERO
var yaw: int = 0
var pitch: int = 0
var health: int = 0
## Standing on walkable ground. False while jumping, falling or sliding.
var on_ground: bool = false
var crouching: bool = false
## Floating or diving in deep water. Swimmers can't build or fire.
var swimming: bool = false
## Breath, stamina and time spent without breath, in ticks. See Water.
var breath_ticks: int = 0
var stamina_ticks: int = 0
var drown_ticks: int = 0
## Where the player is in the drop: Drop.NONE, ABOARD, FREEFALL or GLIDING.
var drop_state: int = 0
func _init(entity_id: int, entity_archetype: int) -> void:
+264
View File
@@ -0,0 +1,264 @@
## Everything solid that players stand on, walk into and see through: a terrain
## heightfield plus axis-aligned box solids (structures, rocks). The island generator
## fills the heightfield; building adds and removes solids.
##
## All queries are pure functions of the stored data, so the server, client prediction
## and the camera all agree.
class_name SimGround
extends RefCounted
## Ray-marching step for terrain, in metres. Small enough for camera-length rays.
const RAY_STEP: float = 0.05
const RAY_REFINE_STEPS: int = 10
## Side of the squares the solid index buckets by, in metres.
const INDEX_CELL: float = 8.0
const _NO_SOLIDS: PackedInt32Array = []
## What a removed solid's slot holds: an empty box far below anything in the world.
const REMOVED: AABB = AABB(Vector3(0.0, -1.0e6, 0.0), Vector3.ZERO)
const _MARGIN_OFFSETS: Array[Vector2] = [
Vector2(1.0, 0.0), Vector2(-1.0, 0.0), Vector2(0.0, 1.0), Vector2(0.0, -1.0),
Vector2(0.7071, 0.7071), Vector2(0.7071, -0.7071), Vector2(-0.7071, 0.7071), Vector2(-0.7071, -0.7071),
]
## Heights in row-major order: index = z * samples + x, `cell` metres apart, starting
## at the world origin. Outside the grid the nearest edge sample is used.
var heights: PackedFloat32Array = PackedFloat32Array()
var samples: int = 0
var cell: float = 1.0
## Every solid, in the order added. Add them with add_solid(), which indexes them.
var solids: Array[AABB] = []
## Solids indexed by the INDEX_CELL squares their footprints overlap, so queries only
## test nearby boxes. Vector2i -> PackedInt32Array of indices into `solids`.
var _index: Dictionary = {}
## A flat world at `height`.
static func flat(height: float = 0.0) -> SimGround:
var ground: SimGround = SimGround.new()
ground.samples = 2
ground.cell = Tuning.WORLD_SIZE_METRES
ground.heights = PackedFloat32Array([height, height, height, height])
return ground
## A heightfield of `side` x `side` samples spaced `spacing` metres apart.
static func from_heights(values: PackedFloat32Array, side: int, spacing: float) -> SimGround:
assert(side >= 2 and values.size() == side * side and spacing > 0.0)
var ground: SimGround = SimGround.new()
ground.heights = values
ground.samples = side
ground.cell = spacing
return ground
## Adds a solid and returns its ID, which stays valid until remove_solid().
func add_solid(box: AABB) -> int:
var normalised: AABB = box.abs()
var id: int = solids.size()
solids.append(normalised)
var low: Vector2i = _cell_of(normalised.position.x, normalised.position.z)
var high: Vector2i = _cell_of(normalised.end.x, normalised.end.z)
for cz: int in range(low.y, high.y + 1):
for cx: int in range(low.x, high.x + 1):
var key: Vector2i = Vector2i(cx, cz)
var bucket: PackedInt32Array = _index.get(key, PackedInt32Array())
bucket.append(id)
_index[key] = bucket
return id
## Removes a solid so no query sees it again. IDs are never reused: the slot in
## `solids` becomes REMOVED, a box far below the world, so other IDs keep their meaning.
## Returns false if the ID is unknown or already removed.
func remove_solid(id: int) -> bool:
if id < 0 or id >= solids.size() or solids[id] == REMOVED:
return false
var box: AABB = solids[id]
var low: Vector2i = _cell_of(box.position.x, box.position.z)
var high: Vector2i = _cell_of(box.end.x, box.end.z)
for cz: int in range(low.y, high.y + 1):
for cx: int in range(low.x, high.x + 1):
var key: Vector2i = Vector2i(cx, cz)
var bucket: PackedInt32Array = _index.get(key, PackedInt32Array())
var at: int = bucket.find(id)
if at >= 0:
bucket.remove_at(at)
if bucket.is_empty():
_index.erase(key)
else:
_index[key] = bucket
solids[id] = REMOVED
return true
## Indices of solids whose footprint may overlap the rectangle. May repeat an index when
## the rectangle spans several cells, which every query tolerates.
func solids_near(min_x: float, min_z: float, max_x: float, max_z: float) -> PackedInt32Array:
if _index.is_empty():
return _NO_SOLIDS
var low: Vector2i = _cell_of(min_x, min_z)
var high: Vector2i = _cell_of(max_x, max_z)
if low == high:
return _index.get(low, _NO_SOLIDS)
var found: PackedInt32Array = PackedInt32Array()
for cz: int in range(low.y, high.y + 1):
for cx: int in range(low.x, high.x + 1):
found.append_array(_index.get(Vector2i(cx, cz), _NO_SOLIDS))
return found
func _cell_of(x: float, z: float) -> Vector2i:
return Vector2i(floori(x / INDEX_CELL), floori(z / INDEX_CELL))
## Terrain height at (x, z), bilinearly interpolated.
func terrain_height(x: float, z: float) -> float:
var limit: float = float(samples - 1)
var gx: float = clampf(x / cell, 0.0, limit)
var gz: float = clampf(z / cell, 0.0, limit)
var x0: int = mini(floori(gx), samples - 2)
var z0: int = mini(floori(gz), samples - 2)
var fx: float = gx - x0
var fz: float = gz - z0
var row: int = z0 * samples
var h00: float = heights[row + x0]
var h10: float = heights[row + x0 + 1]
var h01: float = heights[row + samples + x0]
var h11: float = heights[row + samples + x0 + 1]
return lerpf(lerpf(h00, h10, fx), lerpf(h01, h11, fx), fz)
## Upward terrain normal at (x, z), from central differences.
func terrain_normal(x: float, z: float) -> Vector3:
var d: float = minf(cell * 0.5, 0.5)
var dx: float = terrain_height(x + d, z) - terrain_height(x - d, z)
var dz: float = terrain_height(x, z + d) - terrain_height(x, z - d)
return Vector3(-dx, 2.0 * d, -dz).normalized()
## True if the terrain at (x, z) is gentle enough to stand on.
func walkable_terrain(x: float, z: float) -> bool:
return terrain_normal(x, z).y >= cos(deg_to_rad(Tuning.MAX_SLOPE_DEGREES))
## The highest surface under (x, z) that is no higher than `max_y`: the terrain, or the
## top of a solid. Solid tops are always walkable.
func support_height(x: float, z: float, max_y: float) -> float:
var best: float = terrain_height(x, z)
for id: int in solids_near(x, z, x, z):
var box: AABB = solids[id]
var top: float = box.end.y
if top > best and top <= max_y and _inside_footprint(box, x, z, 0.0):
best = top
return best
## True when the best support under (x, z) up to `max_y` is the top of a solid.
func support_is_solid(x: float, z: float, max_y: float) -> bool:
var terrain: float = terrain_height(x, z)
for id: int in solids_near(x, z, x, z):
var box: AABB = solids[id]
var top: float = box.end.y
if top > terrain and top <= max_y and _inside_footprint(box, x, z, 0.0):
return true
return false
## True if a player body at `feet` overlaps a solid. Solids whose top is within
## `step` of the feet don't count, so they can be stepped onto.
func body_blocked(feet: Vector3, radius: float, height: float, step: float) -> bool:
for id: int in solids_near(feet.x - radius, feet.z - radius, feet.x + radius, feet.z + radius):
var box: AABB = solids[id]
if box.end.y <= feet.y + step or box.position.y >= feet.y + height:
continue
if _inside_footprint(box, feet.x, feet.z, radius):
return true
return false
## Casts from `from` to `to` against terrain and solids. Returns the fraction of the way
## to the first hit, or 1.0 if nothing is hit. A ray starting inside something returns 0.
func raycast(from: Vector3, to: Vector3) -> float:
var nearest: float = 1.0
for id: int in solids_near(minf(from.x, to.x), minf(from.z, to.z), maxf(from.x, to.x), maxf(from.z, to.z)):
nearest = minf(nearest, _ray_box(from, to, solids[id]))
return minf(nearest, _ray_terrain(from, to, nearest))
## True if `point` is inside the terrain or a solid, or within `margin` of one. For the
## terrain, heights are also checked `margin` away on each side, so steep ground counts
## its sideways distance and not just the height under the point.
func point_inside(point: Vector3, margin: float = 0.0) -> bool:
if point.y < terrain_height(point.x, point.z) + margin:
return true
if margin > 0.0:
for offset: Vector2 in _MARGIN_OFFSETS:
var probe: Vector2 = offset * margin
if point.y < terrain_height(point.x + probe.x, point.z + probe.y):
return true
for id: int in solids_near(point.x - margin, point.z - margin, point.x + margin, point.z + margin):
if solids[id].grow(margin).has_point(point):
return true
return false
func _inside_footprint(box: AABB, x: float, z: float, radius: float) -> bool:
return (
x > box.position.x - radius and x < box.end.x + radius
and z > box.position.z - radius and z < box.end.z + radius
)
## Slab test. Returns the entry fraction in [0, 1], or 1.0 for a miss.
func _ray_box(from: Vector3, to: Vector3, box: AABB) -> float:
var direction: Vector3 = to - from
var enter: float = 0.0
var leave: float = 1.0
for axis: int in 3:
var start: float = from[axis]
var span: float = direction[axis]
var low: float = box.position[axis]
var high: float = box.end[axis]
if absf(span) < 0.000001:
if start < low or start > high:
return 1.0
continue
var t1: float = (low - start) / span
var t2: float = (high - start) / span
enter = maxf(enter, minf(t1, t2))
leave = minf(leave, maxf(t1, t2))
if enter > leave:
return 1.0
return enter
## Marches the ray up to `limit`, then refines the first crossing below the terrain.
func _ray_terrain(from: Vector3, to: Vector3, limit: float) -> float:
var length: float = from.distance_to(to)
if length <= 0.0:
return 0.0 if _below_terrain(from) else 1.0
if _below_terrain(from):
return 0.0
var step: float = RAY_STEP / length
var previous: float = 0.0
var t: float = step
while previous < limit:
t = minf(t, limit)
if _below_terrain(from.lerp(to, t)):
var low: float = previous
var high: float = t
for _index: int in RAY_REFINE_STEPS:
var middle: float = (low + high) * 0.5
if _below_terrain(from.lerp(to, middle)):
high = middle
else:
low = middle
return low
previous = t
t += step
return 1.0
func _below_terrain(point: Vector3) -> bool:
return point.y < terrain_height(point.x, point.z)
+1
View File
@@ -0,0 +1 @@
uid://oxycp26a8vmr
+101 -21
View File
@@ -1,15 +1,33 @@
## The authoritative fixed-tick game state. It takes commands and a seed and nothing
## else: no scene tree, no wall clock, no unseeded randomness.
##
## Movement here is a flat placeholder until the character controller lands in v0.2.
## Movement rules live in Movement; the world's solid shape lives in `ground`.
class_name Simulation
extends RefCounted
const SECONDS_PER_TICK: float = 1.0 / Tuning.TICK_RATE_HZ
const SPAWN_ATTEMPTS: int = 64
var tick: int = 0
var entities: EntityRegistry = EntityRegistry.new()
var rng: SimRng
## Terrain and solids. The island's heightfield unless a test supplied its own ground.
var ground: SimGround
## The generated island, or null when a test supplied its own ground.
var island: Island
## The island's points of interest, whose solids are part of `ground`. Empty when a
## test supplied its own ground.
var pois: PoiSet = PoiSet.new()
## Trees, scrub, boulders, wrecks and crates, whose boxes are part of `ground`. Empty
## when a test supplied its own ground.
var props: PropSet = PropSet.new()
## Height of the sea surface, in metres. The tide changes it during a match; movement
## and drowning read it every tick, so a change takes effect on the next step.
var sea_level: float = Tuning.SEA_LEVEL_START
## Damage per second to a player underwater with no breath left. Set by the tide phase.
var drown_dps: int = Tuning.TIDE_PHASES[0]["drown_dps"]
## The sky barge, from start_drop() on. Null in matches and tests that start on foot.
var drop: Drop = null
## Player entity ID -> { command tick -> PlayerCommand }
var _pending: Dictionary = {}
@@ -17,8 +35,18 @@ var _pending: Dictionary = {}
var _players: Array[int] = []
func _init(match_seed: int) -> void:
## Generates the island from the seed, unless `world` is given. Tests that don't care
## about terrain pass `SimGround.flat()` to skip worldgen.
func _init(match_seed: int, world: SimGround = null) -> void:
rng = SimRng.new(match_seed)
if world == null:
island = Island.generate(match_seed)
world = island.ground
pois = PoiSet.generate(island)
pois.add_solids_to(world)
props = PropSet.generate(island, pois)
props.add_solids_to(world)
ground = world
## Adds a player at a seeded spawn position and returns its entity ID.
@@ -26,8 +54,21 @@ func add_player() -> int:
var player: SimEntity = entities.create(SimEntity.ARCHETYPE_PLAYER)
var spawn: RandomNumberGenerator = rng.stream("spawn")
var size: float = Tuning.WORLD_SIZE_METRES
player.position = Vector3(spawn.randf() * size, 0.0, spawn.randf() * size)
var x: float = spawn.randf() * size
var z: float = spawn.randf() * size
# Until the drop arrives (W7), spawn on dry land above the beach when there is any.
for _attempt: int in SPAWN_ATTEMPTS:
var feet: Vector3 = Vector3(x, ground.terrain_height(x, z), z)
if feet.y > Tuning.ISLAND_BEACH_TOP and not ground.body_blocked(feet, 2.0, Tuning.PLAYER_HEIGHT, 0.0):
break
x = spawn.randf() * size
z = spawn.randf() * size
player.position = Vector3(x, ground.terrain_height(x, z), z)
player.on_ground = true
player.health = Tuning.PLAYER_MAX_HEALTH
Water.reset(player)
if drop != null and not drop.finished:
Drop.board(player, drop.barge_position(tick))
_players.append(player.id)
_pending[player.id] = {}
return player.id
@@ -52,36 +93,59 @@ func submit_command(player_id: int, command: PlayerCommand) -> bool:
return true
## Starts the match's drop: plans the barge's route and puts every player aboard.
func start_drop() -> void:
drop = Drop.plan(ground, rng, tick)
for player_id: int in _players:
Drop.board(entities.find(player_id), drop.barge_position(tick))
## Advances the simulation by one tick.
func step() -> void:
for player_id: int in _players:
var queued: Dictionary = _pending[player_id]
var command: PlayerCommand = queued.get(tick)
queued.erase(tick)
_apply_command(entities.find(player_id), command)
var player: SimEntity = entities.find(player_id)
if player.drop_state == Drop.ABOARD:
_ride(player, command)
else:
_apply_command(player, command)
if drop != null and not drop.finished and drop.is_over(tick + 1):
# The end of the route: everyone still aboard goes over the side.
for player_id: int in _players:
var player: SimEntity = entities.find(player_id)
if player.drop_state == Drop.ABOARD:
drop.leap(player, tick + 1)
drop.finished = true
tick += 1
func _apply_command(player: SimEntity, command: PlayerCommand) -> void:
# With no command this tick, the player keeps looking the same way and stands still.
if command == null:
return
## A tick aboard the barge: jump leaps off, anything else rides along.
func _ride(player: SimEntity, command: PlayerCommand) -> void:
if command != null:
player.yaw = command.yaw
player.pitch = command.pitch
if command.is_pressed(PlayerCommand.BUTTON_JUMP):
drop.leap(player, tick)
return
player.position = drop.barge_position(tick + 1)
var move: Vector2 = command.move_vector()
if move.length() > 1.0:
move = move.normalized()
var angle: float = command.yaw_radians()
var forward: Vector3 = Vector3(sin(angle), 0.0, cos(angle))
var right: Vector3 = Vector3(cos(angle), 0.0, -sin(angle))
var speed: float = (
Tuning.SPRINT_SPEED if command.is_pressed(PlayerCommand.BUTTON_SPRINT)
else Tuning.WALK_SPEED
)
var delta: Vector3 = (right * move.x + forward * move.y) * speed * SECONDS_PER_TICK
var size: float = Tuning.WORLD_SIZE_METRES
player.position = (player.position + delta).clamp(Vector3.ZERO, Vector3(size, 0.0, size))
func _apply_command(player: SimEntity, command: PlayerCommand) -> void:
Movement.step(player, command, ground, sea_level)
var sprinting: bool = command != null and command.is_pressed(PlayerCommand.BUTTON_SPRINT)
Water.update(player, sea_level, drown_dps, sprinting)
## Moves the sea surface. Takes effect on the next step.
func set_sea_level(level: float) -> void:
sea_level = level
## Damages a prop. Returns true if this destroyed it; its collision goes at once.
func damage_prop(prop: int, amount: int) -> bool:
return props.damage(prop, amount)
## SHA-256 hex digest of a canonical encoding of the whole state.
@@ -101,11 +165,27 @@ func state_hash() -> String:
buffer.put_32(entity.health)
buffer.put_32(entity.yaw)
buffer.put_32(entity.pitch)
buffer.put_u8((1 if entity.on_ground else 0) | (2 if entity.crouching else 0) | (4 if entity.swimming else 0))
buffer.put_32(entity.breath_ticks)
buffer.put_32(entity.stamina_ticks)
buffer.put_32(entity.drown_ticks)
buffer.put_u8(entity.drop_state)
for value: float in [entity.position.x, entity.position.y, entity.position.z]:
buffer.put_64(roundi(value * 1000.0))
for value: float in [entity.velocity.x, entity.velocity.y, entity.velocity.z]:
buffer.put_64(roundi(value * 1000.0))
if drop != null:
buffer.put_64(drop.began_tick)
buffer.put_64(drop.duration_ticks)
buffer.put_u8(1 if drop.finished else 0)
for value: float in [drop.start.x, drop.start.z, drop.finish.x, drop.finish.z]:
buffer.put_64(roundi(value * 1000.0))
buffer.put_64(roundi(sea_level * 1000.0))
buffer.put_32(drown_dps)
buffer.put_64(props.count())
buffer.put_data(props.health.to_byte_array())
var hasher: HashingContext = HashingContext.new()
hasher.start(HashingContext.HASH_SHA256)
hasher.update(buffer.data_array)
+130
View File
@@ -30,6 +30,136 @@ const SWIM_SPEED: float = 2.0
const CROUCH_SPEED: float = 2.0
const JUMP_VELOCITY: float = 7.5
const GRAVITY: float = 20.0
## Fraction of the gap between current and wanted horizontal velocity closed per tick
## while airborne.
const AIR_CONTROL: float = 0.08
## Ledges up to this height are stepped onto without jumping.
const STEP_HEIGHT: float = 0.45
## Walking keeps the feet on ground that drops away by up to this much per tick.
const GROUND_SNAP: float = 0.35
## Steeper ground can't be walked up or stood on; players slide down it.
const MAX_SLOPE_DEGREES: float = 46.0
## Top speed sliding down ground too steep to stand on.
const SLIDE_MAX_SPEED: float = 8.0
const PLAYER_RADIUS: float = 0.4
const PLAYER_HEIGHT: float = 1.8
const CROUCH_HEIGHT: float = 1.2
## Landing from a drop of this many metres or less does no damage. Measured from impact
## speed, so sliding down a slope is gentler than falling the same height.
const FALL_DAMAGE_SAFE_METRES: float = 6.0
const FALL_DAMAGE_PER_METRE: float = 8.0
# Water, in metres and seconds. Depths are water over the floor under the player.
## The sea level a match starts at. The tide raises it from here.
const SEA_LEVEL_START: float = 0.0
## Deeper than this, walkers wade at WADE_SPEED and can't sprint.
const WADE_DEPTH: float = 0.4
## Water this deep over the floor lifts a player off it to swim.
const SWIM_DEPTH: float = 1.35
## A swimmer stands again where the water over the floor is shallower than this.
const SWIM_EXIT_DEPTH: float = 1.2
## A swimmer floats with the feet this far under the surface, head out.
const SWIM_FLOAT_DEPTH: float = 1.3
## With no stamina left a swimmer sinks until the feet are this far under: head under.
const SWIM_EXHAUSTED_DEPTH: float = 2.2
const SWIM_SPRINT_SPEED: float = 3.2
## Fraction of SWIM_SPEED left to an exhausted swimmer.
const SWIM_EXHAUSTED_FACTOR: float = 0.6
## Diving and rising speed, and how fast vertical speed changes in the water.
const SWIM_VERTICAL_SPEED: float = 2.0
const SWIM_VERTICAL_ACCEL: float = 12.0
## Fraction of downward speed kept on hitting deep water.
const WATER_ENTRY_DAMP: float = 0.25
## Seconds of paddling a full stamina bar allows. Sprint-swimming spends it faster.
const SWIM_STAMINA_SECONDS: float = 45.0
const SWIM_SPRINT_STAMINA_COST: int = 3
## Ticks of stamina and breath regained per tick out of the water or above it.
const STAMINA_RECOVERY_RATE: int = 3
const BREATH_RECOVERY_RATE: int = 4
# The drop, in metres and seconds. The sky barge crosses the island on a straight
# seeded route through a point within BARGE_CENTRE_JITTER of the middle.
const BARGE_ALTITUDE: float = 150.0
const BARGE_SPEED: float = 24.0
## The route starts and ends this far inside the world's edge.
const BARGE_ROUTE_MARGIN: float = 40.0
const BARGE_CENTRE_JITTER: float = 140.0
## Every route crosses at least this much dry land.
const BARGE_MIN_LAND_METRES: float = 250.0
## Fraction of the barge's speed a leaping player keeps.
const LEAP_CARRY: float = 0.4
const FREEFALL_MAX_SPEED: float = 32.0
## Horizontal speed a falling player can steer to, before and after the sail opens.
const FREEFALL_STEER_SPEED: float = 9.0
const GLIDE_SPEED: float = 13.0
## How fast horizontal speed changes while steering a fall, in metres per second squared.
const DROP_STEER_ACCEL: float = 20.0
## Sink rate under an open wing-sail, and how hard opening it brakes the fall.
const GLIDE_FALL_SPEED: float = 5.5
const GLIDE_BRAKE: float = 60.0
## The sail opens by itself this high above the ground or water.
const WING_AUTO_DEPLOY_HEIGHT: float = 40.0
## Within this height of the ground or water, the sail folds and the player drops the rest.
const DROP_LAND_HANDOFF: float = 1.0
# The island. Worldgen fills the whole world square; the island is about a kilometre
# across, sized for 24 players. Heights are metres above the starting sea level.
## Spacing of the terrain heightfield, in metres. The grid covers WORLD_SIZE_METRES.
const ISLAND_GRID_METRES: float = 2.0
## Mean distance from the world centre to the coast, before the coastline is warped.
const ISLAND_RADIUS_METRES: float = 400.0
const ISLAND_MIN_SUMMITS: int = 2
const ISLAND_MAX_SUMMITS: int = 4
## Summits are at least this far apart, so each one is a separate fight.
const ISLAND_SUMMIT_SPACING_METRES: float = 220.0
## The tallest summit lands between these heights. Both stay under ISLAND_MAX_HEIGHT.
const ISLAND_PEAK_MIN: float = 58.0
const ISLAND_PEAK_MAX: float = 67.0
## The open sea floor, in metres below the starting sea.
const ISLAND_SEA_DEPTH: float = 12.0
## Elevation bands, by height above the starting sea. Marsh is wet flat ground below
## ISLAND_MARSH_TOP; land from there up to ISLAND_FOREST_TOP is forest, then highland,
## and anything at or above ISLAND_SUMMIT_BAND is summit ground.
const ISLAND_BEACH_TOP: float = 2.5
const ISLAND_MARSH_TOP: float = 7.0
const ISLAND_FOREST_TOP: float = 32.0
const ISLAND_SUMMIT_BAND: float = 50.0
# Points of interest. Each kind places between its min and max on every island, and the
# total always lands between POI_MIN_TOTAL and POI_MAX_TOTAL.
const POI_KINDS: Dictionary = {
"shrine": {"min": 2, "max": 3},
"lighthouse": {"min": 1, "max": 2},
"dock": {"min": 2, "max": 3},
"salt_works": {"min": 1, "max": 2},
"quarry": {"min": 1, "max": 2},
"hamlet": {"min": 3, "max": 4},
}
const POI_MIN_TOTAL: int = 10
const POI_MAX_TOTAL: int = 16
## No two points of interest are closer than this, centre to centre.
const POI_SPACING_METRES: float = 85.0
# Props: trees, scrub, boulders, wrecks and crates scattered over the island. Each kind
# has health, the material it gives when harvested, and a collision footprint range in
# metres (`width` x `height`; wrecks are `length` long). Density is props per hectare
# in each elevation band; groves and clearings modulate it.
const PROP_KINDS: Dictionary = {
"pine": {"health": 200, "material": "driftwood", "width": [0.5, 0.7], "height": [7.0, 12.0]},
"scrub": {"health": 60, "material": "driftwood", "width": [1.1, 1.8], "height": [0.8, 1.3]},
"boulder": {"health": 400, "material": "stone", "width": [1.6, 3.4], "height": [1.0, 2.4]},
"wreck": {"health": 500, "material": "salvage_iron", "width": [2.2, 2.8], "height": [1.4, 2.0], "length": [5.5, 8.0]},
"crate": {"health": 80, "material": "driftwood", "width": [0.9, 1.2], "height": [0.9, 1.2]},
}
const PROP_DENSITY: Dictionary = {
"beach": {"wreck": 5.0, "crate": 6.0, "scrub": 2.0},
"marsh": {"scrub": 30.0, "crate": 1.0, "boulder": 1.0},
"forest": {"pine": 70.0, "scrub": 16.0, "boulder": 4.0, "crate": 0.3},
"highland": {"pine": 14.0, "boulder": 16.0, "scrub": 10.0},
"summit": {"boulder": 10.0, "scrub": 3.0},
}
## Props keep this far from any point-of-interest solid, loot marker or walking route.
const PROP_POI_CLEARANCE: float = 3.0
# The tide. `hold` and `rise` are seconds, `level` is metres above the starting sea,
# `drown_dps` is damage per second underwater once breath runs out. The last level
+71
View File
@@ -0,0 +1,71 @@
## The sea as the simulation sees it: one global level that the tide (M2) raises during
## a match, and what it does to players. Movement handles swimming itself; this keeps
## breath, stamina and drowning, and answers depth questions.
##
## Depths and states, for a player whose feet are at `y` over a floor at `floor`:
## - wading: on the floor in water deeper than WADE_DEPTH. Slower, no sprint.
## - swimming: water at least SWIM_DEPTH over the floor, so the player floats with the
## head above the surface (feet SWIM_FLOAT_DEPTH under it). Swimming costs stamina;
## with none left the player can't stay up and slips under.
## - under: head below the surface. Breath runs down; at zero the phase's drown damage
## lands once a second until the head is out again.
## Breath and stamina are counted in whole ticks, so they hash and replay exactly.
class_name Water
extends RefCounted
const TICKS: int = Tuning.TICK_RATE_HZ
## Water depth over a floor at `floor_y`, or 0 on dry ground.
static func depth_over(sea_level: float, floor_y: float) -> float:
return maxf(sea_level - floor_y, 0.0)
## True when the water over `floor_y` is deep enough to swim in.
static func is_deep(sea_level: float, floor_y: float) -> bool:
return sea_level - floor_y >= Tuning.SWIM_DEPTH
static func head_under(player: SimEntity, sea_level: float) -> bool:
return player.position.y + Movement.body_height(player) < sea_level
static func max_breath_ticks() -> int:
return roundi(Tuning.BREATH_SECONDS * TICKS)
static func max_stamina_ticks() -> int:
return roundi(Tuning.SWIM_STAMINA_SECONDS * TICKS)
## Gives a new player full breath and stamina.
static func reset(player: SimEntity) -> void:
player.breath_ticks = max_breath_ticks()
player.stamina_ticks = max_stamina_ticks()
player.drown_ticks = 0
## Updates breath, stamina and drowning for one tick, after the player has moved.
## `sprinting` is whether the player asked to swim fast this tick.
static func update(player: SimEntity, sea_level: float, drown_dps: int, sprinting: bool) -> void:
if player.health <= 0:
return
# Stamina: swimming drains it, faster when sprinting; out of the water it returns.
if player.swimming:
var cost: int = Tuning.SWIM_SPRINT_STAMINA_COST if sprinting else 1
player.stamina_ticks = maxi(player.stamina_ticks - cost, 0)
else:
player.stamina_ticks = mini(player.stamina_ticks + Tuning.STAMINA_RECOVERY_RATE, max_stamina_ticks())
if head_under(player, sea_level):
if player.breath_ticks > 0:
player.breath_ticks -= 1
player.drown_ticks = 0
else:
player.drown_ticks += 1
if player.drown_ticks >= TICKS:
player.drown_ticks = 0
player.health = maxi(player.health - drown_dps, 0)
else:
player.drown_ticks = 0
player.breath_ticks = mini(player.breath_ticks + Tuning.BREATH_RECOVERY_RATE, max_breath_ticks())
+1
View File
@@ -0,0 +1 @@
uid://c7e4vegn1qf4y
+6
View File
@@ -0,0 +1,6 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/camera_scene.gd" id="1"]
[node name="CaptureCamera" type="Node3D"]
script = ExtResource("1")
+8
View File
@@ -0,0 +1,8 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/camera_scene.gd" id="1"]
[node name="CaptureCameraAim" type="Node3D"]
script = ExtResource("1")
yaw_degrees = 20.0
aiming = true
+26
View File
@@ -0,0 +1,26 @@
## Capture scenario for the third-person camera: the shore scene with a stand-in player,
## viewed through PlayerCamera and CameraRig as in the game.
extends "res://test/capture/smoke_scene.gd"
@export var feet: Vector3 = Vector3(1.0, 0.0, 0.5)
@export var yaw_degrees: float = 0.0
@export var pitch_degrees: float = -8.0
@export var aiming: bool = false
func _add_camera() -> void:
var body: CapsuleMesh = CapsuleMesh.new()
body.radius = Tuning.PLAYER_RADIUS
body.height = Tuning.PLAYER_HEIGHT
_place(body, feet + Vector3.UP * Tuning.PLAYER_HEIGHT * 0.5, Color(0.2, 0.42, 0.36))
var camera: PlayerCamera = PlayerCamera.new()
camera.ground = ground
camera.target_feet = feet
camera.yaw = deg_to_rad(yaw_degrees)
camera.pitch = deg_to_rad(pitch_degrees)
camera.aiming = aiming
if aiming:
camera.rig.aim_blend = 1.0
add_child(camera)
camera.make_current()
camera.snap()
+1
View File
@@ -0,0 +1 @@
uid://cxokowai701cm
+9
View File
@@ -0,0 +1,9 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/camera_scene.gd" id="1"]
[node name="CaptureCameraWall" type="Node3D"]
script = ExtResource("1")
feet = Vector3(-1.5, 0, 2.4)
yaw_degrees = 180.0
pitch_degrees = -5.0
+8
View File
@@ -0,0 +1,8 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CapturePoi" type="Node3D"]
script = ExtResource("1")
poi_kind = "dock"
poi_view = Vector3(16, 8, 4)
+7
View File
@@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CapturePoi" type="Node3D"]
script = ExtResource("1")
poi_kind = "hamlet"
+8
View File
@@ -0,0 +1,8 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CapturePoi" type="Node3D"]
script = ExtResource("1")
poi_kind = "lighthouse"
poi_view = Vector3(10, 9, 30)
+8
View File
@@ -0,0 +1,8 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CapturePoi" type="Node3D"]
script = ExtResource("1")
poi_kind = "quarry"
poi_view = Vector3(10, 12, 30)
+8
View File
@@ -0,0 +1,8 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CapturePoi" type="Node3D"]
script = ExtResource("1")
poi_kind = "salt_works"
poi_view = Vector3(10, 12, 30)
+8
View File
@@ -0,0 +1,8 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CapturePoi" type="Node3D"]
script = ExtResource("1")
poi_kind = "shrine"
poi_view = Vector3(10, 12, 30)
+10
View File
@@ -0,0 +1,10 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CaptureProps" type="Node3D"]
script = ExtResource("1")
island_seed = 2
prop_kind = "wreck"
prop_crowd = 1
prop_view = Vector3(9, 4, 9)
+10
View File
@@ -0,0 +1,10 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CaptureProps" type="Node3D"]
script = ExtResource("1")
island_seed = 2
prop_kind = "crate"
prop_crowd = 2
prop_view = Vector3(5, 2.5, 6)
+11
View File
@@ -0,0 +1,11 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CaptureProps" type="Node3D"]
script = ExtResource("1")
island_seed = 2
prop_kind = "pine"
prop_crowd = 30
prop_view = Vector3(-20, 7, 28)
knock_out = 2
+10
View File
@@ -0,0 +1,10 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CaptureProps" type="Node3D"]
script = ExtResource("1")
island_seed = 2
prop_kind = "pine"
prop_crowd = 30
prop_view = Vector3(-20, 7, 28)
+10
View File
@@ -0,0 +1,10 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CaptureProps" type="Node3D"]
script = ExtResource("1")
island_seed = 2
prop_kind = "boulder"
prop_crowd = 6
prop_view = Vector3(4, 2.2, 5)
+8
View File
@@ -0,0 +1,8 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CaptureProps" type="Node3D"]
script = ExtResource("1")
island_seed = 2
show_props = true
+11
View File
@@ -2,6 +2,9 @@
## post, under a procedural sky. Everything is built in code, so there are no assets.
extends Node3D
## The solid shape of the scene, for scenarios that need collision (the camera rig).
var ground: SimGround = SimGround.flat(0.0)
func _ready() -> void:
var environment: Environment = Environment.new()
@@ -35,6 +38,11 @@ func _ready() -> void:
_cylinder(0.35, 5.0, Vector3(5.0, 2.5, -2.0), Color(0.55, 0.36, 0.22))
_cylinder(0.6, 0.8, Vector3(5.0, 5.4, -2.0), Color(0.72, 0.22, 0.18))
_add_camera()
## Override to view the scene differently.
func _add_camera() -> void:
var camera: Camera3D = Camera3D.new()
camera.position = Vector3(-6.0, 6.0, -16.0)
add_child(camera)
@@ -46,9 +54,12 @@ func _box(size: Vector3, at: Vector3, colour: Color) -> void:
var mesh: BoxMesh = BoxMesh.new()
mesh.size = size
_place(mesh, at, colour)
if at.y + size.y * 0.5 > 0.0:
ground.add_solid(AABB(at - size * 0.5, size))
func _cylinder(radius: float, height: float, at: Vector3, colour: Color) -> void:
ground.add_solid(AABB(at - Vector3(radius, height * 0.5, radius), Vector3(radius * 2.0, height, radius * 2.0)))
var mesh: CylinderMesh = CylinderMesh.new()
mesh.top_radius = radius
mesh.bottom_radius = radius
+6
View File
@@ -0,0 +1,6 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CaptureTerrain" type="Node3D"]
script = ExtResource("1")
+11
View File
@@ -0,0 +1,11 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CaptureTerrainCracks" type="Node3D"]
script = ExtResource("1")
eye = Vector2(520, 640)
lift = 160.0
target = Vector3(520, 20, 470)
crack_check = true
fov = 60.0
+12
View File
@@ -0,0 +1,12 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CaptureTerrainCracksControl" type="Node3D"]
script = ExtResource("1")
eye = Vector2(520, 640)
lift = 160.0
target = Vector3(520, 20, 470)
crack_check = true
fov = 60.0
skirts = false
+10
View File
@@ -0,0 +1,10 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CaptureTerrainLod" type="Node3D"]
script = ExtResource("1")
eye = Vector2(560, 700)
lift = 140.0
target = Vector3(520, 20, 430)
show_lod = true
+133
View File
@@ -0,0 +1,133 @@
## Capture scenario for the streamed island terrain. The camera stands `lift` metres above
## the ground at `eye` (x, z) and looks at `target`. With `crack_check` the sky is a flat
## magenta that appears nowhere in the terrain, so any crack between chunks shows up as
## magenta pixels for tools/crack_check.gd to count.
extends Node3D
const CRACK_COLOUR: Color = Color(1.0, 0.0, 1.0)
@export var island_seed: int = 2
@export var eye: Vector2 = Vector2(700.0, 760.0)
@export var lift: float = 12.0
@export var target: Vector3 = Vector3(520.0, 35.0, 470.0)
@export var show_lod: bool = false
@export var crack_check: bool = false
@export var fov: float = 70.0
## Off only in terrain_cracks_control, which must show cracks.
@export var skirts: bool = true
## When set, draw the island's points of interest and frame the first one of this kind:
## the camera stands `poi_view` (x right, y up, z out of the front) from its origin.
@export var poi_kind: String = ""
@export var poi_view: Vector3 = Vector3(6.0, 7.0, 22.0)
## Draw the sea at `sea_level`. Never in crack checks, where it would hide seams.
@export var show_water: bool = true
@export var sea_level: float = Tuning.SEA_LEVEL_START
## Draw the island's props too.
@export var show_props: bool = false
## When set, frame the first prop of this kind whose surroundings hold at least
## `prop_crowd` others within 25 m: the camera stands `prop_view` from it (x east, y up,
## z south) and looks at it.
@export var prop_kind: String = ""
@export var prop_crowd: int = 0
@export var prop_view: Vector3 = Vector3(10.0, 4.0, 14.0)
## Destroy every `knock_out`th prop near the framed one, to show felled props vanish.
@export var knock_out: int = 0
func _ready() -> void:
var island: Island = Island.generate(island_seed)
var environment: Environment = Environment.new()
if crack_check:
environment.background_mode = Environment.BG_COLOR
environment.background_color = CRACK_COLOUR
environment.ambient_light_source = Environment.AMBIENT_SOURCE_COLOR
environment.ambient_light_color = Color(0.5, 0.5, 0.5)
environment.tonemap_mode = Environment.TONE_MAPPER_LINEAR
else:
var sky_material: ProceduralSkyMaterial = ProceduralSkyMaterial.new()
sky_material.sky_top_color = Color(0.32, 0.5, 0.68)
sky_material.sky_horizon_color = Color(0.82, 0.78, 0.68)
sky_material.ground_bottom_color = Color(0.18, 0.2, 0.2)
sky_material.ground_horizon_color = Color(0.82, 0.78, 0.68)
var sky: Sky = Sky.new()
sky.sky_material = sky_material
environment.background_mode = Environment.BG_SKY
environment.sky = sky
environment.ambient_light_source = Environment.AMBIENT_SOURCE_SKY
environment.ambient_light_energy = 0.45
environment.tonemap_mode = Environment.TONE_MAPPER_FILMIC
environment.fog_enabled = true
environment.fog_light_color = Color(0.78, 0.78, 0.74)
environment.fog_density = 0.0005
environment.fog_aerial_perspective = 0.4
var world: WorldEnvironment = WorldEnvironment.new()
world.environment = environment
add_child(world)
var sun: DirectionalLight3D = DirectionalLight3D.new()
sun.rotation_degrees = Vector3(-35.0, -130.0, 0.0)
sun.light_energy = 0.95
sun.shadow_enabled = not crack_check
sun.directional_shadow_max_distance = 600.0
add_child(sun)
var camera: Camera3D = Camera3D.new()
camera.fov = fov
camera.far = 2000.0
camera.position = Vector3(eye.x, island.ground.terrain_height(eye.x, eye.y) + lift, eye.y)
var look_at_point: Vector3 = target
if not poi_kind.is_empty():
var placed: PoiSet = PoiSet.generate(island)
var view: PoiView = PoiView.new()
view.setup(placed)
add_child(view)
for poi: Poi in placed.pois:
if poi.kind == poi_kind:
camera.position = poi.to_world(poi_view)
camera.position.y = maxf(camera.position.y, island.ground.terrain_height(camera.position.x, camera.position.z) + 2.0)
look_at_point = poi.origin + Vector3.UP * 2.5
break
if show_props or not prop_kind.is_empty():
var sim_props: PropSet = PropSet.generate(island, PoiSet.generate(island))
var prop_view_node: PropView = PropView.new()
prop_view_node.setup(sim_props)
add_child(prop_view_node)
if not prop_kind.is_empty():
for prop: int in sim_props.count():
if sim_props.kind_name(prop) != prop_kind:
continue
var at: Vector3 = sim_props.boxes[prop].get_center()
var crowd: PackedInt32Array = sim_props.near(at, 25.0)
if crowd.size() <= prop_crowd:
continue
var base: Vector3 = Vector3(at.x, island.ground.terrain_height(at.x, at.z), at.z)
# Back away along the view offset until no canopy is in the camera's face.
var offset: Vector3 = prop_view
for _try: int in 12:
camera.position = base + offset
camera.position.y = maxf(camera.position.y, island.ground.terrain_height(camera.position.x, camera.position.z) + 1.6)
if sim_props.near(Vector3(camera.position.x, island.ground.terrain_height(camera.position.x, camera.position.z), camera.position.z), 6.0).is_empty():
break
offset *= 1.15
look_at_point = base + Vector3.UP * minf(sim_props.boxes[prop].size.y * 0.5, 3.0)
if knock_out > 0:
for index: int in crowd.size():
if index % knock_out == 1:
sim_props.damage(crowd[index], 100000)
prop_view_node.sync()
break
if show_water and not crack_check:
var water: WaterView = WaterView.new()
water.set_level(sea_level)
add_child(water)
add_child(camera)
camera.look_at(look_at_point)
camera.make_current()
var terrain: TerrainView = TerrainView.new()
terrain.setup(island)
terrain.focus = camera.position
terrain.show_lod = show_lod
terrain.skirts = skirts
add_child(terrain)
terrain.build_all_now()
+1
View File
@@ -0,0 +1 @@
uid://bcc26uufsyxi8
+9
View File
@@ -0,0 +1,9 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CaptureWater" type="Node3D"]
script = ExtResource("1")
island_seed = 2
show_props = true
sea_level = 18.0
+10
View File
@@ -0,0 +1,10 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"]
[node name="CaptureWater" type="Node3D"]
script = ExtResource("1")
island_seed = 2
show_props = true
poi_kind = "dock"
poi_view = Vector3(-18, 9, 26)
+134
View File
@@ -0,0 +1,134 @@
extends TestCase
const ASPECT: float = 16.0 / 9.0
func test_open_ground_places_camera_behind_and_right() -> void:
var rig: CameraRig = CameraRig.new()
var feet: Vector3 = Vector3(100.0, 0.0, 100.0)
var view: Transform3D = rig.solve(feet, 0.0, 0.0, false, SimGround.flat())
var pivot: Vector3 = CameraRig.pivot(feet, false)
# Yaw 0 faces +z, so the camera sits on -z, and screen-right is -x.
var expected: Vector3 = pivot + Vector3(-CameraRig.SHOULDER, 0.0, -CameraRig.DISTANCE)
assert_true(view.origin.distance_to(expected) < 0.001, "camera at %s" % view.origin)
assert_true((-view.basis.z).distance_to(Vector3(0.0, 0.0, 1.0)) < 0.001, "camera must look along +z")
func test_strafing_right_moves_towards_screen_right() -> void:
for yaw: float in [0.0, 1.0, 2.5, 4.0, 5.5]:
var view: Transform3D = CameraRig.new().solve(Vector3(500.0, 0.0, 500.0), yaw, 0.0, false, SimGround.flat())
var player: SimEntity = SimEntity.new(1, SimEntity.ARCHETYPE_PLAYER)
player.position = Vector3(500.0, 0.0, 500.0)
player.on_ground = true
Movement.step(player, PlayerCommand.from_input(0, Vector2(1.0, 0.0), yaw, 0.0), SimGround.flat())
var moved: Vector3 = (player.position - Vector3(500.0, 0.0, 500.0)).normalized()
assert_true(moved.dot(view.basis.x) > 0.99, "yaw %f: strafe right went %s" % [yaw, moved])
# And walking forward goes where the camera looks.
var walker: SimEntity = SimEntity.new(2, SimEntity.ARCHETYPE_PLAYER)
walker.position = Vector3(500.0, 0.0, 500.0)
walker.on_ground = true
Movement.step(walker, PlayerCommand.from_input(0, Vector2(0.0, 1.0), yaw, 0.0), SimGround.flat())
var ahead: Vector3 = (walker.position - Vector3(500.0, 0.0, 500.0)).normalized()
assert_true(ahead.dot(-view.basis.z) > 0.99, "yaw %f: forward went %s" % [yaw, ahead])
func test_aiming_pulls_in_and_narrows() -> void:
var rig: CameraRig = CameraRig.new()
var feet: Vector3 = Vector3(100.0, 0.0, 100.0)
var hip: Transform3D = rig.solve(feet, 0.0, 0.0, false, SimGround.flat())
assert_eq(rig.fov(), CameraRig.FOV)
for _index: int in 60:
rig.update_aim(true, 1.0 / 60.0)
assert_eq(rig.aim_blend, 1.0)
var aimed: Transform3D = rig.solve(feet, 0.0, 0.0, false, SimGround.flat())
var pivot: Vector3 = CameraRig.pivot(feet, false)
assert_true(aimed.origin.distance_to(pivot) < hip.origin.distance_to(pivot))
assert_eq(rig.fov(), CameraRig.AIM_FOV)
rig.update_aim(false, 0.05)
assert_true(rig.aim_blend > 0.0 and rig.aim_blend < 1.0, "aim should ease, not snap")
func test_wall_behind_pulls_the_camera_in() -> void:
var ground: SimGround = SimGround.flat()
ground.add_solid(AABB(Vector3(90.0, 0.0, 98.0), Vector3(20.0, 4.0, 1.0)))
var view: Transform3D = CameraRig.new().solve(Vector3(100.0, 0.0, 100.0), 0.0, 0.0, false, ground)
assert_true(view.origin.z > 99.0 + CameraRig.CLEARANCE - 0.001, "camera at z %f is in the wall" % view.origin.z)
func test_scripted_sweep_never_clips() -> void:
var checked: int = 0
for arena: Array in _arenas():
var ground: SimGround = arena[0]
var feet: Vector3 = arena[1]
for crouching: bool in [false, true]:
for blend: float in [0.0, 1.0]:
var rig: CameraRig = CameraRig.new()
rig.aim_blend = blend
for yaw_step: int in 72:
for pitch_step: int in 17:
var yaw: float = yaw_step * TAU / 72.0
var pitch: float = deg_to_rad(-80.0 + pitch_step * 10.0)
var view: Transform3D = rig.solve(feet, yaw, pitch, crouching, ground)
var problem: String = _clipping(ground, view, rig.fov(), CameraRig.pivot(feet, crouching))
checked += 1
if not problem.is_empty():
fail("%s at yaw %d° pitch %d° crouch %s aim %s: %s" % [
arena[2], roundi(rad_to_deg(yaw)), roundi(rad_to_deg(pitch)),
crouching, blend, problem,
])
return
assert_eq(checked, 5 * 2 * 2 * 72 * 17)
## Returns why a view clips, or "" if it doesn't: the eye or a near-plane corner is
## inside geometry, or the line from the pivot to the eye passes through it.
func _clipping(ground: SimGround, view: Transform3D, fov_degrees: float, pivot: Vector3) -> String:
if ground.point_inside(view.origin):
return "eye inside geometry at %s" % view.origin
var half_height: float = CameraRig.NEAR * tan(deg_to_rad(fov_degrees) * 0.5)
var half_width: float = half_height * ASPECT
var centre: Vector3 = view.origin - view.basis.z * CameraRig.NEAR
for sx: float in [-1.0, 1.0]:
for sy: float in [-1.0, 1.0]:
var corner: Vector3 = centre + view.basis.x * half_width * sx + view.basis.y * half_height * sy
if ground.point_inside(corner):
return "near-plane corner inside geometry at %s" % corner
if ground.raycast(pivot, view.origin) < 1.0:
return "line of sight from the pivot is blocked"
return ""
## [ground, feet, name] for each place the sweep is run.
func _arenas() -> Array[Array]:
var arenas: Array[Array] = []
var wall: SimGround = SimGround.flat()
wall.add_solid(AABB(Vector3(90.0, 0.0, 100.0 + Tuning.PLAYER_RADIUS), Vector3(20.0, 4.0, 0.5)))
arenas.append([wall, Vector3(100.0, 0.0, 100.0), "against a wall"])
var corridor: SimGround = SimGround.flat()
corridor.add_solid(AABB(Vector3(98.0, 0.0, 80.0), Vector3(1.5, 4.0, 40.0)))
corridor.add_solid(AABB(Vector3(100.5, 0.0, 80.0), Vector3(1.5, 4.0, 40.0)))
arenas.append([corridor, Vector3(100.0, 0.0, 100.0), "in a narrow corridor"])
var roof: SimGround = SimGround.flat()
roof.add_solid(AABB(Vector3(90.0, 2.2, 90.0), Vector3(20.0, 0.3, 20.0)))
arenas.append([roof, Vector3(100.0, 0.0, 100.0), "under a low roof"])
var corner: SimGround = SimGround.flat()
corner.add_solid(AABB(Vector3(100.5, 0.0, 90.0), Vector3(3.0, 4.0, 20.0)))
corner.add_solid(AABB(Vector3(90.0, 0.0, 100.5), Vector3(20.0, 4.0, 3.0)))
arenas.append([corner, Vector3(100.0, 0.0, 100.0), "in a corner"])
var side: int = 64
var values: PackedFloat32Array = PackedFloat32Array()
values.resize(side * side)
for z: int in side:
for x: int in side:
# A steep bank rising to the east, with ripples.
values[z * side + x] = maxf(float(x) - 30.0, 0.0) * 1.8 + 0.4 * sin(z * 0.9)
var hill: SimGround = SimGround.from_heights(values, side, 1.0)
var foot: Vector3 = Vector3(29.6, 0.0, 32.0)
foot.y = hill.terrain_height(foot.x, foot.z)
arenas.append([hill, foot, "at the foot of a steep bank"])
return arenas
+1
View File
@@ -0,0 +1 @@
uid://dsempouxfbdom
+68
View File
@@ -0,0 +1,68 @@
extends TestCase
const PATH: String = "user://test_input_settings.cfg"
func after_each() -> void:
if FileAccess.file_exists(PATH):
DirAccess.remove_absolute(ProjectSettings.globalize_path(PATH))
func test_sensitivity_scales_turning() -> void:
var settings: InputSettings = InputSettings.new()
var slow: Vector2 = settings.apply_mouse(Vector2(100.0, 0.0), 1.0, 0.0, false)
settings.mouse_sensitivity = 2.0
var fast: Vector2 = settings.apply_mouse(Vector2(100.0, 0.0), 1.0, 0.0, false)
assert_near(1.0 - slow.x, 100.0 * InputSettings.RADIANS_PER_PIXEL, 0.00001)
assert_near(1.0 - fast.x, 2.0 * (1.0 - slow.x), 0.00001)
func test_mouse_right_turns_right_and_up_looks_up() -> void:
var settings: InputSettings = InputSettings.new()
var look: Vector2 = settings.apply_mouse(Vector2(10.0, -10.0), 1.0, 0.0, false)
assert_true(look.x < 1.0, "turning right decreases yaw")
assert_true(look.y > 0.0, "mouse up looks up")
settings.invert_y = true
assert_true(settings.apply_mouse(Vector2(0.0, -10.0), 1.0, 0.0, false).y < 0.0)
func test_aiming_slows_the_mouse() -> void:
var settings: InputSettings = InputSettings.new()
var hip: Vector2 = settings.apply_mouse(Vector2(50.0, 0.0), 1.0, 0.0, false)
var aimed: Vector2 = settings.apply_mouse(Vector2(50.0, 0.0), 1.0, 0.0, true)
assert_near(1.0 - aimed.x, (1.0 - hip.x) * settings.aim_sensitivity_scale, 0.00001)
func test_pitch_is_clamped_and_yaw_wraps() -> void:
var settings: InputSettings = InputSettings.new()
var look: Vector2 = settings.apply_mouse(Vector2(-10.0, -100000.0), TAU - 0.001, 0.0, false)
assert_near(look.y, InputSettings.PITCH_LIMIT, 0.00001)
assert_true(look.x >= 0.0 and look.x < TAU)
func test_sensitivity_is_clamped() -> void:
var settings: InputSettings = InputSettings.new()
settings.mouse_sensitivity = 0.0
assert_eq(settings.mouse_sensitivity, InputSettings.MIN_SENSITIVITY)
settings.mouse_sensitivity = 1000.0
assert_eq(settings.mouse_sensitivity, InputSettings.MAX_SENSITIVITY)
func test_settings_round_trip_through_the_config_file() -> void:
var settings: InputSettings = InputSettings.new()
settings.mouse_sensitivity = 2.75
settings.aim_sensitivity_scale = 0.4
settings.invert_y = true
assert_eq(settings.save(PATH), OK)
var loaded: InputSettings = InputSettings.load_from(PATH)
assert_near(loaded.mouse_sensitivity, 2.75, 0.0001)
assert_near(loaded.aim_sensitivity_scale, 0.4, 0.0001)
assert_true(loaded.invert_y)
func test_missing_or_bad_file_gives_defaults() -> void:
assert_eq(InputSettings.load_from("user://does_not_exist.cfg").mouse_sensitivity, 1.0)
var config: ConfigFile = ConfigFile.new()
config.set_value(InputSettings.SECTION, "mouse_sensitivity", "fast")
config.save(PATH)
assert_eq(InputSettings.load_from(PATH).mouse_sensitivity, 1.0)
+1
View File
@@ -0,0 +1 @@
uid://c517c7silhnhv
+125
View File
@@ -0,0 +1,125 @@
extends TestCase
## The client side of W5: PropView draws every prop, matches collision, hides felled
## props cheaply, and keeps the draw-call count bounded.
const SEED: int = 2
var _island: Island
var _props: PropSet
func before_each() -> void:
if _island == null:
_island = Island.generate(SEED)
_props = PropSet.generate(_island, PoiSet.generate(_island))
func test_every_prop_has_exactly_one_instance() -> void:
var view: PropView = PropView.new()
view.setup(_props)
var seen: Dictionary = {}
var total: int = 0
for child: Node in view.get_children():
total += (child as MultiMeshInstance3D).multimesh.instance_count
assert_eq(total, _props.count())
assert_eq(view.drawn, _props.count())
for prop: int in _props.count():
var key: Vector2i = Vector2i(view.node_for(prop).get_index(), view.instance_index(prop))
assert_false(seen.has(key), "two props share an instance")
seen[key] = true
assert_true(view.node_for(prop).name.begins_with(_props.kind_name(prop)), "prop %d is drawn as the wrong kind" % prop)
view.free()
func test_instances_fit_their_collision_boxes() -> void:
# The unit meshes span -0.5..0.5 and 0..1, so the transformed footprint must match
# the box the simulation collides with (pines' canopies excepted: only the trunk).
for prop: int in _props.count():
var box: AABB = _props.boxes[prop]
var xf: Transform3D = PropView.instance_transform(_props, prop)
assert_near(xf.origin.y, box.position.y, 0.001)
assert_near(xf.origin.x, box.get_center().x, 0.001)
assert_near(xf.origin.z, box.get_center().z, 0.001)
var top: Vector3 = xf * Vector3(0.0, 1.0, 0.0)
assert_near(top.y, box.end.y, 0.001, "prop %d height" % prop)
# Round kinds are checked around their rim, boxy ones at their corners.
var outline: Array[Vector3] = [Vector3(0.5, 0.0, 0.5), Vector3(-0.5, 0.0, 0.5), Vector3(0.5, 0.0, -0.5), Vector3(-0.5, 0.0, -0.5)]
if _props.kind_name(prop) in ["pine", "scrub", "boulder"]:
outline.clear()
for step: int in 12:
outline.append(Vector3(cos(TAU * step / 12.0), 0.0, sin(TAU * step / 12.0)) * 0.5)
for corner: Vector3 in outline:
var at: Vector3 = xf * corner
var spill: float = maxf(maxf(box.position.x - at.x, at.x - box.end.x), maxf(box.position.z - at.z, at.z - box.end.z))
# Crates may turn up to 8 degrees, which pushes a corner out by about 10%.
var allowed: float = 0.12 * maxf(box.size.x, box.size.z) if _props.kind_name(prop) == "crate" else 0.01
assert_true(spill <= allowed, "%s %d footprint spills %.2f m past its box" % [_props.kind_name(prop), prop, spill])
func test_meshes_face_outwards_and_stay_in_the_unit_footprint() -> void:
for kind: String in PropSet.KINDS:
var mesh: ArrayMesh = PropView.build_mesh(kind)
var arrays: Array = mesh.surface_get_arrays(0)
var vertices: PackedVector3Array = arrays[Mesh.ARRAY_VERTEX]
var normals: PackedVector3Array = arrays[Mesh.ARRAY_NORMAL]
assert_true(vertices.size() >= 36, kind + " has too few vertices")
var bounds: AABB = AABB(vertices[0], Vector3.ZERO)
var centre: Vector3 = Vector3.ZERO
for vertex: Vector3 in vertices:
bounds = bounds.expand(vertex)
centre += vertex
centre /= vertices.size()
assert_true(bounds.position.y >= -0.001 and bounds.end.y <= 1.001, "%s spans y %s" % [kind, bounds])
if kind != "pine":
assert_true(bounds.position.x >= -0.501 and bounds.end.x <= 0.501, "%s spans x %s" % [kind, bounds])
assert_true(bounds.position.z >= -0.501 and bounds.end.z <= 0.501, "%s spans z %s" % [kind, bounds])
# Most faces point away from the middle; inside-out winding would flip this.
var outward: int = 0
for index: int in vertices.size():
if normals[index].dot(vertices[index] - centre) > 0.0:
outward += 1
assert_true(outward > vertices.size() * 0.6, "%s: only %d of %d normals face out" % [kind, outward, vertices.size()])
func test_felled_props_vanish_and_the_rest_stay() -> void:
var view: PropView = PropView.new()
view.setup(_props)
var victims: Array[int] = [0, 17, _props.count() - 1]
for prop: int in victims:
while _props.is_standing(prop):
_props.damage(prop, 1000)
assert_eq(view.sync(), victims.size())
assert_eq(view.sync(), 0, "a second sync has nothing new")
assert_eq(view.drawn, _props.count() - victims.size())
assert_eq(view.hidden_count, victims.size())
for prop: int in [0, 1, 17, 18, _props.count() - 1]:
assert_eq(view.is_drawn(prop), not victims.has(prop))
view.free()
func test_draw_calls_and_main_thread_cost_stay_bounded() -> void:
# Software rendering can't time the GPU. What can be checked here: the number of
# instanced draws is bounded by culling squares times kinds, every draw has a
# visibility range, building takes a loading-screen moment, and applying a burst of
# destruction costs well under a millisecond of the frame.
var started: int = Time.get_ticks_usec()
var view: PropView = PropView.new()
view.setup(_props)
var build_ms: int = (Time.get_ticks_usec() - started) / 1000
var squares: int = ceili(Tuning.WORLD_SIZE_METRES / PropView.CHUNK)
assert_true(view.node_count() <= squares * squares * PropSet.KINDS.size())
assert_true(view.node_count() < _props.count() / 10, "%d draws for %d props" % [view.node_count(), _props.count()])
for child: Node in view.get_children():
var instance: MultiMeshInstance3D = child
assert_true(instance.visibility_range_end > 0.0 and instance.visibility_range_end <= 600.0, instance.name)
var burst: int = 0
for prop: int in range(0, _props.count(), 60):
_props.damage(prop, 100000)
burst += 1
view.sync()
print(" prop view: %d props in %d draws, built in %d ms, %d-prop destruction sync %d us"
% [_props.count(), view.node_count(), build_ms, burst, view.last_sync_usec])
assert_true(build_ms < 4000, "setup took %d ms" % build_ms)
assert_true(view.last_sync_usec < 1000, "sync of %d felled props took %d us" % [burst, view.last_sync_usec])
view.free()
+1
View File
@@ -0,0 +1 @@
uid://cd4w660y6qjeg
+132
View File
@@ -0,0 +1,132 @@
extends TestCase
const SEED: int = 2
## The streaming budget from issue W3: no frame's terrain work may exceed this.
const FRAME_SPIKE_USEC: int = 8_000
var _island: Island
func before_each() -> void:
if _island == null:
_island = Island.generate(SEED)
func test_chunk_vertices_sit_on_the_heightfield() -> void:
var ground: SimGround = _island.ground
var chunk: Vector2i = Vector2i(7, 6)
var rect: Rect2 = TerrainChunkBuilder.chunk_rect(ground, chunk)
for lod: int in TerrainChunkBuilder.LOD_STEPS.size():
var arrays: Array = TerrainChunkBuilder.build(ground, _island.bands, chunk, lod)
var vertices: PackedVector3Array = arrays[Mesh.ARRAY_VERTEX]
var per_side: int = TerrainChunkBuilder.CHUNK_CELLS / TerrainChunkBuilder.LOD_STEPS[lod] + 1
assert_eq(vertices.size(), per_side * per_side + 4 * per_side, "vertex count at level %d" % lod)
var triangles: int = 2 * (per_side - 1) * (per_side - 1) + 4 * 2 * (per_side - 1)
assert_eq((arrays[Mesh.ARRAY_INDEX] as PackedInt32Array).size(), triangles * 3)
for index: int in per_side * per_side:
var vertex: Vector3 = vertices[index]
assert_true(rect.grow(0.001).has_point(Vector2(vertex.x, vertex.z)), "vertex %s outside its chunk" % vertex)
assert_near(vertex.y, ground.terrain_height(vertex.x, vertex.z), 0.001)
for normal: Vector3 in arrays[Mesh.ARRAY_NORMAL] as PackedVector3Array:
assert_true(normal.is_normalized() and normal.y > 0.0, "bad normal %s" % normal)
for weights: Color in arrays[Mesh.ARRAY_COLOR] as PackedColorArray:
assert_near(weights.r + weights.g + weights.b + weights.a, 1.0, 0.001)
func test_world_is_covered_by_chunks() -> void:
var ground: SimGround = _island.ground
var count: int = TerrainChunkBuilder.chunks_per_side(ground)
var last: Rect2 = TerrainChunkBuilder.chunk_rect(ground, Vector2i(count - 1, count - 1))
assert_near(last.end.x, Tuning.WORLD_SIZE_METRES, 0.001)
assert_near(last.end.y, Tuning.WORLD_SIZE_METRES, 0.001)
func test_skirts_cover_every_level_pairing_on_shared_edges() -> void:
# Along every shared edge, two neighbours at any two detail levels may disagree on
# height. The skirt of each must hang further than that, or a crack opens.
var ground: SimGround = _island.ground
var count: int = TerrainChunkBuilder.chunks_per_side(ground)
var levels: int = TerrainChunkBuilder.LOD_STEPS.size()
var checked: int = 0
for z: int in range(2, count - 2, 3):
for x: int in range(2, count - 2, 3):
var a: Vector2i = Vector2i(x, z)
var b: Vector2i = Vector2i(x + 1, z)
var depth: float = minf(TerrainChunkBuilder.skirt_depth(ground, a), TerrainChunkBuilder.skirt_depth(ground, b))
for lod_a: int in levels:
var edge_a: PackedFloat32Array = _edge_profile(a, lod_a, 3)
for lod_b: int in levels:
var edge_b: PackedFloat32Array = _edge_profile(b, lod_b, 2)
for index: int in edge_a.size():
var gap: float = absf(edge_a[index] - edge_b[index])
assert_true(gap < depth - TerrainChunkBuilder.SKIRT_MARGIN * 0.5,
"chunks %s/%s levels %d/%d: gap %.2f m, skirt %.2f m" % [a, b, lod_a, lod_b, gap, depth])
checked += 1
assert_true(checked > 100, "checked only %d pairings" % checked)
func test_detail_falls_with_distance() -> void:
var view: TerrainView = TerrainView.new()
view.setup(_island)
view.focus = Vector3(500.0, 30.0, 500.0)
var here: Vector2i = Vector2i(7, 7)
assert_eq(view.wanted_lod(here), 0, "the focus chunk is full detail")
var previous: int = 0
for x: int in range(7, 16):
var lod: int = view.wanted_lod(Vector2i(x, 7))
assert_true(lod >= previous, "detail must not rise with distance")
previous = lod
assert_eq(previous, TerrainChunkBuilder.LOD_STEPS.size() - 1, "the far edge is coarsest")
view.free()
func test_streaming_across_the_island_stays_under_the_frame_budget() -> void:
# The profiler scenario: load the island around one end, then fly the focus across it
# at 30 m/s for a 60 fps frame rate (0.5 m per frame), measuring the main-thread time
# TerrainView spends each frame. Geometry is built on worker threads. Headless, so this
# measures CPU work only; GPU upload time needs a real-GPU playtest.
var tree: SceneTree = Engine.get_main_loop() as SceneTree
var view: TerrainView = TerrainView.new()
view.setup(_island)
view.focus = Vector3(150.0, 30.0, 150.0)
tree.root.add_child(view)
view.build_all_now()
var loaded: int = view.uploads
view.max_frame_usec = 0
var start: Vector3 = view.focus
var finish: Vector3 = Vector3(880.0, 30.0, 860.0)
var frames: int = ceili(start.distance_to(finish) / 0.5)
for frame: int in frames:
view.focus = start.lerp(finish, float(frame) / frames)
await tree.process_frame
for _frame: int in 600:
if view.settled():
break
await tree.process_frame
var streamed: int = view.uploads - loaded
print(" terrain streaming: %d frames, %d chunk rebuilds, worst frame %d us" % [frames, streamed, view.max_frame_usec])
assert_true(streamed > 50, "expected real streaming, got %d rebuilds" % streamed)
assert_true(view.settled(), "terrain never caught up with the focus")
assert_true(view.max_frame_usec < FRAME_SPIKE_USEC, "worst frame %d us" % view.max_frame_usec)
view.queue_free()
await tree.process_frame
## Heights along a chunk's edge at full-resolution spacing, as that chunk draws them at
## `lod`: each coarse span is a straight line between its end samples.
func _edge_profile(chunk: Vector2i, lod: int, edge_column_side: int) -> PackedFloat32Array:
var arrays: Array = TerrainChunkBuilder.build(_island.ground, _island.bands, chunk, lod)
var vertices: PackedVector3Array = arrays[Mesh.ARRAY_VERTEX]
var step: int = TerrainChunkBuilder.LOD_STEPS[lod]
var per_side: int = TerrainChunkBuilder.CHUNK_CELLS / step + 1
# Side 3 is the east column, side 2 the west column; both run along z.
var column: int = per_side - 1 if edge_column_side == 3 else 0
var profile: PackedFloat32Array = PackedFloat32Array()
for position: int in TerrainChunkBuilder.CHUNK_CELLS + 1:
var low: int = position / step
var high: int = mini(low + 1, per_side - 1)
var t: float = float(position % step) / step
var a: float = vertices[low * per_side + column].y
var b: float = vertices[high * per_side + column].y
profile.append(lerpf(a, b, t))
return profile
+1
View File
@@ -0,0 +1 @@
uid://boq3wln8pjs5j
+20
View File
@@ -0,0 +1,20 @@
extends TestCase
## The client sea from issue W6 follows the simulation's sea level.
func test_surface_follows_the_simulation_sea_level() -> void:
var sim: Simulation = Simulation.new(1, SimGround.flat())
var view: WaterView = WaterView.new()
view.follow(sim)
assert_eq(view.surface().position.y, Tuning.SEA_LEVEL_START)
sim.set_sea_level(8.0)
view.follow(sim)
assert_eq(view.surface().position.y, 8.0)
assert_eq(view.level, 8.0)
# The surface covers the whole world and well past it, so no edge is ever in view.
var mesh: PlaneMesh = view.surface().mesh
assert_true(mesh.size.x >= Tuning.WORLD_SIZE_METRES * 4.0)
assert_near(view.surface().position.x, Tuning.WORLD_SIZE_METRES * 0.5, 0.001)
assert_eq(view.surface().cast_shadow, GeometryInstance3D.SHADOW_CASTING_SETTING_OFF)
view.free()
+1
View File
@@ -0,0 +1 @@
uid://bqm81iki1cguk
+10 -6
View File
@@ -40,16 +40,20 @@ func test_percentile_uses_nearest_rank() -> void:
assert_eq(ServerLoop._percentile(PackedInt64Array([9]), 0.99), 9)
func test_bots_move_and_humans_without_commands_stay_put() -> void:
func test_bots_leap_and_humans_without_commands_stay_aboard() -> void:
# Every match starts on the drop carrier. A human who sends nothing rides it; the bot
# leaps at its own fixed moment and falls away.
var loop: ServerLoop = ServerLoop.new(99, 1, 1)
var human: SimEntity = loop.sim.entities.find(1)
var bot: SimEntity = loop.sim.entities.find(2)
var human_start: Vector3 = human.position
var bot_start: Vector3 = bot.position
for _index: int in 90:
assert_eq(human.drop_state, Drop.ABOARD)
assert_eq(bot.drop_state, Drop.ABOARD)
for _index: int in Tuning.TICK_RATE_HZ * 24:
loop.run_tick()
assert_eq(human.position, human_start)
assert_true(bot.position.distance_to(bot_start) > 1.0, "the bot should have walked")
assert_eq(human.drop_state, Drop.ABOARD)
assert_true(human.position.distance_to(loop.sim.drop.barge_position(loop.sim.tick)) < 0.001)
assert_ne(bot.drop_state, Drop.ABOARD, "the bot should have leapt")
assert_true(bot.position.y < Tuning.BARGE_ALTITUDE - 20.0, "the bot should be falling, at %s" % bot.position)
func test_same_seed_gives_the_same_match() -> void:
+133
View File
@@ -0,0 +1,133 @@
## Measures a generated island for the worldgen tests: land area, how land splits up as
## the sea rises, and where the separate high points are. It reads every other
## heightfield sample (4 m apart), which is plenty for kilometre-scale questions.
class_name IslandSurvey
extends RefCounted
const STRIDE: int = 2
const NEIGHBOURS: Array[Vector2i] = [Vector2i(1, 0), Vector2i(-1, 0), Vector2i(0, 1), Vector2i(0, -1)]
var island: Island
var side: int = 0
var spacing: float = 0.0
var heights: PackedFloat32Array = PackedFloat32Array()
func _init(target: Island) -> void:
island = target
var ground: SimGround = target.ground
side = (ground.samples - 1) / STRIDE + 1
spacing = ground.cell * STRIDE
heights.resize(side * side)
for gz: int in side:
for gx: int in side:
heights[gz * side + gx] = ground.heights[gz * STRIDE * ground.samples + gx * STRIDE]
## Fraction of the world above `level`.
func land_fraction(level: float) -> float:
var count: int = 0
for value: float in heights:
if value > level:
count += 1
return float(count) / heights.size()
## How the land splits when the sea stands at `level`. Water floods inward from the
## world edge through every cell at or below the level; low ground the sea can't reach
## stays dry, as the GDD says. Returns the dry area, the largest connected dry piece,
## and the number of dry pieces.
func dry_land(level: float) -> Dictionary:
var flooded: PackedByteArray = PackedByteArray()
flooded.resize(side * side)
var queue: PackedInt32Array = PackedInt32Array()
for index: int in side:
for edge: int in [index, (side - 1) * side + index, index * side, index * side + side - 1]:
if heights[edge] <= level and flooded[edge] == 0:
flooded[edge] = 1
queue.append(edge)
_spread(queue, flooded, func(cell: int) -> bool: return heights[cell] <= level)
var seen: PackedByteArray = flooded.duplicate()
var total: int = 0
var largest: int = 0
var pieces: int = 0
for start: int in side * side:
if seen[start] != 0:
continue
seen[start] = 1
var piece: PackedInt32Array = PackedInt32Array([start])
var size: int = _spread(piece, seen, func(_cell: int) -> bool: return true)
total += size
largest = maxi(largest, size)
pieces += 1
return {"dry": total, "largest": largest, "pieces": pieces}
## Separate high points: cells that are the highest within `radius` metres and at least
## `min_height` high, each with a valley of at least `drop` metres between it and every
## higher peak (measured along the straight line between them).
func peaks(min_height: float, radius: float, drop: float) -> Array[Vector3]:
var reach: int = ceili(radius / spacing)
var found: Array[Vector3] = []
for gz: int in side:
for gx: int in side:
var height: float = heights[gz * side + gx]
if height < min_height or not _local_max(gx, gz, height, reach):
continue
found.append(Vector3(gx * spacing, height, gz * spacing))
found.sort_custom(func(a: Vector3, b: Vector3) -> bool: return a.y > b.y)
var distinct: Array[Vector3] = []
for peak: Vector3 in found:
var separate: bool = true
for higher: Vector3 in distinct:
if _lowest_between(peak, higher) > peak.y - drop:
separate = false
break
if separate:
distinct.append(peak)
return distinct
func _local_max(gx: int, gz: int, height: float, reach: int) -> bool:
for dz: int in range(-reach, reach + 1):
for dx: int in range(-reach, reach + 1):
var x: int = gx + dx
var z: int = gz + dz
if x < 0 or z < 0 or x >= side or z >= side or (dx == 0 and dz == 0):
continue
var other: float = heights[z * side + x]
# Ties go to the lower index, so a flat top yields one peak.
if other > height or (other == height and z * side + x < gz * side + gx):
return false
return true
func _lowest_between(a: Vector3, b: Vector3) -> float:
var lowest: float = INF
var steps: int = ceili(Vector2(a.x, a.z).distance_to(Vector2(b.x, b.z)) / spacing)
for step: int in steps + 1:
var point: Vector3 = a.lerp(b, float(step) / maxf(steps, 1))
lowest = minf(lowest, island.ground.terrain_height(point.x, point.z))
return lowest
## Flood fill from the cells in `queue`, marking `marks`, through cells `admit` accepts.
## Returns how many cells were reached, including the starting ones.
func _spread(queue: PackedInt32Array, marks: PackedByteArray, admit: Callable) -> int:
var head: int = 0
while head < queue.size():
var cell: int = queue[head]
head += 1
var x: int = cell % side
var z: int = cell / side
for step: Vector2i in NEIGHBOURS:
var nx: int = x + step.x
var nz: int = z + step.y
if nx < 0 or nz < 0 or nx >= side or nz >= side:
continue
var next: int = nz * side + nx
if marks[next] == 0 and admit.call(next):
marks[next] = 1
queue.append(next)
return queue.size()
+1
View File
@@ -0,0 +1 @@
uid://b82cq6vtir34x
+252
View File
@@ -0,0 +1,252 @@
extends TestCase
## The drop from issue W7: the sky barge's route, leaping, freefall, the wing-sail,
## steering, landing and the forced ejection at the end of the route.
const SECOND: int = Tuning.TICK_RATE_HZ
var _islands: Dictionary = {}
func _sim(seed_value: int) -> Simulation:
return Simulation.new(seed_value)
func _flat_sim(seed_value: int = 1) -> Simulation:
return Simulation.new(seed_value, SimGround.flat())
func _command(sim: Simulation, move: Vector2, yaw: float, buttons: int = 0) -> PlayerCommand:
return PlayerCommand.from_input(sim.tick, move, yaw, 0.0, buttons)
func test_routes_always_cross_land() -> void:
# 60 seeds: every route starts and ends inside the world, flies at barge altitude, and
# spends a good stretch over dry land, so every player can reach the island.
for seed_value: int in range(1, 61):
var island: Island = Island.generate(seed_value)
var drop: Drop = Drop.plan(island.ground, SimRng.new(seed_value), 0)
var size: float = Tuning.WORLD_SIZE_METRES
for end: Vector3 in [drop.start, drop.finish]:
assert_true(end.x >= 0.0 and end.x <= size and end.z >= 0.0 and end.z <= size, "seed %d route leaves the world" % seed_value)
assert_eq(end.y, Tuning.BARGE_ALTITUDE)
var land: int = 0
var samples: PackedVector2Array = drop.route_samples(4.0)
for point: Vector2 in samples:
if island.ground.terrain_height(point.x, point.y) > Tuning.ISLAND_BEACH_TOP:
land += 1
var land_metres: float = land * 4.0
assert_true(land_metres >= Tuning.BARGE_MIN_LAND_METRES, "seed %d route crosses only %.0f m of land" % [seed_value, land_metres])
var seconds: float = float(drop.duration_ticks) / SECOND
assert_true(seconds >= 20.0 and seconds <= 75.0, "seed %d route takes %.1f s" % [seed_value, seconds])
func test_route_is_seeded() -> void:
var island: Island = Island.generate(5)
var a: Drop = Drop.plan(island.ground, SimRng.new(5), 0)
var b: Drop = Drop.plan(island.ground, SimRng.new(5), 0)
assert_eq(a.start, b.start)
assert_eq(a.finish, b.finish)
var c: Drop = Drop.plan(island.ground, SimRng.new(6), 0)
assert_ne(a.start, c.start)
func test_players_ride_the_barge_until_they_leap() -> void:
var sim: Simulation = _flat_sim()
var id: int = sim.add_player()
sim.start_drop()
var player: SimEntity = sim.entities.find(id)
assert_eq(player.drop_state, Drop.ABOARD)
for _i: int in SECOND * 2:
# Moving and crouching do nothing aboard.
sim.submit_command(id, _command(sim, Vector2(1.0, 1.0), 0.3, PlayerCommand.BUTTON_SPRINT | PlayerCommand.BUTTON_CROUCH))
sim.step()
assert_eq(player.drop_state, Drop.ABOARD)
assert_true(player.position.distance_to(sim.drop.barge_position(sim.tick)) < 0.001, "rider isn't on the barge")
sim.submit_command(id, _command(sim, Vector2.ZERO, 0.0, PlayerCommand.BUTTON_JUMP))
sim.step()
assert_eq(player.drop_state, Drop.FREEFALL)
var height: float = player.position.y
for _i: int in SECOND:
sim.step()
assert_true(player.position.y < height - 10.0, "freefall too slow: %.1f to %.1f" % [height, player.position.y])
# Freefall tops out at its terminal speed.
for _i: int in SECOND * 2:
sim.step()
assert_true(-player.velocity.y <= Tuning.FREEFALL_MAX_SPEED + 0.001)
func test_wing_sail_slows_the_fall_and_steers() -> void:
var sim: Simulation = _flat_sim()
var id: int = sim.add_player()
sim.start_drop()
var player: SimEntity = sim.entities.find(id)
sim.submit_command(id, _command(sim, Vector2.ZERO, 0.0, PlayerCommand.BUTTON_JUMP))
sim.step()
for _i: int in SECOND:
sim.step()
# Open the sail by hand, high up.
sim.submit_command(id, _command(sim, Vector2.ZERO, 0.0, PlayerCommand.BUTTON_JUMP))
sim.step()
assert_eq(player.drop_state, Drop.GLIDING)
for _i: int in SECOND:
sim.step()
assert_near(player.velocity.y, -Tuning.GLIDE_FALL_SPEED, 0.01)
# Steer towards the middle of the world at glide speed, so no edge gets in the way.
var centre: Vector2 = Vector2(Tuning.WORLD_SIZE_METRES, Tuning.WORLD_SIZE_METRES) * 0.5
var to_centre: Vector2 = centre - Vector2(player.position.x, player.position.z)
var yaw: float = atan2(to_centre.x, to_centre.y)
var heading: Vector2 = Vector2(sin(yaw), cos(yaw))
for _i: int in SECOND * 3:
sim.submit_command(id, _command(sim, Vector2(0.0, 1.0), yaw))
sim.step()
var p1: Vector2 = Vector2(player.position.x, player.position.z)
for _i: int in SECOND:
sim.submit_command(id, _command(sim, Vector2(0.0, 1.0), yaw))
sim.step()
var p2: Vector2 = Vector2(player.position.x, player.position.z)
assert_near((p2 - p1).dot(heading), Tuning.GLIDE_SPEED, 0.1, "glide speed ahead")
assert_near(absf((p2 - p1).cross(heading)), 0.0, 0.1, "drifting sideways")
# Turn a quarter: strafing right goes right at the same speed.
var right: Vector2 = Vector2(-cos(yaw), sin(yaw))
for _i: int in SECOND * 2:
sim.submit_command(id, _command(sim, Vector2(1.0, 0.0), yaw))
sim.step()
var p3: Vector2 = Vector2(player.position.x, player.position.z)
for _i: int in SECOND:
sim.submit_command(id, _command(sim, Vector2(1.0, 0.0), yaw))
sim.step()
var p4: Vector2 = Vector2(player.position.x, player.position.z)
assert_near((p4 - p3).dot(right), Tuning.GLIDE_SPEED, 0.1, "glide speed to the right")
# Letting go stops the sail drifting.
for _i: int in SECOND:
sim.step()
assert_near(Vector2(player.velocity.x, player.velocity.z).length(), 0.0, 0.01)
assert_eq(player.drop_state, Drop.GLIDING)
func test_sail_opens_by_itself_near_the_ground_and_landing_is_safe() -> void:
var sim: Simulation = _flat_sim()
var id: int = sim.add_player()
sim.start_drop()
var player: SimEntity = sim.entities.find(id)
sim.submit_command(id, _command(sim, Vector2.ZERO, 0.0, PlayerCommand.BUTTON_JUMP))
sim.step()
var opened_at: float = -1.0
for _i: int in SECOND * 60:
sim.step()
if opened_at < 0.0 and player.drop_state == Drop.GLIDING:
opened_at = player.position.y
if player.on_ground:
break
assert_true(opened_at > 0.0, "the sail never opened")
assert_true(opened_at <= Tuning.WING_AUTO_DEPLOY_HEIGHT + 0.001 and opened_at > Tuning.WING_AUTO_DEPLOY_HEIGHT - 2.0, "opened at %.1f m" % opened_at)
assert_true(player.on_ground, "never landed, at %s" % player.position)
assert_eq(player.drop_state, Drop.NONE)
assert_eq(player.health, Tuning.PLAYER_MAX_HEALTH)
# Back to walking once down.
var x0: float = player.position.x
for _i: int in SECOND:
sim.submit_command(id, _command(sim, Vector2(0.0, 1.0), PI * 0.5))
sim.step()
assert_near(player.position.x - x0, Tuning.WALK_SPEED, 0.05)
func test_gliding_into_the_sea_ends_in_the_water_unhurt() -> void:
var sim: Simulation = _flat_sim()
sim.set_sea_level(10.0)
var id: int = sim.add_player()
sim.start_drop()
var player: SimEntity = sim.entities.find(id)
sim.submit_command(id, _command(sim, Vector2.ZERO, 0.0, PlayerCommand.BUTTON_JUMP))
sim.step()
for _i: int in SECOND * 60:
sim.step()
if player.swimming:
break
assert_true(player.swimming)
assert_eq(player.drop_state, Drop.NONE)
assert_eq(player.health, Tuning.PLAYER_MAX_HEALTH)
func test_riders_are_thrown_off_at_the_end_of_the_route() -> void:
var sim: Simulation = _flat_sim()
var id: int = sim.add_player()
sim.start_drop()
var player: SimEntity = sim.entities.find(id)
for _i: int in sim.drop.duration_ticks - 1:
sim.step()
assert_eq(player.drop_state, Drop.ABOARD)
sim.step()
sim.step()
assert_eq(player.drop_state, Drop.FREEFALL, "still aboard after the route ended")
assert_true(sim.drop.finished)
assert_true(player.position.distance_to(sim.drop.finish) < Tuning.FREEFALL_MAX_SPEED)
func test_forced_landing_brings_every_player_down_alive() -> void:
# A full drop on a real island: 24 players, a third leaping early, a third steering
# and opening their sails high, the rest never pressing anything and thrown off at
# the end. Everyone must reach the ground or the water, unhurt, before the route
# time plus a generous fall.
var sim: Simulation = _sim(11)
var ids: Array[int] = []
for _i: int in Tuning.SOLO_PLAYERS:
ids.append(sim.add_player())
sim.start_drop()
var limit: int = sim.drop.duration_ticks + SECOND * 60
var all_down: bool = false
while sim.tick < limit:
var elapsed: int = sim.tick - sim.drop.began_tick
for index: int in ids.size():
var id: int = ids[index]
var player: SimEntity = sim.entities.find(id)
var buttons: int = 0
var move: Vector2 = Vector2.ZERO
var yaw: float = TAU * index / ids.size()
if index % 3 == 0 and elapsed == SECOND * (3 + index):
buttons = PlayerCommand.BUTTON_JUMP
elif index % 3 == 1:
move = Vector2(0.0, 1.0)
if player.drop_state == Drop.ABOARD and elapsed == sim.drop.duration_ticks / 2:
buttons = PlayerCommand.BUTTON_JUMP
elif player.drop_state == Drop.FREEFALL and elapsed % SECOND == 0:
buttons = PlayerCommand.BUTTON_JUMP
sim.submit_command(id, _command(sim, move, yaw, buttons))
sim.step()
all_down = true
for id: int in ids:
var player: SimEntity = sim.entities.find(id)
if player.drop_state != Drop.NONE or not (player.on_ground or player.swimming):
all_down = false
break
if all_down:
break
assert_true(all_down, "not everyone landed within %d ticks" % limit)
assert_true(sim.drop.finished)
for id: int in ids:
var player: SimEntity = sim.entities.find(id)
assert_eq(player.health, Tuning.PLAYER_MAX_HEALTH, "player %d hurt landing at %s" % [id, player.position])
var size: float = Tuning.WORLD_SIZE_METRES
assert_true(player.position.x >= 0.0 and player.position.x <= size and player.position.z >= 0.0 and player.position.z <= size)
if player.on_ground:
assert_near(player.position.y, sim.ground.support_height(player.position.x, player.position.z, player.position.y + 0.01), 0.01)
func test_drop_is_deterministic_and_hashed() -> void:
var a: Simulation = _flat_sim(3)
var b: Simulation = _flat_sim(3)
for sim: Simulation in [a, b]:
var id: int = sim.add_player()
sim.start_drop()
for _i: int in SECOND * 3:
var buttons: int = PlayerCommand.BUTTON_JUMP if sim.tick == SECOND else 0
sim.submit_command(id, PlayerCommand.from_input(sim.tick, Vector2(0.3, 1.0), 1.0, 0.0, buttons))
sim.step()
assert_eq(a.state_hash(), b.state_hash())
var c: Simulation = _flat_sim(3)
c.add_player()
c.start_drop()
var before: String = c.state_hash()
c.step()
assert_ne(c.state_hash(), before)
+1
View File
@@ -0,0 +1 @@
uid://dq1tvj7bplb7d
+154
View File
@@ -0,0 +1,154 @@
extends TestCase
## The acceptance sweep from issue W2: every one of these seeds must make a good island.
const SWEEP_SEEDS: int = 100
const GENERATION_BUDGET_MSEC: int = 5000
## The sea level of the first flood line. Land must stay joined up to here.
const EARLY_TIDE_LEVELS: Array[float] = [0.0, 8.0]
## Dry land outside the main landmass may be at most this fraction: a few islets and
## sea stacks are fine, a second island is not.
const MAX_STRANDED_FRACTION: float = 0.03
const MIN_LAND_FRACTION: float = 0.30
const MAX_LAND_FRACTION: float = 0.70
## Distinct high points: at least this high, the highest within 80 m, and with a valley
## at least 6 m deep between each and any higher one.
const PEAK_MIN_HEIGHT: float = 35.0
const PEAK_RADIUS: float = 80.0
const PEAK_DROP: float = 6.0
const MIN_WALKABLE_LAND: float = 0.85
func test_same_seed_gives_the_same_heightmap() -> void:
var first: Island = Island.generate(777)
var second: Island = Island.generate(777)
assert_eq(first.heightmap_hash(), second.heightmap_hash())
assert_eq(first.heightmap_hash().length(), 64, "expected a SHA-256 hex digest")
assert_eq(first.summits, second.summits)
func test_different_seeds_give_different_islands() -> void:
assert_ne(Island.generate(777).heightmap_hash(), Island.generate(778).heightmap_hash())
func test_generation_does_not_touch_match_randomness() -> void:
# Worldgen uses its own copy of the "worldgen" stream, so generating the island on a
# client can never shift the server's gameplay rolls.
var sim: Simulation = Simulation.new(31337)
assert_eq(sim.rng.stream_names(), [] as Array[String])
assert_eq(sim.island.heightmap_hash(), Island.generate(31337).heightmap_hash())
func test_a_separate_server_process_builds_the_same_island() -> void:
# The same check a client makes on joining: an independent engine process given only
# the seed must arrive at the same heightmap.
var seed_value: int = 4_000_000_017
var output: Array = []
var args: PackedStringArray = PackedStringArray([
"--headless", "--path", ProjectSettings.globalize_path("res://"),
"--", "--server", "--seed=%d" % seed_value, "--ticks=1", "--unthrottled",
])
var code: int = OS.execute(OS.get_executable_path(), args, output, true)
assert_eq(code, 0, "server exited %d: %s" % [code, "\n".join(output)])
var world_hash: String = ""
for line: String in "\n".join(output).split("\n"):
if line.begins_with("{") and line.contains("\"event\":\"start\""):
world_hash = (JSON.parse_string(line) as Dictionary).get("world_hash", "")
assert_eq(world_hash, Island.generate(seed_value).heightmap_hash())
func test_bands_follow_height() -> void:
var island: Island = Island.generate(5)
var ground: SimGround = island.ground
for index: int in range(0, ground.heights.size(), 97):
var height: float = ground.heights[index]
var band: int = island.bands[index]
match band:
Island.Band.SEA:
assert_true(height <= 0.0, "sea at %.2f m" % height)
Island.Band.BEACH:
assert_true(height > 0.0 and height < Tuning.ISLAND_BEACH_TOP, "beach at %.2f m" % height)
Island.Band.MARSH:
assert_true(height < Tuning.ISLAND_MARSH_TOP, "marsh at %.2f m" % height)
Island.Band.FOREST:
assert_true(height < Tuning.ISLAND_FOREST_TOP, "forest at %.2f m" % height)
Island.Band.HIGHLAND:
assert_true(height >= Tuning.ISLAND_FOREST_TOP, "highland at %.2f m" % height)
Island.Band.SUMMIT:
assert_true(height >= Tuning.ISLAND_SUMMIT_BAND, "summit at %.2f m" % height)
assert_eq(island.band_at(-50.0, -50.0), Island.Band.SEA, "the world corner is open sea")
func test_players_spawn_on_dry_land() -> void:
var sim: Simulation = Simulation.new(2024)
for _index: int in Tuning.SOLO_PLAYERS:
var player: SimEntity = sim.entities.find(sim.add_player())
assert_true(player.position.y > Tuning.ISLAND_BEACH_TOP, "spawned at %s" % player.position)
func test_one_hundred_seeds_make_playable_islands() -> void:
var slowest: int = 0
var marsh_islands: int = 0
var worst_stranded: float = 0.0
var land_range: Vector2 = Vector2(INF, -INF)
var peak_counts: Dictionary = {}
for seed_value: int in range(1, SWEEP_SEEDS + 1):
var started: int = Time.get_ticks_msec()
var island: Island = Island.generate(seed_value)
var elapsed: int = Time.get_ticks_msec() - started
slowest = maxi(slowest, elapsed)
var label: String = "seed %d" % seed_value
assert_true(elapsed < GENERATION_BUDGET_MSEC, "%s took %d ms" % [label, elapsed])
var survey: IslandSurvey = IslandSurvey.new(island)
var land: float = survey.land_fraction(0.0)
assert_true(land >= MIN_LAND_FRACTION and land <= MAX_LAND_FRACTION,
"%s: land covers %.2f of the world" % [label, land])
var highest: float = island.max_height()
assert_true(highest >= Tuning.ISLAND_PEAK_MIN - 1.0 and highest < Tuning.ISLAND_MAX_HEIGHT,
"%s: highest ground %.1f m" % [label, highest])
var final_level: float = Tuning.TIDE_PHASES[-1]["level"]
assert_true(highest < final_level, "%s: the last tide must cover the island" % label)
for level: float in EARLY_TIDE_LEVELS:
var dry: Dictionary = survey.dry_land(level)
var stranded: float = 1.0 - float(dry["largest"]) / maxf(dry["dry"], 1.0)
worst_stranded = maxf(worst_stranded, stranded)
assert_true(stranded <= MAX_STRANDED_FRACTION,
"%s: at %.0f m, %.3f of dry land is cut off from the main landmass" % [label, level, stranded])
var peaks: Array[Vector3] = survey.peaks(PEAK_MIN_HEIGHT, PEAK_RADIUS, PEAK_DROP)
assert_true(peaks.size() >= 2, "%s: %d distinct high points" % [label, peaks.size()])
var walkable: float = _walkable_land(island)
assert_true(walkable >= MIN_WALKABLE_LAND, "%s: only %.2f of land is walkable" % [label, walkable])
var bands: Dictionary = {}
for band: int in island.bands:
bands[band] = true
for needed: int in [Island.Band.BEACH, Island.Band.FOREST, Island.Band.HIGHLAND, Island.Band.SUMMIT]:
assert_true(bands.has(needed), "%s lacks band %s" % [label, Island.Band.keys()[needed]])
if bands.has(Island.Band.MARSH):
marsh_islands += 1
land_range = Vector2(minf(land_range.x, land), maxf(land_range.y, land))
peak_counts[peaks.size()] = peak_counts.get(peaks.size(), 0) + 1
assert_true(marsh_islands >= SWEEP_SEEDS * 0.8, "only %d islands have marsh" % marsh_islands)
print(" island sweep: slowest %d ms, land %.2f to %.2f of the world, worst stranded %.4f," % [
slowest, land_range.x, land_range.y, worst_stranded])
print(" island sweep: islands by distinct high points %s, %d of %d with marsh" % [
peak_counts, marsh_islands, SWEEP_SEEDS])
func _walkable_land(island: Island) -> float:
var ground: SimGround = island.ground
var land: int = 0
var walkable: int = 0
for gz: int in range(0, ground.samples, 4):
for gx: int in range(0, ground.samples, 4):
var x: float = gx * ground.cell
var z: float = gz * ground.cell
if ground.terrain_height(x, z) <= 0.0:
continue
land += 1
if ground.walkable_terrain(x, z):
walkable += 1
return float(walkable) / maxf(land, 1.0)
+1
View File
@@ -0,0 +1 @@
uid://dgg1nqt68f2ei
+60
View File
@@ -0,0 +1,60 @@
extends TestCase
## Character movement on generated islands, in the headless simulation with no renderer:
## the server's collision is SimGround's heightfield, never a render mesh.
const TICKS: int = 900
func test_players_never_sink_into_generated_terrain() -> void:
for seed_value: int in [11, 12]:
var sim: Simulation = Simulation.new(seed_value)
var random: RandomNumberGenerator = RandomNumberGenerator.new()
random.seed = seed_value
var ids: Array[int] = []
for _index: int in 12:
ids.append(sim.add_player())
var grounded: int = 0
var samples: int = 0
for _tick: int in TICKS:
for id: int in ids:
var move: Vector2 = Vector2(random.randf_range(-1.0, 1.0), random.randf_range(-1.0, 1.0))
var buttons: int = PlayerCommand.BUTTON_SPRINT if random.randf() < 0.5 else 0
if random.randf() < 0.004:
buttons |= PlayerCommand.BUTTON_JUMP
sim.submit_command(id, PlayerCommand.from_input(sim.tick, move, random.randf() * TAU, 0.0, buttons))
sim.step()
for id: int in ids:
var player: SimEntity = sim.entities.find(id)
var floor_height: float = sim.ground.terrain_height(player.position.x, player.position.z)
assert_true(player.position.y >= floor_height - 0.01,
"seed %d player %d sank to %.2f below ground at %s" % [seed_value, id, floor_height - player.position.y, player.position])
assert_false(is_nan(player.position.length()), "position became NaN")
samples += 1
if player.on_ground:
grounded += 1
assert_true(grounded > samples * 0.7, "seed %d: players grounded only %d of %d ticks" % [seed_value, grounded, samples])
func test_walking_up_to_a_summit_and_back_down() -> void:
# Head straight for the tallest summit from the plateau below it, then walk away.
var sim: Simulation = Simulation.new(21)
var id: int = sim.add_player()
var player: SimEntity = sim.entities.find(id)
var summit: Vector3 = sim.island.summits[0]
var start: Vector2 = Vector2(summit.x, summit.z) + Vector2(150.0, 0.0)
player.position = Vector3(start.x, sim.ground.terrain_height(start.x, start.y), start.y)
var lowest_start: float = player.position.y
var highest: float = player.position.y
for _tick: int in 60 * Tuning.TICK_RATE_HZ:
var towards: Vector2 = Vector2(summit.x - player.position.x, summit.z - player.position.z)
if towards.length() < 3.0:
break
var yaw: float = atan2(towards.x, towards.y)
sim.submit_command(id, PlayerCommand.from_input(sim.tick, Vector2(0.0, 1.0), yaw, 0.0, PlayerCommand.BUTTON_SPRINT))
sim.step()
highest = maxf(highest, player.position.y)
assert_true(highest > lowest_start + 15.0,
"climbed only from %.1f to %.1f m towards a %.1f m summit" % [lowest_start, highest, summit.y])
assert_true(highest <= sim.island.max_height() + 0.01, "rose above the highest ground without jumping")
assert_eq(player.health, Tuning.PLAYER_MAX_HEALTH, "walking the hills must not hurt")
+1
View File
@@ -0,0 +1 @@
uid://bcjg7fnxpwnju
+302
View File
@@ -0,0 +1,302 @@
extends TestCase
## Yaw that faces +x, since forward is (sin yaw, 0, cos yaw).
const EAST: float = PI * 0.5
const NORTH: float = 0.0
var _tick: int = 0
func before_each() -> void:
_tick = 0
func _player(at: Vector3, on_ground: bool = true) -> SimEntity:
var player: SimEntity = SimEntity.new(1, SimEntity.ARCHETYPE_PLAYER)
player.position = at
player.health = Tuning.PLAYER_MAX_HEALTH
player.on_ground = on_ground
return player
func _command(move: Vector2, yaw: float, buttons: int = 0) -> PlayerCommand:
var command: PlayerCommand = PlayerCommand.from_input(_tick, move, yaw, 0.0, buttons)
_tick += 1
return command
func _run(player: SimEntity, ground: SimGround, ticks: int, move: Vector2, yaw: float, buttons: int = 0) -> void:
for _index: int in ticks:
Movement.step(player, _command(move, yaw, buttons), ground)
## A heightfield that is flat up to x = `start`, then rises at `degrees` along +x.
func _ramp(degrees: float, start: float = 10.0) -> SimGround:
var side: int = 64
var values: PackedFloat32Array = PackedFloat32Array()
values.resize(side * side)
var rise: float = tan(deg_to_rad(degrees))
for z: int in side:
for x: int in side:
values[z * side + x] = maxf(float(x) - start, 0.0) * rise
return SimGround.from_heights(values, side, 1.0)
func test_walk_sprint_and_crouch_speeds() -> void:
var ground: SimGround = SimGround.flat()
var cases: Array[Array] = [
[0, Tuning.WALK_SPEED],
[PlayerCommand.BUTTON_SPRINT, Tuning.SPRINT_SPEED],
[PlayerCommand.BUTTON_CROUCH, Tuning.CROUCH_SPEED],
[PlayerCommand.BUTTON_CROUCH | PlayerCommand.BUTTON_SPRINT, Tuning.CROUCH_SPEED],
]
for entry: Array in cases:
var player: SimEntity = _player(Vector3(100.0, 0.0, 100.0))
_run(player, ground, Tuning.TICK_RATE_HZ, Vector2(0.0, 1.0), EAST, entry[0])
assert_near(player.position.x - 100.0, entry[1], 0.01, "buttons %d" % entry[0])
assert_near(player.position.z, 100.0, 0.001)
assert_eq(player.position.y, 0.0)
func test_sprint_only_applies_moving_forward() -> void:
var player: SimEntity = _player(Vector3(100.0, 0.0, 100.0))
_run(player, SimGround.flat(), Tuning.TICK_RATE_HZ, Vector2(1.0, 0.0), NORTH, PlayerCommand.BUTTON_SPRINT)
assert_near(player.position.distance_to(Vector3(100.0, 0.0, 100.0)), Tuning.WALK_SPEED, 0.01)
func test_diagonal_is_no_faster_than_straight() -> void:
var player: SimEntity = _player(Vector3(100.0, 0.0, 100.0))
_run(player, SimGround.flat(), Tuning.TICK_RATE_HZ, Vector2(1.0, 1.0), NORTH)
assert_near(player.position.distance_to(Vector3(100.0, 0.0, 100.0)), Tuning.WALK_SPEED, 0.05)
func test_jump_height_and_airtime() -> void:
var player: SimEntity = _player(Vector3(100.0, 0.0, 100.0))
var ground: SimGround = SimGround.flat()
Movement.step(player, _command(Vector2.ZERO, NORTH, PlayerCommand.BUTTON_JUMP), ground)
assert_false(player.on_ground)
var peak: float = player.position.y
var ticks_in_air: int = 1
while not player.on_ground and ticks_in_air < 200:
Movement.step(player, _command(Vector2.ZERO, NORTH), ground)
peak = maxf(peak, player.position.y)
ticks_in_air += 1
var expected_peak: float = Tuning.JUMP_VELOCITY * Tuning.JUMP_VELOCITY / (2.0 * Tuning.GRAVITY)
assert_near(peak, expected_peak, 0.01, "jump height")
var expected_ticks: float = 2.0 * Tuning.JUMP_VELOCITY / Tuning.GRAVITY * Tuning.TICK_RATE_HZ
assert_near(ticks_in_air, expected_ticks, 1.5, "time in the air")
assert_eq(player.position.y, 0.0)
assert_eq(player.health, Tuning.PLAYER_MAX_HEALTH, "a jump on flat ground must not hurt")
func test_no_jump_while_crouched_or_in_the_air() -> void:
var ground: SimGround = SimGround.flat()
var crouched: SimEntity = _player(Vector3(100.0, 0.0, 100.0))
Movement.step(crouched, _command(Vector2.ZERO, NORTH, PlayerCommand.BUTTON_JUMP | PlayerCommand.BUTTON_CROUCH), ground)
assert_true(crouched.on_ground)
assert_eq(crouched.position.y, 0.0)
var jumper: SimEntity = _player(Vector3(100.0, 0.0, 100.0))
Movement.step(jumper, _command(Vector2.ZERO, NORTH, PlayerCommand.BUTTON_JUMP), ground)
var rising: float = jumper.velocity.y
Movement.step(jumper, _command(Vector2.ZERO, NORTH, PlayerCommand.BUTTON_JUMP), ground)
assert_true(jumper.velocity.y < rising, "a second jump in the air must not add speed")
func test_without_a_command_an_airborne_player_still_falls() -> void:
var player: SimEntity = _player(Vector3(100.0, 3.0, 100.0), false)
for _index: int in 30:
Movement.step(player, null, SimGround.flat())
assert_true(player.on_ground)
assert_eq(player.position.y, 0.0)
func test_walks_up_a_gentle_slope() -> void:
var player: SimEntity = _player(Vector3(5.0, 0.0, 20.0))
_run(player, _ramp(30.0), Tuning.TICK_RATE_HZ * 5, Vector2(0.0, 1.0), EAST)
assert_true(player.position.x > 20.0, "should have climbed well up the slope, at x %f" % player.position.x)
assert_near(player.position.y, (player.position.x - 10.0) * tan(deg_to_rad(30.0)), 0.05)
assert_true(player.on_ground)
func test_walks_down_a_gentle_slope_without_leaving_the_ground() -> void:
var player: SimEntity = _player(Vector3(30.0, 20.0 * tan(deg_to_rad(30.0)), 20.0))
for _index: int in Tuning.TICK_RATE_HZ * 4:
Movement.step(player, _command(Vector2(0.0, 1.0), -EAST), _ramp(30.0))
assert_true(player.on_ground, "lost the ground at x %f" % player.position.x)
assert_true(player.position.x < 15.0)
func test_too_steep_a_slope_blocks_walking_up() -> void:
var player: SimEntity = _player(Vector3(5.0, 0.0, 20.0))
_run(player, _ramp(60.0), Tuning.TICK_RATE_HZ * 5, Vector2(0.0, 1.0), EAST, PlayerCommand.BUTTON_SPRINT)
assert_true(player.position.x < 11.0, "climbed a 60 degree slope to x %f" % player.position.x)
assert_true(player.position.y < 1.0)
func test_cannot_climb_a_steep_slope_by_jumping_into_it() -> void:
var player: SimEntity = _player(Vector3(5.0, 0.0, 20.0))
var ground: SimGround = _ramp(60.0)
for _index: int in Tuning.TICK_RATE_HZ * 6:
Movement.step(player, _command(Vector2(0.0, 1.0), EAST, PlayerCommand.BUTTON_JUMP), ground)
assert_true(player.position.y < 3.0, "jumped up a cliff to height %f" % player.position.y)
func test_slides_down_ground_too_steep_to_stand_on() -> void:
var ground: SimGround = _ramp(60.0)
var x: float = 20.0
var player: SimEntity = _player(Vector3(x, ground.terrain_height(x, 20.0), 20.0))
for _index: int in Tuning.TICK_RATE_HZ * 5:
Movement.step(player, null, ground)
assert_true(player.position.x < 10.5, "should have slid to the foot, at x %f" % player.position.x)
assert_true(player.on_ground)
assert_eq(player.health, Tuning.PLAYER_MAX_HEALTH, "a capped slide must not hurt")
func test_steps_up_low_ledges_but_not_high_ones() -> void:
var low: SimGround = SimGround.flat()
low.add_solid(AABB(Vector3(10.0, 0.0, 0.0), Vector3(4.0, Tuning.STEP_HEIGHT - 0.05, 40.0)))
var player: SimEntity = _player(Vector3(5.0, 0.0, 20.0))
_run(player, low, Tuning.TICK_RATE_HZ * 2, Vector2(0.0, 1.0), EAST)
assert_true(player.position.x > 10.0)
assert_near(player.position.y, Tuning.STEP_HEIGHT - 0.05, 0.001)
var high: SimGround = SimGround.flat()
high.add_solid(AABB(Vector3(10.0, 0.0, 0.0), Vector3(4.0, 1.0, 40.0)))
var blocked: SimEntity = _player(Vector3(5.0, 0.0, 20.0))
_run(blocked, high, Tuning.TICK_RATE_HZ * 2, Vector2(0.0, 1.0), EAST)
assert_near(blocked.position.x, 10.0 - Tuning.PLAYER_RADIUS, 0.15)
assert_eq(blocked.position.y, 0.0)
func test_jumps_onto_a_ledge_too_high_to_step() -> void:
var ground: SimGround = SimGround.flat()
ground.add_solid(AABB(Vector3(10.0, 0.0, 0.0), Vector3(4.0, 1.0, 40.0)))
var player: SimEntity = _player(Vector3(8.0, 0.0, 20.0))
_run(player, ground, 1, Vector2(0.0, 1.0), EAST, PlayerCommand.BUTTON_JUMP)
_run(player, ground, Tuning.TICK_RATE_HZ, Vector2(0.0, 1.0), EAST)
assert_true(player.position.x > 10.0)
assert_near(player.position.y, 1.0, 0.001)
func test_slides_along_a_wall() -> void:
var ground: SimGround = SimGround.flat()
ground.add_solid(AABB(Vector3(10.0, 0.0, 0.0), Vector3(1.0, 3.0, 100.0)))
var player: SimEntity = _player(Vector3(9.0, 0.0, 20.0))
# North-east, into the wall: x stops, z keeps going.
_run(player, ground, Tuning.TICK_RATE_HZ, Vector2(0.0, 1.0), PI * 0.25)
assert_true(player.position.x <= 10.0 - Tuning.PLAYER_RADIUS + 0.001)
assert_true(player.position.z > 22.0)
func test_ceiling_stops_a_jump() -> void:
var ground: SimGround = SimGround.flat()
ground.add_solid(AABB(Vector3(95.0, 2.2, 95.0), Vector3(10.0, 0.5, 10.0)))
var player: SimEntity = _player(Vector3(100.0, 0.0, 100.0))
var top: float = 0.0
for _index: int in 40:
Movement.step(player, _command(Vector2.ZERO, NORTH, PlayerCommand.BUTTON_JUMP), ground)
top = maxf(top, player.position.y + Tuning.PLAYER_HEIGHT)
assert_true(top <= 2.2 + 0.001, "head reached %f, through the ceiling" % top)
func test_crouching_fits_under_a_low_gap() -> void:
var ground: SimGround = SimGround.flat()
ground.add_solid(AABB(Vector3(10.0, 1.5, 0.0), Vector3(4.0, 1.0, 40.0)))
var standing: SimEntity = _player(Vector3(5.0, 0.0, 20.0))
_run(standing, ground, Tuning.TICK_RATE_HZ * 3, Vector2(0.0, 1.0), EAST)
assert_true(standing.position.x < 10.0)
var crouched: SimEntity = _player(Vector3(5.0, 0.0, 20.0))
_run(crouched, ground, Tuning.TICK_RATE_HZ * 5, Vector2(0.0, 1.0), EAST, PlayerCommand.BUTTON_CROUCH)
assert_true(crouched.position.x > 14.0)
func test_fall_damage() -> void:
var cases: Array[Array] = [[3.0, 0], [6.0, 0], [10.0, 32], [16.0, 80]]
for entry: Array in cases:
var player: SimEntity = _player(Vector3(100.0, entry[0], 100.0), false)
for _index: int in 90:
Movement.step(player, null, SimGround.flat())
var damage: int = Tuning.PLAYER_MAX_HEALTH - player.health
assert_near(damage, entry[1], 3.0, "drop of %f m" % entry[0])
assert_true(player.on_ground)
func test_fall_damage_never_goes_below_zero_health() -> void:
var player: SimEntity = _player(Vector3(100.0, 80.0, 100.0), false)
for _index: int in 200:
Movement.step(player, null, SimGround.flat())
assert_eq(player.health, 0)
func test_stands_on_a_solid_and_falls_off_its_edge() -> void:
var ground: SimGround = SimGround.flat()
ground.add_solid(AABB(Vector3(0.0, 0.0, 0.0), Vector3(10.0, 3.0, 40.0)))
var player: SimEntity = _player(Vector3(5.0, 3.0, 20.0))
_run(player, ground, Tuning.TICK_RATE_HZ * 3, Vector2(0.0, 1.0), EAST)
assert_true(player.position.x > 10.0)
assert_eq(player.position.y, 0.0)
assert_true(player.on_ground)
func test_same_commands_on_rough_ground_are_deterministic() -> void:
var first: Simulation = _rough_simulation()
var second: Simulation = _rough_simulation()
var random: RandomNumberGenerator = RandomNumberGenerator.new()
random.seed = 77
for at_tick: int in 1500:
for id: int in [1, 2, 3, 4]:
var command: PlayerCommand = PlayerCommand.new()
command.tick = at_tick
command.move_x = random.randi_range(-127, 127)
command.move_y = random.randi_range(-127, 127)
command.yaw = random.randi_range(0, 65535)
command.buttons = random.randi_range(0, 31)
first.submit_command(id, command)
second.submit_command(id, command)
first.step()
second.step()
assert_eq(first.state_hash(), second.state_hash())
func _rough_simulation() -> Simulation:
var sim: Simulation = Simulation.new(4242, SimGround.flat())
var side: int = 65
var values: PackedFloat32Array = PackedFloat32Array()
values.resize(side * side)
for z: int in side:
for x: int in side:
values[z * side + x] = 6.0 * sin(x * 0.31) * cos(z * 0.23) + 0.08 * x
sim.ground = SimGround.from_heights(values, side, 16.0)
for index: int in 12:
sim.ground.add_solid(AABB(Vector3(index * 70.0, 0.0, 500.0), Vector3(4.0, 3.0 + index, 4.0)))
for _index: int in 4:
sim.add_player()
return sim
func test_climbs_stairs_with_treads_narrower_than_the_body() -> void:
# Treads of 0.45 m are narrower than the 0.8 m body, so the next riser is under the
# body's front edge before its centre is lifted onto the current step. (Treads
# narrower than the 0.4 m radius can't be climbed: the second riser is reached
# before the centre is on the first.)
var ground: SimGround = SimGround.flat()
for index: int in 12:
ground.add_solid(AABB(Vector3(10.0 + index * 0.45, 0.0, 8.0), Vector3(0.45, 0.35 * (index + 1), 4.0)))
# A landing at the top, so the player stays up there.
ground.add_solid(AABB(Vector3(15.4, 0.0, 8.0), Vector3(20.0, 0.35 * 12, 4.0)))
var player: SimEntity = _player(Vector3(8.0, 0.0, 10.0))
_run(player, ground, 90, Vector2(0.0, 1.0), EAST)
assert_near(player.position.y, 0.35 * 12, 0.01, "should stand on the top step")
assert_true(player.position.x > 15.0, "should have walked up the flight")
func test_a_step_does_not_let_the_body_through_a_wall_behind_it() -> void:
# A climbable 0.4 m step with a 1.5 m wall right behind it: stepping up must not
# carry the body into the wall.
var ground: SimGround = SimGround.flat()
ground.add_solid(AABB(Vector3(10.0, 0.0, 8.0), Vector3(0.5, 0.4, 4.0)))
ground.add_solid(AABB(Vector3(10.5, 0.0, 8.0), Vector3(1.0, 1.5, 4.0)))
var player: SimEntity = _player(Vector3(8.0, 0.0, 10.0))
_run(player, ground, 90, Vector2(0.0, 1.0), EAST)
assert_true(player.position.x < 10.5 - Tuning.PLAYER_RADIUS + 0.01, "walked into the wall to x %.2f" % player.position.x)
+1
View File
@@ -0,0 +1 @@
uid://p72o0ughjt1a
+120
View File
@@ -0,0 +1,120 @@
extends TestCase
## Seeds for the placement checks, and the fewer, slower traversal walks.
const PLACEMENT_SEEDS: int = 30
const TRAVERSAL_SEEDS: Array[int] = [1, 2, 3, 4]
## A route segment must be walked within this many seconds.
const SEGMENT_SECONDS: float = 12.0
const ARRIVE_METRES: float = 0.45
func test_every_island_gets_every_kind_well_spaced() -> void:
var kinds: int = Tuning.POI_KINDS.size()
assert_true(kinds >= 6, "issue W4 asks for at least 6 kinds")
for seed_value: int in range(1, PLACEMENT_SEEDS + 1):
var island: Island = Island.generate(seed_value)
var placed: PoiSet = PoiSet.generate(island)
var label: String = "seed %d" % seed_value
var total: int = placed.pois.size()
assert_true(total >= Tuning.POI_MIN_TOTAL and total <= Tuning.POI_MAX_TOTAL, "%s placed %d" % [label, total])
for kind: String in Tuning.POI_KINDS:
var count: int = placed.count_of(kind)
assert_true(count >= Tuning.POI_KINDS[kind]["min"] and count <= Tuning.POI_KINDS[kind]["max"],
"%s: %d %s" % [label, count, kind])
for a: int in total:
var here: Vector3 = placed.pois[a].origin
assert_true(here.y > 0.0, "%s: %s sited in the sea" % [label, placed.pois[a].kind])
for b: int in range(a + 1, total):
var gap: float = Vector2(here.x, here.z).distance_to(Vector2(placed.pois[b].origin.x, placed.pois[b].origin.z))
assert_true(gap >= Tuning.POI_SPACING_METRES - 0.001, "%s: two sites %.0f m apart" % [label, gap])
_check_sites(placed, label)
func test_same_seed_places_the_same_points_of_interest() -> void:
var first: PoiSet = PoiSet.generate(Island.generate(9))
var second: PoiSet = PoiSet.generate(Island.generate(9))
assert_eq(first.pois.size(), second.pois.size())
for index: int in first.pois.size():
assert_eq(first.pois[index].origin, second.pois[index].origin)
assert_eq(first.pois[index].solids, second.pois[index].solids)
func test_loot_markers_are_exposed_and_stand_on_floors() -> void:
var sim: Simulation = Simulation.new(6)
var markers: Array[Dictionary] = sim.pois.loot_markers()
assert_true(markers.size() >= sim.pois.pois.size(), "every POI should offer loot, got %d markers" % markers.size())
var kinds: Dictionary = {}
for marker: Dictionary in markers:
var at: Vector3 = marker["position"]
kinds[marker["kind"]] = true
var support: float = sim.ground.support_height(at.x, at.z, at.y + 0.5)
assert_near(support, at.y, 0.6, "%s marker at %s floats or is buried" % [marker["kind"], at])
assert_false(sim.ground.body_blocked(at + Vector3.UP * 0.05, 0.3, 1.0, 0.0), "%s marker at %s is inside a solid" % [marker["kind"], at])
assert_eq(kinds.size(), Tuning.POI_KINDS.size(), "every kind has loot")
func test_interiors_are_walkable() -> void:
# The automated traversal: a player walks every route of every POI, from open ground
# outside, through the door and up any stairs, to the loot inside, using the real
# Movement code against the real solids.
var walked: int = 0
for seed_value: int in TRAVERSAL_SEEDS:
var sim: Simulation = Simulation.new(seed_value)
for poi: Poi in sim.pois.pois:
for route: Array in poi.routes:
var failure: String = _walk(sim.ground, route)
assert_eq(failure, "", "seed %d %s at %s" % [seed_value, poi.kind, poi.origin])
walked += 1
assert_true(walked >= 40, "walked only %d routes" % walked)
func test_players_do_not_spawn_inside_buildings() -> void:
var sim: Simulation = Simulation.new(3)
for _index: int in Tuning.SOLO_PLAYERS:
var player: SimEntity = sim.entities.find(sim.add_player())
assert_false(sim.ground.body_blocked(player.position, Tuning.PLAYER_RADIUS, Tuning.PLAYER_HEIGHT, 0.0),
"spawned inside a solid at %s" % player.position)
func _check_sites(placed: PoiSet, label: String) -> void:
for poi: Poi in placed.pois:
var height: float = poi.origin.y
match poi.kind:
"shrine":
assert_true(height >= Tuning.ISLAND_FOREST_TOP * 0.8, "%s: shrine at %.1f m" % [label, height])
"dock":
assert_true(height < 6.0, "%s: dock at %.1f m" % [label, height])
"salt_works":
assert_true(height < Tuning.ISLAND_MARSH_TOP * 3.2, "%s: salt works at %.1f m" % [label, height])
"quarry":
assert_true(height >= Tuning.ISLAND_FOREST_TOP - 6.0, "%s: quarry at %.1f m" % [label, height])
## Walks a player along `route`. Returns "" on success or what went wrong.
func _walk(ground: SimGround, route: Array) -> String:
var player: SimEntity = SimEntity.new(1, SimEntity.ARCHETYPE_PLAYER)
var start: Vector3 = route[0]
player.position = Vector3(start.x, ground.support_height(start.x, start.z, start.y + 1.0), start.z)
player.health = Tuning.PLAYER_MAX_HEALTH
player.on_ground = true
if ground.body_blocked(player.position, Tuning.PLAYER_RADIUS, Tuning.PLAYER_HEIGHT, Tuning.STEP_HEIGHT):
return "route starts inside a solid at %s" % player.position
var tick: int = 0
for index: int in range(1, route.size()):
var target: Vector3 = route[index]
var limit: int = tick + roundi(SEGMENT_SECONDS * Tuning.TICK_RATE_HZ)
while true:
var towards: Vector2 = Vector2(target.x - player.position.x, target.z - player.position.z)
if towards.length() < ARRIVE_METRES:
break
if tick >= limit:
return "stuck at %s heading for waypoint %d %s" % [player.position, index, target]
var speed: float = clampf(towards.length() / (Tuning.WALK_SPEED / Tuning.TICK_RATE_HZ), 0.2, 1.0)
var command: PlayerCommand = PlayerCommand.from_input(tick, Vector2(0.0, speed), atan2(towards.x, towards.y), 0.0)
Movement.step(player, command, ground)
tick += 1
if absf(player.position.y - target.y) > 1.0:
return "reached waypoint %d at height %.2f, expected %.2f" % [index, player.position.y, target.y]
if player.health < Tuning.PLAYER_MAX_HEALTH:
return "took damage on the way"
return ""
+1
View File
@@ -0,0 +1 @@
uid://be2rbacqxhrdk
+176
View File
@@ -0,0 +1,176 @@
extends TestCase
## Props from issue W5: deterministic placement, health, destruction and cost.
const SEEDS: Array[int] = [1, 2, 3, 4, 5, 6]
func test_client_and_server_place_identical_props() -> void:
# The server builds props inside Simulation; a client builds them from the seed alone.
for seed_value: int in [4, 77]:
var server: Simulation = Simulation.new(seed_value)
var island: Island = Island.generate(seed_value)
var client: PropSet = PropSet.generate(island, PoiSet.generate(island))
assert_eq(client.count(), server.props.count(), "seed %d count" % seed_value)
assert_eq(client.layout_hash(), server.props.layout_hash(), "seed %d layout" % seed_value)
var other: PropSet = PropSet.generate(Island.generate(5), PoiSet.generate(Island.generate(5)))
assert_ne(other.layout_hash(), Simulation.new(4).props.layout_hash(), "different seeds should differ")
func test_every_island_gets_thousands_of_props_of_every_kind() -> void:
for seed_value: int in SEEDS:
var island: Island = Island.generate(seed_value)
var props: PropSet = PropSet.generate(island, PoiSet.generate(island))
assert_true(props.count() >= 2000, "seed %d placed only %d props" % [seed_value, props.count()])
for kind: String in PropSet.KINDS:
assert_true(props.count_of(kind) >= 5, "seed %d has %d %s" % [seed_value, props.count_of(kind), kind])
for prop: int in props.count():
assert_eq(props.health[prop], Tuning.PROP_KINDS[props.kind_name(prop)]["health"])
func test_props_sit_on_land_and_keep_clear_of_points_of_interest() -> void:
for seed_value: int in [1, 2, 3]:
var sim: Simulation = Simulation.new(seed_value)
var props: PropSet = sim.props
for prop: int in props.count():
var box: AABB = props.boxes[prop]
var label: String = "seed %d %s at %s" % [seed_value, props.kind_name(prop), box]
var centre: Vector3 = box.get_center()
assert_true(sim.island.band_at(centre.x, centre.z) != Island.Band.SEA, label + " is in the sea")
for corner: Vector2 in [Vector2(box.position.x, box.position.z), Vector2(box.end.x, box.position.z),
Vector2(box.position.x, box.end.z), Vector2(box.end.x, box.end.z)]:
var floor_height: float = sim.ground.terrain_height(corner.x, corner.y)
assert_true(box.position.y <= floor_height + 0.001, label + " floats over a corner")
assert_true(box.end.y > floor_height + 0.3, label + " is buried")
for poi: Poi in sim.pois.pois:
for solid: AABB in poi.solids:
var grown: AABB = solid.grow(Tuning.PROP_POI_CLEARANCE - 0.01)
assert_false(grown.position.x < box.end.x and grown.end.x > box.position.x
and grown.position.z < box.end.z and grown.end.z > box.position.z, label + " crowds a " + poi.kind)
func test_props_block_players_until_destroyed() -> void:
var sim: Simulation = Simulation.new(3)
var props: PropSet = sim.props
var tree: int = _first_open(sim, "pine")
if tree < 0:
fail("no pine with open ground to its west")
return
var box: AABB = props.boxes[tree]
var start: Vector2 = Vector2(box.position.x - 6.0, box.get_center().z)
var id: int = sim.add_player()
var player: SimEntity = sim.entities.find(id)
player.position = Vector3(start.x, sim.ground.terrain_height(start.x, start.y), start.y)
# Walk due east (+x, yaw 90 degrees) into the trunk for three seconds.
_walk(sim, id, PI * 0.5, 90)
assert_true(player.position.x < box.position.x, "walked through a standing pine to %s" % player.position)
assert_true(player.position.x > box.position.x - Tuning.PLAYER_RADIUS - 0.3, "never reached the trunk, stopped at %s" % player.position)
var hits: int = 0
var full: int = props.health[tree]
while props.is_standing(tree):
var destroyed_now: bool = sim.damage_prop(tree, 45)
hits += 1
assert_eq(destroyed_now, not props.is_standing(tree))
if hits >= 100:
fail("pine never fell")
return
assert_eq(hits, ceili(float(full) / 45.0))
assert_eq(props.health[tree], 0)
assert_eq(props.destroyed, PackedInt32Array([tree]))
assert_false(sim.damage_prop(tree, 45), "a fallen pine can't fall again")
assert_eq(props.destroyed.size(), 1)
_walk(sim, id, PI * 0.5, 90)
assert_true(player.position.x > box.end.x + 1.0, "still blocked where the pine stood, at %s" % player.position)
func test_damage_is_part_of_the_state_hash_and_deterministic() -> void:
var a: Simulation = Simulation.new(8)
var b: Simulation = Simulation.new(8)
assert_eq(a.state_hash(), b.state_hash())
for prop: int in [3, 40, 41, 900]:
a.damage_prop(prop, 30)
b.damage_prop(prop, 30)
assert_eq(a.state_hash(), b.state_hash(), "same damage, same hash")
b.damage_prop(5, 1)
assert_ne(a.state_hash(), b.state_hash(), "a single point of prop damage must change the hash")
assert_false(a.damage_prop(-1, 10), "unknown props are ignored")
assert_false(a.damage_prop(a.props.count(), 10), "unknown props are ignored")
assert_false(a.damage_prop(7, 0), "zero damage does nothing")
assert_false(a.damage_prop(7, -5), "negative damage does nothing")
assert_eq(a.props.health[7], Tuning.PROP_KINDS[a.props.kind_name(7)]["health"])
func test_near_finds_standing_props_nearest_first() -> void:
var sim: Simulation = Simulation.new(2)
var props: PropSet = sim.props
var target: int = props.count() / 2
var at: Vector3 = props.boxes[target].get_center()
var found: PackedInt32Array = props.near(at, 3.0)
assert_eq(found[0], target)
while props.is_standing(target):
sim.damage_prop(target, 1000)
assert_false(props.near(at, 3.0).has(target), "destroyed props aren't near anything")
func test_simulation_with_props_stays_within_tick_budget() -> void:
# 24 players walking through the thickest forest: collision against thousands of
# boxes must stay cheap. Generous bound; the smoke run reports the real p95.
var sim: Simulation = Simulation.new(1)
var random: RandomNumberGenerator = RandomNumberGenerator.new()
random.seed = 1
var ids: Array[int] = []
var pines: PackedInt32Array = PackedInt32Array()
for prop: int in sim.props.count():
if sim.props.kind_name(prop) == "pine":
pines.append(prop)
for index: int in Tuning.SOLO_PLAYERS:
var id: int = sim.add_player()
var near: AABB = sim.props.boxes[pines[(index * 97) % pines.size()]]
var spot: Vector2 = Vector2(near.position.x - 1.5, near.position.z - 1.5)
var player: SimEntity = sim.entities.find(id)
player.position = Vector3(spot.x, sim.ground.terrain_height(spot.x, spot.y), spot.y)
ids.append(id)
var worst: int = 0
var total: int = 0
var ticks: int = 300
for _tick: int in ticks:
for id: int in ids:
var move: Vector2 = Vector2(random.randf_range(-1.0, 1.0), 1.0)
sim.submit_command(id, PlayerCommand.from_input(sim.tick, move, random.randf() * TAU, 0.0, PlayerCommand.BUTTON_SPRINT))
var started: int = Time.get_ticks_usec()
sim.step()
var spent: int = Time.get_ticks_usec() - started
total += spent
worst = maxi(worst, spent)
print(" props: 24 players in forest, mean tick %d us, worst %d us" % [total / ticks, worst])
assert_true(total / ticks < 6000, "mean tick %d us" % (total / ticks))
func _walk(sim: Simulation, id: int, yaw: float, ticks: int) -> void:
for _tick: int in ticks:
sim.submit_command(id, PlayerCommand.from_input(sim.tick, Vector2(0.0, 1.0), yaw, 0.0, 0))
sim.step()
## The first standing prop of `kind` with 8 m of open, gentle ground to its west.
func _first_open(sim: Simulation, kind: String) -> int:
for prop: int in sim.props.count():
if sim.props.kind_name(prop) != kind:
continue
var box: AABB = sim.props.boxes[prop]
var z: float = box.get_center().z
var clear: bool = true
var x: float = box.position.x - 8.0
while x < box.end.x + 3.0 and clear:
# Skip the strip where a body would touch the trunk itself.
var reach: float = Tuning.PLAYER_RADIUS + 0.2
if x < box.position.x - reach or x > box.end.x + reach:
var feet: Vector3 = Vector3(x, sim.ground.terrain_height(x, z), z)
if sim.ground.body_blocked(feet, Tuning.PLAYER_RADIUS + 0.1, Tuning.PLAYER_HEIGHT, Tuning.STEP_HEIGHT) or not sim.ground.walkable_terrain(x, z):
clear = false
x += 0.25
var rise: float = absf(sim.ground.terrain_height(box.end.x + 3.0, z) - sim.ground.terrain_height(box.position.x - 8.0, z))
if clear and rise < 1.5:
return prop
return -1
+1
View File
@@ -0,0 +1 @@
uid://byhrm80nv3nm0
+132
View File
@@ -0,0 +1,132 @@
extends TestCase
func _tilted() -> SimGround:
# h = 0.5 * x, a plane rising along +x.
var values: PackedFloat32Array = PackedFloat32Array()
for z: int in 4:
for x: int in 4:
values.append(0.5 * x * 2.0)
return SimGround.from_heights(values, 4, 2.0)
func test_flat_ground() -> void:
var ground: SimGround = SimGround.flat(3.0)
assert_eq(ground.terrain_height(10.0, 900.0), 3.0)
assert_true(ground.terrain_normal(10.0, 10.0).is_equal_approx(Vector3.UP))
assert_true(ground.walkable_terrain(10.0, 10.0))
func test_interpolation_and_edges() -> void:
var ground: SimGround = _tilted()
assert_near(ground.terrain_height(1.0, 1.0), 0.5, 0.0001)
assert_near(ground.terrain_height(3.0, 5.0), 1.5, 0.0001)
# Outside the grid, the edge sample is used.
assert_near(ground.terrain_height(-5.0, 2.0), 0.0, 0.0001)
assert_near(ground.terrain_height(100.0, 2.0), 3.0, 0.0001)
func test_normal_and_walkability() -> void:
var ground: SimGround = _tilted()
var normal: Vector3 = ground.terrain_normal(3.0, 3.0)
assert_near(rad_to_deg(normal.angle_to(Vector3.UP)), rad_to_deg(atan(0.5)), 0.01)
assert_true(normal.x < 0.0, "the normal leans away from the rise")
assert_true(ground.walkable_terrain(3.0, 3.0))
func test_support_from_solids() -> void:
var ground: SimGround = SimGround.flat()
ground.add_solid(AABB(Vector3(0.0, 0.0, 0.0), Vector3(2.0, 1.0, 2.0)))
ground.add_solid(AABB(Vector3(0.0, 5.0, 0.0), Vector3(2.0, 1.0, 2.0)))
assert_eq(ground.support_height(1.0, 1.0, 1.2), 1.0)
assert_eq(ground.support_height(1.0, 1.0, 10.0), 6.0)
assert_eq(ground.support_height(1.0, 1.0, 0.5), 0.0)
assert_eq(ground.support_height(3.0, 1.0, 10.0), 0.0)
assert_true(ground.support_is_solid(1.0, 1.0, 1.2))
assert_false(ground.support_is_solid(3.0, 1.0, 1.2))
func test_negative_size_solids_are_normalised() -> void:
var ground: SimGround = SimGround.flat()
ground.add_solid(AABB(Vector3(2.0, 1.0, 2.0), Vector3(-2.0, -1.0, -2.0)))
assert_eq(ground.support_height(1.0, 1.0, 5.0), 1.0)
func test_raycast_against_a_box() -> void:
var ground: SimGround = SimGround.flat(-100.0)
ground.add_solid(AABB(Vector3(4.0, -1.0, -1.0), Vector3(2.0, 2.0, 2.0)))
assert_near(ground.raycast(Vector3.ZERO, Vector3(10.0, 0.0, 0.0)), 0.4, 0.0001)
assert_eq(ground.raycast(Vector3.ZERO, Vector3(3.0, 0.0, 0.0)), 1.0)
assert_eq(ground.raycast(Vector3(0.0, 5.0, 0.0), Vector3(10.0, 5.0, 0.0)), 1.0)
assert_eq(ground.raycast(Vector3(5.0, 0.0, 0.0), Vector3(10.0, 0.0, 0.0)), 0.0, "starting inside")
func test_raycast_against_terrain() -> void:
var ground: SimGround = SimGround.flat(0.0)
var hit: float = ground.raycast(Vector3(0.0, 2.0, 0.0), Vector3(0.0, -2.0, 0.0))
assert_near(hit, 0.5, 0.001)
assert_eq(ground.raycast(Vector3(0.0, 2.0, 0.0), Vector3(5.0, 1.0, 0.0)), 1.0)
assert_eq(ground.raycast(Vector3(0.0, -1.0, 0.0), Vector3(0.0, 3.0, 0.0)), 0.0, "starting below")
# A ray grazing up a slope finds where it enters.
var tilted: SimGround = _tilted()
var slope_hit: float = tilted.raycast(Vector3(0.0, 2.0, 2.0), Vector3(6.0, 2.0, 2.0))
assert_near(slope_hit * 6.0, 4.0, 0.01)
func test_body_blocked_respects_step_and_height() -> void:
var ground: SimGround = SimGround.flat()
ground.add_solid(AABB(Vector3(0.0, 0.0, 0.0), Vector3(2.0, 0.4, 2.0)))
ground.add_solid(AABB(Vector3(10.0, 2.0, 0.0), Vector3(2.0, 1.0, 2.0)))
assert_false(ground.body_blocked(Vector3(1.0, 0.0, 1.0), 0.4, 1.8, 0.45), "low step")
assert_true(ground.body_blocked(Vector3(1.0, 0.0, 1.0), 0.4, 1.8, 0.0))
assert_true(ground.body_blocked(Vector3(2.3, 0.0, 1.0), 0.4, 1.8, 0.0), "radius overlaps")
assert_false(ground.body_blocked(Vector3(2.5, 0.0, 1.0), 0.4, 1.8, 0.0))
assert_false(ground.body_blocked(Vector3(11.0, 0.0, 1.0), 0.4, 1.8, 0.0), "fits under")
assert_true(ground.body_blocked(Vector3(11.0, 0.0, 1.0), 0.4, 2.5, 0.0))
func test_index_finds_solids_across_cells() -> void:
var ground: SimGround = SimGround.flat()
# Spans several index cells, including negative ones.
ground.add_solid(AABB(Vector3(-5.0, 0.0, -5.0), Vector3(30.0, 2.0, 3.0)))
assert_eq(ground.support_height(20.0, -4.0, 5.0), 2.0)
assert_eq(ground.support_height(-4.0, -4.0, 5.0), 2.0)
assert_eq(ground.support_height(20.0, 4.0, 5.0), 0.0)
assert_true(ground.body_blocked(Vector3(12.0, 0.0, -1.7), 0.4, 1.8, 0.0), "radius reaches into the next cell")
# The box's far side from the ray's start is at z = -2, 22 m along a 40 m ray.
assert_near(ground.raycast(Vector3(15.0, 1.0, 20.0), Vector3(15.0, 1.0, -20.0)), 22.0 / 40.0, 0.0001)
func test_index_gives_the_same_answers_as_a_full_scan() -> void:
var ground: SimGround = SimGround.flat()
var random: RandomNumberGenerator = RandomNumberGenerator.new()
random.seed = 5
for _index: int in 200:
var at: Vector3 = Vector3(random.randf_range(0.0, 100.0), random.randf_range(0.0, 4.0), random.randf_range(0.0, 100.0))
ground.add_solid(AABB(at, Vector3(random.randf_range(0.2, 12.0), random.randf_range(0.2, 3.0), random.randf_range(0.2, 12.0))))
for _index: int in 500:
var x: float = random.randf_range(0.0, 100.0)
var z: float = random.randf_range(0.0, 100.0)
var expected: float = 0.0
for box: AABB in ground.solids:
if box.end.y <= 6.0 and x > box.position.x and x < box.end.x and z > box.position.z and z < box.end.z:
expected = maxf(expected, box.end.y)
assert_eq(ground.support_height(x, z, 6.0), expected)
func test_removed_solids_vanish_from_every_query() -> void:
var ground: SimGround = SimGround.flat()
var keep: int = ground.add_solid(AABB(Vector3(0.0, 0.0, 0.0), Vector3(2.0, 1.0, 2.0)))
var gone: int = ground.add_solid(AABB(Vector3(10.0, 0.0, 10.0), Vector3(20.0, 3.0, 2.0)))
assert_eq(gone, keep + 1)
assert_true(ground.body_blocked(Vector3(15.0, 0.0, 11.0), 0.4, 1.8, 0.0))
assert_true(ground.remove_solid(gone))
assert_false(ground.remove_solid(gone), "removing twice reports false")
assert_false(ground.remove_solid(99), "unknown IDs report false")
assert_false(ground.body_blocked(Vector3(15.0, 0.0, 11.0), 0.4, 1.8, 0.0))
assert_eq(ground.support_height(25.0, 11.0, 10.0), 0.0)
assert_eq(ground.raycast(Vector3(5.0, 1.0, 11.0), Vector3(35.0, 1.0, 11.0)), 1.0)
assert_false(ground.point_inside(Vector3(15.0, 1.0, 11.0)))
# The other solid keeps its ID and still collides, and new IDs never reuse old ones.
assert_eq(ground.support_height(1.0, 1.0, 5.0), 1.0)
assert_eq(ground.add_solid(AABB(Vector3(40.0, 0.0, 40.0), Vector3.ONE)), gone + 1)
+1
View File
@@ -0,0 +1 @@
uid://b2yuyo1vyam3j

Some files were not shown because too many files have changed in this diff Show More