harvest/plan.md
2026-10-03 12:14:28 -04:00

141 lines
20 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

Horde survival prototype — coding-agent implementation plan
1. Mission and confirmed requirements
Build a playable desktop prototype in Godot 4.7.2 using typed GDScript. Begin with an asset-containing project and no gameplay code. Inspect the actual project before editing; preserve its assets and unrelated settings.
- Small, enclosed 3D arena viewed through a fixed orthographic isometric camera.
- Default 50 enemies; configurable to 25 for the normal demo.
- Player moves and aims independently with keyboard/mouse or gamepad.
- Visible projectiles travel through space; no instant hitscan weapon.
- Birds chase the player and attack at close range.
- Player dies on the third accepted hit. Eliminate every bird to win.
- Restart restores the complete initial round, including health, enemies, cooldowns, camera, and UI.
- Use existing bird.obj, mannequin_medium.glb, and prototype_kit assets. Only the mannequin currently has animations. Create a simple gun from primitives.
- All environment obstacles are static and indestructible in this prototype. No building mechanics.
- Target 60 FPS. Minimum hardware is not yet defined; record measured hardware and do not claim universal compliance.
- Design and test a path toward thousands of active enemies, without claiming an unmeasured frame rate.
Deliver a working project, setup/control README, and measured performance report. Do not stop after scaffolding. Do not silently substitute another engine version or language. If the available editor differs, report that discrepancy before making incompatible changes.
2. Proposed tuning defaults
These values are implementation defaults, not additional user requirements. Keep them editable in one configuration resource.
Setting Initial value
Arena playable area Approximately 32 × 32 meters
Camera Orthographic, roughly 45° yaw / 35° downward pitch; frame arena and HUD at 16:9
Reference resolution 1920 × 1080
Physics tick 60 Hz
Player movement 6 m/s, normalized diagonals, no jump
Enemy movement 2.5 m/s, ground movement on XZ plane
Enemy health 1 projectile hit
Player health 3 hits
Damage invulnerability 1 second after an accepted hit
Enemy attack cooldown 1 second
Fire rate 6 shots/second, hold to fire
Projectile speed/lifetime 24 m/s / 2 seconds
Projectile pool capacity 64
Enemy capacity 64 normal; selected stress capacity allocated before the run
Navigation grid 0.5 m cells, tuned after asset scale inspection
Flow-field rebuild On player-cell change, at most 10 Hz
Steering refresh 20 Hz, staggered across three cohorts
Birds are ground-bound for this prototype despite their model. No flying navigation. Fit their collision proxies to the body rather than the wings. Adjust arena size and visual scale to keep birds readable and the round winnable. 3. Architecture: centralized simulation with reusable storage
Use ordinary scenes for the arena, player, camera, weapon, and UI. Manage the horde and projectiles through centralized systems with preallocated data. Do not create a CharacterBody3D, NavigationAgent3D, Timer, or independent processing script for every bird.
Keep this a small project-specific design, not a general ECS framework. Separate responsibilities into scripts with typed interfaces:
Component Responsibility
RoundController Loading/ready/playing/won/lost/resetting state, seed, round lifecycle
PrototypeConfig Gameplay settings, capacities, performance preset
AssetCatalog Explicit resolved asset references; shared resources loaded before play
PlayerController Camera-relative movement, aim, world collision, animation
WeaponController Fire cadence, gun placement, projectile requests
HordeSystem Active enemy data, motion, attack evaluation, release/death
ChaseBehavior Compute desired direction from navigation data; replaceable later
ArenaNavigation Shared occupancy grid, flow field, obstacle collision queries
SpatialGrid Reusable nearby-enemy buckets for separation, contact, projectile candidates
ProjectileSystem Fixed pool, travel, swept hit resolution, expiry
HordeRenderer Shared bird mesh rendering and active-index mapping
PrototypeHUD Health, enemies remaining, end screen, performance overlay
Suggested organization: res://prototype/{scenes,scripts,resources,tests}. Reference existing assets where they are; do not duplicate or reorganize the user's asset folders unnecessarily.
Assets and rendering
Inspect asset names, import results, mesh surfaces, material counts, triangle counts, orientation, scale, and mannequin animation clips. Produce an inventory before implementation. Do not assume particular clip or skeleton bone names.
Use a shared bird mesh/material through MultiMeshInstance3D. Render active enemies as a dense prefix, and set visible_instance_count to the active count. On removal, swap the last active entry into the removed slot and update all mappings. Never leave dead birds rendering at a remote coordinate or at zero scale as the sole deactivation mechanism.
MultiMesh reduces rendering submission overhead; it does not reduce triangle count or perform per-bird culling. Start with one batch for this fully visible arena. Spatially split batches only when visibility or profiling justifies it. Inspect the OBJ's surface/material cost before promising thousands at 60 FPS. Preserve source assets; propose a derived low-detail version if mesh cost is excessive.
Use the mannequin's existing idle/walk/run clips when available. Disable root motion; gameplay owns the position. If clips do not match the planned behavior, use the closest available clip and document the fallback. Construct the gun from a few primitives, attached to a suitable hand bone if practical or a stable aiming pivot otherwise. Full-body facing follows aim; perfect strafing animation and inverse kinematics are out of scope.
Use a modest lighting setup. Begin with the Mobile renderer as a proposed desktop baseline, subject to device support and asset verification. Avoid real-time GI, per-enemy lights, expensive transparency, and per-bird shadows initially. Keep effects optional and bounded.
Reuse rules
Load resources and instantiate permanent scenes before PLAYING. Allocate enemy/projectile arrays and render capacity during loading or stress-preset selection, not during combat.
Use preallocated packed arrays or other measured typed storage, active counts, and an O(1) free-list/dense-slot strategy. A reused slot must reset every state field: current/previous position, velocity, health, behavior state, attack cooldown, lifetime, render data, and generation/identity if handles escape the owning system.
Deaths and expired bullets return slots to their pools. They must leave rendering, collision queries, and simulation immediately. Pooling reduces creation/destruction churn; it does not reduce active simulation or draw work by itself. Only iterate active entries.
No routine load(), scene instantiate(), queue_free(), growing per-entity arrays, or per-frame diagnostic strings in the hot combat path. Do not claim zero allocations: engine physics query results may allocate. Reuse query parameters and profile remaining costs.
When a pool is exhausted, skip the spawn and increment a visible diagnostic counter. Never steal a live projectile or silently expand capacity mid-round. A normal round must not exhaust its pools. 4. Arena, navigation, and collisions
Build an enclosed floor, perimeter, and roughly four to six obstacle clusters from prototype_kit. Use flat terrain, no stairs or jumping, and passages wide enough for several birds. Keep visual obstructions low enough to see the player. Validate every spawn can reach the player region.
Use simple box/capsule collision proxies rather than render-mesh collision. Give each obstacle an explicit footprint from which both its physics shape and navigation occupancy are derived. This prevents visual, physical, and navigational boundaries drifting apart.
Use Godot CharacterBody3D for the player against floor/world geometry. For birds, implement lightweight circle-versus-obstacle collision in the XZ plane, with bounded swept movement/sliding against the same footprints. Resolve crowd/player contacts centrally; do not rely on absent bird physics bodies. Prevent player and bird centers passing through one another, and recheck corrected positions against world obstacles. Dense crowds may compress slightly; exact rigid-body packing is out of scope.
Use one shared flow field toward the player's reachable grid cell. Inflate blocked cells by bird radius, prevent diagonal corner cutting, and use cost-aware integration if diagonals are enabled. Rebuild only when needed and at the configured rate; retain the last completed field until the next is ready. A grid of this size should be measured before adding threading or complicated incremental jobs.
The flow field handles routes around walls. Local separation handles neighbors. Neither alone substitutes for collision. Treat unreachable cells explicitly: hold position or use a safe fallback, never move through walls.
Rebuild reusable spatial buckets from current enemy positions each simulation tick. Search nearby buckets instead of comparing every enemy with every other enemy. Bound separation candidate inspections and selected neighbors, with fair/staggered selection in crowded cells. Merely capping selected neighbors while scanning an unlimited bucket is insufficient. Count candidate checks to expose dense-crowd cost. Accurate projectile hit candidates must not be arbitrarily dropped to meet this separation budget.
Compute steering at 20 Hz and integrate motion/collision at 60 Hz using delta. Interpolate rendering from previous/current state; ensure custom MultiMesh transforms are covered, not just ordinary Node3D interpolation. Reset previous state to current on spawn and restart to prevent visual streaks.
Keep ChaseBehavior separate from integration, damage, and rendering. It should be replaceable by another shared behavior policy without rewriting the horde system. Multiple goals, base attacks, dynamic obstacles, and flow-field invalidation for construction are future work. 5. Input, aiming, and projectiles
Define InputMap actions for move, aim, fire, restart, UI accept/cancel, and debug overlay. Use WASD / left stick for camera-relative XZ movement. Flatten and normalize camera basis vectors so diagonal travel is not faster.
Mouse aims by projecting onto the arena floor plane; compute the horizontal direction from the player to that point. Projectiles originate at the gun muzzle and travel horizontally at a consistent combat height. Align bird hit proxies and gun height accordingly. Display an aim marker so mouse behavior is clear.
Right stick supplies camera-relative horizontal aim, with an adjustable radial dead zone. Retain the last valid aim when the stick is released. Left-click/right trigger fires. Switch active aiming device on meaningful input; mouse drift or stick noise must not fight the other device. UI must be fully operable by either input method.
Projectiles use pooled state and shared visuals, not one rigid body per bullet. Each physics tick, test the entire segment between previous and proposed position. Use a world ray query and exact segment-versus-enemy proxy tests among spatial-grid candidates. Check all cells crossed by the segment, including the proxy-radius margin. Compare hit fractions and resolve the nearest hit across walls and enemies. A wall must block a bird behind it.
For this prototype bullets may be mathematically zero-width with a visible tracer; document that choice. If a nonzero gameplay radius is added, use consistent swept-volume tests for both world and enemy hits. Account for enemy movement across the tick through relative-motion tests or an explicitly validated conservative broad phase. Endpoint overlap alone is insufficient.
Check the path from weapon origin to muzzle/initial bullet position so a barrel near a wall cannot spawn shots on its far side. Ignore the shooter. No piercing: one bullet hits one target, applies damage once, and releases its slot. Recycle bullets on collision, lifetime expiry, and arena exit. Visual travel and damage timing must agree; ray queries cover only the distance traveled during that tick, not the weapon's full range. 6. Damage and complete restart
Evaluate close-range attacks with world-obstruction checks so birds cannot damage through walls. Each enemy has an attack cooldown. The player's invulnerability check is authoritative: multiple same-tick contacts can reduce health only once. Show a brief flash or other inexpensive hit cue.
Round states: LOADING → READY → PLAYING → WON or LOST. Evaluate lethal player damage before victory on a tick where both could occur, making loss the documented tie policy. Terminal states disable combat and show an overlay with focused Restart button.
Restart via R, a mapped gamepad button such as Start, or the UI. Route all triggers through one idempotent function and ignore duplicate requests. Apply mutations at a safe simulation boundary:
1. Enter RESETTING and stop combat/input-driven firing.
2. Release all enemies, projectiles, and optional effects; clear pending hits/spawns.
3. Reset all arrays, active counts, spatial buckets, cooldowns, timers, and render mappings.
4. Restore player position, three health, facing, animation, gun state, and camera.
5. Rebuild the navigation target and recreate the seeded starting population from the already allocated pool.
6. Reset interpolation state, counters, and overlays; require a fresh fire input after terminal-state restart.
7. Return to PLAYING with exactly the configured enemy count.
Do not reload the project or scene to conceal reset bugs. Restart must reuse the loaded arena and resources.
8. Implementation milestones and gates
Complete each gate before progressing. Profile incrementally rather than leaving performance until the final step.
Phase Work Exit gate
9. Inspect and configure Verify Godot, inventory assets/animations, config, InputMap, folder structure Project imports and opens without script errors; asset paths and clip names documented
10. Arena and player Camera, environment, world collisions, both control schemes, mannequin/gun Player moves, aims, animates, and cannot leave arena or cross obstacles
11. Horde core Pooled data, MultiMesh, grid, flow field, separation, collision 50 birds spawn visibly, route around obstacles, and contact player without crossing walls
12. Combat Traveling pooled bullets, swept tests, attacks, three-hit health Shots hit the nearest valid obstruction/target; player takes correctly spaced hits
13. Round lifecycle Win/loss HUD, reset, complete pool cleanup Both end states work; repeated reset exactly restores initial state
14. Performance Overlay, exported-build benchmarks, stress presets, bottleneck fixes Normal-demo measurements recorded; actual tested scaling limit and caveats reported
15. Performance measurement and scaling gates
60 FPS gives approximately 16.67 ms per frame. Treat this as a measurement goal, not a guarantee before hardware is known. Proposed normal-demo acceptance is p95 frame time at or below 16.67 ms in the recorded 1080p release-build scenario. Also report p99 and recurring spikes so average FPS cannot hide stutter. Keep meaningful frame-time headroom where measured; do not fabricate subsystem budgets as results.
Record CPU, GPU, OS, renderer, engine version, resolution, release/debug status, VSync, seed, and all gameplay capacities. Use a release export for the primary result; use Godot's profiler to investigate CPU/physics/render costs separately. Headless tests cannot establish rendering performance. Measure uncapped throughput with VSync off, then check playability with VSync on.
Show a throttled overlay (about 4 updates/second): frame-time summary, active/capacity enemy and bullet counts, pool exhaustion, navigation rebuild time, simulation time, draw calls/visible primitives where available, and memory/object counts where available. Keep timing collection lightweight and comparable with the overlay disabled.
For each measured preset, allow 10 seconds of warm-up and capture at least 60 seconds. Use the same seed and scripted player route/fire pattern for comparisons. Separately inspect first-shot/first-hit behavior for shader or effect stutter; warm-up must not conceal those issues.
Preset Purpose
25 / 50 Required normal playable demo
250 / 500 Intermediate scaling measurements
1,000 / 2,000 Explicit thousands-scale tests; report pass/fail against frame-time goal
Stress mode is separate from the normal game. It may enable invulnerability and maintain population by recycling defeated birds; label those changes. Include spread-out and concentrated crowd cases, continuous shooting, and obstacle bottlenecks. A compact arena cannot physically contain thousands of non-overlapping birds at normal scale: use a clearly labeled enlarged copy of the same layout for representative density tests, and retain a compact congestion test with documented soft overlap. Report camera framing and visible count, since off-screen enemies do not test the same rendering workload.
Use the same simulation/rendering architecture across presets. Allocate the selected capacity before starting. No preset may disable collision, attacks, or navigation without labeling the result as a partial-system diagnostic. Do not present such a diagnostic as full-game throughput.
Profile before escalating complexity. Address measured mesh/material cost, GDScript loops, crowded spatial buckets, transform uploads, and navigation spikes first. Thousands at 60 FPS are a scaling objective until measured on named hardware. Report the largest tested passing population, not an extrapolated promise. Native extensions or language changes require a separate scope decision. 9. Verification checklist
Use small automated tests for the highest-risk reusable logic, plus in-engine gameplay checks. Do not build a large test framework solely for this demo.
- Pool acquire/release/exhaustion and swap-removal preserve active identities and counts.
- Reused slots have no stale health, hit flags, cooldowns, or previous transforms.
- Flow field routes around a U-shaped obstacle and forbids diagonal corner cutting; unreachable spawns are rejected.
- Swept bullets hit at high speed, hit the nearest target, stop at walls, and cannot damage a removed/reused enemy through stale handles.
- Player/world and bird/world contacts remain valid at corners and bottlenecks; melee cannot pass through cover.
- Three accepted hits cause death; simultaneous attacks obey invulnerability; the final enemy triggers victory.
- Mouse and gamepad aim work in every direction; dead zones prevent drift; held inputs do not immediately fire through reset/UI.
- Restart from active play, victory, and death restores exactly 50 enemies (or configured count), three health, zero bullets, and the initial seed/state.
- Repeat 20 resets and a 10-minute recycle stress run. Object/resource counts stabilize after warm-up, with no systematic memory growth, duplicate signal connections, or increasing update time.
- Verify runtime errors/warnings, missing resources, and invalid pool handles are absent.
Final handoff must include controls, exact asset mappings and animation fallbacks, configuration locations, collision-layer meanings, benchmark reproduction steps, measured results, and known limitations. If hardware testing or a physical gamepad is unavailable, explicitly mark those checks unverified rather than claiming success.
10. Scope boundaries and reference notes
Do not add crafting, construction, destructible props, inventory, ammunition/reload systems, multiple weapons, multiple enemy types, multiplayer, ragdolls, save games, or complex AI behavior trees. Preserve seams for later building and alternative enemy goals without implementing those features now.
This plan uses engineering choices tailored to a flat, small, single-target arena. It has not inspected the user's local assets or measured their hardware. Asset compatibility and performance remain implementation gates.
Official references checked when drafting:
- Godot 4.7.2 release
- MultiMesh optimization: shared instance rendering, active instance counts, and batch-level culling. The page flags incomplete 4.7 review; verify exact APIs against the installed editor.
- Physics ray casting: direct-space queries, collision masks, and physics-tick execution.
The flow-field design, capacities, tuning, milestones, and acceptance thresholds above are proposed project decisions, not performance guarantees from Godot documentation.