This commit is contained in:
Forrest 2026-10-03 12:14:28 -04:00
commit 276d43613d
1687 changed files with 109059 additions and 0 deletions

View file

@ -0,0 +1,96 @@
class_name Arena
extends Node3D
## Builds the static arena from an ArenaLayout: floor, fitted prototype_kit visuals, and one
## StaticBody3D whose box shapes match the footprints exactly. Built once during LOADING and
## reused across restarts (everything here is static and indestructible).
const WORLD_LAYER := 1 # Collision layer 1 "world": floor + obstacles.
var layout: ArenaLayout
var rects: PackedFloat32Array
var _materials := {}
func build(p_layout: ArenaLayout, catalog: AssetCatalog) -> void:
layout = p_layout
rects = layout.packed_rects()
_make_materials(catalog)
_build_floor(catalog)
var body := StaticBody3D.new()
body.name = "WorldCollision"
body.collision_layer = WORLD_LAYER
body.collision_mask = 0
add_child(body)
var floor_shape := CollisionShape3D.new()
var outer := layout.outer_rect()
var floor_box := BoxShape3D.new()
floor_box.size = Vector3(outer.size.x, 1.0, outer.size.y)
floor_shape.shape = floor_box
floor_shape.position = Vector3(outer.get_center().x, -0.5, outer.get_center().y)
body.add_child(floor_shape)
var visuals := Node3D.new()
visuals.name = "Obstacles"
add_child(visuals)
for o in layout.obstacles:
var shape := CollisionShape3D.new()
var box := BoxShape3D.new()
box.size = Vector3(o.size.x, o.height, o.size.y)
shape.shape = box
shape.position = Vector3(o.center.x, o.height * 0.5, o.center.y)
body.add_child(shape)
visuals.add_child(_fit_piece(catalog, o))
## Instantiates a prototype_kit piece and maps its measured AABB exactly onto the footprint.
## Pieces carry baked offsets from their source scene, so the AABB (not the origin) is used.
func _fit_piece(catalog: AssetCatalog, o: ArenaLayout.Obstacle) -> Node3D:
var inst := (catalog.pieces[o.piece] as PackedScene).instantiate() as Node3D
var a: AABB = catalog.piece_aabbs[o.piece]
var size_local := Vector3(o.size.y, o.height, o.size.x) if o.rotate_piece else Vector3(o.size.x, o.height, o.size.y)
var k := Vector3(size_local.x / a.size.x, size_local.y / a.size.y, size_local.z / a.size.z)
var rot := Basis(Vector3.UP, PI * 0.5) if o.rotate_piece else Basis.IDENTITY
var b := rot * Basis.from_scale(k)
var bottom_center := Vector3(a.get_center().x, a.position.y, a.get_center().z)
inst.transform = Transform3D(b, Vector3(o.center.x, 0.0, o.center.y) - b * bottom_center)
inst.name = "%s_%s" % [o.group, o.piece]
var mat: Material = _materials.get(o.group, _materials["default"])
for mi in inst.find_children("*", "MeshInstance3D", true, false):
(mi as MeshInstance3D).material_override = mat
return inst
func _build_floor(catalog: AssetCatalog) -> void:
var outer := layout.outer_rect()
var floor_inst := (catalog.pieces["ground"] as PackedScene).instantiate() as Node3D
var a: AABB = catalog.piece_aabbs["ground"]
var k := Vector3(outer.size.x / a.size.x, 1.0, outer.size.y / a.size.z)
var b := Basis.from_scale(k)
var c := Vector3(a.get_center().x, a.position.y, a.get_center().z)
floor_inst.transform = Transform3D(b, Vector3(outer.get_center().x, 0.0, outer.get_center().y) - b * c)
floor_inst.name = "Floor"
for mi in floor_inst.find_children("*", "MeshInstance3D", true, false):
var m := mi as MeshInstance3D
m.material_override = _materials["floor"]
m.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
add_child(floor_inst)
func _make_materials(catalog: AssetCatalog) -> void:
var floor_mat := ShaderMaterial.new()
floor_mat.shader = load("res://prototype/resources/floor.gdshader") as Shader
_materials["floor"] = floor_mat
var tints := {
"default": Color(0.78, 0.74, 0.68),
"perimeter": Color(0.62, 0.52, 0.42),
"crates": Color(0.80, 0.60, 0.38),
"u_fence": Color(0.55, 0.62, 0.72),
"pillars": Color(0.70, 0.70, 0.74),
"corridor": Color(0.66, 0.72, 0.58),
"center": Color(0.74, 0.58, 0.58),
}
for group: String in tints:
var m := StandardMaterial3D.new()
m.albedo_color = tints[group]
m.roughness = 0.9
_materials[group] = m

View file

@ -0,0 +1 @@
uid://bhjfieb40soqq

View file

@ -0,0 +1,126 @@
class_name ArenaLayout
extends RefCounted
## Authored arena data. Every obstacle is an axis-aligned XZ footprint plus a height; the
## visual piece, the physics box, and the navigation occupancy are all derived from it, so the
## three boundaries cannot drift apart.
##
## Compact layout (playable area x, z in [-16, 16]); the camera looks from the +X/+Z corner,
## so the -X and -Z perimeter is "far" (tall fence) and the +X/+Z perimeter is "near" (low fence
## that bullets fly over before despawning at the arena edge).
class Obstacle:
var piece: String
var center: Vector2
var size: Vector2
var height: float
## Rotate the visual 90 degrees so the piece's long (X) axis runs along world Z.
var rotate_piece: bool
var group: String
func _init(p_piece: String, p_center: Vector2, p_size: Vector2, p_height: float, p_rotate: bool, p_group: String) -> void:
piece = p_piece
center = p_center
size = p_size
height = p_height
rotate_piece = p_rotate
group = p_group
func rect() -> Rect2:
return Rect2(center - size * 0.5, size)
const FAR_FENCE_HEIGHT := 2.0
const NEAR_FENCE_HEIGHT := 0.6
const COVER_HEIGHT := 1.5
const WALL_THICKNESS := 0.5
var scale: float = 1.0
var half_extent: Vector2 # playable half size (meters)
var obstacles: Array[Obstacle] = []
var player_start: Vector2
var concentrated_point: Vector2
var bottleneck_point: Vector2
## Closed loop used by the scripted benchmark player in the SPREAD scenario.
var route: PackedVector2Array = PackedVector2Array()
static func build(cfg: PrototypeConfig) -> ArenaLayout:
var l := ArenaLayout.new()
l.scale = cfg.layout_scale()
var s := l.scale
l.half_extent = cfg.arena_size * 0.5 * s
var hx := cfg.arena_size.x * 0.5
var hz := cfg.arena_size.y * 0.5
var t := WALL_THICKNESS
# Perimeter: 4 m fence segments just outside the playable area, plus corner posts.
var x := -hx + 2.0
while x < hx:
l._add("fence", Vector2(x, -hz - t * 0.5), Vector2(4.0, t), FAR_FENCE_HEIGHT, false, "perimeter")
l._add("fence", Vector2(x, hz + t * 0.5), Vector2(4.0, t), NEAR_FENCE_HEIGHT, false, "perimeter")
x += 4.0
var z := -hz + 2.0
while z < hz:
l._add("fence", Vector2(-hx - t * 0.5, z), Vector2(t, 4.0), FAR_FENCE_HEIGHT, true, "perimeter")
l._add("fence", Vector2(hx + t * 0.5, z), Vector2(t, 4.0), NEAR_FENCE_HEIGHT, true, "perimeter")
z += 4.0
var c := Vector2(hx + t * 0.5, hz + t * 0.5)
l._add("pillar", Vector2(-c.x, -c.y), Vector2(t, t), FAR_FENCE_HEIGHT, false, "perimeter")
l._add("pillar", Vector2(c.x, -c.y), Vector2(t, t), FAR_FENCE_HEIGHT, false, "perimeter")
l._add("pillar", Vector2(-c.x, c.y), Vector2(t, t), FAR_FENCE_HEIGHT, false, "perimeter")
l._add("pillar", Vector2(c.x, c.y), Vector2(t, t), NEAR_FENCE_HEIGHT, false, "perimeter")
var h := COVER_HEIGHT
# A: crate L (far quadrant).
l._add("box", Vector2(-9, -9), Vector2(2, 2), h, false, "crates")
l._add("box", Vector2(-7, -9), Vector2(2, 2), h, false, "crates")
l._add("box", Vector2(-9, -7), Vector2(2, 2), h, false, "crates")
# B: U-shaped fence opening toward the far (-Z) fence; birds inside must route out of it.
l._add("fence", Vector2(9, -5), Vector2(6, t), h, false, "u_fence")
l._add("fence", Vector2(6.25, -7.5), Vector2(t, 5), h, true, "u_fence")
l._add("fence", Vector2(11.75, -7.5), Vector2(t, 5), h, true, "u_fence")
# C: pillar grove (near quadrant); 2 m gaps between pillar faces.
for p: Vector2 in [Vector2(8, 8), Vector2(11, 8), Vector2(8, 11), Vector2(11, 11)]:
l._add("pillar", p, Vector2(1, 1), h, false, "pillars")
# D: corridor of two thin walls, 3.5 m wide (bottleneck scenario).
l._add("thin_wall", Vector2(-9, 6), Vector2(6, t), h, false, "corridor")
l._add("thin_wall", Vector2(-9, 10), Vector2(6, t), h, false, "corridor")
# E: central cover wall.
l._add("wall", Vector2(0, -6), Vector2(4, 1), h, false, "center")
l.player_start = cfg.player_start * s
l.concentrated_point = Vector2(0, 2) * s
l.bottleneck_point = Vector2(-9, 8) * s
for p: Vector2 in [Vector2(-4, -2), Vector2(4, -2), Vector2(4, 4.5), Vector2(-4, 4.5)]:
l.route.append(p * s)
return l
func _add(piece: String, center: Vector2, size: Vector2, height: float, rotate_piece: bool, group: String) -> void:
obstacles.append(Obstacle.new(piece, center * scale, size * scale, height, rotate_piece, group))
## Footprints packed as [min_x, min_z, max_x, max_z] per obstacle.
func packed_rects() -> PackedFloat32Array:
var out := PackedFloat32Array()
out.resize(obstacles.size() * 4)
for i in obstacles.size():
var r := obstacles[i].rect()
out[i * 4] = r.position.x
out[i * 4 + 1] = r.position.y
out[i * 4 + 2] = r.end.x
out[i * 4 + 3] = r.end.y
return out
## Bounds including the perimeter footprints.
func outer_rect() -> Rect2:
var m := WALL_THICKNESS * scale
return Rect2(-half_extent - Vector2(m, m), (half_extent + Vector2(m, m)) * 2.0)
func min_thickness() -> float:
var m := INF
for o in obstacles:
m = minf(m, minf(o.size.x, o.size.y))
return m

View file

@ -0,0 +1 @@
uid://bquemffxp3s5h

View file

@ -0,0 +1,525 @@
class_name ArenaNavigation
extends RefCounted
## Shared navigation and obstacle queries for the horde, derived from the arena footprints.
##
## * Occupancy grid (nav_cell_size cells, 1-cell blocked border) with obstacles inflated by the
## bird radius, so a free cell center always keeps a bird clear of the footprints.
## * One flow field toward the player's reachable cell: Dijkstra over 8 neighbors with octile
## integer costs (orthogonal 5, diagonal 7 ~ 5 * sqrt(2)) using a circular bucket queue with
## lazy deletion (exact for integer costs below BUCKETS). Diagonal moves are only allowed when
## both adjacent orthogonal cells are free (no corner cutting). Unreachable cells keep
## UNREACHABLE.
## * The rebuild is a resumable job: begin_flow() then step_flow(max_cells) each tick, so the
## per-tick cost is bounded and deterministic (a fixed cell budget, not a time budget).
## * Circle-vs-footprint push-out and segment-vs-footprint line-of-sight queries, accelerated by
## a static coarse bucket grid of footprint indices.
## The integration field is double-buffered: steering always reads the last completed field.
const UNREACHABLE := 1 << 29
const COST_ORTH := 5
const COST_DIAG := 7
const BUCKETS := 8 # > max edge cost, so each pending distance maps to a unique bucket
var cell_size: float
var inv_cell: float
var origin_x: float # world position of cell (0, 0)'s min corner
var origin_z: float
var width: int
var height: int
var blocked: PackedByteArray
## Integration field (completed). Indexed by cell; UNREACHABLE where no path exists.
var dist: PackedInt32Array
var target_cell: int = -1
var rebuild_count: int = 0
## Total CPU time of the last completed rebuild (sum of its slices).
var last_rebuild_usec: int = 0
var max_rebuild_usec: int = 0
var total_rebuild_usec: int = 0
## Largest single slice (the per-tick cost that actually lands in one frame).
var max_slice_usec: int = 0
var last_rebuild_slices: int = 0
## Footprints [min_x, min_z, max_x, max_z] (not inflated).
var rects: PackedFloat32Array
var rect_count: int = 0
var bounds: Rect2 # playable area
var _back: PackedInt32Array
var _bucket_buf := PackedInt32Array() # BUCKETS stacks of capacity cell_count()
var _bucket_cnt := PackedInt32Array()
var _seen := PackedByteArray()
var _job_active := false
var _job_target: int = -1
var _job_cur: int = 0
var _job_queued: int = 0
var _job_usec: int = 0
var _job_slices: int = 0
var _offsets := PackedInt32Array()
var _side_a := PackedInt32Array()
var _side_b := PackedInt32Array()
var _dir_x := PackedFloat32Array()
var _dir_z := PackedFloat32Array()
var _queue := PackedInt32Array()
# Static obstacle buckets (coarse grid of footprint indices).
const OBS_CELL := 2.0
## Footprints are bucketed with this margin: circle queries with radius <= OBS_MARGIN and segment
## queries up to 2 * OBS_MARGIN long find every footprint they can touch.
const OBS_MARGIN := 1.5
var _obs_w: int
var _obs_h: int
var _obs_origin := Vector2.ZERO
var _obs_start := PackedInt32Array()
var _obs_items := PackedInt32Array()
## Read-only views of the obstacle buckets for hot loops that inline the "no footprint nearby"
## test (an empty bucket means resolve_circle / segment_blocked would be no-ops there).
var obs_cols: int
var obs_rows: int
var obs_origin_x: float
var obs_origin_z: float
var obs_start: PackedInt32Array
func setup(p_rects: PackedFloat32Array, playable: Rect2, outer: Rect2, p_cell_size: float, inflate: float) -> void:
rects = p_rects
@warning_ignore("integer_division")
rect_count = rects.size() / 4
bounds = playable
cell_size = p_cell_size
inv_cell = 1.0 / cell_size
width = ceili(outer.size.x * inv_cell) + 2
height = ceili(outer.size.y * inv_cell) + 2
origin_x = outer.position.x - cell_size
origin_z = outer.position.y - cell_size
var n := width * height
blocked = PackedByteArray()
blocked.resize(n)
for cz in height:
for cx in width:
var i := cz * width + cx
if cx == 0 or cz == 0 or cx == width - 1 or cz == height - 1:
blocked[i] = 1
continue
var x := origin_x + (cx + 0.5) * cell_size
var z := origin_z + (cz + 0.5) * cell_size
var b := 0
if x < playable.position.x + inflate or x > playable.end.x - inflate \
or z < playable.position.y + inflate or z > playable.end.y - inflate:
b = 1
else:
for r in rect_count:
var o := r * 4
if x > rects[o] - inflate and x < rects[o + 2] + inflate \
and z > rects[o + 1] - inflate and z < rects[o + 3] + inflate:
b = 1
break
blocked[i] = b
dist = PackedInt32Array()
dist.resize(n)
dist.fill(UNREACHABLE)
_back = PackedInt32Array()
_back.resize(n)
# Within one bucket's window a cell has a single possible distance, so each stack holds at
# most one entry per cell.
_bucket_buf = PackedInt32Array()
_bucket_buf.resize(n * BUCKETS)
_bucket_cnt = PackedInt32Array()
_bucket_cnt.resize(BUCKETS)
_seen = PackedByteArray()
_seen.resize(n)
_queue = PackedInt32Array()
_queue.resize(n)
var w := width
# Orthogonal first (indices 0..3), then diagonals (4..7) with their two side cells.
_offsets = PackedInt32Array([1, -1, w, -w, w + 1, w - 1, -w + 1, -w - 1])
_side_a = PackedInt32Array([0, 0, 0, 0, 1, -1, 1, -1])
_side_b = PackedInt32Array([0, 0, 0, 0, w, w, -w, -w])
var s := 1.0 / sqrt(2.0)
_dir_x = PackedFloat32Array([1, -1, 0, 0, s, -s, s, -s])
_dir_z = PackedFloat32Array([0, 0, 1, -1, s, s, -s, -s])
_build_obstacle_buckets(outer)
func cell_count() -> int:
return width * height
func cell_of(x: float, z: float) -> int:
var cx := clampi(int((x - origin_x) * inv_cell), 0, width - 1)
var cz := clampi(int((z - origin_z) * inv_cell), 0, height - 1)
return cz * width + cx
func cell_center(i: int) -> Vector2:
@warning_ignore("integer_division")
var cz := i / width
var cx := i - cz * width
return Vector2(origin_x + (cx + 0.5) * cell_size, origin_z + (cz + 0.5) * cell_size)
func is_free(i: int) -> bool:
return blocked[i] == 0
func is_reachable(i: int) -> bool:
return dist[i] < UNREACHABLE
## Nearest free cell to i (breadth-first over 4-neighbors), or -1 if none within max_steps rings.
func nearest_free(i: int, max_cells: int = 4096) -> int:
if blocked[i] == 0:
return i
var q := _queue
var seen := _seen
seen.fill(0)
var head := 0
var tail := 0
q[tail] = i
tail += 1
seen[i] = 1
while head < tail and head < max_cells:
var c := q[head]
head += 1
for k in 4:
var nb := c + _offsets[k]
if nb < 0 or nb >= blocked.size() or seen[nb] == 1:
continue
if blocked[nb] == 0:
return nb
seen[nb] = 1
q[tail] = nb
tail += 1
return -1
## Synchronous rebuild (load, reset, tests): runs the whole job immediately.
func rebuild_flow(target_x: float, target_z: float) -> bool:
if not begin_flow(target_x, target_z):
return false
while not step_flow(1 << 30):
pass
return true
func is_rebuilding() -> bool:
return _job_active
## Starts a rebuild toward the free cell nearest the target. The previous field stays active
## until the job completes. Returns false (keeping the previous field) if no free cell is near.
func begin_flow(target_x: float, target_z: float) -> bool:
var t0 := Time.get_ticks_usec()
var target := nearest_free(cell_of(target_x, target_z))
if target < 0:
return false
_back.fill(UNREACHABLE)
_bucket_cnt.fill(0)
_back[target] = 0
_bucket_buf[0] = target
_bucket_cnt[0] = 1
_job_target = target
_job_cur = 0
_job_queued = 1
_job_active = true
_job_slices = 0
_job_usec = Time.get_ticks_usec() - t0
return true
## Processes up to max_cells finalized cells. Returns true when the field is complete (and has
## been swapped in as the active field).
func step_flow(max_cells: int) -> bool:
if not _job_active:
return true
var t0 := Time.get_ticks_usec()
var d := _back
var buf := _bucket_buf
var cnt := _bucket_cnt
var blk := blocked
var w := width
var cap := cell_count()
var cur := _job_cur
var queued := _job_queued
var done := 0
# Hand-unrolled 8-neighbor relaxation (measured 3.3 -> 2.2 ms on the compact grid versus a
# loop over offset tables).
# Orthogonal pushes all land in bucket (cur + 5) & 7 and diagonal pushes in (cur + 7) & 7,
# neither of which is the bucket being drained, so their counts are kept in locals.
while queued > 0 and done < max_cells:
var b := cur & 7
var k := cnt[b]
if k == 0:
cur += 1
continue
var base := b * cap
var bo := (cur + COST_ORTH) & 7
var bd := (cur + COST_DIAG) & 7
var ob := bo * cap
var db := bd * cap
var ko := cnt[bo]
var kd := cnt[bd]
var ndo := cur + COST_ORTH
var ndd := cur + COST_DIAG
while k > 0 and done < max_cells:
k -= 1
queued -= 1
var c := buf[base + k]
if d[c] != cur:
continue # stale entry: finalized earlier at a smaller distance
done += 1
var e := c + 1
var wst := c - 1
var s := c + w
var nr := c - w
var fe := blk[e] == 0
var fw := blk[wst] == 0
var fs := blk[s] == 0
var fn := blk[nr] == 0
if fe and ndo < d[e]:
d[e] = ndo
buf[ob + ko] = e
ko += 1
queued += 1
if fw and ndo < d[wst]:
d[wst] = ndo
buf[ob + ko] = wst
ko += 1
queued += 1
if fs and ndo < d[s]:
d[s] = ndo
buf[ob + ko] = s
ko += 1
queued += 1
if fn and ndo < d[nr]:
d[nr] = ndo
buf[ob + ko] = nr
ko += 1
queued += 1
# Diagonals only when both adjacent orthogonal cells are free (no corner cutting).
if fe and fs:
var x := s + 1
if blk[x] == 0 and ndd < d[x]:
d[x] = ndd
buf[db + kd] = x
kd += 1
queued += 1
if fw and fs:
var x := s - 1
if blk[x] == 0 and ndd < d[x]:
d[x] = ndd
buf[db + kd] = x
kd += 1
queued += 1
if fe and fn:
var x := nr + 1
if blk[x] == 0 and ndd < d[x]:
d[x] = ndd
buf[db + kd] = x
kd += 1
queued += 1
if fw and fn:
var x := nr - 1
if blk[x] == 0 and ndd < d[x]:
d[x] = ndd
buf[db + kd] = x
kd += 1
queued += 1
cnt[b] = k
cnt[bo] = ko
cnt[bd] = kd
_job_cur = cur
_job_queued = queued
var slice := Time.get_ticks_usec() - t0
_job_usec += slice
_job_slices += 1
max_slice_usec = maxi(max_slice_usec, slice)
if queued > 0:
return false
_back = dist
dist = d
target_cell = _job_target
_job_active = false
rebuild_count += 1
last_rebuild_usec = _job_usec
last_rebuild_slices = _job_slices
total_rebuild_usec += _job_usec
max_rebuild_usec = maxi(max_rebuild_usec, _job_usec)
return true
## Desired direction (unit XZ) for a bird at (x, z), written to out. Normally the cheapest
## legal neighbor step from the bird's cell. A bird whose center sits inside the inflated
## clearance band (blocked cell, still legally clear of the footprint) steers toward the center
## of its cheapest free neighbor instead. Returns false when no route exists (hold position).
func flow_direction(x: float, z: float, out: PackedFloat32Array) -> bool:
var i := cell_of(x, z)
var di := dist[i]
if di == 0:
return false
var best := di
var best_k := -1
var inside_band := blocked[i] != 0
for k in 8:
var nb := i + _offsets[k]
if nb < 0 or nb >= dist.size():
continue
var dn := dist[nb]
if dn >= best:
continue
if not inside_band and k >= 4 and (blocked[i + _side_a[k]] != 0 or blocked[i + _side_b[k]] != 0):
continue
best = dn
best_k = k
if best_k < 0:
return false
if inside_band:
var c := cell_center(i + _offsets[best_k])
var v := Vector2(c.x - x, c.y - z)
var l := v.length()
if l < 1e-4:
return false
out[0] = v.x / l
out[1] = v.y / l
else:
out[0] = _dir_x[best_k]
out[1] = _dir_z[best_k]
return true
func reset_stats() -> void:
rebuild_count = 0
last_rebuild_usec = 0
max_rebuild_usec = 0
total_rebuild_usec = 0
max_slice_usec = 0
last_rebuild_slices = 0
_job_active = false
# --- Footprint queries -------------------------------------------------------------------
func _build_obstacle_buckets(outer: Rect2) -> void:
_obs_origin = outer.position - Vector2(OBS_MARGIN, OBS_MARGIN)
_obs_w = ceili((outer.size.x + OBS_MARGIN * 2.0) / OBS_CELL) + 1
_obs_h = ceili((outer.size.y + OBS_MARGIN * 2.0) / OBS_CELL) + 1
var lists: Array[PackedInt32Array] = []
lists.resize(_obs_w * _obs_h)
for i in lists.size():
lists[i] = PackedInt32Array()
for r in rect_count:
var o := r * 4
var x0 := clampi(int((rects[o] - OBS_MARGIN - _obs_origin.x) / OBS_CELL), 0, _obs_w - 1)
var z0 := clampi(int((rects[o + 1] - OBS_MARGIN - _obs_origin.y) / OBS_CELL), 0, _obs_h - 1)
var x1 := clampi(int((rects[o + 2] + OBS_MARGIN - _obs_origin.x) / OBS_CELL), 0, _obs_w - 1)
var z1 := clampi(int((rects[o + 3] + OBS_MARGIN - _obs_origin.y) / OBS_CELL), 0, _obs_h - 1)
for cz in range(z0, z1 + 1):
for cx in range(x0, x1 + 1):
lists[cz * _obs_w + cx].append(r)
_obs_start.resize(lists.size() + 1)
_obs_items.clear()
for i in lists.size():
_obs_start[i] = _obs_items.size()
_obs_items.append_array(lists[i])
_obs_start[lists.size()] = _obs_items.size()
obs_cols = _obs_w
obs_rows = _obs_h
obs_origin_x = _obs_origin.x
obs_origin_z = _obs_origin.y
obs_start = _obs_start
func obstacle_bucket(x: float, z: float) -> int:
var cx := clampi(int((x - _obs_origin.x) / OBS_CELL), 0, _obs_w - 1)
var cz := clampi(int((z - _obs_origin.y) / OBS_CELL), 0, _obs_h - 1)
return cz * _obs_w + cx
## Pushes a circle out of every footprint it overlaps and keeps it inside the playable area.
## Two passes settle corners formed by touching footprints. Writes the result to out[0], out[1].
## Valid for radius <= OBS_MARGIN; per-call displacement is bounded by the caller (see
## HordeSystem) so a center can never cross a footprint's midline in one step.
func resolve_circle(x: float, z: float, r: float, out: PackedFloat32Array) -> void:
var rr := r * r
var bucket := obstacle_bucket(x, z)
var s0 := _obs_start[bucket]
var s1 := _obs_start[bucket + 1]
for _pass in 2:
for k in range(s0, s1):
var o := _obs_items[k] * 4
var qx := clampf(x, rects[o], rects[o + 2])
var qz := clampf(z, rects[o + 1], rects[o + 3])
var dx := x - qx
var dz := z - qz
var d2 := dx * dx + dz * dz
if d2 >= rr:
continue
if d2 > 1e-10:
var d := sqrt(d2)
var push := (r - d) / d
x += dx * push
z += dz * push
else:
# Center inside the footprint: leave through the nearest face.
var left := x - rects[o]
var right := rects[o + 2] - x
var top := z - rects[o + 1]
var bottom := rects[o + 3] - z
var m := minf(minf(left, right), minf(top, bottom))
if m == left:
x = rects[o] - r
elif m == right:
x = rects[o + 2] + r
elif m == top:
z = rects[o + 1] - r
else:
z = rects[o + 3] + r
out[0] = clampf(x, bounds.position.x + r, bounds.end.x - r)
out[1] = clampf(z, bounds.position.y + r, bounds.end.y - r)
## True if the segment crosses any footprint (slab test). Valid for segments up to
## 2 * OBS_MARGIN long (melee line of sight and the direct-chase check).
func segment_blocked(ax: float, az: float, bx: float, bz: float) -> bool:
var bucket := obstacle_bucket((ax + bx) * 0.5, (az + bz) * 0.5)
var dx := bx - ax
var dz := bz - az
for k in range(_obs_start[bucket], _obs_start[bucket + 1]):
var o := _obs_items[k] * 4
var t0 := 0.0
var t1 := 1.0
var hit := true
for axis in 2:
var a := ax if axis == 0 else az
var dd := dx if axis == 0 else dz
var lo := rects[o + axis]
var hi := rects[o + 2 + axis]
if absf(dd) < 1e-9:
if a < lo or a > hi:
hit = false
break
else:
var ta := (lo - a) / dd
var tb := (hi - a) / dd
if ta > tb:
var tmp := ta
ta = tb
tb = tmp
t0 = maxf(t0, ta)
t1 = minf(t1, tb)
if t0 > t1:
hit = false
break
if hit:
return true
return false
## Debug/test helper: true if the circle overlaps any footprint.
func circle_overlaps(x: float, z: float, r: float) -> bool:
for i in rect_count:
var o := i * 4
var qx := clampf(x, rects[o], rects[o + 2])
var qz := clampf(z, rects[o + 1], rects[o + 3])
if (x - qx) * (x - qx) + (z - qz) * (z - qz) < r * r - 1e-6:
return true
return false

View file

@ -0,0 +1 @@
uid://cxvgymf4uxd1n

View file

@ -0,0 +1,164 @@
class_name AssetCatalog
extends RefCounted
## Explicit, resolved references to every asset the prototype uses. Everything is loaded and
## derived during LOADING; nothing here is touched from the combat hot path.
## Source assets are never modified: derived data (oriented bird mesh, filtered animation
## library) lives only in memory.
const BIRD_PATH := "res://assets/bird/Bird_01.obj"
const MANNEQUIN_PATH := "res://assets/kaykit_characters/characters/Mannequin_Medium.glb"
const ANIM_DIR := "res://assets/kaykit_characters/animations/Rig_Medium/"
const PIECE_DIR := "res://assets/prototype_kit/Pieces/"
## Layout piece keys -> prototype_kit file names.
const PIECES := {
"fence": "fence.fbx",
"box": "box.fbx",
"pillar": "pillar.fbx",
"thin_wall": "cube6.fbx",
"wall": "wall.fbx",
"ground": "ground.fbx",
}
## Gameplay animation role -> [source file, clip name, loops]. Clip names were taken from the
## asset inventory (see prototype/README.md); the mannequin itself ships without clips.
const CLIPS := {
"idle": ["Rig_Medium_General.glb", "Idle_A", true],
"run": ["Rig_Medium_MovementBasic.glb", "Running_A", true],
"back": ["Rig_Medium_MovementAdvanced.glb", "Walking_Backwards", true],
"strafe_left": ["Rig_Medium_MovementAdvanced.glb", "Running_Strafe_Left", true],
"strafe_right": ["Rig_Medium_MovementAdvanced.glb", "Running_Strafe_Right", true],
"aim": ["Rig_Medium_CombatRanged.glb", "Ranged_1H_Aiming", true],
"death": ["Rig_Medium_General.glb", "Death_A", false],
"win": ["Rig_Medium_Simulation.glb", "Cheering", true],
}
## Center of the bird's torso in OBJ source units, measured during the asset inventory
## (torso bounds x[-39.9, 77.1], z[62.5, 105.5]; wings span y[-120.7, 120.7]).
const BIRD_SOURCE_PIVOT := Vector3(18.6, 0.0, 84.0)
var bird_mesh: ArrayMesh
var bird_triangles: int = 0
var mannequin_scene: PackedScene
var animation_library: AnimationLibrary
var dropped_animation_tracks: int = 0
var pieces: Dictionary = {} # String -> PackedScene
var piece_aabbs: Dictionary = {} # String -> AABB (piece root space)
var errors: PackedStringArray = PackedStringArray()
func load_all(cfg: PrototypeConfig) -> bool:
_load_bird(cfg)
_load_mannequin()
for key: String in PIECES:
_load_piece(key)
for e in errors:
push_error("AssetCatalog: " + e)
return errors.is_empty()
## Builds the bird mesh used by the horde: re-centered on the torso, scaled to meters, and
## rotated so the beak faces -Z (Godot forward) with wings along X. The OBJ is authored with
## +X forward, +Z up, and wings along Y.
func _load_bird(cfg: PrototypeConfig) -> void:
var src := load(BIRD_PATH) as Mesh
if src == null or src.get_surface_count() == 0:
errors.append("missing bird mesh " + BIRD_PATH)
return
var s := cfg.enemy_visual_scale
# Source axes -> local: x' = -y, y' = z, z' = -x.
var basis := Basis(Vector3(0, 0, -1), Vector3(-1, 0, 0), Vector3(0, 1, 0))
bird_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] - BIRD_SOURCE_PIVOT) * s)
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 # Tangents would need the same rotation; unused.
bird_mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
var idx: PackedInt32Array = arrays[Mesh.ARRAY_INDEX]
@warning_ignore("integer_division")
bird_triangles += (idx.size() if idx.size() > 0 else verts.size()) / 3
func _load_mannequin() -> void:
mannequin_scene = load(MANNEQUIN_PATH) as PackedScene
if mannequin_scene == null:
errors.append("missing mannequin " + MANNEQUIN_PATH)
return
# Collect the mannequin's bone names so foreign tracks can be filtered out.
var probe := mannequin_scene.instantiate()
var skel := probe.get_node_or_null("Rig_Medium/Skeleton3D") as Skeleton3D
if skel == null:
errors.append("mannequin skeleton not found at Rig_Medium/Skeleton3D")
probe.free()
return
var bones := {}
for b in skel.get_bone_count():
bones[skel.get_bone_name(b)] = true
probe.free()
animation_library = AnimationLibrary.new()
var sources := {} # file -> AnimationPlayer owner node (freed after extraction)
for role: String in CLIPS:
var spec: Array = CLIPS[role]
var file: String = spec[0]
if not sources.has(file):
var scene := load(ANIM_DIR + file) as PackedScene
if scene == null:
errors.append("missing animation file " + file)
continue
sources[file] = scene.instantiate()
var root: Node = sources[file]
var player := root.get_node_or_null("AnimationPlayer") as AnimationPlayer
if player == null or not player.has_animation(spec[1]):
errors.append("clip %s not found in %s" % [spec[1], file])
continue
var anim := player.get_animation(spec[1]).duplicate(true) as Animation
for t in range(anim.get_track_count() - 1, -1, -1):
var path := anim.track_get_path(t)
var ok := String(path.get_concatenated_names()) == "Rig_Medium/Skeleton3D" \
and path.get_subname_count() == 1 and bones.has(String(path.get_subname(0)))
if not ok:
anim.remove_track(t)
dropped_animation_tracks += 1
anim.loop_mode = Animation.LOOP_LINEAR if spec[2] else Animation.LOOP_NONE
animation_library.add_animation(role, anim)
for file: String in sources:
(sources[file] as Node).free()
func _load_piece(key: String) -> void:
var path: String = PIECE_DIR + PIECES[key]
var scene := load(path) as PackedScene
if scene == null:
errors.append("missing piece " + path)
return
pieces[key] = scene
var root := scene.instantiate() as Node3D
piece_aabbs[key] = _merged_aabb(root, root)
root.free()
static func _merged_aabb(root: Node3D, node: Node) -> AABB:
var out := AABB()
var first := true
var stack: Array[Node] = [node]
while not stack.is_empty():
var n: Node = stack.pop_back()
if n is MeshInstance3D:
var xf := Transform3D.IDENTITY
var cur: Node = n
while cur != root and cur is Node3D:
xf = (cur as Node3D).transform * xf
cur = cur.get_parent()
var a := xf * (n as MeshInstance3D).get_aabb()
out = a if first else out.merge(a)
first = false
stack.append_array(n.get_children())
return out

View file

@ -0,0 +1 @@
uid://c57tvilkftaci

View file

@ -0,0 +1,436 @@
class_name BenchmarkRunner
extends Node
## Command-line driven presets, scripted runs, measurements, and screenshots. Inactive (no
## per-frame work) unless arguments are passed after "--":
##
## --enemies=N normal-game enemy count override (e.g. 25 for the demo)
## --seed=N round seed
## --overlay start with the performance overlay visible
## --preset=NAME normal25 | normal50 | stress250 | stress500 | stress1000 | stress2000
## --layout=NAME compact | enlarged (enlarged = labeled 2x copy of the layout)
## --scenario=NAME spread | concentrated | bottleneck | idle
## --bench measure: --warmup=10 --duration=60 [--out=path] [--label=text]
## --vsync=on|off default on
## --fire-delay=seconds scripted fire starts this long after the round starts (default 0.1);
## used to separate first-shot stutter from start-up hitches
## --screenshot=path save frames at --screenshot-at=t1,t2,... seconds (default 3);
## multiple times produce path_<t>.png
## --camera-zoom=K debug: shrink the ortho view K times and follow the player
## --physics-ticks=N debug: override the physics tick rate (interpolation checks)
## --quit-after=seconds quit after this much round time
##
## Every preset is a labeled stress configuration: the player is invulnerable and defeated birds
## are recycled so the population stays at the preset size. Collision, attacks, and navigation
## stay fully enabled (attacks are evaluated; accepted hits are absorbed and counted).
const PRESETS := {
"normal25": 25, "normal50": 50, "stress250": 250, "stress500": 500,
"stress1000": 1000, "stress2000": 2000,
}
const MAX_FRAMES := 400000
var active := false
var _round: RoundController
var _args := {}
var _scripted: ScriptedInput
var _bench := false
var _warmup: float = 10.0
var _duration: float = 60.0
var _capture_started := false
var _done := false
var _t: float = 0.0
var _frame := PackedInt32Array()
var _frame_n: int = 0
var _tick := PackedInt32Array()
var _tick_n: int = 0
var _phase_sum := PackedFloat64Array([0, 0, 0, 0, 0, 0, 0, 0])
var _phase_max := PackedInt32Array([0, 0, 0, 0, 0, 0, 0, 0])
var _gpu := PackedFloat32Array()
var _cpu_render := PackedFloat32Array()
var _draw_calls_sum: float = 0.0
var _draw_calls_max: int = 0
var _prims_sum: float = 0.0
var _last_usec: int = 0
var _first_shot_t: float = -1.0
var _first_hit_t: float = -1.0
var _first_shot_max_ms: float = 0.0
var _first_hit_max_ms: float = 0.0
var _first_shot_before_ms: float = 0.0
var _first_hit_before_ms: float = 0.0
var _startup_max_ms: float = 0.0
var _recent_t := PackedFloat32Array() # ring of (time, frame ms) for "before" baselines
var _recent_ms := PackedFloat32Array()
var _recent_i: int = 0
const FIRST_USE_WINDOW := 0.5
const RECENT := 4096
var _mem_start: int = 0
var _obj_start: int = 0
var _timeline: Array = []
var _next_sample: float = 0.0
var _shot_times := PackedFloat32Array()
var _shot_index: int = 0
var _vp_rid: RID
func configure(round_controller: RoundController) -> void:
_round = round_controller
for a in OS.get_cmdline_user_args():
var s := String(a).trim_prefix("--")
var eq := s.find("=")
if eq >= 0:
_args[s.substr(0, eq)] = s.substr(eq + 1)
else:
_args[s] = "true"
if _args.is_empty():
set_process(false)
set_physics_process(false)
return
active = true
var cfg := _round.config
if _args.has("seed"):
cfg.round_seed = int(_args["seed"])
if _args.has("enemies"):
cfg.enemy_count = int(_args["enemies"])
cfg.enemy_capacity = maxi(cfg.enemy_capacity, cfg.enemy_count)
if _args.has("overlay"):
cfg.show_overlay = true
if _args.has("physics-ticks"):
cfg.physics_ticks = int(_args["physics-ticks"])
if _args.has("layout"):
cfg.layout = PrototypeConfig.Layout.ENLARGED if _args["layout"] == "enlarged" else PrototypeConfig.Layout.COMPACT
if _args.has("preset"):
var preset_name: String = _args["preset"]
if not PRESETS.has(preset_name):
push_error("Unknown preset " + preset_name)
else:
cfg.enemy_count = PRESETS[preset_name]
cfg.enemy_capacity = maxi(64, cfg.enemy_count)
cfg.stress_invulnerable = true
cfg.stress_recycle = true
cfg.stress_label = preset_name
var scenario: String = _args.get("scenario", "spread" if _args.has("preset") else "")
if scenario != "":
match scenario:
"spread": cfg.scenario = PrototypeConfig.Scenario.SPREAD
"concentrated": cfg.scenario = PrototypeConfig.Scenario.CONCENTRATED
"bottleneck": cfg.scenario = PrototypeConfig.Scenario.BOTTLENECK
_: cfg.scenario = PrototypeConfig.Scenario.PLAY
_scripted = ScriptedInput.new(cfg)
_scripted.fire_enabled = scenario != "idle"
_scripted.fire_delay = float(_args.get("fire-delay", "0.1"))
_round.input = _scripted
_round.round_reset.connect(_on_round_reset)
if _args.get("vsync", "on") == "off":
DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_DISABLED)
Engine.max_fps = 0
if _args.has("screenshot"):
for part in String(_args.get("screenshot-at", "3")).split(","):
_shot_times.append(float(part))
_bench = _args.has("bench")
_warmup = float(_args.get("warmup", "10"))
_duration = float(_args.get("duration", "60"))
if _bench:
_recent_t.resize(RECENT)
_recent_t.fill(-1e9)
_recent_ms.resize(RECENT)
_frame.resize(MAX_FRAMES)
_gpu.resize(MAX_FRAMES)
_cpu_render.resize(MAX_FRAMES)
_tick.resize(int((_duration + 1.0) * cfg.physics_ticks))
_vp_rid = get_viewport().get_viewport_rid()
RenderingServer.viewport_set_measure_render_time(_vp_rid, true)
func _on_round_reset() -> void:
var l := _round.layout
_scripted.route = l.route
match _round.config.scenario:
PrototypeConfig.Scenario.SPREAD:
_scripted.mode = ScriptedInput.Mode.ROUTE
PrototypeConfig.Scenario.CONCENTRATED:
_scripted.mode = ScriptedInput.Mode.HOLD_POINT
_scripted.hold_point = l.concentrated_point
PrototypeConfig.Scenario.BOTTLENECK:
_scripted.mode = ScriptedInput.Mode.HOLD_POINT
_scripted.hold_point = l.bottleneck_point
_:
_scripted.mode = ScriptedInput.Mode.IDLE
_t = 0.0
func _physics_process(_dt: float) -> void:
if _round.state != RoundController.State.PLAYING:
return
if _capture_started and not _done and _tick_n < _tick.size():
_tick[_tick_n] = _round.last_tick_usec
_tick_n += 1
for k in 8:
_phase_sum[k] += _round.phase_usec[k]
_phase_max[k] = maxi(_phase_max[k], _round.phase_usec[k])
func _process(delta: float) -> void:
if _round == null or _round.state == RoundController.State.LOADING:
return
_t += delta
var now := Time.get_ticks_usec()
var frame_us := now - _last_usec if _last_usec != 0 else 0
_last_usec = now
if _args.has("camera-zoom"):
_follow_player(float(_args["camera-zoom"]))
if _shot_index < _shot_times.size() and _t >= _shot_times[_shot_index]:
var path := String(_args["screenshot"])
if _shot_times.size() > 1:
path = "%s_%s.%s" % [path.get_basename(), str(_shot_times[_shot_index]), path.get_extension()]
_shot_index += 1
get_viewport().get_texture().get_image().save_png(path)
print("BenchmarkRunner: screenshot t=%.2f tick=%d state=%s -> %s" % [_t, _round.ticks, RoundController.State.keys()[_round.state], path])
if _bench and not _done:
_measure(frame_us)
if _args.has("quit-after") and _t >= float(_args["quit-after"]) and (not _bench or _done):
get_tree().quit()
func _follow_player(zoom: float) -> void:
var cam := _round.camera
cam.reset_view()
cam.size /= zoom
var target := _round.player.get_global_transform_interpolated().origin + Vector3(0, 1.0, 0)
var b := cam.global_transform.basis
cam.global_position = target + b.z * _round.config.camera_distance
func _measure(frame_us: int) -> void:
var p := _round.projectiles
var ms := frame_us / 1000.0
if _t <= 1.0:
_startup_max_ms = maxf(_startup_max_ms, ms)
if _first_shot_t < 0.0 and p.fired > 0:
_first_shot_t = _t
_first_shot_before_ms = _recent_max(_t - FIRST_USE_WINDOW)
if _first_hit_t < 0.0 and p.hits_enemy > 0:
_first_hit_t = _t
_first_hit_before_ms = _recent_max(_t - FIRST_USE_WINDOW)
if _first_shot_t >= 0.0 and _t - _first_shot_t <= FIRST_USE_WINDOW:
_first_shot_max_ms = maxf(_first_shot_max_ms, ms)
if _first_hit_t >= 0.0 and _t - _first_hit_t <= FIRST_USE_WINDOW:
_first_hit_max_ms = maxf(_first_hit_max_ms, ms)
_recent_t[_recent_i] = _t
_recent_ms[_recent_i] = ms
_recent_i = (_recent_i + 1) % RECENT
if not _capture_started:
if _t >= _warmup:
_capture_started = true
_mem_start = OS.get_static_memory_usage()
_obj_start = int(Performance.get_monitor(Performance.OBJECT_COUNT))
_next_sample = _t
_t = _warmup
return
if _frame_n < MAX_FRAMES and frame_us > 0:
_frame[_frame_n] = frame_us
_gpu[_frame_n] = RenderingServer.viewport_get_measured_render_time_gpu(_vp_rid)
_cpu_render[_frame_n] = RenderingServer.viewport_get_measured_render_time_cpu(_vp_rid)
_frame_n += 1
var dc := RenderingServer.get_rendering_info(RenderingServer.RENDERING_INFO_TOTAL_DRAW_CALLS_IN_FRAME)
_draw_calls_sum += dc
_draw_calls_max = maxi(_draw_calls_max, dc)
_prims_sum += RenderingServer.get_rendering_info(RenderingServer.RENDERING_INFO_TOTAL_PRIMITIVES_IN_FRAME)
if _t >= _next_sample:
_next_sample += 10.0
_timeline.append({
"t": snappedf(_t - _warmup, 0.1),
"static_mem_mb": snappedf(OS.get_static_memory_usage() / 1048576.0, 0.01),
"objects": int(Performance.get_monitor(Performance.OBJECT_COUNT)),
"nodes": int(Performance.get_monitor(Performance.OBJECT_NODE_COUNT)),
"birds": _round.horde.active_count,
"bullets": _round.projectiles.active_count,
"recent_tick_ms_avg": snappedf(_round.stats.tick_summary().x, 0.001),
})
if _t >= _warmup + _duration:
_done = true
_write_report()
func _recent_max(since: float) -> float:
var m := 0.0
for k in RECENT:
if _recent_t[k] >= since:
m = maxf(m, _recent_ms[k])
return m
func _write_report() -> void:
# Read end-of-capture counters before the report allocates its own copies.
var mem_end := OS.get_static_memory_usage()
var obj_end := int(Performance.get_monitor(Performance.OBJECT_COUNT))
var cfg := _round.config
var frames := _frame.slice(0, _frame_n)
var ticks := _tick.slice(0, _tick_n)
var gpu := _gpu.slice(0, _frame_n)
var cpu := _cpu_render.slice(0, _frame_n)
var fs := _stats_int(frames)
var ts := _stats_int(ticks)
var spikes_16 := 0
var spikes_33 := 0
for f in frames:
if f > 16667:
spikes_16 += 1
if f > 33333:
spikes_33 += 1
var phases := {}
for k in 8:
phases[RoundController.PHASES[k]] = {
"mean_ms": snappedf(_phase_sum[k] / maxf(_tick_n, 1) / 1000.0, 0.001),
"max_ms": snappedf(_phase_max[k] / 1000.0, 0.001),
}
var info := Engine.get_version_info()
var vp_size := get_viewport().get_visible_rect().size
var report := {
"label": _args.get("label", cfg.stress_label),
"preset": cfg.stress_label,
"scenario": PrototypeConfig.Scenario.keys()[cfg.scenario],
"layout": PrototypeConfig.Layout.keys()[cfg.layout],
"layout_scale": cfg.layout_scale(),
"labels": {
"stress_invulnerable": cfg.stress_invulnerable,
"stress_recycle": cfg.stress_recycle,
"partial_system_diagnostic": false,
},
"hardware": {
"cpu": OS.get_processor_name(),
"cpu_threads": OS.get_processor_count(),
"gpu": RenderingServer.get_video_adapter_name(),
"gpu_vendor": RenderingServer.get_video_adapter_vendor(),
"graphics_api_version": RenderingServer.get_video_adapter_api_version(),
"os": "%s %s (%s)" % [OS.get_name(), OS.get_distribution_name(), OS.get_version()],
"display_server": DisplayServer.get_name(),
},
"engine": {
"version": "%s (%s)" % [info["string"], info.get("hash", "")],
"renderer": RenderingServer.get_current_rendering_method(),
"debug_build": OS.is_debug_build(),
"binary": OS.get_executable_path().get_file(),
"build_note": "editor binary running the project (no release export templates installed); not a release build",
"msaa_3d": ProjectSettings.get_setting("rendering/anti_aliasing/quality/msaa_3d"),
"physics_interpolation": ProjectSettings.get_setting("physics/common/physics_interpolation"),
},
"display": {
"viewport": "%dx%d" % [vp_size.x, vp_size.y],
"window": "%dx%d" % [DisplayServer.window_get_size().x, DisplayServer.window_get_size().y],
"vsync": ["disabled", "enabled", "adaptive", "mailbox"][DisplayServer.window_get_vsync_mode()],
"refresh_hz": DisplayServer.screen_get_refresh_rate(),
"camera_ortho_size_m": snappedf(_round.camera.size, 0.01),
"visible_birds_note": "camera frames the whole arena; all active birds are on screen",
},
"config": {
"seed": cfg.round_seed,
"enemy_count": cfg.enemy_count,
"enemy_capacity": cfg.enemy_capacity,
"projectile_capacity": cfg.projectile_capacity,
"physics_ticks": cfg.physics_ticks,
"nav_cells": _round.nav.cell_count(),
"nav_cell_size": cfg.nav_cell_size,
"steering_hz": cfg.steering_hz,
"flow_rebuild_hz": cfg.flow_rebuild_hz,
"bird_triangles": _round.catalog.bird_triangles,
},
"warmup_s": _warmup,
"capture_s": _duration,
"frame_ms": fs,
"frames_over_16_67ms": spikes_16,
"frames_over_33_3ms": spikes_33,
"fps_mean": snappedf(1000.0 / maxf(fs["mean"], 0.001), 0.1),
"sim_tick_ms": ts,
"sim_phase_ms": phases,
"gpu_render_ms": _stats_float(gpu),
"cpu_render_ms": _stats_float(cpu),
"draw_calls_mean": snappedf(_draw_calls_sum / maxf(_frame_n, 1), 0.1),
"draw_calls_max": _draw_calls_max,
"primitives_mean": snappedf(_prims_sum / maxf(_frame_n, 1), 1.0),
"nav_rebuild_ms": {
"count": _round.nav.rebuild_count,
"mean": snappedf(_round.nav.total_rebuild_usec / 1000.0 / maxf(_round.nav.rebuild_count, 1), 0.001),
"max_total": snappedf(_round.nav.max_rebuild_usec / 1000.0, 0.001),
"max_slice_per_tick": snappedf(_round.nav.max_slice_usec / 1000.0, 0.001),
"slices_last_rebuild": _round.nav.last_rebuild_slices,
"note": "rebuilds are sliced; max_slice_per_tick is the cost that lands in one tick (includes the synchronous rebuild at reset)",
},
"separation_checks_peak_per_tick": _round.horde.separation_checks_peak,
"pool": {
"bird_spawn_skipped": _round.horde.spawn_skipped,
"bullet_exhausted": _round.projectiles.exhausted,
"bullet_peak_active": _round.projectiles.peak_active,
"birds_recycled": _round.horde.recycled,
"birds_active_end": _round.horde.active_count,
},
"combat": {
"shots": _round.projectiles.fired,
"bird_hits": _round.projectiles.hits_enemy,
"wall_hits": _round.projectiles.hits_world,
"melee_attempts": _round.horde.attacks_attempted,
"melee_blocked_by_cover": _round.horde.attacks_blocked_by_cover,
"stress_absorbed_hits": _round.player.stress_absorbed_hits,
},
"first_use": {
"startup_max_frame_ms_first_1s": snappedf(_startup_max_ms, 0.01),
"window_s": FIRST_USE_WINDOW,
"first_shot_s": snappedf(_first_shot_t, 0.001),
"max_frame_ms_before_first_shot": snappedf(_first_shot_before_ms, 0.01),
"max_frame_ms_after_first_shot": snappedf(_first_shot_max_ms, 0.01),
"first_hit_s": snappedf(_first_hit_t, 0.001),
"max_frame_ms_before_first_hit": snappedf(_first_hit_before_ms, 0.01),
"max_frame_ms_after_first_hit": snappedf(_first_hit_max_ms, 0.01),
},
"memory": {
"static_mb_capture_start": snappedf(_mem_start / 1048576.0, 0.01),
"static_mb_capture_end": snappedf(mem_end / 1048576.0, 0.01),
"objects_capture_start": _obj_start,
"objects_capture_end": obj_end,
},
"timeline": _timeline,
}
var out: String = _args.get("out", "res://benchmarks/results/%s.json" % report["label"])
var path := ProjectSettings.globalize_path(out) if out.begins_with("res://") or out.begins_with("user://") else out
DirAccess.make_dir_recursive_absolute(path.get_base_dir())
var f := FileAccess.open(path, FileAccess.WRITE)
if f:
f.store_string(JSON.stringify(report, " "))
f.close()
print("BENCH %s: frames=%d mean=%.2fms p95=%.2fms p99=%.2fms max=%.2fms sim_p95=%.2fms gpu_p95=%.2fms -> %s" % [
report["label"], fs["count"], fs["mean"], fs["p95"], fs["p99"], fs["max"], ts["p95"], report["gpu_render_ms"]["p95"], path])
static func _stats_int(a: PackedInt32Array) -> Dictionary:
var n := a.size()
if n == 0:
return {"count": 0, "mean": 0.0, "p50": 0.0, "p95": 0.0, "p99": 0.0, "max": 0.0}
var s := a.duplicate()
s.sort()
var total := 0
for v in s:
total += v
return {
"count": n,
"mean": snappedf(total / float(n) / 1000.0, 0.001),
"p50": snappedf(s[int(n * 0.50)] / 1000.0, 0.001),
"p95": snappedf(s[mini(n - 1, int(n * 0.95))] / 1000.0, 0.001),
"p99": snappedf(s[mini(n - 1, int(n * 0.99))] / 1000.0, 0.001),
"max": snappedf(s[n - 1] / 1000.0, 0.001),
}
static func _stats_float(a: PackedFloat32Array) -> Dictionary:
var n := a.size()
if n == 0:
return {"count": 0, "mean": 0.0, "p95": 0.0, "max": 0.0}
var s := a.duplicate()
s.sort()
var total := 0.0
for v in s:
total += v
return {
"count": n,
"mean": snappedf(total / n, 0.001),
"p95": snappedf(s[mini(n - 1, int(n * 0.95))], 0.001),
"max": snappedf(s[n - 1], 0.001),
}

View file

@ -0,0 +1 @@
uid://cjog8j1glr7li

View file

@ -0,0 +1,66 @@
class_name CameraRig
extends Camera3D
## Fixed orthographic isometric camera. Framing is computed from the arena bounds so the whole
## arena (plus a margin for the HUD) is visible at any aspect ratio.
var _bounds_min: Vector3
var _bounds_max: Vector3
var _cfg: PrototypeConfig
func setup(cfg: PrototypeConfig, outer: Rect2, max_height: float) -> void:
_cfg = cfg
_bounds_min = Vector3(outer.position.x, 0.0, outer.position.y)
_bounds_max = Vector3(outer.end.x, max_height, outer.end.y)
projection = Camera3D.PROJECTION_ORTHOGONAL
keep_aspect = Camera3D.KEEP_HEIGHT
physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
if not get_viewport().size_changed.is_connected(reset_view):
get_viewport().size_changed.connect(reset_view)
reset_view()
## Restores the initial framing (used on load, restart, and window resize).
func reset_view() -> void:
var b := Basis.from_euler(Vector3(deg_to_rad(-_cfg.camera_pitch_deg), deg_to_rad(_cfg.camera_yaw_deg), 0.0))
var center := (_bounds_min + _bounds_max) * 0.5
var inv := b.inverse()
var lo := Vector2(INF, INF)
var hi := Vector2(-INF, -INF)
for i in 8:
var corner := Vector3(
_bounds_max.x if i & 1 else _bounds_min.x,
_bounds_max.y if i & 2 else _bounds_min.y,
_bounds_max.z if i & 4 else _bounds_min.z)
var p := inv * (corner - center)
lo = Vector2(minf(lo.x, p.x), minf(lo.y, p.y))
hi = Vector2(maxf(hi.x, p.x), maxf(hi.y, p.y))
var vp := get_viewport().get_visible_rect().size
var aspect := vp.x / maxf(vp.y, 1.0)
size = maxf(hi.y - lo.y, (hi.x - lo.x) / aspect) * _cfg.camera_margin
var mid := (lo + hi) * 0.5
var look := center + b * Vector3(mid.x, mid.y, 0.0)
global_transform = Transform3D(b, look + b.z * _cfg.camera_distance)
near = 0.5
far = _cfg.camera_distance * 2.0 + 50.0
## Camera-relative movement basis flattened onto XZ: forward = screen up, right = screen right.
func flat_forward() -> Vector3:
var f := -global_transform.basis.z
return Vector3(f.x, 0.0, f.z).normalized()
func flat_right() -> Vector3:
var r := global_transform.basis.x
return Vector3(r.x, 0.0, r.z).normalized()
## Intersects the mouse ray with the horizontal plane y = height.
func screen_to_plane(screen_pos: Vector2, height: float) -> Vector3:
var o := project_ray_origin(screen_pos)
var d := project_ray_normal(screen_pos)
if absf(d.y) < 1e-5:
return Vector3(o.x, height, o.z)
var t := (height - o.y) / d.y
return o + d * t

View file

@ -0,0 +1 @@
uid://bi1oqws7aine3

View file

@ -0,0 +1,57 @@
class_name ChaseBehavior
extends RefCounted
## Shared behavior policy: computes each bird's desired (unit) direction from navigation data.
## It knows nothing about integration, damage, or rendering, so another policy (other goals,
## base attacks, ...) can replace it without touching HordeSystem. Called once per steering
## cohort with the dense indices to update; writes desired directions into out_x / out_z and a
## behavior state per bird (STATE_CHASE or STATE_HOLD).
const STATE_CHASE := 0
## No route exists (unreachable cell): hold position instead of moving through walls.
const STATE_HOLD := 1
var _dir := PackedFloat32Array([0.0, 0.0])
func compute(horde: HordeSystem, first: int, stride: int, target: Vector2,
out_x: PackedFloat32Array, out_z: PackedFloat32Array, out_state: PackedByteArray) -> void:
var nav := horde.nav
var px := horde.pos_x
var pz := horde.pos_z
var count := horde.active_count
var direct2 := horde.config.direct_chase_distance * horde.config.direct_chase_distance
var dir := _dir
var obs := nav.obs_start
var ocols := nav.obs_cols
var orows := nav.obs_rows
var oox := nav.obs_origin_x
var ooz := nav.obs_origin_z
var oinv := 1.0 / ArenaNavigation.OBS_CELL
var i := first
while i < count:
var x := px[i]
var z := pz[i]
var tx := target.x - x
var tz := target.y - z
var d2 := tx * tx + tz * tz
var clear := false
if d2 < direct2:
# segment_blocked() checks the midpoint's obstacle bucket; an empty bucket is clear.
var ob := clampi(int((z + tz * 0.5 - ooz) * oinv), 0, orows - 1) * ocols \
+ clampi(int((x + tx * 0.5 - oox) * oinv), 0, ocols - 1)
clear = obs[ob] == obs[ob + 1] or not nav.segment_blocked(x, z, target.x, target.y)
if clear:
# Close with clear line of sight: steer straight at the player.
var inv := 1.0 / sqrt(maxf(d2, 1e-6))
out_x[i] = tx * inv
out_z[i] = tz * inv
out_state[i] = STATE_CHASE
elif nav.flow_direction(x, z, dir):
out_x[i] = dir[0]
out_z[i] = dir[1]
out_state[i] = STATE_CHASE
else:
out_x[i] = 0.0
out_z[i] = 0.0
out_state[i] = STATE_HOLD
i += stride

View file

@ -0,0 +1 @@
uid://ew46lyuao6s7

View file

@ -0,0 +1,114 @@
class_name HordeRenderer
extends MultiMeshInstance3D
## Shared-mesh instanced rendering for pooled entities (birds, and projectiles via the same
## class). Active entities occupy the dense prefix [0, count); visible_instance_count is set to
## count, so released entities stop rendering immediately (no parking at a remote coordinate or
## zero scale). The buffer is written each physics tick and handed to the RenderingServer with
## physics interpolation enabled; the server interpolates between ticks. Slots that receive a
## different entity (spawn, swap-removal) have their interpolation reset so nothing streaks.
##
## Instance layout per slot: 12 floats (3x4 transform rows) + 4 floats custom data.
const STRIDE := 16
var capacity: int = 0
var buffer := PackedFloat32Array()
var _reset_slots := PackedInt32Array()
var _reset_count: int = 0
var _y: float = 0.0
func setup(mesh: Mesh, material: Material, p_capacity: int, y: float, bounds: AABB) -> void:
capacity = p_capacity
_y = y
var mm := MultiMesh.new()
mm.transform_format = MultiMesh.TRANSFORM_3D
mm.use_custom_data = true
mm.mesh = mesh
mm.instance_count = capacity
mm.visible_instance_count = 0
# Fixed AABB covering the arena: skips per-update AABB recomputation; the single batch is
# culled as a whole (the fully visible arena needs no spatial split).
mm.custom_aabb = bounds
multimesh = mm
RenderingServer.multimesh_set_physics_interpolated(mm.get_rid(), true)
material_override = material
cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
buffer.resize(capacity * STRIDE)
buffer.fill(0.0)
_reset_slots.resize(capacity)
_reset_count = 0
## Writes a full slot for a newly placed entity (heading hx, hz is the unit forward on XZ).
func write_new(slot: int, x: float, z: float, hx: float, hz: float, custom: float) -> void:
var o := slot * STRIDE
var b := buffer
b[o] = -hz
b[o + 1] = 0.0
b[o + 2] = -hx
b[o + 3] = x
b[o + 4] = 0.0
b[o + 5] = 1.0
b[o + 6] = 0.0
b[o + 7] = _y
b[o + 8] = hx
b[o + 9] = 0.0
b[o + 10] = -hz
b[o + 11] = z
b[o + 12] = custom
b[o + 13] = 0.0
b[o + 14] = 0.0
b[o + 15] = 0.0
mark_reset(slot)
## Copies slot `from` into slot `to` (swap-removal) and resets its interpolation.
func move_slot(from: int, to: int) -> void:
var b := buffer
var a := from * STRIDE
var c := to * STRIDE
for k in STRIDE:
b[c + k] = b[a + k]
mark_reset(to)
func mark_reset(slot: int) -> void:
if _reset_count < _reset_slots.size():
_reset_slots[_reset_count] = slot
_reset_count += 1
## Writes the per-tick pose (position + yaw) of the dense prefix from packed state arrays.
## Rotation maps local -Z (model forward) onto the heading: rows [c 0 s], [0 1 0], [-s 0 c]
## with c = -hz, s = -hx.
func write_poses(count: int, px: PackedFloat32Array, pz: PackedFloat32Array,
hx: PackedFloat32Array, hz: PackedFloat32Array) -> void:
var b := buffer
var o := 0
for i in count:
var c := -hz[i]
var s := -hx[i]
b[o] = c
b[o + 2] = s
b[o + 3] = px[i]
b[o + 8] = -s
b[o + 10] = c
b[o + 11] = pz[i]
o += STRIDE
func commit(count: int) -> void:
var mm := multimesh
mm.visible_instance_count = count
mm.buffer = buffer
for k in _reset_count:
mm.reset_instance_physics_interpolation(_reset_slots[k])
_reset_count = 0
## Restart: drop everything and make the next commit snap instead of interpolate.
func clear() -> void:
_reset_count = 0
multimesh.visible_instance_count = 0
multimesh.reset_instances_physics_interpolation()

View file

@ -0,0 +1 @@
uid://c56hg0b1g1gqi

View file

@ -0,0 +1,652 @@
class_name HordeSystem
extends Node3D
## Centralized horde simulation over preallocated, dense, typed storage. No per-bird nodes,
## bodies, agents, timers, or scripts.
##
## Storage: per-bird state lives in packed arrays indexed by dense slot [0, active_count).
## Each bird also has a stable id (free-list) with a generation counter; handles that escape
## this system encode (generation, id) so a removed or reused slot can never be damaged
## through a stale handle. Removal swaps the last active bird into the freed slot and updates
## every mapping (state arrays, id <-> dense, render slot). Kills are deferred to the end of the
## tick (commit_removals) so dense indices stay valid while projectiles resolve.
##
## Tick order (driven by RoundController): step_motion -> rebuild_grid -> evaluate_attacks ->
## [projectiles] -> step_steering -> commit_removals -> commit_render.
signal enemy_killed(remaining: int)
const ID_BITS := 16
const ID_MASK := (1 << ID_BITS) - 1
## Separation scan order: own cell first, then the 8 neighbors.
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]
var config: PrototypeConfig
var nav: ArenaNavigation
var grid := SpatialGrid.new()
var behavior: ChaseBehavior = ChaseBehavior.new()
var renderer: HordeRenderer
var capacity: int = 0
var active_count: int = 0
# Dense per-bird state.
var pos_x := PackedFloat32Array()
var pos_z := PackedFloat32Array()
var prev_x := PackedFloat32Array()
var prev_z := PackedFloat32Array()
var vel_x := PackedFloat32Array()
var vel_z := PackedFloat32Array()
var steer_x := PackedFloat32Array()
var steer_z := PackedFloat32Array()
var desire_x := PackedFloat32Array()
var desire_z := PackedFloat32Array()
var head_x := PackedFloat32Array()
var head_z := PackedFloat32Array()
var attack_cd := PackedFloat32Array()
var flap_phase := PackedFloat32Array()
var health := PackedInt32Array()
var state := PackedByteArray()
var alive := PackedByteArray()
var dense_id := PackedInt32Array()
# Identity, indexed by id.
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
# Diagnostics (all reset on restart).
var spawn_skipped: int = 0
var kills: int = 0
var attacks_attempted: int = 0
var attacks_blocked_by_cover: int = 0
var separation_checks: int = 0
var separation_checks_peak: int = 0
var recycled: int = 0
## Fraction along the last sweep_hit() segment where the nearest hit occurred.
var hit_t: float = 0.0
var _tick: int = 0
var _cohorts: int = 3
var _tmp := PackedFloat32Array([0.0, 0.0])
var _rng := RandomNumberGenerator.new()
var _recycle_points := PackedVector2Array()
var _recycle_cursor: int = 0
var _player := Vector2.ZERO
func setup(cfg: PrototypeConfig, p_nav: ArenaNavigation, mesh: Mesh, material: Material, area: Rect2) -> void:
config = cfg
nav = p_nav
capacity = cfg.enemy_capacity
_cohorts = cfg.steering_cohorts()
for a: PackedFloat32Array in [pos_x, pos_z, prev_x, prev_z, vel_x, vel_z, steer_x, steer_z,
desire_x, desire_z, head_x, head_z, attack_cd, flap_phase]:
a.resize(capacity)
a.fill(0.0)
for a: PackedInt32Array in [health, dense_id, id_dense, id_generation, _free_ids, _pending]:
a.resize(capacity)
a.fill(0)
for a: PackedByteArray in [state, alive]:
a.resize(capacity)
a.fill(0)
id_dense.fill(-1)
grid.setup(area, cfg.spatial_cell_size, capacity)
renderer = HordeRenderer.new()
renderer.name = "HordeRenderer"
add_child(renderer)
var aabb := AABB(Vector3(area.position.x, 0.0, area.position.y), Vector3(area.size.x, 3.0, area.size.y))
renderer.setup(mesh, material, capacity, cfg.combat_height, aabb)
_reset_pool()
## Releases every bird and clears all counters, ids, and render state.
func _reset_pool() -> 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
spawn_skipped = 0
kills = 0
attacks_attempted = 0
attacks_blocked_by_cover = 0
separation_checks = 0
separation_checks_peak = 0
recycled = 0
_tick = 0
if renderer:
renderer.clear()
## Restart: release all, reseed, and spawn the starting population from the preallocated pool.
func reset_round(spawn_points: PackedVector2Array, recycle_points: PackedVector2Array, seed_value: int, player: Vector2) -> void:
_reset_pool()
_rng.seed = seed_value
_recycle_points = recycle_points
_recycle_cursor = 0
_player = player
for p in spawn_points:
spawn(p.x, p.y)
commit_render()
## Acquires a slot and initializes every state field. Returns a handle, or -1 if the pool is
## exhausted (the spawn is skipped and counted; capacity never grows mid-round).
func spawn(x: float, z: float) -> int:
if active_count >= capacity or _free_top <= 0:
spawn_skipped += 1
return -1
_free_top -= 1
var id := _free_ids[_free_top]
var d := active_count
active_count += 1
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
steer_x[d] = 0.0
steer_z[d] = 0.0
desire_x[d] = 0.0
desire_z[d] = 0.0
var to_player := Vector2(_player.x - x, _player.y - z)
var h := to_player.normalized() if to_player.length_squared() > 1e-6 else Vector2(0.0, -1.0)
head_x[d] = h.x
head_z[d] = h.y
attack_cd[d] = 0.0
flap_phase[d] = _rng.randf()
health[d] = config.enemy_health
state[d] = ChaseBehavior.STATE_CHASE
alive[d] = 1
dense_id[d] = id
id_dense[id] = d
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:
var id := handle & ID_MASK
if id < 0 or id >= capacity:
return -1
if 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
## Applies one projectile hit. Returns false for dead/pending slots (no double kills).
func apply_hit(d: int) -> bool:
if not is_alive_slot(d):
return false
health[d] -= 1
if health[d] <= 0:
alive[d] = 0
_pending[_pending_count] = dense_id[d]
_pending_count += 1
kills += 1
return true
func apply_hit_handle(handle: int) -> bool:
return apply_hit(resolve_handle(handle))
func alive_count() -> int:
return active_count - _pending_count
## Integrates motion for every active bird, then resolves player contact and world collision.
## Returns the correction to apply to the player for birds pinned between player and walls.
func step_motion(dt: float, player_pos: Vector2, player_radius: float) -> Vector2:
_player = player_pos
var cfg := config
var ax := cfg.enemy_acceleration * dt
var r := cfg.enemy_radius
var contact := r + player_radius
var contact2 := contact * contact
var max_corr := cfg.max_correction_per_tick
var ppx := player_pos.x
var ppz := player_pos.y
var corr_x := 0.0
var corr_z := 0.0
var px := pos_x
var pz := pos_z
var qx := prev_x
var qz := prev_z
var vx_a := vel_x
var vz_a := vel_z
var sx_a := steer_x
var sz_a := steer_z
var hx_a := head_x
var hz_a := head_z
var cd := attack_cd
var tmp := _tmp
var nv := nav
# Inlined "nothing to collide with" test: empty obstacle bucket and well inside the bounds
# means resolve_circle would leave the position unchanged, so the call is skipped.
var obs := nv.obs_start
var ocols := nv.obs_cols
var orows := nv.obs_rows
var oox := nv.obs_origin_x
var ooz := nv.obs_origin_z
var oinv := 1.0 / ArenaNavigation.OBS_CELL
var bx0 := nv.bounds.position.x + r
var bx1 := nv.bounds.end.x - r
var bz0 := nv.bounds.position.y + r
var bz1 := nv.bounds.end.y - r
for i in active_count:
var x := px[i]
var z := pz[i]
qx[i] = x
qz[i] = z
cd[i] = maxf(cd[i] - dt, 0.0)
var vx := vx_a[i]
var vz := vz_a[i]
var dvx := sx_a[i] - vx
var dvz := sz_a[i] - vz
var dl2 := dvx * dvx + dvz * dvz
if dl2 > ax * ax:
var k := ax / sqrt(dl2)
dvx *= k
dvz *= k
vx += dvx
vz += dvz
x += vx * dt
z += vz * dt
# Player contact: birds yield (bounded push), and stop pressing inward.
var ox := x - ppx
var oz := z - ppz
var od2 := ox * ox + oz * oz
if od2 < contact2:
var od := sqrt(maxf(od2, 1e-8))
var nx := ox / od if od2 > 1e-8 else 1.0
var nz := oz / od if od2 > 1e-8 else 0.0
var push := minf(contact - od, max_corr)
x += nx * push
z += nz * push
var vn := vx * nx + vz * nz
if vn < 0.0:
vx -= vn * nx
vz -= vn * nz
# World collision on the corrected position; slide along the push normal.
var ob := clampi(int((z - ooz) * oinv), 0, orows - 1) * ocols + clampi(int((x - oox) * oinv), 0, ocols - 1)
if obs[ob] != obs[ob + 1] or x < bx0 or x > bx1 or z < bz0 or z > bz1:
nv.resolve_circle(x, z, r, tmp)
var wx := tmp[0] - x
var wz := tmp[1] - z
var w2 := wx * wx + wz * wz
if w2 > 1e-10:
var wl := sqrt(w2)
var wn := (vx * wx + vz * wz) / wl
if wn < 0.0:
vx -= wn * wx / wl
vz -= wn * wz / wl
x = tmp[0]
z = tmp[1]
# Still overlapping after the world pushed back (pinned): the player must yield.
ox = x - ppx
oz = z - ppz
od2 = ox * ox + oz * oz
if od2 < contact2 - 1e-4 and od2 > 1e-8:
var od := sqrt(od2)
corr_x -= ox / od * (contact - od)
corr_z -= oz / od * (contact - od)
px[i] = x
pz[i] = z
vx_a[i] = vx
vz_a[i] = vz
var sp2 := vx * vx + vz * vz
if sp2 > 0.04:
var inv := 1.0 / sqrt(sp2)
var hx := hx_a[i] + (vx * inv - hx_a[i]) * 0.25
var hz := hz_a[i] + (vz * inv - hz_a[i]) * 0.25
var hl := sqrt(hx * hx + hz * hz)
if hl > 1e-4:
hx_a[i] = hx / hl
hz_a[i] = hz / hl
return Vector2(corr_x, corr_z).limit_length(max_corr)
func rebuild_grid() -> void:
grid.rebuild(pos_x, pos_z, active_count)
## Melee: birds within reach, off cooldown, and with an unobstructed line to the player attack.
## The player's invulnerability (authoritative) decides whether a hit is accepted.
func evaluate_attacks(player: PlayerController) -> void:
var cfg := config
var reach := cfg.enemy_radius + cfg.player_radius + cfg.enemy_attack_reach
var reach2 := reach * reach
var ppx := _player.x
var ppz := _player.y
var g := grid
var cx0 := g.cell_x(ppx - reach)
var cx1 := g.cell_x(ppx + reach)
var cz0 := g.cell_z(ppz - reach)
var cz1 := g.cell_z(ppz + 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 alive[i] == 0 or attack_cd[i] > 0.0:
continue
var dx := pos_x[i] - ppx
var dz := pos_z[i] - ppz
if dx * dx + dz * dz > reach2:
continue
if nav.segment_blocked(pos_x[i], pos_z[i], ppx, ppz):
attacks_blocked_by_cover += 1
continue
attack_cd[i] = cfg.enemy_attack_cooldown
attacks_attempted += 1
player.try_damage()
## Swept projectile test against bird hit proxies (vertical cylinders, radius enemy_hit_radius,
## centered at combat height; projectiles fly horizontally at that height, so the test is a 2D
## circle test). Uses each bird's motion across the tick (prev -> current) relative to the
## projectile's motion, so a bird moving into or out of the path is handled exactly.
## Candidates come from every grid cell overlapped by the segment's bounds expanded by the hit
## radius plus the largest per-tick bird displacement (conservative broad phase).
## 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 rr := config.enemy_hit_radius
var margin := rr + config.enemy_speed / float(config.physics_ticks) + 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 alive[i] == 0:
continue
var ex0 := prev_x[i] if use_motion else pos_x[i]
var ez0 := prev_z[i] if use_motion else pos_z[i]
# Relative motion: bullet relative to bird, starting at s, moving by m.
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 # already inside the proxy at the start of the tick
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
## Computes steering for one cohort (staggered: each bird re-steers every _cohorts ticks):
## desired direction from the behavior policy, plus bounded separation from nearby birds and a
## soft overlap correction that is re-checked against world footprints.
func step_steering() -> void:
var cohort := _tick % _cohorts
_tick += 1
behavior.compute(self, cohort, _cohorts, _player, desire_x, desire_z, state)
var cfg := config
var speed := cfg.enemy_speed
var sep_r := cfg.separation_radius
var sep_r2 := sep_r * sep_r
var two_r := cfg.enemy_radius * 2.0
var max_cand := cfg.separation_max_candidates
var max_nb := cfg.separation_max_neighbors
var max_corr := cfg.max_correction_per_tick
var w_sep := cfg.separation_weight
var g := grid
var gw := g.width
var gh := g.height
var cs := g.cell_start
var items := g.items
var px := pos_x
var pz := pos_z
var tmp := _tmp
var checks := 0
var i := cohort
while i < active_count:
if alive[i] == 0:
i += _cohorts
continue
var x := px[i]
var z := pz[i]
var gx := g.cell_x(x)
var gz := g.cell_z(z)
var sepx := 0.0
var sepz := 0.0
var ovx := 0.0
var ovz := 0.0
var inspected := 0
var selected := 0
# Own cell first, then the 8 neighbors; each bucket is scanned from a rotating start
# so crowded cells do not always favor the same neighbors.
for n in 9:
if inspected >= max_cand or selected >= max_nb:
break
var ncx := gx + NB_DX[n]
var ncz := gz + NB_DZ[n]
if ncx < 0 or ncz < 0 or ncx >= gw or ncz >= gh:
continue
var c := ncz * gw + ncx
var s0 := cs[c]
var cnt := cs[c + 1] - s0
if cnt == 0:
continue
var idx := s0 + (i + _tick) % cnt
var s_end := s0 + cnt
for j in cnt:
if inspected >= max_cand or selected >= max_nb:
break
var o := items[idx]
idx += 1
if idx == s_end:
idx = s0
inspected += 1
if o == i:
continue
var dx := x - px[o]
var dz := z - pz[o]
var d2 := dx * dx + dz * dz
if d2 >= sep_r2:
continue
selected += 1
var d := sqrt(d2)
if d < 1e-4:
# Coincident: deterministic split by slot order.
dx = 1.0 if i > o else -1.0
dz = 0.0
d = 1.0
var wgt := (sep_r - d) / sep_r
sepx += dx / d * wgt
sepz += dz / d * wgt
if d < two_r:
var pen := (two_r - d) * 0.5
ovx += dx / d * pen
ovz += dz / d * pen
checks += inspected
# Soft overlap correction (bounded), re-resolved against the world.
var ol2 := ovx * ovx + ovz * ovz
if ol2 > 1e-10:
if ol2 > max_corr * max_corr:
var k := max_corr / sqrt(ol2)
ovx *= k
ovz *= k
nav.resolve_circle(x + ovx, z + ovz, cfg.enemy_radius, tmp)
px[i] = tmp[0]
pz[i] = tmp[1]
var tx := desire_x[i] * speed + sepx * w_sep * speed
var tz := desire_z[i] * speed + sepz * w_sep * speed
var tl2 := tx * tx + tz * tz
if tl2 > speed * speed:
var k2 := speed / sqrt(tl2)
tx *= k2
tz *= k2
steer_x[i] = tx
steer_z[i] = tz
i += _cohorts
separation_checks = checks
separation_checks_peak = maxi(separation_checks_peak, checks)
## Removes this tick's kills: swap the last active bird into each freed slot and update every
## mapping. In labeled stress-recycle mode, each kill is replaced by a fresh spawn.
func commit_removals() -> void:
var n := _pending_count
for k in n:
var id := _pending[k]
var d := id_dense[id]
if d >= 0:
_release_slot(d)
_pending_count = 0
if n > 0:
enemy_killed.emit(active_count)
if config.stress_recycle:
for k in n:
_recycle_one()
func _release_slot(d: int) -> void:
var id := dense_id[d]
var last := active_count - 1
if d != last:
pos_x[d] = pos_x[last]
pos_z[d] = pos_z[last]
prev_x[d] = prev_x[last]
prev_z[d] = prev_z[last]
vel_x[d] = vel_x[last]
vel_z[d] = vel_z[last]
steer_x[d] = steer_x[last]
steer_z[d] = steer_z[last]
desire_x[d] = desire_x[last]
desire_z[d] = desire_z[last]
head_x[d] = head_x[last]
head_z[d] = head_z[last]
attack_cd[d] = attack_cd[last]
flap_phase[d] = flap_phase[last]
health[d] = health[last]
state[d] = state[last]
alive[d] = alive[last]
var moved := dense_id[last]
dense_id[d] = moved
id_dense[moved] = d
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
func _recycle_one() -> void:
var n := _recycle_points.size()
if n == 0:
return
var min_d2 := config.enemy_min_spawn_distance * config.layout_scale()
min_d2 *= min_d2
for attempt in 16:
var p := _recycle_points[_recycle_cursor]
_recycle_cursor = (_recycle_cursor + 1) % n
if p.distance_squared_to(_player) >= min_d2 or attempt == 15:
if spawn(p.x, p.y) >= 0:
recycled += 1
return
## Chooses spawn points on free cells reachable from the current flow-field target (the
## player's start), at least min_distance away from it, seeded and spaced. If the requested
## count does not fit at the preferred spacing, spacing relaxes (documented soft overlap for
## compact congestion tests); every returned point is still on a reachable free cell.
static func plan_spawn_points(p_nav: ArenaNavigation, origin: Vector2, count: int,
min_distance: float, spacing: float, rng: RandomNumberGenerator) -> PackedVector2Array:
var candidates := PackedInt32Array()
var min_d2 := min_distance * min_distance
for c in p_nav.cell_count():
if p_nav.is_free(c) and p_nav.is_reachable(c) and p_nav.cell_center(c).distance_squared_to(origin) >= min_d2:
candidates.append(c)
for k in range(candidates.size() - 1, 0, -1):
var j := rng.randi_range(0, k)
var t := candidates[k]
candidates[k] = candidates[j]
candidates[j] = t
var out := PackedVector2Array()
if candidates.is_empty():
return out
var taken := PackedByteArray()
taken.resize(p_nav.cell_count())
var radius_cells := ceili(spacing / p_nav.cell_size)
while out.size() < count and radius_cells >= 0:
taken.fill(0)
for p in out:
taken[p_nav.cell_of(p.x, p.y)] = 1
for c in candidates:
if out.size() >= count:
break
if _near_taken(p_nav, taken, c, radius_cells):
continue
out.append(p_nav.cell_center(c))
taken[c] = 1
radius_cells -= 1
var k := 0
while out.size() < count: # more birds than free cells: jitter inside reused cells
var base := p_nav.cell_center(candidates[k % candidates.size()])
var j := p_nav.cell_size * 0.3
out.append(base + Vector2(rng.randf_range(-j, j), rng.randf_range(-j, j)))
k += 1
return out
static func _near_taken(p_nav: ArenaNavigation, taken: PackedByteArray, c: int, radius: int) -> bool:
if radius <= 0:
return taken[c] == 1
@warning_ignore("integer_division")
var cz := c / p_nav.width
var cx := c - cz * p_nav.width
for dz in range(-radius, radius + 1):
for dx in range(-radius, radius + 1):
if dx * dx + dz * dz > radius * radius:
continue
var x := cx + dx
var z := cz + dz
if x < 0 or z < 0 or x >= p_nav.width or z >= p_nav.height:
continue
if taken[z * p_nav.width + x] == 1:
return true
return false
func commit_render() -> void:
renderer.write_poses(active_count, pos_x, pos_z, head_x, head_z)
renderer.commit(active_count)

View file

@ -0,0 +1 @@
uid://cxyeqs6d6ukmb

View file

@ -0,0 +1,78 @@
class_name PerfStats
extends RefCounted
## Lightweight timing collection: fixed-size rings of recent frame / simulation-tick times
## (always on, a few writes per frame) and a sorted-scratch percentile query used by the
## throttled overlay. No allocation after construction.
const WINDOW := 256
var frame_usec := PackedInt32Array()
var tick_usec := PackedInt32Array()
var nav_usec_last: int = 0
var nav_usec_max: int = 0
var nav_rebuilds: int = 0
var _fi: int = 0
var _fn: int = 0
var _ti: int = 0
var _tn: int = 0
var _scratch := PackedInt32Array()
func _init() -> void:
frame_usec.resize(WINDOW)
tick_usec.resize(WINDOW)
_scratch.resize(WINDOW)
reset()
func reset() -> void:
frame_usec.fill(0)
tick_usec.fill(0)
_fi = 0
_fn = 0
_ti = 0
_tn = 0
nav_usec_last = 0
nav_usec_max = 0
nav_rebuilds = 0
func record_frame(usec: int) -> void:
frame_usec[_fi] = usec
_fi = (_fi + 1) % WINDOW
_fn = mini(_fn + 1, WINDOW)
func record_tick(usec: int) -> void:
tick_usec[_ti] = usec
_ti = (_ti + 1) % WINDOW
_tn = mini(_tn + 1, WINDOW)
func record_nav(usec: int) -> void:
nav_usec_last = usec
nav_usec_max = maxi(nav_usec_max, usec)
nav_rebuilds += 1
## Returns [mean, p95, max] in milliseconds over the recent frame window.
func frame_summary() -> Vector3:
return _summary(frame_usec, _fn)
func tick_summary() -> Vector3:
return _summary(tick_usec, _tn)
func _summary(src: PackedInt32Array, n: int) -> Vector3:
if n == 0:
return Vector3.ZERO
var total := 0
for i in n:
_scratch[i] = src[i]
total += src[i]
for i in range(n, WINDOW):
_scratch[i] = 0x7fffffff
_scratch.sort()
var p95 := _scratch[mini(n - 1, int(ceil(n * 0.95)) - 1)]
return Vector3(total / float(n), p95, _scratch[n - 1]) / 1000.0

View file

@ -0,0 +1 @@
uid://dk5trcwtnwq0m

View file

@ -0,0 +1,195 @@
class_name PlayerController
extends CharacterBody3D
## Camera-relative movement against world collision, aim facing, mannequin animation, and the
## authoritative health / invulnerability state. Stepped by RoundController each physics tick.
const PLAYER_LAYER := 2
## KayKit glTF characters face +Z; Godot forward is -Z.
const MODEL_YAW := PI
const ARM_BONES := ["upperarm.r", "lowerarm.r", "wrist.r", "hand.r"]
signal damaged(health: int)
@onready var visual: Node3D = $Visual
@onready var weapon: WeaponController = $Visual/Weapon
@onready var aim_marker: MeshInstance3D = $AimMarker
var health: int = 3
var invulnerable_left: float = 0.0
var accepted_hits: int = 0
var rejected_hits: int = 0
## Hits absorbed by the labeled stress-mode invulnerability (never in the normal game).
var stress_absorbed_hits: int = 0
var aim := Vector2(0.0, -1.0)
var alive := true
var _cfg: PrototypeConfig
var _start := Vector3.ZERO
var _initial_aim := Vector2(0.0, -1.0)
var _mannequin: Node3D
var _tree: AnimationTree
var _flash_mat: ShaderMaterial
var _input: PlayerInput
func setup(cfg: PrototypeConfig, catalog: AssetCatalog, start: Vector2, initial_aim: Vector2) -> void:
_cfg = cfg
_start = Vector3(start.x, 0.0, start.y)
_initial_aim = initial_aim.normalized()
motion_mode = CharacterBody3D.MOTION_MODE_FLOATING
collision_layer = PLAYER_LAYER
collision_mask = Arena.WORLD_LAYER
var shape := CapsuleShape3D.new()
shape.radius = cfg.player_radius
shape.height = cfg.player_height
($CollisionShape3D as CollisionShape3D).shape = shape
($CollisionShape3D as CollisionShape3D).position = Vector3(0.0, cfg.player_height * 0.5, 0.0)
_mannequin = catalog.mannequin_scene.instantiate() as Node3D
_mannequin.name = "Mannequin"
_mannequin.rotation.y = MODEL_YAW
visual.add_child(_mannequin)
_flash_mat = ShaderMaterial.new()
_flash_mat.shader = load("res://prototype/resources/hit_flash.gdshader") as Shader
for mi in _mannequin.find_children("*", "MeshInstance3D", true, false):
(mi as MeshInstance3D).material_overlay = _flash_mat
_build_animation_tree(catalog)
aim_marker.top_level = true
aim_marker.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
func _build_animation_tree(catalog: AssetCatalog) -> void:
var root := AnimationNodeBlendTree.new()
var loco := AnimationNodeBlendSpace2D.new()
loco.add_blend_point(_clip("idle"), Vector2.ZERO, -1, &"idle")
loco.add_blend_point(_clip("run"), Vector2(0, 1), -1, &"run")
loco.add_blend_point(_clip("back"), Vector2(0, -1), -1, &"back")
loco.add_blend_point(_clip("strafe_left"), Vector2(-1, 0), -1, &"strafe_left")
loco.add_blend_point(_clip("strafe_right"), Vector2(1, 0), -1, &"strafe_right")
root.add_node(&"loco", loco)
root.add_node(&"aim", _clip("aim"))
var arm := AnimationNodeBlend2.new()
arm.filter_enabled = true
for bone: String in ARM_BONES:
arm.set_filter_path(NodePath("Rig_Medium/Skeleton3D:" + bone), true)
root.add_node(&"arm", arm)
root.connect_node(&"arm", 0, &"loco")
root.connect_node(&"arm", 1, &"aim")
root.add_node(&"death", _clip("death"))
root.add_node(&"win", _clip("win"))
var end := AnimationNodeTransition.new()
end.input_count = 3
end.set_input_name(0, "play")
end.set_input_name(1, "dead")
end.set_input_name(2, "win")
end.xfade_time = 0.15
for i in 3:
end.set_input_reset(i, true)
root.add_node(&"end", end)
root.connect_node(&"end", 0, &"arm")
root.connect_node(&"end", 1, &"death")
root.connect_node(&"end", 2, &"win")
root.connect_node(&"output", 0, &"end")
_tree = AnimationTree.new()
_tree.name = "AnimationTree"
_mannequin.add_child(_tree) # root_node ".." -> the mannequin, matching "Rig_Medium/Skeleton3D:<bone>" tracks
_tree.add_animation_library(&"", catalog.animation_library)
_tree.tree_root = root
_tree.set("parameters/arm/blend_amount", 1.0)
_tree.active = true
func _clip(role: String) -> AnimationNodeAnimation:
var n := AnimationNodeAnimation.new()
n.animation = StringName(role)
return n
## Restores position, health, facing, animation, and interpolation state.
func reset_state() -> void:
global_position = _start
velocity = Vector3.ZERO
health = _cfg.player_max_health
invulnerable_left = 0.0
accepted_hits = 0
rejected_hits = 0
stress_absorbed_hits = 0
alive = true
aim = _initial_aim
_apply_facing()
_tree.set("parameters/end/transition_request", "play")
_tree.set("parameters/loco/blend_position", Vector2.ZERO)
_flash_mat.set_shader_parameter("flash", 0.0)
reset_physics_interpolation()
visual.reset_physics_interpolation()
func physics_step(dt: float, input: PlayerInput) -> void:
_input = input
invulnerable_left = maxf(invulnerable_left - dt, 0.0)
var target := Vector3(input.move.x, 0.0, input.move.y) * _cfg.player_speed
velocity = velocity.move_toward(target, _cfg.player_acceleration * dt)
move_and_slide()
global_position.y = 0.0
aim = input.aim
_apply_facing()
var right := Vector2(-aim.y, aim.x)
var v := Vector2(velocity.x, velocity.z) / _cfg.player_speed
_tree.set("parameters/loco/blend_position", Vector2(v.dot(right), v.dot(aim)))
## Pushes the player out of birds that could not yield (pinned against walls). Uses a
## collision-checked move so the correction can never push the player through geometry.
func apply_crowd_correction(correction: Vector2) -> void:
if correction.length_squared() > 1e-8:
move_and_collide(Vector3(correction.x, 0.0, correction.y))
global_position.y = 0.0
## Authoritative damage entry point. Returns true only for accepted hits; any hit during the
## invulnerability window (including several on the same tick) is rejected.
func try_damage() -> bool:
if not alive:
return false
if invulnerable_left > 0.0:
rejected_hits += 1
return false
invulnerable_left = _cfg.invulnerability_time
if _cfg.stress_invulnerable:
stress_absorbed_hits += 1
return true
health -= 1
accepted_hits += 1
damaged.emit(health)
if health <= 0:
alive = false
return true
func play_end(won: bool) -> void:
_tree.set("parameters/end/transition_request", "win" if won else "dead")
func combat_origin() -> Vector3:
return Vector3(global_position.x, _cfg.combat_height, global_position.z)
func _apply_facing() -> void:
visual.rotation.y = atan2(-aim.x, -aim.y)
func _process(_delta: float) -> void:
if _cfg == null:
return
var f := 0.0
if invulnerable_left > 0.0:
f = 0.65 if fmod(invulnerable_left, 0.2) > 0.1 else 0.15
_flash_mat.set_shader_parameter("flash", f)
if _input != null:
if _input.active_device == PlayerInput.Device.MOUSE:
aim_marker.global_position = Vector3(_input.aim_point.x, _cfg.combat_height, _input.aim_point.z)
else:
var gp := get_global_transform_interpolated().origin
aim_marker.global_position = Vector3(gp.x + aim.x * 3.0, _cfg.combat_height, gp.z + aim.y * 3.0)
aim_marker.visible = alive

View file

@ -0,0 +1 @@
uid://013do1hs1yc4

View file

@ -0,0 +1,90 @@
class_name PlayerInput
extends RefCounted
## Reads keyboard/mouse and gamepad input and turns it into camera-relative world intents.
## The active aiming device switches only on meaningful input: accumulated mouse travel past a
## threshold or a mouse click (mouse), right-stick deflection past the radial dead zone or the
## fire trigger (gamepad). Mouse drift and stick noise below those thresholds are ignored.
## ScriptedInput (benchmarks) overrides poll() with the same outputs.
enum Device { MOUSE, GAMEPAD }
var active_device: Device = Device.MOUSE
## Camera-relative movement on XZ (length <= 1).
var move := Vector2.ZERO
## Last valid horizontal aim direction (unit, XZ). Retained when the stick is released.
var aim := Vector2(0.0, -1.0)
## World point the mouse aims at (on the combat-height plane); valid in MOUSE mode.
var aim_point := Vector3.ZERO
var fire := false
var _mouse_travel := 0.0
var _cfg: PrototypeConfig
func _init(cfg: PrototypeConfig) -> void:
_cfg = cfg
func reset(initial_aim: Vector2) -> void:
move = Vector2.ZERO
aim = initial_aim
fire = false
_mouse_travel = 0.0
func handle_event(event: InputEvent) -> void:
if event is InputEventMouseMotion:
if active_device == Device.GAMEPAD:
_mouse_travel += (event as InputEventMouseMotion).relative.length()
if _mouse_travel >= _cfg.mouse_switch_threshold:
active_device = Device.MOUSE
elif event is InputEventMouseButton and (event as InputEventMouseButton).pressed:
active_device = Device.MOUSE
elif event is InputEventJoypadButton and (event as InputEventJoypadButton).pressed:
if event.is_action("fire"):
_switch_to_gamepad()
elif event is InputEventJoypadMotion:
var jm := event as InputEventJoypadMotion
if jm.axis == JOY_AXIS_TRIGGER_RIGHT and jm.axis_value > 0.5:
_switch_to_gamepad()
## The gun sits SIDE_OFFSET to the right of the player's center line, and bullets fly parallel
## to the facing direction. For a mouse target, rotate the facing slightly left so the muzzle
## line passes exactly through the cursor point: d = (t * u - s * v) / L, where u is the unit
## vector to the target, v its right-hand perpendicular, s the offset, t = sqrt(L^2 - s^2).
## Keeps the previous aim when the cursor is too close to the player.
static func muzzle_corrected_aim(to_target: Vector2, previous: Vector2) -> Vector2:
var s := WeaponController.SIDE_OFFSET
var l := to_target.length()
if l < s + 0.25:
return previous
var u := to_target / l
var v := Vector2(-u.y, u.x)
var t := sqrt(l * l - s * s)
return (u * t - v * s) / l
func _switch_to_gamepad() -> void:
active_device = Device.GAMEPAD
_mouse_travel = 0.0
## Polls continuous input once per physics tick.
func poll(camera: CameraRig, player_pos: Vector3) -> void:
var raw := Input.get_vector("move_left", "move_right", "move_back", "move_forward", _cfg.move_dead_zone)
var fwd := camera.flat_forward()
var right := camera.flat_right()
var world := right * raw.x + fwd * raw.y
move = Vector2(world.x, world.z).limit_length(1.0)
var stick := Input.get_vector("aim_left", "aim_right", "aim_down", "aim_up", _cfg.aim_dead_zone)
if stick != Vector2.ZERO:
_switch_to_gamepad()
var w := right * stick.x + fwd * stick.y
aim = Vector2(w.x, w.z).normalized()
elif active_device == Device.MOUSE:
var vp := camera.get_viewport()
aim_point = camera.screen_to_plane(vp.get_mouse_position(), _cfg.combat_height)
aim = muzzle_corrected_aim(Vector2(aim_point.x - player_pos.x, aim_point.z - player_pos.z), aim)
fire = Input.is_action_pressed("fire")

View file

@ -0,0 +1 @@
uid://c0segjai0xgdd

View file

@ -0,0 +1,166 @@
class_name ProjectileSystem
extends Node3D
## Fixed-capacity pooled projectiles with shared instanced visuals (no rigid body per bullet).
##
## Bullets are mathematically zero-width rays with a visible tracer, flying horizontally at the
## combat height. Each physics tick a bullet's full segment (previous -> proposed position) is
## tested against the world (one physics ray query over the footprint boxes) and against bird
## hit proxies (HordeSystem.sweep_hit, exact relative-motion circle test over every grid cell
## the segment can touch). The nearest of the two hits wins, so a wall blocks a bird behind it.
## No piercing: a hit applies damage once and releases the bullet immediately. Bullets are also
## released on lifetime expiry and on leaving the arena. Exhaustion skips the shot and is
## counted; live bullets are never stolen and the pool never grows mid-round.
const STRIDE := HordeRenderer.STRIDE
var capacity: int = 0
var active_count: int = 0
var peak_active: int = 0
# Diagnostics (reset on restart).
var exhausted: int = 0
var fired: int = 0
var hits_enemy: int = 0
var hits_world: int = 0
var expired: int = 0
var exited: int = 0
var blocked_at_muzzle: int = 0
var _px := PackedFloat32Array()
var _pz := PackedFloat32Array()
var _dx := PackedFloat32Array()
var _dz := PackedFloat32Array()
var _life := PackedFloat32Array()
var _cfg: PrototypeConfig
var _horde: HordeSystem
var _bounds: Rect2
var _renderer: HordeRenderer
var _ray := PhysicsRayQueryParameters3D.new()
func setup(cfg: PrototypeConfig, horde: HordeSystem, bounds: Rect2, shooter: RID) -> void:
_cfg = cfg
_horde = horde
_bounds = bounds
capacity = cfg.projectile_capacity
for a: PackedFloat32Array in [_px, _pz, _dx, _dz, _life]:
a.resize(capacity)
a.fill(0.0)
_ray.collision_mask = Arena.WORLD_LAYER
_ray.collide_with_areas = false
_ray.collide_with_bodies = true
_ray.hit_from_inside = true
_ray.exclude = [shooter]
var mesh := BoxMesh.new()
mesh.size = Vector3(0.08, 0.08, 0.6)
var mat := StandardMaterial3D.new()
mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
mat.albedo_color = Color(1.0, 0.85, 0.25)
_renderer = HordeRenderer.new()
_renderer.name = "ProjectileRenderer"
add_child(_renderer)
var aabb := AABB(Vector3(bounds.position.x, 0.0, bounds.position.y), Vector3(bounds.size.x, 3.0, bounds.size.y))
_renderer.setup(mesh, mat, capacity, cfg.combat_height, aabb)
func reset_state() -> void:
active_count = 0
peak_active = 0
exhausted = 0
fired = 0
hits_enemy = 0
hits_world = 0
expired = 0
exited = 0
blocked_at_muzzle = 0
_renderer.clear()
_renderer.commit(0)
## Fires from the weapon origin (player center at combat height) through the muzzle.
## The origin -> muzzle segment is tested first, so a barrel poking through a wall (or into a
## bird pressed against the player) resolves there instead of spawning on the far side.
## Returns false if the shot was skipped (pool exhausted) or resolved before leaving the muzzle.
func fire(origin: Vector3, muzzle: Vector3, dir: Vector3) -> bool:
if active_count >= capacity:
exhausted += 1
return false
fired += 1
if _resolve_segment(origin.x, origin.z, muzzle.x, muzzle.z, false):
blocked_at_muzzle += 1
return false
var d := active_count
active_count += 1
peak_active = maxi(peak_active, active_count)
_px[d] = muzzle.x
_pz[d] = muzzle.z
_dx[d] = dir.x
_dz[d] = dir.z
_life[d] = _cfg.projectile_lifetime
_renderer.write_new(d, muzzle.x, muzzle.z, dir.x, dir.z, 0.0)
return true
func step(dt: float) -> void:
var step_len := _cfg.projectile_speed * dt
var i := 0
while i < active_count:
var x0 := _px[i]
var z0 := _pz[i]
var x1 := x0 + _dx[i] * step_len
var z1 := z0 + _dz[i] * step_len
if _resolve_segment(x0, z0, x1, z1, true):
_release(i)
continue
_px[i] = x1
_pz[i] = z1
_life[i] -= dt
if _life[i] <= 0.0:
expired += 1
_release(i)
continue
if not _bounds.has_point(Vector2(x1, z1)):
exited += 1
_release(i)
continue
i += 1
## Resolves the nearest world/enemy hit along a segment. Returns true if something was hit
## (damage is applied for enemy hits). use_motion selects the relative-motion enemy test.
func _resolve_segment(x0: float, z0: float, x1: float, z1: float, use_motion: bool) -> bool:
var h := _cfg.combat_height
var world_t := 2.0
_ray.from = Vector3(x0, h, z0)
_ray.to = Vector3(x1, h, z1)
var res := get_world_3d().direct_space_state.intersect_ray(_ray)
if not res.is_empty():
var seg := Vector2(x1 - x0, z1 - z0).length()
var p: Vector3 = res["position"]
world_t = Vector2(p.x - x0, p.z - z0).length() / maxf(seg, 1e-6)
var e := _horde.sweep_hit(x0, z0, x1, z1, use_motion)
if e >= 0 and _horde.hit_t <= world_t:
_horde.apply_hit(e)
hits_enemy += 1
return true
if world_t <= 1.0:
hits_world += 1
return true
return false
func _release(i: int) -> void:
var last := active_count - 1
if i != last:
_px[i] = _px[last]
_pz[i] = _pz[last]
_dx[i] = _dx[last]
_dz[i] = _dz[last]
_life[i] = _life[last]
_renderer.move_slot(last, i)
active_count -= 1
func commit_render() -> void:
_renderer.write_poses(active_count, _px, _pz, _dx, _dz)
_renderer.commit(active_count)

View file

@ -0,0 +1 @@
uid://do56nngcmpp1p

View file

@ -0,0 +1,121 @@
class_name PrototypeConfig
extends Resource
## Every tunable gameplay, capacity, and performance setting, kept in one resource.
## The defaults live in res://prototype/resources/default_config.tres.
enum Layout { COMPACT, ENLARGED }
enum Scenario { PLAY, SPREAD, CONCENTRATED, BOTTLENECK }
@export_group("Round")
@export var round_seed: int = 20261002
@export_range(1, 4096) var enemy_count: int = 50
@export_range(1, 4096) var enemy_capacity: int = 64
@export_range(1, 1024) var projectile_capacity: int = 64
@export_group("Arena")
## Playable area (meters) of the compact layout; obstacle footprints are authored against it.
@export var arena_size: Vector2 = Vector2(32.0, 32.0)
@export var layout: Layout = Layout.COMPACT
## Uniform XZ scale applied to the layout when layout == ENLARGED (stress density tests only).
@export var enlarged_scale: float = 2.0
@export_group("Camera")
@export var camera_yaw_deg: float = 45.0
@export var camera_pitch_deg: float = 35.0
## Extra framing around the arena so the HUD does not cover the play area.
@export var camera_margin: float = 1.06
@export var camera_distance: float = 80.0
@export_group("Simulation")
@export var physics_ticks: int = 60
@export var combat_height: float = 1.1
@export_group("Player")
@export var player_speed: float = 6.0
@export var player_acceleration: float = 60.0
@export var player_radius: float = 0.4
@export var player_height: float = 2.0
@export var player_max_health: int = 3
@export var invulnerability_time: float = 1.0
@export var player_start: Vector2 = Vector2(0.0, 2.0)
@export_group("Weapon")
@export var fire_rate: float = 6.0
@export var projectile_speed: float = 24.0
@export var projectile_lifetime: float = 2.0
## Horizontal distance from the player center to the muzzle along the aim direction.
@export var muzzle_distance: float = 1.05
@export_group("Enemies")
@export var enemy_speed: float = 2.5
@export var enemy_acceleration: float = 12.0
## Body collision radius (fit to the torso, not the wings).
@export var enemy_radius: float = 0.3
## Projectile hit proxy radius (vertical cylinder centered at combat height).
@export var enemy_hit_radius: float = 0.35
@export var enemy_health: int = 1
@export var enemy_attack_cooldown: float = 1.0
## Extra reach beyond touching (bird radius + player radius) for a melee attack.
@export var enemy_attack_reach: float = 0.2
## Uniform scale from the bird OBJ's source units to meters.
@export var enemy_visual_scale: float = 0.0055
@export var enemy_min_spawn_distance: float = 9.0
@export var enemy_spawn_spacing: float = 0.8
@export_group("Navigation")
@export var nav_cell_size: float = 0.5
## Extra clearance added to the bird radius when inflating blocked cells.
@export var nav_inflate_margin: float = 0.05
@export var flow_rebuild_hz: float = 10.0
## Cells finalized per physics tick while a flow-field rebuild is in progress (bounds the
## per-tick navigation cost deterministically; the previous field stays active meanwhile).
@export var flow_slice_cells: int = 1200
@export_group("Steering")
## Each bird re-steers at this rate; birds are split into physics_ticks / steering_hz cohorts
## (3 at the defaults) and one cohort is processed per physics tick.
@export var steering_hz: float = 20.0
@export var spatial_cell_size: float = 1.0
@export var separation_radius: float = 0.75
@export var separation_weight: float = 1.4
@export var separation_max_candidates: int = 16
@export var separation_max_neighbors: int = 6
## Largest positional correction a bird may receive per tick (keeps pushes from tunneling).
@export var max_correction_per_tick: float = 0.15
## Within this distance (and with clear line of sight) birds steer straight at the player.
@export var direct_chase_distance: float = 2.5
@export_group("Input")
@export var move_dead_zone: float = 0.2
@export var aim_dead_zone: float = 0.3
## Accumulated mouse travel (pixels) needed to take aim control back from the gamepad.
@export var mouse_switch_threshold: float = 12.0
@export_group("Diagnostics")
@export var show_overlay: bool = false
@export var overlay_hz: float = 4.0
@export_group("Stress (labeled, never used by the normal game)")
@export var stress_label: String = ""
@export var stress_invulnerable: bool = false
@export var stress_recycle: bool = false
@export var scenario: Scenario = Scenario.PLAY
func layout_scale() -> float:
return enlarged_scale if layout == Layout.ENLARGED else 1.0
func is_stress() -> bool:
return stress_invulnerable or stress_recycle or scenario != Scenario.PLAY
## Number of steering cohorts (= physics ticks between two steering updates of one bird).
func steering_cohorts() -> int:
return maxi(1, roundi(float(physics_ticks) / steering_hz))
func describe() -> String:
return "seed=%d enemies=%d/%d bullets=%d layout=%s scenario=%s invuln=%s recycle=%s" % [
round_seed, enemy_count, enemy_capacity, projectile_capacity,
Layout.keys()[layout], Scenario.keys()[scenario], stress_invulnerable, stress_recycle]

View file

@ -0,0 +1 @@
uid://bb655eby41ens

View file

@ -0,0 +1,126 @@
class_name PrototypeHUD
extends CanvasLayer
## Health, enemies remaining, hit flash, end screen (focused Restart button usable by mouse,
## keyboard, or gamepad), and a throttled performance overlay (overlay_hz, default 4 Hz).
## Labels change only on events; the overlay text is the only periodic string formatting.
@onready var health_label: Label = $Root/TopBar/Health
@onready var enemies_label: Label = $Root/TopBar/Enemies
@onready var hint_label: Label = $Root/Hint
@onready var overlay_label: Label = $Root/Overlay
@onready var stress_label: Label = $Root/StressLabel
@onready var hit_flash: ColorRect = $Root/HitFlash
@onready var end_panel: PanelContainer = $Root/EndPanel
@onready var end_title: Label = $Root/EndPanel/VBox/Title
@onready var end_detail: Label = $Root/EndPanel/VBox/Detail
@onready var restart_button: Button = $Root/EndPanel/VBox/RestartButton
var _round: RoundController
var _overlay_accum: float = 0.0
var _flash: float = 0.0
func setup(round_controller: RoundController) -> void:
_round = round_controller
overlay_label.visible = _round.config.show_overlay
restart_button.pressed.connect(_round.request_restart)
_round.round_reset.connect(_on_round_reset)
_round.player.damaged.connect(_on_player_damaged)
_round.horde.enemy_killed.connect(_on_enemy_killed)
var cfg := _round.config
stress_label.visible = cfg.is_stress()
if cfg.is_stress():
stress_label.text = "STRESS MODE%s — %s" % [(" " + cfg.stress_label) if cfg.stress_label != "" else "", cfg.describe()]
hint_label.text = "Move WASD / left stick Aim mouse / right stick Fire LMB / RT Restart R / Start Overlay F3 / Back"
func show_fatal(message: String) -> void:
end_panel.visible = true
end_title.text = "ERROR"
end_detail.text = message
restart_button.visible = false
func show_end(won: bool) -> void:
end_panel.visible = true
end_title.text = "VICTORY" if won else "YOU DIED"
end_title.modulate = Color(0.55, 1.0, 0.55) if won else Color(1.0, 0.45, 0.4)
end_detail.text = "All %d birds eliminated in %.1f s" % [_round.config.enemy_count, _round.round_time] if won \
else "%d of %d birds remaining" % [_round.horde.active_count, _round.config.enemy_count]
restart_button.grab_focus()
func toggle_overlay() -> void:
overlay_label.visible = not overlay_label.visible
_overlay_accum = 1e9
func _on_round_reset() -> void:
end_panel.visible = false
restart_button.release_focus()
_flash = 0.0
hit_flash.visible = false
_update_health(_round.player.health)
_update_enemies(_round.horde.active_count)
func _on_player_damaged(health: int) -> void:
_update_health(health)
_flash = 0.35
func _on_enemy_killed(remaining: int) -> void:
_update_enemies(remaining)
func _update_health(health: int) -> void:
health_label.text = "HEALTH %d / %d" % [maxi(health, 0), _round.config.player_max_health]
health_label.modulate = Color(1, 1, 1) if health >= _round.config.player_max_health else Color(1.0, 0.55, 0.45)
func _update_enemies(remaining: int) -> void:
enemies_label.text = "BIRDS %d / %d" % [remaining, _round.config.enemy_count]
func _process(delta: float) -> void:
if _round == null:
return
if _flash > 0.0:
_flash = maxf(_flash - delta, 0.0)
hit_flash.visible = _flash > 0.0
hit_flash.color.a = _flash * 0.45
if overlay_label.visible:
_overlay_accum += delta
if _overlay_accum >= 1.0 / _round.config.overlay_hz:
_overlay_accum = 0.0
overlay_label.text = _overlay_text()
func _overlay_text() -> String:
var r := _round
var f := r.stats.frame_summary()
var t := r.stats.tick_summary()
var h := r.horde
var p := r.projectiles
var lines := PackedStringArray()
lines.append("FPS %d frame avg %.2f p95 %.2f max %.2f ms" % [Engine.get_frames_per_second(), f.x, f.y, f.z])
lines.append("sim tick avg %.2f p95 %.2f max %.2f ms" % [t.x, t.y, t.z])
lines.append("flow rebuild last %.2f max %.2f ms (%d rebuilds, %d cells)" % [
r.stats.nav_usec_last / 1000.0, r.stats.nav_usec_max / 1000.0, r.stats.nav_rebuilds, r.nav.cell_count()])
lines.append("birds %d / %d bullets %d / %d (peak %d)" % [h.active_count, h.capacity, p.active_count, p.capacity, p.peak_active])
lines.append("pool exhausted: birds %d bullets %d recycled %d" % [h.spawn_skipped, p.exhausted, h.recycled])
lines.append("separation checks %d / tick (peak %d)" % [h.separation_checks, h.separation_checks_peak])
lines.append("shots %d hits bird %d wall %d muzzle-blocked %d expired %d exited %d" % [
p.fired, p.hits_enemy, p.hits_world, p.blocked_at_muzzle, p.expired, p.exited])
lines.append("melee attempts %d blocked by cover %d player hits accepted %d rejected %d" % [
h.attacks_attempted, h.attacks_blocked_by_cover, r.player.accepted_hits, r.player.rejected_hits])
lines.append("draw calls %d primitives %d objects %d" % [
RenderingServer.get_rendering_info(RenderingServer.RENDERING_INFO_TOTAL_DRAW_CALLS_IN_FRAME),
RenderingServer.get_rendering_info(RenderingServer.RENDERING_INFO_TOTAL_PRIMITIVES_IN_FRAME),
Performance.get_monitor(Performance.OBJECT_COUNT)])
lines.append("static mem %.1f MB nodes %d orphans %d" % [
OS.get_static_memory_usage() / 1048576.0, Performance.get_monitor(Performance.OBJECT_NODE_COUNT),
Performance.get_monitor(Performance.OBJECT_ORPHAN_NODE_COUNT)])
lines.append("state %s seed %d resets %d %s" % [
RoundController.State.keys()[r.state], r.config.round_seed, r.resets, RenderingServer.get_current_rendering_method()])
return "\n".join(lines)

View file

@ -0,0 +1 @@
uid://cba2i5y4yqojo

View file

@ -0,0 +1,246 @@
class_name RoundController
extends Node3D
## Round lifecycle and simulation driver.
##
## LOADING -> load assets, build arena/navigation, allocate every pool and render buffer.
## READY -> everything allocated; the initial round is created through the same reset path
## used by restarts.
## PLAYING -> one deterministic simulation step per physics tick (see sim_tick for order).
## WON/LOST -> combat stops; the end overlay offers a focused Restart button.
## RESETTING-> transient state while a restart is applied at a tick boundary.
##
## Restart requests (R, gamepad Start, UI button) all go through request_restart(), which is
## idempotent; the reset itself runs at the start of the next physics tick and reuses the
## loaded arena, resources, and pools (no scene reload).
enum State { LOADING, READY, PLAYING, WON, LOST, RESETTING }
signal state_changed(new_state: State)
signal round_reset
@export var config: PrototypeConfig
@onready var arena: Arena = $Arena
@onready var camera: CameraRig = $CameraRig
@onready var player: PlayerController = $Player
@onready var horde: HordeSystem = $HordeSystem
@onready var projectiles: ProjectileSystem = $ProjectileSystem
@onready var hud: PrototypeHUD = $HUD
var state: State = State.LOADING
var catalog := AssetCatalog.new()
var layout: ArenaLayout
var nav := ArenaNavigation.new()
var input: PlayerInput
var stats := PerfStats.new()
var spawn_points := PackedVector2Array()
var recycle_points := PackedVector2Array()
var initial_aim := Vector2(0.0, -1.0)
var resets: int = 0
var ticks: int = 0
var round_time: float = 0.0
var load_msec: int = 0
var last_tick_usec: int = 0
## Per-phase simulation cost of the last tick (usec), in PHASES order.
const PHASES := ["player", "flow", "motion", "grid", "melee", "projectiles", "steering", "commit"]
var phase_usec := PackedInt32Array([0, 0, 0, 0, 0, 0, 0, 0])
var _restart_pending := false
var _last_flow_cell: int = -1
var _flow_cooldown: int = 0
var _flow_interval: int = 6
var _last_frame_usec: int = 0
func _ready() -> void:
if config == null:
config = load("res://prototype/resources/default_config.tres") as PrototypeConfig
config = config.duplicate() as PrototypeConfig # runtime overrides never touch the asset
var runner := get_node_or_null("BenchmarkRunner") as BenchmarkRunner
if runner:
runner.configure(self)
_load()
func _load() -> void:
var t0 := Time.get_ticks_msec()
_set_state(State.LOADING)
Engine.physics_ticks_per_second = config.physics_ticks
_flow_interval = maxi(1, roundi(float(config.physics_ticks) / config.flow_rebuild_hz))
if not catalog.load_all(config):
hud.show_fatal("Asset loading failed:\n" + "\n".join(catalog.errors))
return
layout = ArenaLayout.build(config)
# Each world resolve sees at most one tick of motion plus one bounded push; keeping that
# below half the thinnest footprint means a center can never cross a footprint's midline.
var max_step := config.enemy_speed / float(config.physics_ticks) + config.max_correction_per_tick
if layout.min_thickness() < max_step * 2.0:
push_warning("Thinnest footprint %.2f m is below twice the max displacement per world resolve %.2f m" % [layout.min_thickness(), max_step])
arena.build(layout, catalog)
var outer := layout.outer_rect()
var playable := Rect2(-layout.half_extent, layout.half_extent * 2.0)
nav.setup(arena.rects, playable, outer, config.nav_cell_size, config.enemy_radius + config.nav_inflate_margin)
camera.setup(config, outer, 2.4)
var fwd := camera.flat_forward()
initial_aim = Vector2(fwd.x, fwd.z).normalized()
if input == null:
input = PlayerInput.new(config)
player.setup(config, catalog, layout.player_start, initial_aim)
projectiles.setup(config, horde, outer, player.get_rid())
player.weapon.setup(config, projectiles)
var bird_mat := ShaderMaterial.new()
bird_mat.shader = load("res://prototype/resources/bird.gdshader") as Shader
horde.setup(config, nav, catalog.bird_mesh, bird_mat, outer)
_plan_spawns()
hud.setup(self)
load_msec = Time.get_ticks_msec() - t0
_set_state(State.READY)
_reset_round()
## Spawn points are planned once (seeded) and reused by every restart, so each round starts
## from the identical state. Only cells reachable from the player's start are eligible.
func _plan_spawns() -> void:
var start := layout.player_start
nav.rebuild_flow(start.x, start.y)
var rng := RandomNumberGenerator.new()
rng.seed = config.round_seed
var min_d := config.enemy_min_spawn_distance * layout.scale
spawn_points = HordeSystem.plan_spawn_points(nav, start, config.enemy_count, min_d, config.enemy_spawn_spacing, rng)
if config.stress_recycle:
recycle_points = HordeSystem.plan_spawn_points(nav, start, maxi(256, config.enemy_capacity), min_d * 0.5, config.enemy_spawn_spacing, rng)
func request_restart() -> void:
if state == State.LOADING or state == State.RESETTING or _restart_pending:
return
_restart_pending = true
## Applies a full reset at a safe simulation boundary (plan steps 1-7).
func _reset_round() -> void:
_set_state(State.RESETTING)
input.reset(initial_aim) # 1. stop input-driven firing
projectiles.reset_state() # 2-3. release bullets, clear counters and render mapping
player.reset_state() # 4. position, health, facing, animation
player.weapon.reset_state() # 4. gun state; 6. requires a fresh fire press
camera.reset_view() # 4. camera
nav.reset_stats()
var start := layout.player_start
nav.rebuild_flow(start.x, start.y) # 5. navigation target
_last_flow_cell = nav.cell_of(start.x, start.y)
_flow_cooldown = 0
horde.reset_round(spawn_points, recycle_points, config.round_seed, start) # 2-3, 5. seeded population
stats.reset() # 6. counters and overlays
ticks = 0
round_time = 0.0
resets += 1
round_reset.emit()
_set_state(State.PLAYING) # 7.
func _physics_process(dt: float) -> void:
if _restart_pending:
_restart_pending = false
_reset_round()
return
if state != State.PLAYING:
return
var t0 := Time.get_ticks_usec()
sim_tick(dt)
last_tick_usec = Time.get_ticks_usec() - t0
stats.record_tick(last_tick_usec)
## One simulation step. Order matters:
## input -> player move -> flow field -> bird motion/contacts -> grid -> melee -> firing ->
## projectile sweeps -> steering cohort -> deferred removals -> render upload -> outcome.
func sim_tick(dt: float) -> void:
ticks += 1
round_time += dt
var pu := phase_usec
var t := Time.get_ticks_usec()
input.poll(camera, player.global_position)
player.physics_step(dt, input)
var pp := Vector2(player.global_position.x, player.global_position.z)
var t1 := Time.get_ticks_usec()
pu[0] = t1 - t
_update_flow(pp)
t = Time.get_ticks_usec()
pu[1] = t - t1
var corr := horde.step_motion(dt, pp, config.player_radius)
if corr != Vector2.ZERO:
player.apply_crowd_correction(corr)
t1 = Time.get_ticks_usec()
pu[2] = t1 - t
horde.rebuild_grid()
t = Time.get_ticks_usec()
pu[3] = t - t1
horde.evaluate_attacks(player)
t1 = Time.get_ticks_usec()
pu[4] = t1 - t
player.weapon.step(input.fire, player.combat_origin(), player.aim)
projectiles.step(dt)
t = Time.get_ticks_usec()
pu[5] = t - t1
horde.step_steering()
t1 = Time.get_ticks_usec()
pu[6] = t1 - t
horde.commit_removals()
horde.commit_render()
projectiles.commit_render()
pu[7] = Time.get_ticks_usec() - t1
# Tie policy: lethal damage is evaluated before victory, so a tick that both kills the
# last bird and the player is a loss.
if not player.alive:
_end(State.LOST)
elif horde.active_count == 0 and not config.stress_recycle:
_end(State.WON)
## Rebuilds the shared flow field when the player's cell changes, starting at most
## flow_rebuild_hz. A rebuild is processed in slices of flow_slice_cells per tick; steering
## keeps using the last completed field until the new one is swapped in.
func _update_flow(pp: Vector2) -> void:
if _flow_cooldown > 0:
_flow_cooldown -= 1
if not nav.is_rebuilding():
var cell := nav.cell_of(pp.x, pp.y)
if cell == _last_flow_cell or _flow_cooldown > 0 or not nav.begin_flow(pp.x, pp.y):
return
_last_flow_cell = cell
_flow_cooldown = _flow_interval
if nav.step_flow(config.flow_slice_cells):
stats.record_nav(nav.last_rebuild_usec)
func _end(result: State) -> void:
_set_state(result)
player.play_end(result == State.WON)
hud.show_end(result == State.WON)
func _set_state(s: State) -> void:
state = s
state_changed.emit(s)
func _input(event: InputEvent) -> void:
if input != null:
input.handle_event(event)
func _unhandled_input(event: InputEvent) -> void:
if event.is_action_pressed("restart"):
request_restart()
get_viewport().set_input_as_handled()
elif event.is_action_pressed("toggle_overlay"):
hud.toggle_overlay()
get_viewport().set_input_as_handled()
func _process(_delta: float) -> void:
var now := Time.get_ticks_usec()
if _last_frame_usec != 0:
stats.record_frame(now - _last_frame_usec)
_last_frame_usec = now

View file

@ -0,0 +1 @@
uid://6mjv205o5x3k

View file

@ -0,0 +1,56 @@
class_name ScriptedInput
extends PlayerInput
## Deterministic input for benchmarks and automated checks: walks a closed route (or holds a
## point), sweeps the aim at a constant angular rate, and fires on a fixed pattern. The same
## seed + script gives the same run, so presets are comparable.
enum Mode { IDLE, ROUTE, HOLD_POINT }
var mode: Mode = Mode.IDLE
var route := PackedVector2Array()
var hold_point := Vector2.ZERO
var aim_rate: float = 1.3 # rad/s
var fire_enabled := true
## Seconds after a reset before firing starts (>= one tick, so the weapon sees a release).
var fire_delay: float = 0.1
var _wp: int = 0
var _t: float = 0.0
var _dt: float = 1.0 / 60.0
func _init(cfg: PrototypeConfig) -> void:
super(cfg)
_dt = 1.0 / float(cfg.physics_ticks)
active_device = Device.GAMEPAD
func reset(initial_aim: Vector2) -> void:
super(initial_aim)
_wp = 0
_t = 0.0
active_device = Device.GAMEPAD
func handle_event(_event: InputEvent) -> void:
pass # scripted runs ignore physical devices
func poll(_camera: CameraRig, player_pos: Vector3) -> void:
_t += _dt
var p := Vector2(player_pos.x, player_pos.z)
move = Vector2.ZERO
match mode:
Mode.ROUTE:
if not route.is_empty():
var target := route[_wp]
if p.distance_to(target) < 0.6:
_wp = (_wp + 1) % route.size()
target = route[_wp]
move = (target - p).normalized()
Mode.HOLD_POINT:
if p.distance_to(hold_point) > 0.3:
move = (hold_point - p).normalized()
aim = Vector2(cos(_t * aim_rate), sin(_t * aim_rate))
# Fire is released for the first ticks after a reset, like a human releasing the button:
# the weapon requires a fresh press after every restart.
fire = fire_enabled and _t > fire_delay

View file

@ -0,0 +1 @@
uid://6bdyyycf8vql

View file

@ -0,0 +1,68 @@
class_name SpatialGrid
extends RefCounted
## Reusable uniform buckets of active enemy (dense) indices, rebuilt from current positions each
## simulation tick with a counting sort into preallocated arrays (no per-tick allocation).
## Items of cell c are items[cell_start[c] .. cell_start[c + 1]).
var cell_size: float
var inv_cell: float
var origin_x: float
var origin_z: float
var width: int
var height: int
var cell_start := PackedInt32Array()
var items := PackedInt32Array()
var item_cell := PackedInt32Array()
var _cursor := PackedInt32Array()
func setup(area: Rect2, p_cell_size: float, capacity: int) -> void:
cell_size = p_cell_size
inv_cell = 1.0 / cell_size
origin_x = area.position.x
origin_z = area.position.y
width = maxi(1, ceili(area.size.x * inv_cell))
height = maxi(1, ceili(area.size.y * inv_cell))
cell_start.resize(width * height + 1)
cell_start.fill(0)
_cursor.resize(width * height)
items.resize(capacity)
item_cell.resize(capacity)
func cell_x(x: float) -> int:
return clampi(int((x - origin_x) * inv_cell), 0, width - 1)
func cell_z(z: float) -> int:
return clampi(int((z - origin_z) * inv_cell), 0, height - 1)
func rebuild(px: PackedFloat32Array, pz: PackedFloat32Array, count: int) -> void:
var cur := _cursor
var ic := item_cell
var cs := cell_start
var w := width
var wm := width - 1
var hm := height - 1
var ox := origin_x
var oz := origin_z
var inv := inv_cell
cur.fill(0)
for i in count:
var c := clampi(int((pz[i] - oz) * inv), 0, hm) * w + clampi(int((px[i] - ox) * inv), 0, wm)
ic[i] = c
cur[c] += 1
var run := 0
var n := width * height
for c in n:
var k := cur[c]
cs[c] = run
cur[c] = run
run += k
cs[n] = run
var it := items
for i in count:
var c := ic[i]
it[cur[c]] = i
cur[c] += 1

View file

@ -0,0 +1 @@
uid://buio32gxhwicl

View file

@ -0,0 +1,91 @@
class_name WeaponController
extends Node3D
## Fire cadence, gun placement, and projectile requests. The gun is built from primitives on a
## stable aiming pivot (child of the player's facing node) rather than the animated hand bone,
## so the visible muzzle always coincides with the gameplay muzzle point.
## Lateral offset of the gun from the player's center line. Together with muzzle_distance and
## combat_height this puts the grip in the right hand of the aim clip (hand.r measured at
## (0.35, 1.0, -0.6) in the facing frame by prototype/tools/probe_hand_pose.gd).
const SIDE_OFFSET := 0.35
const BARREL_LENGTH := 0.25
const GRIP_BEHIND_MUZZLE := 0.44
var shots_fired: int = 0
var shots_blocked_at_muzzle: int = 0
var _cfg: PrototypeConfig
var _projectiles: ProjectileSystem
var _interval_ticks: int = 10
var _cooldown_ticks: int = 0
var _needs_release := true
func setup(cfg: PrototypeConfig, projectiles: ProjectileSystem) -> void:
_cfg = cfg
_projectiles = projectiles
_interval_ticks = maxi(1, roundi(float(cfg.physics_ticks) / cfg.fire_rate))
position = Vector3(SIDE_OFFSET, cfg.combat_height, -cfg.muzzle_distance)
_build_gun()
## Requires a fresh fire press after every reset, so a held button (or the click that pressed
## the Restart button) cannot fire into the new round.
func reset_state() -> void:
_cooldown_ticks = 0
_needs_release = true
shots_fired = 0
shots_blocked_at_muzzle = 0
func step(fire_held: bool, origin: Vector3, aim: Vector2) -> void:
if _cooldown_ticks > 0:
_cooldown_ticks -= 1
if _needs_release:
if fire_held:
return
_needs_release = false
if not fire_held or _cooldown_ticks > 0:
return
_cooldown_ticks = _interval_ticks
var dir := Vector3(aim.x, 0.0, aim.y)
var right := Vector3(-aim.y, 0.0, aim.x)
var muzzle := origin + dir * _cfg.muzzle_distance + right * SIDE_OFFSET
shots_fired += 1
if not _projectiles.fire(origin, muzzle, dir):
shots_blocked_at_muzzle += 1
## Gun geometry in this node's space: the muzzle is at the local origin, the gun extends back
## along +Z toward the player.
func _build_gun() -> void:
var metal := StandardMaterial3D.new()
metal.albedo_color = Color(0.18, 0.19, 0.22)
metal.metallic = 0.6
metal.roughness = 0.4
var accent := StandardMaterial3D.new()
accent.albedo_color = Color(0.95, 0.55, 0.15)
accent.roughness = 0.6
var barrel_mesh := CylinderMesh.new()
barrel_mesh.top_radius = 0.035
barrel_mesh.bottom_radius = 0.035
barrel_mesh.height = BARREL_LENGTH
barrel_mesh.radial_segments = 10
barrel_mesh.rings = 1
_part("Barrel", barrel_mesh, metal, Vector3(0, 0, BARREL_LENGTH * 0.5), Vector3(PI * 0.5, 0, 0))
var body_mesh := BoxMesh.new()
body_mesh.size = Vector3(0.1, 0.13, 0.3)
_part("Body", body_mesh, accent, Vector3(0, -0.01, BARREL_LENGTH + 0.13), Vector3.ZERO)
var grip_mesh := BoxMesh.new()
grip_mesh.size = Vector3(0.08, 0.18, 0.08)
_part("Grip", grip_mesh, metal, Vector3(0, -0.11, GRIP_BEHIND_MUZZLE), Vector3(-0.3, 0, 0))
func _part(part_name: String, mesh: Mesh, mat: Material, pos: Vector3, rot: Vector3) -> void:
var mi := MeshInstance3D.new()
mi.name = part_name
mi.mesh = mesh
mi.material_override = mat
mi.position = pos
mi.rotation = rot
add_child(mi)

View file

@ -0,0 +1 @@
uid://dtysj6ieenrh