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>
This commit is contained in:
2026-11-11 12:17:42 -05:00
co-authored by Claude Opus 5.5
parent 283d0e966e
commit 5db53de4e8
20 changed files with 1116 additions and 1 deletions
+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
+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
+29 -1
View File
@@ -13,6 +13,8 @@ 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),
@@ -50,7 +52,8 @@ static func from_heights(values: PackedFloat32Array, side: int, spacing: float)
return ground
func add_solid(box: AABB) -> void:
## 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)
@@ -62,6 +65,31 @@ func add_solid(box: AABB) -> void:
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
+13
View File
@@ -18,6 +18,9 @@ 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()
## Player entity ID -> { command tick -> PlayerCommand }
var _pending: Dictionary = {}
@@ -34,6 +37,8 @@ func _init(match_seed: int, world: SimGround = null) -> void:
world = island.ground
pois = PoiSet.generate(island)
pois.add_solids_to(world)
props = PropSet.generate(island, pois)
props.add_solids_to(world)
ground = world
@@ -92,6 +97,11 @@ func _apply_command(player: SimEntity, command: PlayerCommand) -> void:
Movement.step(player, command, ground)
## 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.
func state_hash() -> String:
var buffer: StreamPeerBuffer = StreamPeerBuffer.new()
@@ -115,6 +125,9 @@ func state_hash() -> String:
for value: float in [entity.velocity.x, entity.velocity.y, entity.velocity.z]:
buffer.put_64(roundi(value * 1000.0))
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)
+21
View File
@@ -87,6 +87,27 @@ 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
# must exceed ISLAND_MAX_HEIGHT, so that every match ends.