Files
tidewall/src/sim/weapons.gd
T
claudeandClaude Opus 5.5 6e1c87fe32 M3: Eliminations, spectating and results
The simulation now names what ended each player: weapon, fall, drown or tide, from
the cause of the blow that took the last health. Hits carry the weapon's item code.

Match keeps a kill feed (eliminator, cause, weapon, tick), per-player stats (damage
dealt and taken between opponents, eliminations, never teammates), and a summary()
with place, eliminations, damage and survival time. Players who fall on the same
tick share the better place and are marked tied. When the last players fall
together, the tie-break raises one team to first and the rest share the next place.

Eliminated players spectate: first whoever knocked them out, then a living
teammate, then the next living player in join order. When a target falls or
leaves, the view follows its eliminator or moves on, on the same step. Spectators
can cycle forwards and back. In results everyone watches the winner.

The headless server logs every placement and the match summary.

Closes #26

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 23:13:15 -05:00

292 lines
12 KiB
GDScript

## Firing, reloading and damage for slot weapons. Stats come from ItemDef, built from
## Tuning.WEAPONS, so a new weapon is a table entry and needs no code.
##
## The client only presses fire, aim and reload. The server fires from its own copy of
## the player's eye and look, at the weapon's fire rate, from the loaded magazine.
##
## A shot is one or more pellets, each turned by a random angle inside the spread cone
## from the "weapons" stream. Spread is the weapon's hip spread (times its aim factor
## when aiming), plus bloom from recent shots, plus a penalty for moving or being in the
## air. Hitscan pellets trace at once to the weapon's range; projectile pellets become
## entities that fly under gravity and trace each tick's path.
##
## A trace stops at the first of terrain, a solid (a built piece, a prop or a point of
## interest) or another player's body. Players lose armor first, then health; the top
## Tuning.HEAD_HEIGHT of the body takes the weapon's headshot multiplier. Damage falls
## off linearly with distance, see ItemDef.damage_at().
class_name Weapons
extends RefCounted
## What a trace hit.
const HIT_NONE: int = 0
const HIT_TERRAIN: int = 1
const HIT_SOLID: int = 2
const HIT_PIECE: int = 3
const HIT_PROP: int = 4
const HIT_PLAYER: int = 5
## Traces are checked in pieces this long, so long shots stop early and don't query a
## huge area of solids at once.
const TRACE_SEGMENT_METRES: float = 16.0
## The result of a trace.
class Hit:
extends RefCounted
var kind: int = HIT_NONE
## Fraction of the traced segment, 1.0 when nothing was hit.
var fraction: float = 1.0
var point: Vector3 = Vector3.ZERO
## Piece ID, prop index or player entity ID.
var target: int = -1
var headshot: bool = false
## Counts down reloads and bloom. Called every tick for a player on foot, after the
## action cooldown. Bloom only recovers on ticks the weapon is ready to fire, so
## sustained fire builds it up and a pause clears it.
static func update(player: SimEntity) -> void:
if player.action_cooldown == 0:
player.bloom = maxf(player.bloom - Tuning.BLOOM_DECAY_DEGREES_PER_SECOND / Tuning.TICK_RATE_HZ, 0.0)
if player.reload_ticks > 0:
player.reload_ticks -= 1
if player.reload_ticks == 0:
_finish_reload(player)
## Starts reloading the held weapon if it has room and there's ammunition. Returns true
## if a reload started.
static func start_reload(player: SimEntity) -> bool:
var def: ItemDef = Inventory.held_def(player)
if def == null or not def.uses_magazine() or player.reload_ticks > 0:
return false
var slot: int = Inventory.held_slot(player)
if player.slot_rounds[slot] >= def.magazine:
return false
if player.ammo[Inventory.ammo_index(def.ammo_code)] <= 0:
return false
player.reload_ticks = maxi(def.reload_ticks(player.slot_tiers[slot]), 1)
return true
static func _finish_reload(player: SimEntity) -> void:
var def: ItemDef = Inventory.held_def(player)
if def == null or not def.uses_magazine():
return
var slot: int = Inventory.held_slot(player)
var index: int = Inventory.ammo_index(def.ammo_code)
var loaded: int = mini(def.magazine - player.slot_rounds[slot], player.ammo[index])
player.slot_rounds[slot] += loaded
player.ammo[index] -= loaded
## Fires the held weapon if it's ready. Returns true if a shot was fired. An empty
## magazine starts a reload instead. Thrown weapons are handled by explosives (B8).
static func fire(sim: Simulation, player: SimEntity, aiming: bool) -> bool:
var def: ItemDef = Inventory.held_def(player)
if def == null or not def.is_weapon() or def.thrown:
return false
if player.action_cooldown > 0 or player.reload_ticks > 0:
return false
var slot: int = Inventory.held_slot(player)
if def.uses_magazine():
if player.slot_rounds[slot] <= 0:
start_reload(player)
return false
player.slot_rounds[slot] -= 1
player.action_cooldown = def.fire_interval_ticks()
var cone: float = spread_degrees(player, def, aiming)
player.bloom = minf(player.bloom + def.bloom_degrees, Tuning.MAX_BLOOM_DEGREES)
var from: Vector3 = Harvest.eye(player)
var look: Vector3 = Harvest.look_direction(player)
var stream: RandomNumberGenerator = sim.rng.stream("weapons")
sim.events.append({"type": "shot", "player": player.id, "item": def.code, "from": from, "direction": look})
for _pellet: int in def.pellets:
var direction: Vector3 = scatter(look, cone, stream)
if def.projectile_speed > 0.0:
_launch(sim, player, def, slot, from, direction)
else:
var to: Vector3 = from + direction * def.range_max
var hit: Hit = trace(sim, from, to, player.id)
_apply_hit(sim, player.id, def, player.slot_tiers[slot], hit, from.distance_to(hit.point))
return true
## The cone half-angle a shot would have now, in degrees.
static func spread_degrees(player: SimEntity, def: ItemDef, aiming: bool) -> float:
var cone: float = def.spread_degrees * (def.aim_spread_factor if aiming else 1.0)
cone += player.bloom
if not player.on_ground or player.swimming:
cone += Tuning.AIRBORNE_SPREAD_DEGREES
elif Vector2(player.velocity.x, player.velocity.z).length() > 0.5:
cone += Tuning.MOVING_SPREAD_DEGREES
return cone
## A direction within `cone_degrees` of `look`, spread evenly over the cone's area.
static func scatter(look: Vector3, cone_degrees: float, stream: RandomNumberGenerator) -> Vector3:
var u: float = stream.randf()
var v: float = stream.randf()
if cone_degrees <= 0.0:
return look
var angle: float = deg_to_rad(cone_degrees) * sqrt(u)
var around: float = TAU * v
var side: Vector3 = look.cross(Vector3.UP)
if side.length_squared() < 0.000001:
side = Vector3.RIGHT
side = side.normalized()
var up: Vector3 = side.cross(look).normalized()
var offset: Vector3 = (side * cos(around) + up * sin(around)) * sin(angle)
return (look * cos(angle) + offset).normalized()
## The first thing between `from` and `to`, skipping the player `ignore_id`.
static func trace(sim: Simulation, from: Vector3, to: Vector3, ignore_id: int = 0) -> Hit:
var length: float = from.distance_to(to)
var pieces: int = maxi(ceili(length / TRACE_SEGMENT_METRES), 1)
for index: int in pieces:
var start: float = float(index) / pieces
var end: float = float(index + 1) / pieces
var hit: Hit = _trace_segment(sim, from.lerp(to, start), from.lerp(to, end), ignore_id)
if hit.kind != HIT_NONE:
hit.fraction = lerpf(start, end, hit.fraction)
return hit
var miss: Hit = Hit.new()
miss.point = to
return miss
static func _trace_segment(sim: Simulation, from: Vector3, to: Vector3, ignore_id: int) -> Hit:
var hit: Hit = Hit.new()
var ground: SimGround = sim.ground
# The nearest solid, and what it belongs to.
for solid_id: int in ground.solids_near(minf(from.x, to.x), minf(from.z, to.z), maxf(from.x, to.x), maxf(from.z, to.z)):
var t: float = ground.ray_box(from, to, ground.solids[solid_id])
if t < hit.fraction or (t == hit.fraction and hit.kind != HIT_NONE and solid_id < hit.target):
hit.fraction = t
hit.kind = HIT_SOLID
hit.target = solid_id
if hit.kind == HIT_SOLID:
var piece: int = sim.structures.piece_of_solid(hit.target)
var prop: int = sim.props.prop_of_solid(hit.target)
if piece != 0:
hit.kind = HIT_PIECE
hit.target = piece
elif prop >= 0:
hit.kind = HIT_PROP
hit.target = prop
# Terrain in front of the solid.
var terrain: float = ground.raycast(from, to)
if terrain < hit.fraction - 0.0001:
hit.fraction = terrain
hit.kind = HIT_TERRAIN
hit.target = -1
# Players in front of both.
for entity: SimEntity in sim.entities.entities():
if entity.archetype != SimEntity.ARCHETYPE_PLAYER or entity.id == ignore_id or entity.eliminated:
continue
if entity.drop_state == Drop.ABOARD:
continue
var box: AABB = body_box(entity)
var t: float = ground.ray_box(from, to, box)
if t < hit.fraction:
hit.fraction = t
hit.kind = HIT_PLAYER
hit.target = entity.id
var point: Vector3 = from.lerp(to, t)
hit.headshot = point.y >= box.end.y - Tuning.HEAD_HEIGHT
hit.point = from.lerp(to, hit.fraction)
return hit
## The box a player's body occupies.
static func body_box(player: SimEntity) -> AABB:
var radius: float = Tuning.PLAYER_RADIUS
return AABB(player.position - Vector3(radius, 0.0, radius), Vector3(radius * 2.0, Movement.body_height(player), radius * 2.0))
## Applies a pellet's hit. `distance` is from where the shot started.
static func _apply_hit(sim: Simulation, attacker: int, def: ItemDef, tier: int, hit: Hit, distance: float) -> void:
sim.events.append({"type": "impact", "player": attacker, "item": def.code, "point": hit.point, "hit": hit.kind, "target": hit.target})
if def.pull_speed > 0.0 and hit.kind != HIT_NONE:
_pull(sim, sim.entities.find(attacker), hit.point, def.pull_speed)
if def.damage <= 0:
return
var amount: float = def.damage_at(distance) * tier_multiplier(tier)
match hit.kind:
HIT_PLAYER:
if hit.headshot:
amount *= def.headshot_multiplier
damage_player(sim, sim.entities.find(hit.target), roundi(amount), attacker, hit.headshot, def.code)
HIT_PIECE:
sim.damage_piece(hit.target, roundi(amount * def.structure_factor), "weapon")
HIT_PROP:
if sim.damage_prop(hit.target, roundi(amount * def.structure_factor)):
sim.events.append({"type": "prop_destroyed", "prop": hit.target})
## Damage multiplier for a quality tier, from Tuning.WEAPON_TIERS.
static func tier_multiplier(tier: int) -> float:
return float(ItemDef.tier_stats(tier)["damage"])
## Yanks a player on foot towards `point`, lifting them off the ground.
static func _pull(sim: Simulation, player: SimEntity, point: Vector3, speed: float) -> void:
if player == null or player.eliminated or player.drop_state != Drop.NONE or player.swimming:
return
var direction: Vector3 = point - Harvest.eye(player)
if direction.length_squared() < 0.0001:
return
player.velocity = direction.normalized() * speed + Vector3(0.0, Tuning.LINE_PULL_LIFT, 0.0)
player.on_ground = false
sim.events.append({"type": "line_pull", "player": player.id, "point": point})
## Takes `amount` from armor, then health. Returns the damage actually done. `item` is
## the weapon's item code, or -1, for the kill feed.
static func damage_player(sim: Simulation, victim: SimEntity, amount: int, attacker: int, headshot: bool = false, item: int = -1) -> int:
if victim == null or victim.eliminated or amount <= 0:
return 0
var to_armor: int = mini(victim.armor, amount)
victim.armor -= to_armor
var to_health: int = mini(victim.health, amount - to_armor)
victim.health -= to_health
victim.last_cause = SimEntity.CAUSE_WEAPON
if attacker != 0 and attacker != victim.id:
victim.last_attacker = attacker
sim.events.append({
"type": "player_hit", "player": attacker, "victim": victim.id,
"armor": to_armor, "health": to_health, "headshot": headshot, "item": item,
})
return to_armor + to_health
static func _launch(sim: Simulation, player: SimEntity, def: ItemDef, slot: int, from: Vector3, direction: Vector3) -> void:
var shot: SimEntity = sim.entities.create(SimEntity.ARCHETYPE_PROJECTILE)
shot.position = from
shot.origin = from
shot.velocity = direction * def.projectile_speed
shot.owner_id = player.id
shot.item = def.code
shot.item_tier = player.slot_tiers[slot]
sim.projectiles.append(shot.id)
## Moves every projectile one tick and resolves what they hit.
static func advance_projectiles(sim: Simulation) -> void:
var dt: float = Simulation.SECONDS_PER_TICK
for shot_id: int in sim.projectiles.duplicate():
var shot: SimEntity = sim.entities.find(shot_id)
var def: ItemDef = ItemCatalog.get_def(shot.item)
shot.velocity.y -= def.projectile_gravity * dt
var to: Vector3 = shot.position + shot.velocity * dt
var hit: Hit = trace(sim, shot.position, to, shot.owner_id)
var travelled: float = shot.origin.distance_to(hit.point)
var out_of_world: bool = to.y < Tuning.BUILD_MIN_LEVEL * Tuning.BUILD_LEVEL_METRES - 10.0
if hit.kind != HIT_NONE:
_apply_hit(sim, shot.owner_id, def, shot.item_tier, hit, travelled)
if hit.kind != HIT_NONE or travelled >= def.range_max or out_of_world:
sim.entities.remove(shot_id)
sim.projectiles.erase(shot_id)
else:
shot.position = to