diff --git a/docs/GDD.md b/docs/GDD.md index 7ca8130..1d0e79b 100644 --- a/docs/GDD.md +++ b/docs/GDD.md @@ -85,6 +85,26 @@ Each is assembled from modular parts (walls with doors, plinths, steps, roofs, s 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. + ## Tide phases `TIDE_PHASES` is an ordered list of phases. Each one sets: diff --git a/src/client/props/prop_view.gd b/src/client/props/prop_view.gd new file mode 100644 index 0000000..30f54b9 --- /dev/null +++ b/src/client/props/prop_view.gd @@ -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 diff --git a/src/client/props/prop_view.gd.uid b/src/client/props/prop_view.gd.uid new file mode 100644 index 0000000..36e5b76 --- /dev/null +++ b/src/client/props/prop_view.gd.uid @@ -0,0 +1 @@ +uid://c4qtatighmhh7 diff --git a/src/sim/prop_set.gd b/src/sim/prop_set.gd new file mode 100644 index 0000000..1b1b30c --- /dev/null +++ b/src/sim/prop_set.gd @@ -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) diff --git a/src/sim/prop_set.gd.uid b/src/sim/prop_set.gd.uid new file mode 100644 index 0000000..ed0ba09 --- /dev/null +++ b/src/sim/prop_set.gd.uid @@ -0,0 +1 @@ +uid://mdvwhfhnp6nk diff --git a/src/sim/sim_ground.gd b/src/sim/sim_ground.gd index cdaeefe..d38a400 100644 --- a/src/sim/sim_ground.gd +++ b/src/sim/sim_ground.gd @@ -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 diff --git a/src/sim/simulation.gd b/src/sim/simulation.gd index 5ed2982..87151ab 100644 --- a/src/sim/simulation.gd +++ b/src/sim/simulation.gd @@ -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) diff --git a/src/sim/tuning.gd b/src/sim/tuning.gd index 20756a8..c9289ea 100644 --- a/src/sim/tuning.gd +++ b/src/sim/tuning.gd @@ -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. diff --git a/test/capture/props_beach.tscn b/test/capture/props_beach.tscn new file mode 100644 index 0000000..229e3a4 --- /dev/null +++ b/test/capture/props_beach.tscn @@ -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) diff --git a/test/capture/props_crate.tscn b/test/capture/props_crate.tscn new file mode 100644 index 0000000..bc24e53 --- /dev/null +++ b/test/capture/props_crate.tscn @@ -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) diff --git a/test/capture/props_felled.tscn b/test/capture/props_felled.tscn new file mode 100644 index 0000000..1ad2f39 --- /dev/null +++ b/test/capture/props_felled.tscn @@ -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 diff --git a/test/capture/props_forest.tscn b/test/capture/props_forest.tscn new file mode 100644 index 0000000..3670afd --- /dev/null +++ b/test/capture/props_forest.tscn @@ -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) diff --git a/test/capture/props_highland.tscn b/test/capture/props_highland.tscn new file mode 100644 index 0000000..d94c4b9 --- /dev/null +++ b/test/capture/props_highland.tscn @@ -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) diff --git a/test/capture/props_overview.tscn b/test/capture/props_overview.tscn new file mode 100644 index 0000000..42325c5 --- /dev/null +++ b/test/capture/props_overview.tscn @@ -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 diff --git a/test/capture/terrain_scene.gd b/test/capture/terrain_scene.gd index fb6a57c..eb2e7ef 100644 --- a/test/capture/terrain_scene.gd +++ b/test/capture/terrain_scene.gd @@ -19,6 +19,16 @@ const CRACK_COLOUR: Color = Color(1.0, 0.0, 1.0) ## 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 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: @@ -74,6 +84,35 @@ func _ready() -> void: 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 add_child(camera) camera.look_at(look_at_point) camera.make_current() diff --git a/test/client/test_prop_view.gd b/test/client/test_prop_view.gd new file mode 100644 index 0000000..fae22b4 --- /dev/null +++ b/test/client/test_prop_view.gd @@ -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() diff --git a/test/client/test_prop_view.gd.uid b/test/client/test_prop_view.gd.uid new file mode 100644 index 0000000..15323a1 --- /dev/null +++ b/test/client/test_prop_view.gd.uid @@ -0,0 +1 @@ +uid://cd4w660y6qjeg diff --git a/test/sim/test_props.gd b/test/sim/test_props.gd new file mode 100644 index 0000000..13b53b7 --- /dev/null +++ b/test/sim/test_props.gd @@ -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 diff --git a/test/sim/test_props.gd.uid b/test/sim/test_props.gd.uid new file mode 100644 index 0000000..5e860db --- /dev/null +++ b/test/sim/test_props.gd.uid @@ -0,0 +1 @@ +uid://byhrm80nv3nm0 diff --git a/test/sim/test_sim_ground.gd b/test/sim/test_sim_ground.gd index 3ab137f..96a3c6d 100644 --- a/test/sim/test_sim_ground.gd +++ b/test/sim/test_sim_ground.gd @@ -112,3 +112,21 @@ func test_index_gives_the_same_answers_as_a_full_scan() -> void: 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)