B2: Grid building and placement preview

Server-authoritative grid building with wall, floor, ramp, roof and
breakwater pieces in driftwood, stone and salvage iron, plus a client
placement ghost.

- StructureSet: pieces in grid slots (floor, two wall edges, cell
  volume), their collision boxes in SimGround, and touching-neighbour
  links kept up to date for B3. Ramps are stairs of 0.4 m steps; walls
  over lower ground get a skirt down to the terrain; roofs are a low
  stepped pyramid. Pieces are part of the state hash.
- Building: target() snaps look and position to a slot, and check()
  validates any slot as if a hostile client chose it: state, range,
  occupancy, trapping a player, cost and support. Fire in build mode
  places at most 10 pieces a second; players in a low step are lifted.
- Levels are half a cell (2 m) apart, so ground pieces sit within a
  metre of the builder's feet instead of being half buried.
- Client: StructureView draws pieces from their boxes in plank, course
  or panel strips; ramps draw as a sloped deck. BuildGhost shows sea
  green or rust red from the same target() and check().
- Tests: 15 sim tests (targeting, every rejection, overlap, support,
  stairs climbable, skirts, determinism, 24 builders at 10 pieces a
  second within the tick budget) and 5 client tests (ghost states,
  ghost agrees with the server, view sync, mesh orientation).
- Capture scenarios build_fort and build_fort_side.

Closes #16

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-11 14:23:29 -05:00
co-authored by Claude Opus 5.5
parent b847ba9695
commit f35ebf7171
21 changed files with 1327 additions and 0 deletions
+14
View File
@@ -154,6 +154,20 @@ and `build_seconds`, and materials trade speed for strength. A piece goes up qui
reaches full health only after its `build_seconds` have passed. Pieces with no connection reaches full health only after its `build_seconds` have passed. Pieces with no connection
to the ground collapse. to the ground collapse.
**Placing.** Build mode (Q) shows a ghost of the selected piece where it would go:
sea green if it can be placed, rust red if not. The look direction snaps to a quarter
turn. Walls and breakwaters go on the edge of your own cell in that direction; floors,
ramps and roofs go in the next cell, or in your own cell when you look well down. Ramps
rise away from you. Pieces snap up and down to levels `BUILD_LEVEL_METRES` (half a cell)
apart, choosing the level nearest your feet, or a whole cell higher when you look well
up. A wall built over lower ground gets a skirt down to the terrain, so there is no gap
underneath. The server places a piece only if it is in range (`BUILD_RANGE`), its slot
(and the same slot half a cell up or down) is empty, it wouldn't trap a player, you can
afford it, and it touches the terrain or another piece. A player standing in the low
step of a new floor or ramp is lifted onto it. Holding fire places up to 10 pieces a
second (`BUILD_INTERVAL_TICKS`). Ramps are stairs of `RAMP_STEPS` steps underneath,
drawn as a sloped deck.
**Harvesting.** Holding fire with the boathook swings once every `1 / fire_rate` seconds. **Harvesting.** Holding fire with the boathook swings once every `1 / fire_rate` seconds.
A swing reaches the boathook's `range_max` plus `HARVEST_REACH_SLACK` from the eye, and A swing reaches the boathook's `range_max` plus `HARVEST_REACH_SLACK` from the eye, and
hits the nearest standing prop it passes within `HARVEST_AIM_SLACK` of, unless terrain or hits the nearest standing prop it passes within `HARVEST_AIM_SLACK` of, unless terrain or
+51
View File
@@ -0,0 +1,51 @@
## The placement preview: a translucent copy of the piece where fire would put it, sea
## green when the server would accept it and rust red when it wouldn't. It asks the same
## Building.target() and Building.check() the server runs, so the ghost and the server
## agree on the client's predicted state.
class_name BuildGhost
extends Node3D
const VALID_COLOUR: Color = Color(0.46, 0.80, 0.70, 0.38)
const INVALID_COLOUR: Color = Color(0.86, 0.32, 0.22, 0.38)
## Whether the last update showed a placement the server would accept.
var valid: bool = false
var result: Building.Result = Building.Result.BAD_REQUEST
var target: Building.Target = null
var _mesh: MeshInstance3D = MeshInstance3D.new()
var _surface: StandardMaterial3D = StandardMaterial3D.new()
var _shown_key: String = ""
func _init() -> void:
_surface.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
_surface.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
_surface.cull_mode = BaseMaterial3D.CULL_DISABLED
_surface.no_depth_test = false
_mesh.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
_mesh.material_override = _surface
add_child(_mesh)
## Recomputes the ghost for `player` building `kind` in `material`. Hides it for an
## unknown kind.
func update(sim: Simulation, player: SimEntity, kind: int, material: int) -> void:
target = Building.target(player, kind)
if target == null:
visible = false
valid = false
result = Building.Result.BAD_REQUEST
return
result = Building.check(sim, player, target, material)
valid = result == Building.Result.OK
visible = player.health > 0
var key: String = "%d %s %d" % [target.kind, target.slot, target.facing]
if key != _shown_key:
_shown_key = key
_mesh.mesh = PieceMesher.box_mesh(Building.boxes_for_target(target, sim.ground), Color.WHITE)
_surface.albedo_color = VALID_COLOUR if valid else INVALID_COLOUR
func colour() -> Color:
return _surface.albedo_color
+1
View File
@@ -0,0 +1 @@
uid://bx55hrsf4dmym
+150
View File
@@ -0,0 +1,150 @@
## Builds meshes for structure pieces from their collision boxes, so what players see is
## what blocks them. Faces are split into planks, stone courses or iron panels, each
## with its own slight tint, in the weathered palette from docs/ORIGINALITY.md. This is
## a blockout look; the v0.6 art pass replaces it.
class_name PieceMesher
extends RefCounted
## Base colour per material code, in sRGB.
const COLOURS: Array[Color] = [Color(0.62, 0.50, 0.36), Color(0.60, 0.59, 0.55), Color(0.50, 0.34, 0.26)]
## Size of a plank, course or panel, in metres, per material code.
const STRIP: Array[float] = [0.5, 0.5, 1.0]
## Gap between strips, shown as a darker seam.
const SEAM: float = 0.03
const SEAM_DARKEN: float = 0.45
## A mesh for a piece of `material` made of `boxes`, with strips tinted from `salt`.
static func build(boxes: Array[AABB], material: int, salt: int) -> ArrayMesh:
var tool: SurfaceTool = SurfaceTool.new()
tool.begin(Mesh.PRIMITIVE_TRIANGLES)
var base: Color = COLOURS[clampi(material, 0, COLOURS.size() - 1)]
var strip: float = STRIP[clampi(material, 0, STRIP.size() - 1)]
var index: int = 0
for box: AABB in boxes:
# Seam colour behind the strips.
_box(tool, box.grow(-SEAM * 0.5), base.darkened(SEAM_DARKEN))
# Wood runs vertically; stone and iron in horizontal bands.
var axis: int = 1 if material != Materials.DRIFTWOOD else (0 if box.size.x >= box.size.z else 2)
if box.size[axis] < strip * 1.5 and axis != 1:
axis = 2 if axis == 0 else 0
var count: int = maxi(1, roundi(box.size[axis] / strip))
var step: float = box.size[axis] / count
for part: int in count:
var piece: AABB = box
piece.position[axis] = box.position[axis] + part * step + SEAM * 0.5
piece.size[axis] = step - SEAM
_box(tool, piece, _tint(base, salt * 131 + index * 17 + part))
index += 1
tool.generate_normals()
var mesh: ArrayMesh = tool.commit()
var surface: StandardMaterial3D = StandardMaterial3D.new()
surface.vertex_color_use_as_albedo = true
surface.vertex_color_is_srgb = true
surface.roughness = 0.95 if material != Materials.SALVAGE_IRON else 0.7
surface.metallic = 0.0 if material != Materials.SALVAGE_IRON else 0.25
mesh.surface_set_material(0, surface)
return mesh
## A ramp drawn as a sloped plank deck on a solid wedge, rather than its stair-step
## collision boxes. The slope runs from the cell's low edge at `base` to its far edge
## one cell up, so the deck passes through the nose of every step.
static func build_ramp(slot: Vector4i, facing: int, material: int, salt: int) -> ArrayMesh:
var g: float = Tuning.GRID_CELL_METRES
var base: Color = COLOURS[clampi(material, 0, COLOURS.size() - 1)]
var origin: Vector3 = Vector3(slot.x * g, slot.y * Tuning.BUILD_LEVEL_METRES, slot.z * g)
var direction: Vector2i = StructureSet.FACING_DIRECTIONS[facing]
var tool: SurfaceTool = SurfaceTool.new()
tool.begin(Mesh.PRIMITIVE_TRIANGLES)
tool.set_smooth_group(-1)
var planks: int = 8
for plank: int in planks:
var u0: float = (plank + 0.04) / planks
var u1: float = (plank + 0.96) / planks
var colour: Color = _tint(base, salt * 131 + plank)
var corners: Array[Vector3] = []
for corner: Vector2 in [Vector2(u0, 0.0), Vector2(u1, 0.0), Vector2(u1, 1.0), Vector2(u0, 1.0)]:
corners.append(origin + _ramp_point(direction, corner.x, corner.y, g) + Vector3(0.0, 0.02, 0.0))
_quad(tool, corners, colour, Vector3.UP)
# Sides and back of the wedge, in the seam colour.
var dark: Color = base.darkened(0.35)
for side: float in [0.0, 1.0]:
var low: Vector3 = origin + _ramp_point(direction, 0.0, side, g)
var high: Vector3 = origin + _ramp_point(direction, 1.0, side, g)
var foot: Vector3 = Vector3(high.x, origin.y, high.z)
tool.set_color(dark)
for point: Vector3 in [low, high, foot, low, foot, high]:
tool.add_vertex(point)
var back: Array[Vector3] = [
origin + _ramp_point(direction, 1.0, 0.0, g), origin + _ramp_point(direction, 1.0, 1.0, g),
]
var back_low: Array[Vector3] = [Vector3(back[0].x, origin.y, back[0].z), Vector3(back[1].x, origin.y, back[1].z)]
tool.set_color(dark)
for point: Vector3 in [back[0], back[1], back_low[1], back[0], back_low[1], back_low[0], back[0], back_low[1], back[1], back[0], back_low[0], back_low[1]]:
tool.add_vertex(point)
tool.generate_normals()
var mesh: ArrayMesh = tool.commit()
var surface: StandardMaterial3D = StandardMaterial3D.new()
surface.vertex_color_use_as_albedo = true
surface.vertex_color_is_srgb = true
surface.roughness = 0.95
surface.cull_mode = BaseMaterial3D.CULL_DISABLED
mesh.surface_set_material(0, surface)
return mesh
## A point on a ramp's deck: `along` 0..1 up the slope, `across` 0..1 side to side.
static func _ramp_point(direction: Vector2i, along: float, across: float, g: float) -> Vector3:
var height: float = along * g
if direction.x > 0:
return Vector3(along * g, height, across * g)
if direction.x < 0:
return Vector3((1.0 - along) * g, height, across * g)
if direction.y > 0:
return Vector3(across * g, height, along * g)
return Vector3(across * g, height, (1.0 - along) * g)
## Adds a quad with both windings, so it shows from either side.
static func _quad(tool: SurfaceTool, corners: Array[Vector3], colour: Color, _up: Vector3) -> void:
tool.set_color(colour)
for index: int in [0, 1, 2, 0, 2, 3, 0, 2, 1, 0, 3, 2]:
tool.add_vertex(corners[index])
## A plain box mesh, every face flat.
static func box_mesh(boxes: Array[AABB], colour: Color) -> ArrayMesh:
var tool: SurfaceTool = SurfaceTool.new()
tool.begin(Mesh.PRIMITIVE_TRIANGLES)
for box: AABB in boxes:
_box(tool, box, colour)
tool.generate_normals()
return tool.commit()
static func _tint(base: Color, key: int) -> Color:
var h: int = hash(key * 2654435761)
var shift: float = (float(h & 0xff) / 255.0 - 0.5) * 0.14
var warm: float = (float((h >> 8) & 0xff) / 255.0 - 0.5) * 0.06
return Color(clampf(base.r + shift + warm, 0.0, 1.0), clampf(base.g + shift, 0.0, 1.0), clampf(base.b + shift - warm, 0.0, 1.0))
static func _box(tool: SurfaceTool, box: AABB, colour: Color) -> void:
var a: Vector3 = box.position
var b: Vector3 = box.end
var corners: Array[Vector3] = [
Vector3(a.x, a.y, a.z), Vector3(b.x, a.y, a.z), Vector3(b.x, a.y, b.z), Vector3(a.x, a.y, b.z),
Vector3(a.x, b.y, a.z), Vector3(b.x, b.y, a.z), Vector3(b.x, b.y, b.z), Vector3(a.x, b.y, b.z),
]
# Each face as four corner indices, wound clockwise seen from outside (Godot's front).
var faces: Array[PackedInt32Array] = [
PackedInt32Array([4, 5, 6, 7]), PackedInt32Array([3, 2, 1, 0]),
PackedInt32Array([0, 1, 5, 4]), PackedInt32Array([2, 3, 7, 6]),
PackedInt32Array([3, 0, 4, 7]), PackedInt32Array([1, 2, 6, 5]),
]
tool.set_smooth_group(-1)
tool.set_color(colour)
for face: PackedInt32Array in faces:
for corner: int in [0, 1, 2, 0, 2, 3]:
tool.add_vertex(corners[face[corner]])
+1
View File
@@ -0,0 +1 @@
uid://c3ndxshlqtytj
+42
View File
@@ -0,0 +1,42 @@
## Draws every built piece. `sync()` adds a mesh for each piece the simulation has that
## isn't drawn yet and drops meshes for pieces that are gone. Collision never comes from
## here; the simulation's SimGround holds the pieces' boxes.
class_name StructureView
extends Node3D
var _structures: StructureSet
## Piece ID -> MeshInstance3D.
var _drawn: Dictionary = {}
func setup(structures: StructureSet) -> void:
_structures = structures
sync()
func sync() -> void:
if _structures == null:
return
for piece_id: int in _drawn.keys():
if _structures.find(piece_id) == null:
_drawn[piece_id].queue_free()
_drawn.erase(piece_id)
for piece: StructureSet.Piece in _structures.pieces.values():
if _drawn.has(piece.id):
continue
var instance: MeshInstance3D = MeshInstance3D.new()
instance.name = "piece_%d" % piece.id
if piece.kind == StructureSet.RAMP:
instance.mesh = PieceMesher.build_ramp(piece.slot, piece.facing, piece.material, piece.id)
else:
instance.mesh = PieceMesher.build(piece.boxes, piece.material, piece.id)
add_child(instance)
_drawn[piece.id] = instance
func drawn_count() -> int:
return _drawn.size()
func _process(_delta: float) -> void:
sync()
@@ -0,0 +1 @@
uid://cekgr5ql1etfr
+193
View File
@@ -0,0 +1,193 @@
## Server-authoritative placement. In build mode (BUTTON_BUILD held) a command's
## `selection` is the piece kind and `material` the material code, and fire places.
## The server works out the slot from its own copy of the player's position and look,
## with target(), the same function the client's ghost uses. check() then validates the
## slot as if a hostile client had chosen it.
##
## Targeting: the look direction is snapped to a quarter turn. Walls and breakwaters go
## on the edge of the builder's own cell in that direction. Floors, ramps and roofs go
## in the next cell that way, or in the builder's own cell when looking well down. Ramps
## rise away from the builder. The level is the one nearest the feet, plus a whole cell
## (two levels) when looking well up.
class_name Building
extends RefCounted
enum Result {
OK,
## Dead, swimming, aboard the barge or falling.
NOT_ALLOWED,
## Unknown piece kind or material.
BAD_REQUEST,
OUT_OF_WORLD,
OUT_OF_RANGE,
OCCUPIED,
## Would trap a player inside it.
BLOCKED_BY_PLAYER,
UNAFFORDABLE,
## Touches neither the terrain nor another piece.
UNSUPPORTED,
}
## Where a piece would go.
class Target:
extends RefCounted
var kind: int = 0
var slot: Vector4i = Vector4i.ZERO
var facing: int = 0
static func is_allowed(player: SimEntity) -> bool:
return player.health > 0 and player.drop_state == Drop.NONE and not player.swimming
## Quarter-turn facing (0 +z, 1 +x, 2 -z, 3 -x) nearest the player's yaw.
static func facing_of(player: SimEntity) -> int:
return posmod(roundi(float(player.yaw) / PlayerCommand.YAW_STEPS * 4.0), 4)
## The slot a piece of `kind` would go in from the player's current pose, or null for
## an unknown kind.
static func target(player: SimEntity, kind: int) -> Target:
if kind < 0 or kind >= StructureSet.KINDS.size():
return null
var g: float = StructureSet.cell_size()
var facing: int = facing_of(player)
var direction: Vector2i = StructureSet.FACING_DIRECTIONS[facing]
var pitch_degrees: float = float(player.pitch) / PlayerCommand.PITCH_MAX * 90.0
var feet: Vector3 = player.position
var cell: Vector2i = Vector2i(floori(feet.x / g), floori(feet.z / g))
var level: int = roundi(feet.y / Tuning.BUILD_LEVEL_METRES)
if pitch_degrees > Tuning.BUILD_LOOK_UP_DEGREES:
level += roundi(g / Tuning.BUILD_LEVEL_METRES)
var result: Target = Target.new()
result.kind = kind
result.facing = facing
if StructureSet.is_wall_kind(kind):
match facing:
0:
result.slot = Vector4i(cell.x, level, cell.y + 1, StructureSet.SLOT_WALL_Z)
1:
result.slot = Vector4i(cell.x + 1, level, cell.y, StructureSet.SLOT_WALL_X)
2:
result.slot = Vector4i(cell.x, level, cell.y, StructureSet.SLOT_WALL_Z)
_:
result.slot = Vector4i(cell.x, level, cell.y, StructureSet.SLOT_WALL_X)
# A wall's facing only records which side the builder stood on.
return result
var looking_down: bool = pitch_degrees < -Tuning.BUILD_LOOK_DOWN_DEGREES
if not looking_down:
cell += direction
result.slot = Vector4i(cell.x, level, cell.y, StructureSet.slot_type_of(kind))
return result
## The boxes the piece would have, skirt included, as placed in `ground`.
static func boxes_for_target(at: Target, ground: SimGround) -> Array[AABB]:
var boxes: Array[AABB] = StructureSet.boxes_for(at.kind, at.slot, at.facing)
if StructureSet.is_wall_kind(at.kind):
var skirt: AABB = StructureSet.skirt_for(at.kind, boxes[0], ground)
if skirt.size != Vector3.ZERO:
boxes.append(skirt)
return boxes
## Whether `player` may place a piece of `at.kind` in `material` at `at`. Checks
## everything, as if a hostile client had picked the slot.
static func check(sim: Simulation, player: SimEntity, at: Target, material: int) -> Result:
if not is_allowed(player):
return Result.NOT_ALLOWED
if at == null or at.kind < 0 or at.kind >= StructureSet.KINDS.size() or not Materials.is_valid(material):
return Result.BAD_REQUEST
if at.facing < 0 or at.facing > 3 or at.slot.w != _expected_slot_type(at):
return Result.BAD_REQUEST
var boxes: Array[AABB] = boxes_for_target(at, sim.ground)
if not _inside_world(at, boxes[0]):
return Result.OUT_OF_WORLD
var centre: Vector3 = boxes[0].get_center()
if at.kind == StructureSet.RAMP:
var whole: AABB = boxes[0]
for box: AABB in boxes:
whole = whole.merge(box)
centre = whole.get_center()
if Harvest.eye(player).distance_to(centre) > Tuning.BUILD_RANGE:
return Result.OUT_OF_RANGE
if sim.structures.occupied(at.slot):
return Result.OCCUPIED
if _traps_a_player(sim, boxes):
return Result.BLOCKED_BY_PLAYER
if player.materials[material] < StructureSet.cost_of(at.kind):
return Result.UNAFFORDABLE
if not StructureSet.touches_terrain(boxes, sim.ground) and sim.structures.touching(boxes, sim.ground).is_empty():
return Result.UNSUPPORTED
return Result.OK
## Validates and places. Returns the result; on OK the piece is in `sim.structures`, its
## cost is spent, players standing in a low step of it are lifted onto it, and a
## "piece_placed" event is recorded.
static func place(sim: Simulation, player: SimEntity, at: Target, material: int) -> Result:
var result: Result = check(sim, player, at, material)
if result != Result.OK:
return result
Materials.spend(player, material, StructureSet.cost_of(at.kind))
var piece: StructureSet.Piece = sim.structures.add(at.kind, material, at.slot, at.facing, player.id, sim.tick, sim.ground)
_lift_players(sim, piece.boxes)
sim.events.append({"type": "piece_placed", "player": player.id, "piece": piece.id, "kind": at.kind, "material": material})
return result
## A tick of build mode: fire places at the target if the cooldown allows.
static func act(sim: Simulation, player: SimEntity, command: PlayerCommand) -> void:
if player.action_cooldown > 0 or not command.is_pressed(PlayerCommand.BUTTON_FIRE):
return
var at: Target = target(player, command.selection)
if place(sim, player, at, command.material) == Result.OK:
player.action_cooldown = Tuning.BUILD_INTERVAL_TICKS
static func _expected_slot_type(at: Target) -> int:
if StructureSet.is_wall_kind(at.kind):
return at.slot.w if at.slot.w == StructureSet.SLOT_WALL_X or at.slot.w == StructureSet.SLOT_WALL_Z else -1
return StructureSet.slot_type_of(at.kind)
static func _inside_world(at: Target, box: AABB) -> bool:
if at.slot.y < Tuning.BUILD_MIN_LEVEL or at.slot.y > Tuning.BUILD_MAX_LEVEL:
return false
var size: float = Tuning.WORLD_SIZE_METRES
var slack: float = Tuning.BREAKWATER_THICKNESS
return box.position.x >= -slack and box.position.z >= -slack and box.end.x <= size + slack and box.end.z <= size + slack
## True if any player's body overlaps the boxes by more than a step.
static func _traps_a_player(sim: Simulation, boxes: Array[AABB]) -> bool:
for entity: SimEntity in sim.entities.entities():
if entity.archetype != SimEntity.ARCHETYPE_PLAYER or entity.health <= 0:
continue
var feet: Vector3 = entity.position
var height: float = Movement.body_height(entity)
for box: AABB in boxes:
if not _body_overlaps(box, feet, height):
continue
if box.end.y - feet.y > Tuning.STEP_HEIGHT:
return true
return false
static func _lift_players(sim: Simulation, boxes: Array[AABB]) -> void:
for entity: SimEntity in sim.entities.entities():
if entity.archetype != SimEntity.ARCHETYPE_PLAYER:
continue
var feet: Vector3 = entity.position
var height: float = Movement.body_height(entity)
for box: AABB in boxes:
if _body_overlaps(box, feet, height) and box.end.y > entity.position.y:
entity.position.y = box.end.y
static func _body_overlaps(box: AABB, feet: Vector3, height: float) -> bool:
var r: float = Tuning.PLAYER_RADIUS
if box.end.y <= feet.y or box.position.y >= feet.y + height:
return false
return feet.x > box.position.x - r and feet.x < box.end.x + r and feet.z > box.position.z - r and feet.z < box.end.z + r
+1
View File
@@ -0,0 +1 @@
uid://br7ubbpapogdb
+6
View File
@@ -28,6 +28,8 @@ var props: PropSet = PropSet.new()
var sea_level: float = Tuning.SEA_LEVEL_START var sea_level: float = Tuning.SEA_LEVEL_START
## Damage per second to a player underwater with no breath left. Set by the tide phase. ## 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"] var drown_dps: int = Tuning.TIDE_PHASES[0]["drown_dps"]
## Every built piece. Their boxes are part of `ground`.
var structures: StructureSet = StructureSet.new()
## The sky barge, from start_drop() on. Null in matches and tests that start on foot. ## The sky barge, from start_drop() on. Null in matches and tests that start on foot.
var drop: Drop = null var drop: Drop = null
@@ -147,7 +149,10 @@ func _apply_command(player: SimEntity, command: PlayerCommand) -> void:
player.action_cooldown -= 1 player.action_cooldown -= 1
if command == null or not command.is_pressed(PlayerCommand.BUTTON_FIRE): if command == null or not command.is_pressed(PlayerCommand.BUTTON_FIRE):
return return
if not Building.is_allowed(player):
return
if command.is_pressed(PlayerCommand.BUTTON_BUILD): if command.is_pressed(PlayerCommand.BUTTON_BUILD):
Building.act(self, player, command)
return return
if command.selection == BOATHOOK_SLOT: if command.selection == BOATHOOK_SLOT:
Harvest.swing(player, ground, props, events) Harvest.swing(player, ground, props, events)
@@ -202,6 +207,7 @@ func state_hash() -> String:
buffer.put_32(drown_dps) buffer.put_32(drown_dps)
buffer.put_64(props.count()) buffer.put_64(props.count())
buffer.put_data(props.health.to_byte_array()) buffer.put_data(props.health.to_byte_array())
structures.write_state(buffer)
var hasher: HashingContext = HashingContext.new() var hasher: HashingContext = HashingContext.new()
hasher.start(HashingContext.HASH_SHA256) hasher.start(HashingContext.HASH_SHA256)
+278
View File
@@ -0,0 +1,278 @@
## Every built piece in a match: walls, floors, ramps, roofs and breakwaters, snapped to
## a grid of Tuning.GRID_CELL_METRES cells. Each piece fills one slot, and each slot holds
## at most one piece. Pieces are axis-aligned boxes in the SimGround, so movement,
## cameras and line of sight treat them like any other solid.
##
## Slots are Vector4i(x, level, z, type), where a piece's base is `level` times
## Tuning.BUILD_LEVEL_METRES (half a cell) above the starting sea:
## - FLOOR: the bottom face of cell (x, level, z).
## - WALL_X: the face at x = x * GRID between cells x - 1 and x, in row z.
## - WALL_Z: the face at z = z * GRID between cells z - 1 and z, in column x.
## - VOLUME: the inside of cell (x, level, z), for a ramp or a roof.
## Walls and breakwaters share wall slots, so a breakwater can't overlap a wall. A
## piece is a whole cell tall, so a slot also counts as taken when the same slot one
## level above or below holds a piece.
##
## Piece IDs count up from 1 and are never reused. Neighbours are pieces whose boxes
## touch, kept up to date as pieces come and go, for structural integrity.
class_name StructureSet
extends RefCounted
## Piece kind codes index this list. Each name is a key of Tuning.BUILD_PIECES.
const KINDS: Array[String] = ["wall", "floor", "ramp", "roof", "breakwater"]
const WALL: int = 0
const FLOOR: int = 1
const RAMP: int = 2
const ROOF: int = 3
const BREAKWATER: int = 4
const SLOT_FLOOR: int = 0
const SLOT_WALL_X: int = 1
const SLOT_WALL_Z: int = 2
const SLOT_VOLUME: int = 3
## Facings: the way a ramp rises, matching yaw (0 is +z, a quarter turn is +x).
const FACING_DIRECTIONS: Array[Vector2i] = [Vector2i(0, 1), Vector2i(1, 0), Vector2i(0, -1), Vector2i(-1, 0)]
## Boxes closer than this count as touching.
const TOUCH: float = 0.05
## Roof tiers: inset from the cell edge and height of each stacked slab, in metres.
const ROOF_TIERS: Array[Vector2] = [Vector2(0.0, 0.3), Vector2(0.7, 0.3), Vector2(1.4, 0.3)]
## A placed piece.
class Piece:
extends RefCounted
var id: int = 0
var kind: int = 0
var material: int = 0
var slot: Vector4i = Vector4i.ZERO
var facing: int = 0
var owner: int = 0
var health: int = 0
var max_health: int = 0
var placed_tick: int = 0
var boxes: Array[AABB] = []
var solid_ids: PackedInt32Array = PackedInt32Array()
## Touches the terrain.
var grounded: bool = false
## Piece ID -> Piece, in ascending ID order.
var pieces: Dictionary = {}
## Piece ID -> PackedInt32Array of touching piece IDs, ascending.
var neighbours: Dictionary = {}
## Removed piece IDs, in the order they went, for views to catch up on.
var removed: PackedInt32Array = PackedInt32Array()
var _next_id: int = 1
var _by_slot: Dictionary = {}
## SimGround solid ID -> piece ID.
var _by_solid: Dictionary = {}
static func cell_size() -> float:
return Tuning.GRID_CELL_METRES
static func slot_type_of(kind: int) -> int:
match kind:
FLOOR:
return SLOT_FLOOR
RAMP, ROOF:
return SLOT_VOLUME
return -1
static func is_wall_kind(kind: int) -> bool:
return kind == WALL or kind == BREAKWATER
static func cost_of(kind: int) -> int:
return Tuning.BUILD_PIECES[KINDS[kind]]["cost"]
static func max_health_of(material: int) -> int:
return Tuning.MATERIALS[Materials.NAMES[material]]["health"]
func count() -> int:
return pieces.size()
func find(piece_id: int) -> Piece:
return pieces.get(piece_id)
## The piece in a slot, or 0.
func at_slot(slot: Vector4i) -> int:
return _by_slot.get(slot, 0)
## True if the slot, or the same slot a level above or below, holds a piece.
func occupied(slot: Vector4i) -> bool:
for dy: int in [-1, 0, 1]:
if _by_slot.has(Vector4i(slot.x, slot.y + dy, slot.z, slot.w)):
return true
return false
## The piece whose box is ground solid `solid_id`, or 0.
func piece_of_solid(solid_id: int) -> int:
return _by_solid.get(solid_id, 0)
func next_id() -> int:
return _next_id
## The collision boxes a piece of `kind` in `slot` would have, before any skirt.
static func boxes_for(kind: int, slot: Vector4i, facing: int) -> Array[AABB]:
var g: float = cell_size()
var base: float = slot.y * Tuning.BUILD_LEVEL_METRES
var boxes: Array[AABB] = []
match kind:
WALL, BREAKWATER:
var t: float = Tuning.BREAKWATER_THICKNESS if kind == BREAKWATER else Tuning.WALL_THICKNESS
if slot.w == SLOT_WALL_X:
boxes.append(AABB(Vector3(slot.x * g - t * 0.5, base, slot.z * g - t * 0.5), Vector3(t, g, g + t)))
else:
boxes.append(AABB(Vector3(slot.x * g - t * 0.5, base, slot.z * g - t * 0.5), Vector3(g + t, g, t)))
FLOOR:
boxes.append(AABB(Vector3(slot.x * g, base, slot.z * g), Vector3(g, Tuning.FLOOR_THICKNESS, g)))
RAMP:
var steps: int = Tuning.RAMP_STEPS
var depth: float = g / steps
var direction: Vector2i = FACING_DIRECTIONS[facing]
for step: int in steps:
var rise: float = (step + 1) * depth
# Distance along the facing of this step's near edge, from the cell's low side.
var along: float = step * depth
var x0: float = slot.x * g
var z0: float = slot.z * g
var box: AABB
if direction.x != 0:
var start: float = x0 + along if direction.x > 0 else x0 + g - along - depth
box = AABB(Vector3(start, base, z0), Vector3(depth, rise, g))
else:
var start_z: float = z0 + along if direction.y > 0 else z0 + g - along - depth
box = AABB(Vector3(x0, base, start_z), Vector3(g, rise, depth))
boxes.append(box)
ROOF:
var y: float = base
for tier: Vector2 in ROOF_TIERS:
boxes.append(AABB(Vector3(slot.x * g + tier.x, y, slot.z * g + tier.x), Vector3(g - tier.x * 2.0, tier.y, g - tier.x * 2.0)))
y += tier.y
return boxes
## A wall or breakwater standing over lower terrain gets a skirt down to the terrain,
## no deeper than one cell, so ground-level walls leave no gap underneath. Returns the
## skirt box, or an empty AABB when none is needed.
static func skirt_for(kind: int, wall_box: AABB, ground: SimGround) -> AABB:
if not is_wall_kind(kind):
return AABB()
var lowest: float = INF
for fx: float in [0.0, 0.25, 0.5, 0.75, 1.0]:
for fz: float in [0.0, 0.5, 1.0]:
var x: float = lerpf(wall_box.position.x, wall_box.end.x, fx if wall_box.size.x > wall_box.size.z else fz)
var z: float = lerpf(wall_box.position.z, wall_box.end.z, fz if wall_box.size.x > wall_box.size.z else fx)
lowest = minf(lowest, ground.terrain_height(x, z))
var gap: float = wall_box.position.y - lowest
if gap <= 0.0 or gap > cell_size():
return AABB()
var bottom: float = lowest - 0.1
return AABB(Vector3(wall_box.position.x, bottom, wall_box.position.z),
Vector3(wall_box.size.x, wall_box.position.y - bottom, wall_box.size.z))
## True if any of `boxes` reaches down to the terrain.
static func touches_terrain(boxes: Array[AABB], ground: SimGround) -> bool:
for box: AABB in boxes:
for fx: float in [0.0, 0.25, 0.5, 0.75, 1.0]:
for fz: float in [0.0, 0.25, 0.5, 0.75, 1.0]:
var x: float = lerpf(box.position.x, box.end.x, fx)
var z: float = lerpf(box.position.z, box.end.z, fz)
if ground.terrain_height(x, z) >= box.position.y - TOUCH:
return true
return false
## IDs of pieces whose boxes touch any of `boxes`, ascending, without repeats.
func touching(boxes: Array[AABB], ground: SimGround) -> PackedInt32Array:
var found: Dictionary = {}
for box: AABB in boxes:
var grown: AABB = box.grow(TOUCH)
for solid_id: int in ground.solids_near(grown.position.x, grown.position.z, grown.end.x, grown.end.z):
var other: int = piece_of_solid(solid_id)
if other != 0 and not found.has(other) and grown.intersects(ground.solids[solid_id]):
found[other] = true
var ids: PackedInt32Array = PackedInt32Array(found.keys())
ids.sort()
return ids
## Adds a piece, its solids and its neighbour links. The caller has validated it.
func add(kind: int, material: int, slot: Vector4i, facing: int, owner: int, tick: int, ground: SimGround) -> Piece:
var piece: Piece = Piece.new()
piece.id = _next_id
_next_id += 1
piece.kind = kind
piece.material = material
piece.slot = slot
piece.facing = facing
piece.owner = owner
piece.placed_tick = tick
piece.max_health = max_health_of(material)
piece.health = piece.max_health
piece.boxes = boxes_for(kind, slot, facing)
if is_wall_kind(kind):
var skirt: AABB = skirt_for(kind, piece.boxes[0], ground)
if skirt.size != Vector3.ZERO:
piece.boxes.append(skirt)
piece.grounded = touches_terrain(piece.boxes, ground)
var links: PackedInt32Array = touching(piece.boxes, ground)
for box: AABB in piece.boxes:
var solid_id: int = ground.add_solid(box)
piece.solid_ids.append(solid_id)
_by_solid[solid_id] = piece.id
pieces[piece.id] = piece
_by_slot[slot] = piece.id
neighbours[piece.id] = links
for other: int in links:
var theirs: PackedInt32Array = neighbours[other]
theirs.append(piece.id)
neighbours[other] = theirs
return piece
## Removes a piece, its solids and its neighbour links. Returns false if unknown.
func remove(piece_id: int, ground: SimGround) -> bool:
var piece: Piece = pieces.get(piece_id)
if piece == null:
return false
for solid_id: int in piece.solid_ids:
ground.remove_solid(solid_id)
_by_solid.erase(solid_id)
for other: int in neighbours[piece_id]:
var theirs: PackedInt32Array = neighbours[other]
theirs.remove_at(theirs.find(piece_id))
neighbours[other] = theirs
neighbours.erase(piece_id)
_by_slot.erase(piece.slot)
pieces.erase(piece_id)
removed.append(piece_id)
return true
## Appends every piece to a hash buffer in ID order.
func write_state(buffer: StreamPeerBuffer) -> void:
buffer.put_64(_next_id)
buffer.put_64(pieces.size())
for piece: Piece in pieces.values():
buffer.put_64(piece.id)
buffer.put_u8(piece.kind)
buffer.put_u8(piece.material)
buffer.put_u8(piece.facing)
for value: int in [piece.slot.x, piece.slot.y, piece.slot.z, piece.slot.w]:
buffer.put_32(value)
buffer.put_64(piece.owner)
buffer.put_32(piece.health)
buffer.put_64(piece.placed_tick)
+1
View File
@@ -0,0 +1 @@
uid://co6d50yd1osd1
+20
View File
@@ -201,6 +201,26 @@ const MATERIALS: Dictionary = {
"stone": {"health": 300, "build_seconds": 5.0}, "stone": {"health": 300, "build_seconds": 5.0},
"salvage_iron": {"health": 500, "build_seconds": 9.0}, "salvage_iron": {"health": 500, "build_seconds": 9.0},
} }
## Pieces are GRID_CELL_METRES on a side and tall, and snap across to the grid. Up and
## down they snap to levels BUILD_LEVEL_METRES apart, half a cell, so a piece built on
## the ground is never more than a metre above or below the builder's feet. Level 0 is
## the starting sea level; levels run from BUILD_MIN_LEVEL to BUILD_MAX_LEVEL.
const BUILD_LEVEL_METRES: float = 2.0
const BUILD_MIN_LEVEL: int = -8
const BUILD_MAX_LEVEL: int = 63
## A piece's centre must be within this distance of the builder's eye.
const BUILD_RANGE: float = 9.5
## Ticks between placements while fire is held: 10 pieces a second.
const BUILD_INTERVAL_TICKS: int = 3
## Looking further up than this, in degrees, targets the level above.
const BUILD_LOOK_UP_DEGREES: float = 35.0
## Looking further down than this puts floors, ramps and roofs in the builder's own cell.
const BUILD_LOOK_DOWN_DEGREES: float = 40.0
const WALL_THICKNESS: float = 0.3
const BREAKWATER_THICKNESS: float = 0.6
const FLOOR_THICKNESS: float = 0.2
## Ramps are stairs of this many steps, so each riser can be stepped up.
const RAMP_STEPS: int = 10
const BREAKWATER_MAX_HEAD: float = 6.0 const BREAKWATER_MAX_HEAD: float = 6.0
const BREAKWATER_WEAR_PER_METRE: float = 2.0 const BREAKWATER_WEAR_PER_METRE: float = 2.0
const BREACH_FLOW_METRES_PER_SECOND: float = 1.5 const BREACH_FLOW_METRES_PER_SECOND: float = 1.5
+6
View File
@@ -0,0 +1,6 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/build_scene.gd" id="1"]
[node name="CaptureBuild" type="Node3D"]
script = ExtResource("1")
+7
View File
@@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/build_scene.gd" id="1"]
[node name="CaptureBuild" type="Node3D"]
script = ExtResource("1")
view = Vector3(-14, 6, 16)
+154
View File
@@ -0,0 +1,154 @@
## Capture scenario for building (B2): a small fort of every piece kind in all three
## materials on real island terrain, with one valid and one invalid placement ghost.
extends Node3D
@export var island_seed: int = 2
## Camera offset from the fort's corner: x east, y up, z south.
@export var view: Vector3 = Vector3(-11.0, 8.5, -12.0)
func _ready() -> void:
var sim: Simulation = Simulation.new(island_seed)
var g: float = Tuning.GRID_CELL_METRES
var site: Vector2i = _find_site(sim)
var builder_id: int = sim.add_player()
var broke_id: int = sim.add_player()
var builder: SimEntity = sim.entities.find(builder_id)
var broke: SimEntity = sim.entities.find(broke_id)
for code: int in 3:
builder.materials[code] = Tuning.MATERIAL_CAP
var feet: Vector3 = Vector3((site.x + 0.5) * g, 0.0, (site.y + 0.5) * g)
# Fell the trees around the site, so the fort stands in a clearing.
for prop: int in sim.props.near(feet, 40.0):
sim.props.damage(prop, 100000)
feet.y = sim.ground.terrain_height(feet.x, feet.z)
var level: int = roundi(feet.y / Tuning.BUILD_LEVEL_METRES)
var up: int = roundi(g / Tuning.BUILD_LEVEL_METRES)
var placed: Array[String] = []
# A two-cell room: floor, walls in three materials, a roof, a ramp up its side and a
# breakwater on the seaward... well, the near side.
var plan: Array = [
[StructureSet.FLOOR, Vector4i(site.x, level, site.y, StructureSet.SLOT_FLOOR), 0, Materials.DRIFTWOOD],
[StructureSet.FLOOR, Vector4i(site.x + 1, level, site.y, StructureSet.SLOT_FLOOR), 0, Materials.STONE],
[StructureSet.WALL, Vector4i(site.x, level, site.y + 1, StructureSet.SLOT_WALL_Z), 0, Materials.DRIFTWOOD],
[StructureSet.WALL, Vector4i(site.x + 1, level, site.y + 1, StructureSet.SLOT_WALL_Z), 0, Materials.STONE],
[StructureSet.WALL, Vector4i(site.x + 2, level, site.y, StructureSet.SLOT_WALL_X), 0, Materials.SALVAGE_IRON],
[StructureSet.BREAKWATER, Vector4i(site.x + 1, level, site.y, StructureSet.SLOT_WALL_Z), 0, Materials.STONE],
[StructureSet.RAMP, Vector4i(site.x - 1, level, site.y, StructureSet.SLOT_VOLUME), 1, Materials.DRIFTWOOD],
[StructureSet.FLOOR, Vector4i(site.x, level + up, site.y, StructureSet.SLOT_FLOOR), 0, Materials.DRIFTWOOD],
[StructureSet.ROOF, Vector4i(site.x + 1, level + up, site.y, StructureSet.SLOT_VOLUME), 0, Materials.SALVAGE_IRON],
]
for entry: Array in plan:
var at: Building.Target = Building.Target.new()
at.kind = entry[0]
at.slot = entry[1]
at.facing = entry[2]
builder.position = feet + Vector3(0.0, 0.5, 0.0)
var result: Building.Result = Building.place(sim, builder, at, entry[3])
placed.append("%s %s" % [StructureSet.KINDS[at.kind], Building.Result.keys()[result]])
print("build_scene: site %s level %d: %s" % [site, level, ", ".join(placed)])
_environment()
var structures: StructureView = StructureView.new()
structures.setup(sim.structures)
add_child(structures)
var props: PropView = PropView.new()
props.setup(sim.props)
add_child(props)
# Valid ghost: the builder, in the second cell, facing +x for a wall on the far edge
# one level up... looking up, so it targets the level above the iron wall.
builder.position = Vector3((site.x + 0.5) * g, level * Tuning.BUILD_LEVEL_METRES + Tuning.FLOOR_THICKNESS, (site.y + 0.5) * g)
_face(builder, 180.0, 0.0)
var good: BuildGhost = BuildGhost.new()
good.update(sim, builder, StructureSet.WALL, Materials.DRIFTWOOD)
add_child(good)
# Invalid ghost: a player with no materials trying a breakwater beside the fort.
broke.position = Vector3((site.x + 2.5) * g, 0.0, (site.y + 0.5) * g)
broke.position.y = sim.ground.terrain_height(broke.position.x, broke.position.z)
_face(broke, 180.0, 0.0)
var bad: BuildGhost = BuildGhost.new()
bad.update(sim, broke, StructureSet.BREAKWATER, Materials.STONE)
add_child(bad)
print("build_scene: ghosts %s (%s) and %s (%s)" % [good.valid, Building.Result.keys()[good.result], bad.valid, Building.Result.keys()[bad.result]])
var camera: Camera3D = Camera3D.new()
camera.fov = 62.0
camera.far = 1500.0
var corner: Vector3 = Vector3(site.x * g, level * Tuning.BUILD_LEVEL_METRES, site.y * g)
camera.position = corner + view
camera.position.y = maxf(camera.position.y, sim.ground.terrain_height(camera.position.x, camera.position.z) + 2.0)
add_child(camera)
camera.look_at(corner + Vector3(g, 2.5, g * 0.5))
camera.make_current()
var terrain: TerrainView = TerrainView.new()
terrain.setup(sim.island)
terrain.focus = camera.position
add_child(terrain)
terrain.build_all_now()
var water: WaterView = WaterView.new()
water.set_level(sim.sea_level)
add_child(water)
func _face(player: SimEntity, yaw_degrees: float, pitch_degrees: float) -> void:
var command: PlayerCommand = PlayerCommand.from_input(0, Vector2.ZERO, deg_to_rad(yaw_degrees), deg_to_rad(pitch_degrees))
player.yaw = command.yaw
player.pitch = command.pitch
## A cell in open, gently sloping forest with nothing standing within a few cells.
func _find_site(sim: Simulation) -> Vector2i:
var g: float = Tuning.GRID_CELL_METRES
var cells: int = floori(Tuning.WORLD_SIZE_METRES / g)
for cz: int in range(cells / 2, cells - 4):
for cx: int in range(cells / 2, cells - 4):
var centre: Vector2 = Vector2((cx + 1.0) * g, (cz + 0.5) * g)
var h: float = sim.ground.terrain_height(centre.x, centre.y)
if h < Tuning.ISLAND_MARSH_TOP + 3.0 or h > Tuning.ISLAND_FOREST_TOP - 10.0:
continue
var low: float = INF
var high: float = -INF
for dz: float in [-1.0, 0.0, 1.0, 2.0]:
for dx: float in [-2.0, -1.0, 0.0, 1.0, 2.0, 3.0]:
var y: float = sim.ground.terrain_height(cx * g + dx * g, cz * g + dz * g)
low = minf(low, y)
high = maxf(high, y)
if high - low > 2.0 or sim.island.band_at(centre.x + 30.0, centre.y + 30.0) != Island.Band.FOREST:
continue
if not sim.pois.pois.is_empty() and _near_poi(sim, centre, 60.0):
continue
return Vector2i(cx, cz)
return Vector2i(cells / 2, cells / 2)
func _near_poi(sim: Simulation, at: Vector2, radius: float) -> bool:
for poi: Poi in sim.pois.pois:
if Vector2(poi.origin.x, poi.origin.z).distance_to(at) < radius:
return true
return false
func _environment() -> void:
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
var environment: Environment = Environment.new()
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
var world: WorldEnvironment = WorldEnvironment.new()
world.environment = environment
add_child(world)
var sun: DirectionalLight3D = DirectionalLight3D.new()
sun.rotation_degrees = Vector3(-40.0, -130.0, 0.0)
sun.light_energy = 0.95
sun.shadow_enabled = true
add_child(sun)
+1
View File
@@ -0,0 +1 @@
uid://ck6qnglo16at
+108
View File
@@ -0,0 +1,108 @@
extends TestCase
## Client side of issue B2: the placement ghost and the structure view.
func _sim() -> Simulation:
var sim: Simulation = Simulation.new(3, SimGround.flat())
var id: int = sim.add_player()
var player: SimEntity = sim.entities.find(id)
player.position = Vector3(10.0, 0.0, 10.0)
player.materials[0] = 100
return sim
func test_ghost_shows_valid_and_invalid_states() -> void:
var sim: Simulation = _sim()
var player: SimEntity = sim.entities.find(1)
var ghost: BuildGhost = BuildGhost.new()
ghost.update(sim, player, StructureSet.WALL, Materials.DRIFTWOOD)
assert_true(ghost.valid)
assert_true(ghost.visible)
assert_eq(ghost.colour(), BuildGhost.VALID_COLOUR)
assert_eq(ghost.target.slot, Vector4i(2, 0, 3, StructureSet.SLOT_WALL_Z))
# Unaffordable in stone.
ghost.update(sim, player, StructureSet.WALL, Materials.STONE)
assert_false(ghost.valid)
assert_eq(ghost.result, Building.Result.UNAFFORDABLE)
assert_eq(ghost.colour(), BuildGhost.INVALID_COLOUR)
# Occupied once the server has placed it.
assert_eq(Building.place(sim, player, Building.target(player, StructureSet.WALL), 0), Building.Result.OK)
ghost.update(sim, player, StructureSet.WALL, Materials.DRIFTWOOD)
assert_eq(ghost.result, Building.Result.OCCUPIED)
assert_eq(ghost.colour(), BuildGhost.INVALID_COLOUR)
ghost.update(sim, player, 42, 0)
assert_false(ghost.visible)
ghost.free()
func test_ghost_agrees_with_the_server() -> void:
# Whatever the ghost says, the server does the same with the same state.
var sim: Simulation = _sim()
var player: SimEntity = sim.entities.find(1)
var ghost: BuildGhost = BuildGhost.new()
for yaw_step: int in 8:
for kind: int in StructureSet.KINDS.size():
var command: PlayerCommand = PlayerCommand.from_input(sim.tick, Vector2.ZERO, yaw_step * PI / 4.0, 0.0,
PlayerCommand.BUTTON_BUILD | PlayerCommand.BUTTON_FIRE, kind, 0)
player.yaw = command.yaw
player.action_cooldown = 0
ghost.update(sim, player, kind, 0)
var before: int = sim.structures.count()
sim.submit_command(1, command)
sim.step()
assert_eq(sim.structures.count() > before, ghost.valid, "yaw step %d kind %d (%s)" % [yaw_step, kind, ghost.result])
ghost.free()
func test_structure_view_follows_the_simulation() -> void:
var sim: Simulation = _sim()
var player: SimEntity = sim.entities.find(1)
var view: StructureView = StructureView.new()
view.setup(sim.structures)
assert_eq(view.drawn_count(), 0)
Building.place(sim, player, Building.target(player, StructureSet.WALL), 0)
Building.place(sim, player, Building.target(player, StructureSet.RAMP), 0)
view.sync()
assert_eq(view.drawn_count(), 2)
sim.structures.remove(1, sim.ground)
view.sync()
assert_eq(view.drawn_count(), 1)
view.free()
func test_piece_meshes_face_outward_and_match_the_boxes() -> void:
var box: AABB = AABB(Vector3(0.0, 0.0, 0.0), Vector3(4.0, 4.0, 0.3))
var mesh: ArrayMesh = PieceMesher.box_mesh([box], Color.WHITE)
var arrays: Array = mesh.surface_get_arrays(0)
var vertices: PackedVector3Array = arrays[Mesh.ARRAY_VERTEX]
var normals: PackedVector3Array = arrays[Mesh.ARRAY_NORMAL]
assert_eq(vertices.size(), 36)
var centre: Vector3 = box.get_center()
for index: int in vertices.size():
var outward: Vector3 = vertices[index] - centre
assert_true(normals[index].dot(outward) > 0.0, "normal %s at %s points inward" % [normals[index], vertices[index]])
for material: int in 3:
var built: ArrayMesh = PieceMesher.build(StructureSet.boxes_for(StructureSet.WALL, Vector4i(0, 0, 0, StructureSet.SLOT_WALL_X), 0), material, 1)
var bounds: AABB = built.get_aabb()
var wall: AABB = StructureSet.boxes_for(StructureSet.WALL, Vector4i(0, 0, 0, StructureSet.SLOT_WALL_X), 0)[0]
assert_true(wall.grow(0.001).encloses(bounds), "mesh stays within the wall's box")
assert_true(bounds.size.y > wall.size.y - 0.1, "mesh fills the wall's height")
func test_ramp_meshes_cover_their_stairs() -> void:
for facing: int in 4:
var slot: Vector4i = Vector4i(3, 5, 7, StructureSet.SLOT_VOLUME)
var stairs: Array[AABB] = StructureSet.boxes_for(StructureSet.RAMP, slot, facing)
var whole: AABB = stairs[0]
for box: AABB in stairs:
whole = whole.merge(box)
var bounds: AABB = PieceMesher.build_ramp(slot, facing, 0, 1).get_aabb()
assert_true(whole.grow(0.05).encloses(bounds), "facing %d: mesh %s outside stairs %s" % [facing, bounds, whole])
assert_true(bounds.grow(0.05).encloses(whole), "facing %d: mesh %s doesn't cover stairs %s" % [facing, bounds, whole])
# The deck's high side is the way the ramp faces.
var top_step: AABB = stairs[-1]
var direction: Vector2i = StructureSet.FACING_DIRECTIONS[facing]
var centre: Vector3 = whole.get_center()
var toward: Vector3 = top_step.get_center() - centre
assert_true(toward.x * direction.x + toward.z * direction.y > 0.0, "facing %d: top step on the wrong side" % facing)
+1
View File
@@ -0,0 +1 @@
uid://cpynfjs2mk0ba
+290
View File
@@ -0,0 +1,290 @@
extends TestCase
## Grid building from issue B2: targeting, validation and placement on the server.
const W: int = StructureSet.WALL
const F: int = StructureSet.FLOOR
const R: int = StructureSet.RAMP
const ROOF: int = StructureSet.ROOF
const BW: int = StructureSet.BREAKWATER
func _sim(feet: Vector3 = Vector3(10.0, 0.0, 10.0), stock: int = 200) -> Simulation:
var sim: Simulation = Simulation.new(3, SimGround.flat())
var id: int = sim.add_player()
var player: SimEntity = sim.entities.find(id)
player.position = feet
for code: int in Materials.NAMES.size():
player.materials[code] = stock
return sim
func _player(sim: Simulation, id: int = 1) -> SimEntity:
return sim.entities.find(id)
## Sets the player's look from degrees.
func _look(player: SimEntity, yaw_degrees: float, pitch_degrees: float = 0.0) -> void:
var command: PlayerCommand = PlayerCommand.from_input(0, Vector2.ZERO, deg_to_rad(yaw_degrees), deg_to_rad(pitch_degrees))
player.yaw = command.yaw
player.pitch = command.pitch
func _slot(x: int, level: int, z: int, type: int) -> Building.Target:
var at: Building.Target = Building.Target.new()
at.slot = Vector4i(x, level, z, type)
return at
func _build(sim: Simulation, kind: int, material: int, ticks: int = 1, yaw_degrees: float = 0.0, pitch_degrees: float = 0.0) -> int:
var placed: int = 0
for _i: int in ticks:
var command: PlayerCommand = PlayerCommand.from_input(sim.tick, Vector2.ZERO, deg_to_rad(yaw_degrees),
deg_to_rad(pitch_degrees), PlayerCommand.BUTTON_BUILD | PlayerCommand.BUTTON_FIRE, kind, material)
sim.submit_command(1, command)
sim.step()
for event: Dictionary in sim.events:
if event["type"] == "piece_placed":
placed += 1
return placed
func test_targeting_snaps_to_the_grid() -> void:
var sim: Simulation = _sim()
var player: SimEntity = _player(sim)
# Player in cell (2, 2) at level 0, facing +z.
_look(player, 0.0)
assert_eq(Building.target(player, W).slot, Vector4i(2, 0, 3, StructureSet.SLOT_WALL_Z))
assert_eq(Building.target(player, F).slot, Vector4i(2, 0, 3, StructureSet.SLOT_FLOOR))
assert_eq(Building.target(player, R).slot, Vector4i(2, 0, 3, StructureSet.SLOT_VOLUME))
_look(player, 90.0)
assert_eq(Building.target(player, BW).slot, Vector4i(3, 0, 2, StructureSet.SLOT_WALL_X))
assert_eq(Building.target(player, R).facing, 1)
_look(player, 180.0)
assert_eq(Building.target(player, W).slot, Vector4i(2, 0, 2, StructureSet.SLOT_WALL_Z))
_look(player, -90.0)
assert_eq(Building.target(player, W).slot, Vector4i(2, 0, 2, StructureSet.SLOT_WALL_X))
_look(player, 0.0, 60.0)
assert_eq(Building.target(player, W).slot.y, 2, "looking up targets a cell higher")
player.position.y = 0.9
assert_eq(Building.target(player, W).slot.y, 2, "levels are half a cell")
player.position.y = 1.1
_look(player, 0.0)
assert_eq(Building.target(player, W).slot.y, 1, "the level nearest the feet")
player.position.y = 0.0
_look(player, 0.0, -60.0)
assert_eq(Building.target(player, F).slot, Vector4i(2, 0, 2, StructureSet.SLOT_FLOOR), "looking down builds under you")
assert_null(Building.target(player, 99))
func test_placing_spends_material_and_adds_collision() -> void:
var sim: Simulation = _sim()
assert_eq(_build(sim, W, Materials.STONE), 1)
assert_eq(sim.structures.count(), 1)
assert_eq(_player(sim).materials[Materials.STONE], 200 - Tuning.BUILD_PIECES["wall"]["cost"])
var piece: StructureSet.Piece = sim.structures.find(1)
assert_eq(piece.material, Materials.STONE)
assert_eq(piece.health, Tuning.MATERIALS["stone"]["health"])
assert_true(piece.grounded)
# The wall stands at z = 12 across x 8..12 and blocks walking.
for _i: int in 60:
sim.submit_command(1, PlayerCommand.from_input(sim.tick, Vector2(0.0, 1.0), 0.0, 0.0))
sim.step()
assert_true(_player(sim).position.z < 12.0 - Tuning.PLAYER_RADIUS + 0.01, "the wall should stop the player")
func test_rejects_unaffordable() -> void:
var sim: Simulation = _sim(Vector3(10.0, 0.0, 10.0), 9)
assert_eq(Building.check(sim, _player(sim), Building.target(_player(sim), W), Materials.DRIFTWOOD), Building.Result.UNAFFORDABLE)
assert_eq(_build(sim, W, Materials.DRIFTWOOD), 0)
assert_eq(_player(sim).materials[Materials.DRIFTWOOD], 9, "nothing spent")
_player(sim).materials[Materials.DRIFTWOOD] = 29
assert_eq(Building.check(sim, _player(sim), Building.target(_player(sim), BW), Materials.DRIFTWOOD), Building.Result.UNAFFORDABLE, "breakwaters cost 30")
func test_rejects_out_of_range_slots() -> void:
var sim: Simulation = _sim()
var player: SimEntity = _player(sim)
var far: Building.Target = _slot(5, 0, 2, StructureSet.SLOT_FLOOR)
far.kind = F
assert_eq(Building.check(sim, player, far, 0), Building.Result.OUT_OF_RANGE)
var high: Building.Target = _slot(2, 6, 3, StructureSet.SLOT_FLOOR)
high.kind = F
assert_eq(Building.check(sim, player, high, 0), Building.Result.OUT_OF_RANGE)
var near: Building.Target = _slot(3, 0, 2, StructureSet.SLOT_FLOOR)
near.kind = F
assert_eq(Building.check(sim, player, near, 0), Building.Result.OK)
var outside: Building.Target = _slot(-1, 0, 2, StructureSet.SLOT_FLOOR)
outside.kind = F
player.position = Vector3(1.0, 0.0, 10.0)
assert_eq(Building.check(sim, player, outside, 0), Building.Result.OUT_OF_WORLD)
var bad: Building.Target = _slot(2, 0, 3, StructureSet.SLOT_FLOOR)
bad.kind = W
assert_eq(Building.check(sim, player, bad, 0), Building.Result.BAD_REQUEST, "a wall can't take a floor slot")
assert_eq(Building.check(sim, player, near, 7), Building.Result.BAD_REQUEST, "unknown material")
func test_rejects_overlapping_pieces() -> void:
var sim: Simulation = _sim()
assert_eq(_build(sim, W, 0), 1)
assert_eq(Building.check(sim, _player(sim), Building.target(_player(sim), W), 0), Building.Result.OCCUPIED)
assert_eq(Building.check(sim, _player(sim), Building.target(_player(sim), BW), 0), Building.Result.OCCUPIED, "a breakwater shares the wall slot")
# Holding fire for a second on the same slot places nothing more.
assert_eq(_build(sim, W, 0, 30), 0)
assert_eq(sim.structures.count(), 1)
# A wall half a cell up would overlap it too, but a whole cell up is free.
var half_up: Building.Target = _slot(2, 1, 3, StructureSet.SLOT_WALL_Z)
half_up.kind = W
assert_eq(Building.check(sim, _player(sim), half_up, 0), Building.Result.OCCUPIED)
var full_up: Building.Target = _slot(2, 2, 3, StructureSet.SLOT_WALL_Z)
full_up.kind = W
assert_eq(Building.check(sim, _player(sim), full_up, 0), Building.Result.OK)
# A ramp and a roof share the volume slot.
assert_eq(_build(sim, R, 0, 1, 90.0), 1)
assert_eq(Building.check(sim, _player(sim), Building.target(_player(sim), ROOF), 0), Building.Result.OCCUPIED)
func test_rejects_pieces_that_would_trap_a_player() -> void:
var sim: Simulation = _sim()
var other: int = sim.add_player()
# Another player stands right on the edge where the wall would go.
sim.entities.find(other).position = Vector3(10.0, 0.0, 12.0)
assert_eq(Building.check(sim, _player(sim), Building.target(_player(sim), W), 0), Building.Result.BLOCKED_BY_PLAYER)
# A floor under a player's feet is only a step, so it lifts them instead.
sim.entities.find(other).position = Vector3(10.0, 0.0, 14.0)
assert_eq(_build(sim, F, 0), 1)
assert_near(sim.entities.find(other).position.y, Tuning.FLOOR_THICKNESS, 0.001)
func test_rejects_floating_pieces_but_accepts_attached_ones() -> void:
var sim: Simulation = _sim()
var player: SimEntity = _player(sim)
var floating: Building.Target = _slot(2, 2, 3, StructureSet.SLOT_FLOOR)
floating.kind = F
assert_eq(Building.check(sim, player, floating, 0), Building.Result.UNSUPPORTED)
# A wall below holds it up.
assert_eq(_build(sim, W, 0), 1)
assert_eq(Building.check(sim, player, floating, 0), Building.Result.OK)
assert_eq(Building.place(sim, player, floating, 0), Building.Result.OK)
var piece: StructureSet.Piece = sim.structures.find(2)
assert_false(piece.grounded)
assert_eq(sim.structures.neighbours[2], PackedInt32Array([1]))
assert_eq(sim.structures.neighbours[1], PackedInt32Array([2]))
func test_no_building_while_swimming_or_falling() -> void:
var sim: Simulation = _sim()
var player: SimEntity = _player(sim)
player.swimming = true
assert_eq(Building.check(sim, player, Building.target(player, W), 0), Building.Result.NOT_ALLOWED)
player.swimming = false
player.drop_state = Drop.FREEFALL
assert_eq(Building.check(sim, player, Building.target(player, W), 0), Building.Result.NOT_ALLOWED)
func test_ramps_are_climbable_stairs() -> void:
var sim: Simulation = _sim(Vector3(10.0, 0.0, 11.0))
assert_eq(_build(sim, R, 0), 1)
var ramp: StructureSet.Piece = sim.structures.find(1)
assert_eq(ramp.boxes.size(), Tuning.RAMP_STEPS)
assert_true(Tuning.GRID_CELL_METRES / Tuning.RAMP_STEPS <= Tuning.STEP_HEIGHT, "each riser must be a step")
assert_true(Tuning.GRID_CELL_METRES / Tuning.RAMP_STEPS >= Tuning.PLAYER_RADIUS, "each tread must hold a foot")
# Walk up it, then onto a floor at the next level.
var top: Building.Target = _slot(2, 2, 4, StructureSet.SLOT_FLOOR)
top.kind = F
assert_eq(Building.check(sim, _player(sim), top, 0), Building.Result.OK)
Building.place(sim, _player(sim), top, 0)
# 2 s at walking pace: 8 m, from z = 11 to about 19, short of the floor's far edge.
for _i: int in 60:
sim.submit_command(1, PlayerCommand.from_input(sim.tick, Vector2(0.0, 1.0), 0.0, 0.0))
sim.step()
var player: SimEntity = _player(sim)
assert_true(player.position.z > 16.5 and player.position.z < 20.0, "should have walked up and along, z=%f" % player.position.z)
assert_near(player.position.y, Tuning.GRID_CELL_METRES + Tuning.FLOOR_THICKNESS, 0.05, "standing on the upper floor")
func test_walls_meet_at_corners_without_gaps() -> void:
var g: float = Tuning.GRID_CELL_METRES
var x_wall: AABB = StructureSet.boxes_for(W, Vector4i(1, 0, 0, StructureSet.SLOT_WALL_X), 0)[0]
var z_wall: AABB = StructureSet.boxes_for(W, Vector4i(0, 0, 0, StructureSet.SLOT_WALL_Z), 0)[0]
assert_true(x_wall.intersects(z_wall), "corner walls should overlap")
assert_true(x_wall.has_point(Vector3(g, 1.0, -Tuning.WALL_THICKNESS * 0.49)))
func test_walls_on_low_ground_get_a_skirt() -> void:
# A slope: terrain height rises 1 m per 4 m along x.
var values: PackedFloat32Array = PackedFloat32Array()
var side: int = 65
for z: int in side:
for x: int in side:
values.append(x * 4.0)
var ground: SimGround = SimGround.from_heights(values, side, 16.0)
var sim: Simulation = Simulation.new(3, ground)
var id: int = sim.add_player()
var player: SimEntity = sim.entities.find(id)
player.position = Vector3(10.0, ground.terrain_height(10.0, 10.0), 10.0)
player.materials[0] = 100
_look(player, 0.0)
var at: Building.Target = Building.target(player, W)
assert_eq(Building.place(sim, player, at, 0), Building.Result.OK)
var piece: StructureSet.Piece = sim.structures.find(1)
assert_eq(piece.boxes.size(), 2, "the wall should get a skirt")
var skirt: AABB = piece.boxes[1]
assert_true(skirt.position.y <= ground.terrain_height(8.0, 12.0), "the skirt reaches the ground")
func test_rapid_placement_stays_within_the_tick_budget() -> void:
# 24 builders, each holding fire in build mode and turning, for three seconds.
var sim: Simulation = Simulation.new(3, SimGround.flat())
for index: int in 24:
var id: int = sim.add_player()
var player: SimEntity = sim.entities.find(id)
player.position = Vector3(40.0 + (index % 6) * 40.0, 0.0, 40.0 + (index / 6) * 40.0)
for code: int in 3:
player.materials[code] = Tuning.MATERIAL_CAP
var kinds: Array[int] = [W, F, R, W, BW, ROOF]
var times: Array[int] = []
var placed: int = 0
for _tick: int in 90:
for id: int in range(1, 25):
var turn: float = float((sim.tick / Tuning.BUILD_INTERVAL_TICKS) % 4) * 90.0
var pitch: float = 50.0 if (sim.tick / 12) % 2 == 1 else 0.0
var kind: int = kinds[(sim.tick / Tuning.BUILD_INTERVAL_TICKS + id) % kinds.size()]
sim.submit_command(id, PlayerCommand.from_input(sim.tick, Vector2.ZERO, deg_to_rad(turn), deg_to_rad(pitch),
PlayerCommand.BUTTON_BUILD | PlayerCommand.BUTTON_FIRE, kind, id % 3))
var started: int = Time.get_ticks_usec()
sim.step()
times.append(Time.get_ticks_usec() - started)
for event: Dictionary in sim.events:
if event["type"] == "piece_placed":
placed += 1
times.sort()
var p95: int = times[int(times.size() * 0.95)]
print("rapid placement: %d pieces in 3 s by 24 builders, tick p50 %d us p95 %d us max %d us" % [placed, times[45], p95, times[-1]])
assert_true(placed >= 24 * 10, "builders should place many pieces, placed %d" % placed)
assert_true(p95 < 12000, "tick p95 %d us is over the 12 ms budget" % p95)
# One builder can't beat 10 per second.
var solo: Simulation = _sim(Vector3(10.0, 0.0, 10.0), Tuning.MATERIAL_CAP)
var solo_placed: int = 0
for tick: int in 30:
var turn: float = float(tick % 4) * 90.0
var kind: int = [W, F, R][tick % 3]
solo.submit_command(1, PlayerCommand.from_input(solo.tick, Vector2.ZERO, deg_to_rad(turn), 0.0,
PlayerCommand.BUTTON_BUILD | PlayerCommand.BUTTON_FIRE, kind, 0))
solo.step()
solo_placed += solo.events.filter(func(e: Dictionary) -> bool: return e["type"] == "piece_placed").size()
assert_true(solo_placed <= 10, "no more than 10 pieces a second, placed %d" % solo_placed)
func test_building_is_deterministic_and_hashed() -> void:
var hashes: Array[String] = []
for _run: int in 2:
var sim: Simulation = _sim()
_build(sim, W, 1)
_build(sim, R, 2, 4, 90.0)
hashes.append(sim.state_hash())
assert_eq(hashes[0], hashes[1])
var other: Simulation = _sim()
_build(other, W, 0)
_build(other, R, 2, 4, 90.0)
assert_ne(other.state_hash(), hashes[0], "the material is part of the hash")
+1
View File
@@ -0,0 +1 @@
uid://bbpwsvc84egyd