harvest/game/scripts/enemy_system.gd
Forrest a0aee34e3c Task #18: Alien Ray fires a beam
The Alien Ray is now a held beam instead of a copy of the potato shot.
While fire is held it ticks every alien_ray_tick_interval (0.15 s). Each
tick traces a path from the scarecrow's center through the muzzle and on
alien_ray_range (20 m) past it, cut short at the first wall
(AlienBeam.trace on the world layer). It damages every enemy within
alien_ray_width / 2 (0.25 m) plus its hit radius of that path, flyers
included as with shots, nearest first, up to alien_ray_pierce (4), for
alien_ray_damage (1). That is about 6.7 damage a second per enemy on the
beam. Hits stay inside combat.step, so enemies.attacker credits kills.

- EnemySystem.path_hits: every enemy along a polyline, ordered along it,
  with flat ends (nothing behind the scarecrow or past the wall).
  sweep_hit is unchanged.
- AlienBeam: a WeaponModels held effect (hold 1.5 ticks, no fade). It is
  an unshaded HDR green core and glow, a muzzle light, and a flare where a
  wall stops it. Each frame it lays itself out from the muzzle along the
  model's -Z, with the same trace, so the partner's machine recomputes the
  wall clip locally. No protocol change.
- Counters: a beam_ticks counter joins attacks(), and ray ticks no
  longer count as shots_fired.
- Config: alien_ray_speed, alien_ray_lifetime and alien_ray_cooldown are
  removed. alien_ray_range, _width, _tick_interval and _pierce are added.
  The shop text says what it does now. Cost and hidden/reveal are
  unchanged.
- Sound: a zapped signal and a "zap" cue (synth alien_beam.wav, its own
  seed). The other synth files regenerate byte-identical.

Tests (test_weapons) replace the projectile-travel ray check and keep
buy/equip:
- a far target is hit on the same step;
- nothing beside, behind or past the end is hit;
- two in line and a crow are all hit;
- a line is capped at pierce;
- a wall stops it, including a barrel poking through one;
- held ticks repeat and stop on release;
- the beam is lit only while held, ends at the wall clip, follows the
  model's yaw, and the replica and attack-event paths work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 13:39:00 -04:00

792 lines
28 KiB
GDScript

class_name EnemySystem
extends Node3D
## Pooled enemy simulation for the farm, forked from the prototype's HordeSystem: dense slots
## with stable ids and generation counters (handles that go stale when a slot is reused),
## swap-removal, removals deferred to the end of the tick, and MultiMesh batches (HordeRenderer)
## for the flyers: one for crows (the bird mesh) and one for UFOs (a saucer built from primitives,
## build_ufo_mesh). Both mirror the dense slots, and each draws only its own type (the other
## slots scaled to nothing). Adds per-slot type, behavior state, target and carried loot,
## and a state timer. Each type's stats come from GameConfig.enemy_types (cached per type here).
## Ground enemies collide with the farm through the FarmNavigation grid: an enemy's center stays
## in walkable cells (free of static obstacles and of player-built structures, both already
## inflated by its radius), so it keeps clear of every shape the scarecrow collides with and
## can't pass a fence or gate without breaking it; slowing traps (StructureSystem.try_trap) slow
## it down; it is drawn by a pooled KayKit character (EnemyCharacters). Flyers ignore all of
## that, keep apart only from each other, and fly at a visual altitude (alt) in the MultiMesh;
## their hit proxy stays at combat height. What each enemy wants is decided by the behavior
## policy (ThiefBehavior); motion, damage, removal, and rendering live here.
enum Removal { KILLED, ESCAPED, LEFT }
enum Aggression { NONE, CONTACT, FIGHT }
const ID_BITS := 16
const ID_MASK := (1 << ID_BITS) - 1
## How fast a hit's flash (hurt) fades, per second.
const HURT_FADE := 4.0
const TYPE_THIEF := 0
const TYPE_CROW := 1
const TYPE_BREAKER := 2
const TYPE_UFO := 3
## GameConfig.enemy_types keys, by type id.
const TYPE_NAMES: Array[String] = ["thief", "crow", "breaker", "ufo"]
## Display names, singular and plural.
const NAMES: Array[String] = ["alien", "crow", "alien robot", "UFO"]
const PLURALS: Array[String] = ["aliens", "crows", "alien robots", "UFOs"]
## "a" or "an" for NAMES[t], by type id.
const ARTICLES: Array[String] = ["an", "a", "an", "a"]
const NB_DX: Array[int] = [0, -1, 0, 1, -1, 1, -1, 0, 1]
const NB_DZ: Array[int] = [0, -1, -1, -1, 0, 0, 1, 1, 1]
## Emitted for every removal at the end of the tick, while the handle is still valid, with the
## loot item the enemy carried and the one it targeted (-1 for none).
signal enemy_removed(handle: int, reason: Removal, x: float, z: float, carry: int, target: int)
var config: GameConfig
var nav: FarmNavigation
var behavior: ThiefBehavior
## Set by FarmSim: slowing traps, and the characters that draw ground enemies.
var structures: StructureSystem
var characters: EnemyCharacters
var grid := SpatialGrid.new()
## Draws the crows (the bird mesh); ufo_renderer draws the UFOs.
var renderer: HordeRenderer
var ufo_renderer: HordeRenderer
# Per type (index = type id), from GameConfig.enemy_types.
var t_speed := PackedFloat32Array()
var t_accel := PackedFloat32Array()
var t_hp := PackedInt32Array()
var t_flying := PackedByteArray()
## Loot categories it takes (bit per LootSystem.Category); t_breaks for "structures".
var t_targets := PackedInt32Array()
var t_breaks := PackedByteArray()
var t_steal := PackedFloat32Array()
var t_carry := PackedFloat32Array()
var t_structure_damage := PackedInt32Array()
var t_damage := PackedInt32Array()
var t_hit_interval := PackedFloat32Array()
var t_aggression := PackedByteArray()
var t_aggro_range := PackedFloat32Array()
var t_hit_radius := PackedFloat32Array()
var capacity: int = 0
var active_count: int = 0
# Dense per-slot state (index = slot in [0, active_count)).
var pos_x := PackedFloat32Array()
var pos_z := PackedFloat32Array()
var prev_x := PackedFloat32Array()
var prev_z := PackedFloat32Array()
var vel_x := PackedFloat32Array()
var vel_z := PackedFloat32Array()
## Desired unit direction and pace (share of full speed) written by the behavior each tick.
var desire_x := PackedFloat32Array()
var desire_z := PackedFloat32Array()
var pace := PackedFloat32Array()
var head_x := PackedFloat32Array()
var head_z := PackedFloat32Array()
var flap_phase := PackedFloat32Array()
## Hit flash (1 on a hit, fading), shown by the shader.
var hurt := PackedFloat32Array()
var timer := PackedFloat32Array()
## Flyers: visual altitude.
var alt := PackedFloat32Array()
## Seconds until the enemy can attack again.
var attack_cd := PackedFloat32Array()
## Seconds of slowing-trap slowdown left.
var slow_left := PackedFloat32Array()
## Structure being broken (BREAK) and the state to resume after it (-1 / 0 when none).
var barrier := PackedInt32Array()
var resume := PackedByteArray()
var health := PackedInt32Array()
## Loot item the enemy is after and the one it carries (-1 for none).
var target := PackedInt32Array()
var carry := PackedInt32Array()
## The loot category it goes for (LootSystem.Category, or LootSystem.ANY).
var want := PackedByteArray()
var type := PackedByteArray()
var state := PackedByteArray()
var alive := PackedByteArray()
var removal := PackedByteArray()
var dense_id := PackedInt32Array()
# Stable ids: slot of each id (-1 when free) and its generation.
var id_dense := PackedInt32Array()
var id_generation := PackedInt32Array()
var _free_ids := PackedInt32Array()
var _free_top: int = 0
var _pending := PackedInt32Array()
var _pending_count: int = 0
## Co-op goop credit: the avatar slot whose attack is being resolved right now (FarmSim sets it
## around each scarecrow's combat step; -1 otherwise: turrets, bombs going off, tests), and the
## slot that landed each enemy's killing hit, by stable id (read through killer_of()).
var attacker: int = -1
var _killer := PackedInt32Array()
# Diagnostics.
var spawn_skipped: int = 0
var kills: int = 0
var escapes: int = 0
var attacks_attempted: int = 0
var attacks_blocked_by_cover: int = 0
## Fraction along the last sweep_hit() segment where the nearest hit happened.
var hit_t: float = 0.0
## mesh / material draw the crows, ufo_mesh / ufo_material the UFOs.
func setup(cfg: GameConfig, p_nav: FarmNavigation, p_behavior: ThiefBehavior, mesh: Mesh,
material: Material, area: Rect2, ufo_mesh: Mesh, ufo_material: Material) -> void:
config = cfg
nav = p_nav
behavior = p_behavior
capacity = cfg.enemy_capacity
_load_types(cfg)
for a: PackedFloat32Array in [pos_x, pos_z, prev_x, prev_z, vel_x, vel_z, desire_x, desire_z,
pace, head_x, head_z, flap_phase, hurt, timer, attack_cd, slow_left, alt]:
a.resize(capacity)
a.fill(0.0)
for a: PackedInt32Array in [health, target, carry, barrier, dense_id, id_dense, id_generation, _free_ids, _pending, _killer]:
a.resize(capacity)
a.fill(0)
for a: PackedByteArray in [type, state, alive, removal, resume, want]:
a.resize(capacity)
a.fill(0)
id_dense.fill(-1)
grid.setup(area, 1.0, capacity)
var aabb := AABB(Vector3(area.position.x, 0.0, area.position.y), Vector3(area.size.x, 4.0, area.size.y))
renderer = HordeRenderer.new()
renderer.name = "EnemyRenderer"
add_child(renderer)
renderer.setup(mesh, material, capacity, cfg.combat_height, aabb)
ufo_renderer = HordeRenderer.new()
ufo_renderer.name = "UfoRenderer"
add_child(ufo_renderer)
ufo_renderer.setup(ufo_mesh, ufo_material, capacity, cfg.combat_height, aabb)
clear()
func _load_types(cfg: GameConfig) -> void:
var n := TYPE_NAMES.size()
for a: PackedFloat32Array in [t_speed, t_accel, t_steal, t_carry, t_hit_interval, t_aggro_range, t_hit_radius]:
a.resize(n)
for a: PackedInt32Array in [t_hp, t_targets, t_structure_damage, t_damage]:
a.resize(n)
for a: PackedByteArray in [t_flying, t_breaks, t_aggression]:
a.resize(n)
for t in n:
var row := cfg.enemy(TYPE_NAMES[t])
t_speed[t] = float(row.get("speed", 3.0))
t_accel[t] = float(row.get("acceleration", 14.0))
t_hp[t] = int(row.get("hp", 1))
t_flying[t] = 1 if bool(row.get("flying", false)) else 0
var mask := 0
for target in row.get("targets", []):
var c := LootSystem.CATEGORY_KEYS.find(String(target))
if c >= 0:
mask |= 1 << c
t_targets[t] = mask
t_breaks[t] = 1 if (row.get("targets", []) as Array).has("structures") else 0
t_steal[t] = float(row.get("steal_time", 1.0))
t_carry[t] = float(row.get("carry_speed", 0.7))
t_structure_damage[t] = int(row.get("structure_damage", 0))
t_damage[t] = int(row.get("damage", 0))
t_hit_interval[t] = float(row.get("hit_interval", 1.2))
t_aggression[t] = maxi(["none", "contact", "fight"].find(String(row.get("aggression", "none"))), 0)
t_aggro_range[t] = float(row.get("aggro_range", 0.0))
t_hit_radius[t] = float(row.get("hit_radius", 0.4))
func is_flying(d: int) -> bool:
return t_flying[type[d]] == 1
func max_speed() -> float:
var best := 0.0
for v in t_speed:
best = maxf(best, v)
return best
## Releases every enemy at once, without removal events (used when the farm state is replaced,
## e.g. on retry: the loot system resyncs from the new state).
func clear() -> void:
active_count = 0
_pending_count = 0
_free_top = capacity
for id in capacity:
_free_ids[id] = capacity - 1 - id # pop order 0, 1, 2, ...
if id_dense[id] >= 0:
id_generation[id] += 1
id_dense[id] = -1
for r: HordeRenderer in [renderer, ufo_renderer]:
if r:
r.clear()
r.commit(0)
if characters:
characters.clear()
## Acquires a slot and initializes every state field. Returns a handle, or -1 if the pool is
## exhausted, or for a ground enemy there's no free character to draw it (the spawn is skipped
## and counted; nothing grows).
func spawn(enemy_type: int, x: float, z: float, heading: Vector2, p_want: int = LootSystem.ANY) -> int:
if active_count >= capacity or _free_top <= 0:
spawn_skipped += 1
return -1
var id := _free_ids[_free_top - 1]
if characters != null and t_flying[enemy_type] == 0 and not characters.acquire(enemy_type, id):
spawn_skipped += 1
return -1
_free_top -= 1
_killer[id] = -1
var d := active_count
active_count += 1
var h := heading.normalized() if heading.length_squared() > 1e-6 else Vector2(0.0, -1.0)
pos_x[d] = x
pos_z[d] = z
prev_x[d] = x
prev_z[d] = z
vel_x[d] = 0.0
vel_z[d] = 0.0
desire_x[d] = 0.0
desire_z[d] = 0.0
pace[d] = 0.0
head_x[d] = h.x
head_z[d] = h.y
flap_phase[d] = randf()
hurt[d] = 0.0
timer[d] = 0.0
attack_cd[d] = 0.0
slow_left[d] = 0.0
alt[d] = config.cruise_altitude
health[d] = t_hp[enemy_type]
target[d] = -1
carry[d] = -1
barrier[d] = -1
resume[d] = 0
type[d] = enemy_type
want[d] = p_want
state[d] = 0
alive[d] = 1
removal[d] = 0
dense_id[d] = id
id_dense[id] = d
renderer.write_new(d, x, z, h.x, h.y, flap_phase[d])
ufo_renderer.write_new(d, x, z, h.x, h.y, flap_phase[d])
return handle_of(d)
func handle_of(d: int) -> int:
var id := dense_id[d]
return id | (id_generation[id] << ID_BITS)
## Returns the dense slot for a handle, or -1 if the handle is stale or released.
func resolve_handle(handle: int) -> int:
if handle < 0:
return -1
var id := handle & ID_MASK
if id >= capacity or id_generation[id] != (handle >> ID_BITS):
return -1
return id_dense[id]
func is_alive_slot(d: int) -> bool:
return d >= 0 and d < active_count and alive[d] == 1
func alive_count() -> int:
return active_count - _pending_count
## Interpolated render-time position of a slot (between the last two ticks).
func visual_position(d: int) -> Vector2:
var f := Engine.get_physics_interpolation_fraction()
return Vector2(lerpf(prev_x[d], pos_x[d], f), lerpf(prev_z[d], pos_z[d], f))
## Applies one hit. Returns false for dead or pending slots (no double kills). by: the avatar
## slot that landed it (a shot's shooter), or -1 for whoever is attacking now (attacker).
func apply_hit(d: int, damage: int = 1, by: int = -1) -> bool:
if not is_alive_slot(d):
return false
health[d] -= damage
hurt[d] = 1.0
if characters != null and t_flying[type[d]] == 0:
characters.hit(dense_id[d])
if health[d] <= 0:
kills += 1
_killer[dense_id[d]] = by if by >= 0 else attacker
queue_removal(d, Removal.KILLED)
elif behavior != null:
behavior.on_hit(self, d)
return true
func apply_hit_handle(handle: int, damage: int = 1, by: int = -1) -> bool:
return apply_hit(resolve_handle(handle), damage, by)
## The avatar slot whose hit killed this enemy (while enemy_removed is emitted for it), or -1:
## killed by a turret or a bomb, not killed, or a stale handle.
func killer_of(handle: int) -> int:
var d := resolve_handle(handle)
return _killer[dense_id[d]] if d >= 0 else -1
## Takes a living enemy out of the simulation now; its slot is released (and enemy_removed
## emitted) at the end of the tick by commit_removals().
func queue_removal(d: int, reason: Removal) -> void:
if not is_alive_slot(d):
return
alive[d] = 0
removal[d] = reason
if reason == Removal.ESCAPED:
escapes += 1
_pending[_pending_count] = dense_id[d]
_pending_count += 1
## Every living enemy leaves now (end of the night): removal reason LEFT.
func remove_all() -> void:
for d in active_count:
queue_removal(d, Removal.LEFT)
commit_removals()
## One tick: behavior decides desired directions, then steering (desire plus separation from
## nearby enemies of the same kind, ground or air) and motion. Ground enemies collide with the
## grid and yield to the scarecrow; flyers do neither and ease toward their altitude.
## Co-op: player 2's scarecrow, which ground enemies yield to as well (INF when there's none).
var scarecrow2 := Vector2(INF, INF)
func step(dt: float, scarecrow: Vector2, scarecrow_radius: float) -> void:
var scarecrows: Array[Vector2] = [scarecrow, scarecrow2]
if behavior != null:
behavior.update(self, dt)
var cfg := config
var sep_r := cfg.separation_radius
var contact := cfg.enemy_radius + scarecrow_radius
var max_corr := cfg.max_correction_per_tick
var g := grid
for i in active_count:
hurt[i] = maxf(hurt[i] - dt * HURT_FADE, 0.0)
attack_cd[i] = maxf(attack_cd[i] - dt, 0.0)
slow_left[i] = maxf(slow_left[i] - dt, 0.0)
var x := pos_x[i]
var z := pos_z[i]
prev_x[i] = x
prev_z[i] = z
if alive[i] == 0:
continue
var t := type[i]
var flying := t_flying[t] == 1
var speed := t_speed[t]
var accel := t_accel[t] * dt
if flying:
var want_alt := behavior.altitude_for(self, i) if behavior != null else cfg.cruise_altitude
alt[i] = move_toward(alt[i], want_alt, dt * 2.5)
elif structures != null and slow_left[i] == 0.0 and structures.try_trap(x, z):
slow_left[i] = structures.trap_slow_time()
# Separation from neighbors (previous tick's buckets).
var sx := 0.0
var sz := 0.0
var gx := g.cell_x(x)
var gz := g.cell_z(z)
for n in 9:
var ncx := gx + NB_DX[n]
var ncz := gz + NB_DZ[n]
if ncx < 0 or ncz < 0 or ncx >= g.width or ncz >= g.height:
continue
var c := ncz * g.width + ncx
for k in range(g.cell_start[c], g.cell_start[c + 1]):
var o := g.items[k]
if o == i or o >= active_count or alive[o] == 0 or t_flying[type[o]] != t_flying[t]:
continue
var dx := x - pos_x[o]
var dz := z - pos_z[o]
var d2 := dx * dx + dz * dz
if d2 >= sep_r * sep_r or d2 < 1e-8:
continue
var d := sqrt(d2)
sx += dx / d * (sep_r - d) / sep_r
sz += dz / d * (sep_r - d) / sep_r
var top := speed * pace[i] * (cfg.trap_slow_factor if slow_left[i] > 0.0 else 1.0)
var tx := desire_x[i] * top + sx * cfg.separation_weight * speed * 0.5
var tz := desire_z[i] * top + sz * cfg.separation_weight * speed * 0.5
var vx := vel_x[i]
var vz := vel_z[i]
var dvx := tx - vx
var dvz := tz - vz
var dl2 := dvx * dvx + dvz * dvz
if dl2 > accel * accel:
var kk := accel / sqrt(dl2)
dvx *= kk
dvz *= kk
vx += dvx
vz += dvz
var nx := x + vx * dt
var nz := z + vz * dt
if flying:
pos_x[i] = nx
pos_z[i] = nz
vel_x[i] = vx
vel_z[i] = vz
_turn(i, vx, vz)
continue
# Yield to the scarecrow (bounded push), and stop pressing into it.
for sc: Vector2 in scarecrows:
if not sc.is_finite():
continue
var ox := nx - sc.x
var oz := nz - sc.y
var od2 := ox * ox + oz * oz
if od2 < contact * contact and od2 > 1e-8:
var od := sqrt(od2)
var push := minf(contact - od, max_corr)
nx += ox / od * push
nz += oz / od * push
var vn := (vx * ox + vz * oz) / od
if vn < 0.0:
vx -= vn * ox / od
vz -= vn * oz / od
# Grid collision: keep the center in walkable cells, sliding along an axis when blocked.
if not nav.is_walkable(nav.cell_of(nx, nz)):
if nav.is_walkable(nav.cell_of(nx, z)):
nz = z
vz = 0.0
elif nav.is_walkable(nav.cell_of(x, nz)):
nx = x
vx = 0.0
else:
nx = x
nz = z
vx = 0.0
vz = 0.0
pos_x[i] = nx
pos_z[i] = nz
vel_x[i] = vx
vel_z[i] = vz
_turn(i, vx, vz)
grid.rebuild(pos_x, pos_z, active_count)
## Turns the heading toward the velocity (or the desire, when nearly still).
func _turn(i: int, vx: float, vz: float) -> void:
var sp2 := vx * vx + vz * vz
var fx := vx if sp2 > 0.04 else desire_x[i]
var fz := vz if sp2 > 0.04 else desire_z[i]
var fl := sqrt(fx * fx + fz * fz)
if fl > 1e-4:
var hx := head_x[i] + (fx / fl - head_x[i]) * 0.25
var hz := head_z[i] + (fz / fl - head_z[i]) * 0.25
var hl := sqrt(hx * hx + hz * hz)
if hl > 1e-4:
head_x[i] = hx / hl
head_z[i] = hz / hl
## Melee: enemies the behavior allows to attack, touching the scarecrow (within
## enemy_attack_reach of contact), off cooldown, and with a clear line to it, attack for their
## type's damage. The scarecrow's invulnerability decides whether a hit lands, so several attacks
## on one tick cost at most one hit. The cooldown (the type's hit_interval) starts on every
## attempt.
func evaluate_attacks(scarecrow_pos: Vector2, scarecrow_radius: float, target_kit: Scarecrow) -> void:
var cfg := config
var reach := cfg.enemy_radius + scarecrow_radius + cfg.enemy_attack_reach
var g := grid
var cx0 := g.cell_x(scarecrow_pos.x - reach)
var cx1 := g.cell_x(scarecrow_pos.x + reach)
var cz0 := g.cell_z(scarecrow_pos.y - reach)
var cz1 := g.cell_z(scarecrow_pos.y + reach)
for cz in range(cz0, cz1 + 1):
for cx in range(cx0, cx1 + 1):
var c := cz * g.width + cx
for k in range(g.cell_start[c], g.cell_start[c + 1]):
var i := g.items[k]
if i >= active_count or alive[i] == 0 or attack_cd[i] > 0.0:
continue
if behavior != null and not behavior.can_attack(self, i):
continue
var dx := pos_x[i] - scarecrow_pos.x
var dz := pos_z[i] - scarecrow_pos.y
if dx * dx + dz * dz > reach * reach:
continue
attack_cd[i] = t_hit_interval[type[i]]
attacks_attempted += 1
if not nav.line_clear(pos_x[i], pos_z[i], scarecrow_pos.x, scarecrow_pos.y):
attacks_blocked_by_cover += 1
continue
target_kit.try_damage(t_damage[type[i]])
## Swept projectile test against enemy hit proxies (vertical cylinders of the type's hit_radius;
## shots fly horizontally at combat height, so it is a 2D circle test, flyers included), using
## each enemy's motion across the tick relative to the shot's (the prototype's exact
## relative-motion test). Returns the dense slot of the nearest hit (fraction in hit_t) or -1.
func sweep_hit(x0: float, z0: float, x1: float, z1: float, use_motion: bool) -> int:
var widest := 0.0
for v in t_hit_radius:
widest = maxf(widest, v)
var margin := widest + max_speed() / float(Engine.physics_ticks_per_second) + config.max_correction_per_tick * 2.0
var g := grid
var cx0 := g.cell_x(minf(x0, x1) - margin)
var cx1 := g.cell_x(maxf(x0, x1) + margin)
var cz0 := g.cell_z(minf(z0, z1) - margin)
var cz1 := g.cell_z(maxf(z0, z1) + margin)
var best := -1
var best_t := 2.0
var mbx := x1 - x0
var mbz := z1 - z0
for cz in range(cz0, cz1 + 1):
for cx in range(cx0, cx1 + 1):
var c := cz * g.width + cx
for k in range(g.cell_start[c], g.cell_start[c + 1]):
var i := g.items[k]
if i >= active_count or alive[i] == 0:
continue
var rr := t_hit_radius[type[i]]
var ex0 := prev_x[i] if use_motion else pos_x[i]
var ez0 := prev_z[i] if use_motion else pos_z[i]
var sx := x0 - ex0
var sz := z0 - ez0
var mx := mbx - (pos_x[i] - ex0)
var mz := mbz - (pos_z[i] - ez0)
var cc := sx * sx + sz * sz - rr * rr
var t := 2.0
if cc <= 0.0:
t = 0.0
else:
var a := mx * mx + mz * mz
var bb := sx * mx + sz * mz
if a > 1e-12 and bb < 0.0:
var disc := bb * bb - a * cc
if disc >= 0.0:
t = (-bb - sqrt(disc)) / a
if t <= 1.0 and t < best_t:
best_t = t
best = i
hit_t = best_t
return best
## Every living enemy along a path at combat height (a polyline: the Alien Ray's beam, #18, from
## the scarecrow through the muzzle to where it ends), flyers included like sweep_hit (their hit
## proxy stays at combat height): those whose hit proxy (hit_radius) comes within half_width of
## the path, ordered by how far along it they are (dense slots, at most max_hits; 0: all). Unlike
## sweep_hit (the nearest only, for shots that stop) it's for a beam that pierces. The ends are
## flat: nothing behind the path's start or past its end (a wall that cut it short) is hit, even
## if its proxy reaches across. Current positions (no motion test), every slot checked rather than
## the grid, which misses enemies spawned since the last step.
func path_hits(path: PackedVector2Array, half_width: float, max_hits: int = 0) -> PackedInt32Array:
var out := PackedInt32Array()
var last := path.size() - 2
if last < 0:
return out
var head := path[1] - path[0]
var tail := path[last + 1] - path[last]
var found: Array = [] # [distance along the path, slot]
for i in active_count:
if alive[i] == 0:
continue
var e := Vector2(pos_x[i], pos_z[i])
if (e - path[0]).dot(head) < 0.0 or (e - path[last + 1]).dot(tail) > 0.0:
continue # behind its start, or past its end
var reach := half_width + t_hit_radius[type[i]]
var along := 0.0
for k in last + 1:
var a := path[k]
var ab := path[k + 1] - a
var seg := ab.length()
if seg > 1e-6:
var u := clampf((e - a).dot(ab) / (seg * seg), 0.0, 1.0)
if e.distance_squared_to(a + ab * u) <= reach * reach:
found.append([along + u * seg, i])
break
along += seg
found.sort_custom(func(x: Array, y: Array) -> bool: return x[0] < y[0])
for k in (found.size() if max_hits <= 0 else mini(found.size(), max_hits)):
out.append(found[k][1])
return out
## Releases this tick's removals: emits enemy_removed (handle still valid), then swaps the last
## active enemy into each freed slot and updates every mapping.
func commit_removals() -> void:
var n := _pending_count
_pending_count = 0
for k in n:
var id := _pending[k]
var d := id_dense[id]
if d < 0:
continue
enemy_removed.emit(handle_of(d), removal[d] as Removal, pos_x[d], pos_z[d], carry[d], target[d])
if characters != null and t_flying[type[d]] == 0:
characters.release(id, removal[d] == Removal.KILLED)
_release_slot(d)
## Uploads the flyers' poses (with their altitude) to the MultiMeshes: each slot is written to
## both batches, scaled to nothing in the one that doesn't draw its type (crows in renderer, UFOs
## in ufo_renderer). Ground enemies are drawn by their characters, so they're hidden in both.
func commit_render() -> void:
var b := renderer.buffer
var u := ufo_renderer.buffer
var o := 0
for i in active_count:
var t := type[i]
var saucer := 1.0 if t == TYPE_UFO else 0.0
var bird := 1.0 if t_flying[t] == 1 and t != TYPE_UFO else 0.0
var c := -head_z[i]
var s := -head_x[i]
var x := pos_x[i]
var y := alt[i]
var z := pos_z[i]
var flash := hurt[i]
b[o] = c * bird
b[o + 2] = s * bird
b[o + 3] = x
b[o + 5] = bird
b[o + 7] = y
b[o + 8] = -s * bird
b[o + 10] = c * bird
b[o + 11] = z
b[o + 13] = flash
u[o] = c * saucer
u[o + 2] = s * saucer
u[o + 3] = x
u[o + 5] = saucer
u[o + 7] = y
u[o + 8] = -s * saucer
u[o + 10] = c * saucer
u[o + 11] = z
u[o + 13] = flash
o += HordeRenderer.STRIDE
renderer.commit(active_count)
ufo_renderer.commit(active_count)
func _release_slot(d: int) -> void:
var id := dense_id[d]
var last := active_count - 1
if d != last:
for a: PackedFloat32Array in [pos_x, pos_z, prev_x, prev_z, vel_x, vel_z, desire_x, desire_z,
pace, head_x, head_z, flap_phase, hurt, timer, attack_cd, slow_left, alt]:
a[d] = a[last]
for a: PackedInt32Array in [health, target, carry, barrier]:
a[d] = a[last]
for a: PackedByteArray in [type, state, alive, removal, resume, want]:
a[d] = a[last]
var moved := dense_id[last]
dense_id[d] = moved
id_dense[moved] = d
renderer.move_slot(last, d)
ufo_renderer.move_slot(last, d)
alive[last] = 0
id_dense[id] = -1
id_generation[id] += 1
_free_ids[_free_top] = id
_free_top += 1
active_count -= 1
## The prototype's bird, re-centered on the torso and scaled to meters, beak along -Z.
static func build_bird_mesh(scale: float) -> ArrayMesh:
var src := load(AssetCatalog.BIRD_PATH) as Mesh
var basis := Basis(Vector3(0, 0, -1), Vector3(-1, 0, 0), Vector3(0, 1, 0))
var mesh := ArrayMesh.new()
for surface in src.get_surface_count():
var arrays := src.surface_get_arrays(surface)
var verts: PackedVector3Array = arrays[Mesh.ARRAY_VERTEX]
var normals: PackedVector3Array = arrays[Mesh.ARRAY_NORMAL]
for i in verts.size():
verts[i] = basis * ((verts[i] - AssetCatalog.BIRD_SOURCE_PIVOT) * scale)
for i in normals.size():
normals[i] = basis * normals[i]
arrays[Mesh.ARRAY_VERTEX] = verts
arrays[Mesh.ARRAY_NORMAL] = normals
arrays[Mesh.ARRAY_TANGENT] = null
mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
return mesh
## The UFO: a flattened saucer merged from primitives into one surface (no imported asset),
## centered on its origin with the hull's widest edge at y = 0. About 1.65 m across and 0.6 m tall
## (-0.13 .. 0.45) at scale 1, a little wider than a crow's 1.33 m wingspan. A metal hull, light
## grey above and darker below; a dark rim ring around the edge; a tinted glass dome on top; and
## eight lights on the rim. Per part, the vertex COLOR holds its color and UV its (glow,
## metalness) for ufo.gdshader, which spins it slowly and pulses the lights (glow 1). It's round,
## so forward (-Z) only matters to the instance's yaw.
static func build_ufo_mesh(scale: float = 1.0) -> ArrayMesh:
var upper := CylinderMesh.new()
upper.top_radius = 0.38
upper.bottom_radius = 0.74
upper.height = 0.16
upper.radial_segments = 24
upper.rings = 0
upper.cap_bottom = false
var lower := CylinderMesh.new()
lower.top_radius = 0.74
lower.bottom_radius = 0.3
lower.height = 0.13
lower.radial_segments = 24
lower.rings = 0
lower.cap_top = false
var rim := TorusMesh.new()
rim.inner_radius = 0.68
rim.outer_radius = 0.82
rim.rings = 28
rim.ring_segments = 8
var dome := SphereMesh.new() # a hemisphere: flat base at its origin, the top at its height
dome.radius = 0.36
dome.height = 0.3
dome.is_hemisphere = true
dome.radial_segments = 18
dome.rings = 8
var bulb := SphereMesh.new()
bulb.radius = 0.065
bulb.height = 0.13
bulb.radial_segments = 6
bulb.rings = 3
# [mesh, offset, color (sRGB), (glow, metalness)]
var parts: Array = [
[upper, Vector3(0.0, 0.08, 0.0), Color(0.68, 0.71, 0.76), Vector2(0.0, 0.6)],
[lower, Vector3(0.0, -0.065, 0.0), Color(0.38, 0.4, 0.46), Vector2(0.0, 0.6)],
[rim, Vector3.ZERO, Color(0.26, 0.28, 0.33), Vector2(0.0, 0.4)],
[dome, Vector3(0.0, 0.15, 0.0), Color(0.42, 0.95, 0.82), Vector2(0.3, 0.0)],
]
const LIGHTS := 8
for k in LIGHTS:
var a := TAU * k / LIGHTS
var color := Color(1.0, 0.72, 0.2) if k % 2 == 0 else Color(0.4, 1.0, 0.35)
parts.append([bulb, Vector3(cos(a) * 0.76, 0.05, sin(a) * 0.76), color, Vector2(1.0, 0.0)])
var verts := PackedVector3Array()
var normals := PackedVector3Array()
var colors := PackedColorArray()
var uvs := PackedVector2Array()
var indices := PackedInt32Array()
for part: Array in parts:
var src := (part[0] as PrimitiveMesh).get_mesh_arrays()
var pv: PackedVector3Array = src[Mesh.ARRAY_VERTEX]
var pn: PackedVector3Array = src[Mesh.ARRAY_NORMAL]
var offset: Vector3 = part[1]
var color := (part[2] as Color).srgb_to_linear()
var uv: Vector2 = part[3]
var base := verts.size()
for k in pv.size():
verts.append((pv[k] + offset) * scale)
normals.append(pn[k])
colors.append(color)
uvs.append(uv)
for k: int in src[Mesh.ARRAY_INDEX]:
indices.append(base + k)
var arrays := []
arrays.resize(Mesh.ARRAY_MAX)
arrays[Mesh.ARRAY_VERTEX] = verts
arrays[Mesh.ARRAY_NORMAL] = normals
arrays[Mesh.ARRAY_COLOR] = colors
arrays[Mesh.ARRAY_TEX_UV] = uvs
arrays[Mesh.ARRAY_INDEX] = indices
var mesh := ArrayMesh.new()
mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
return mesh