This commit is contained in:
Forrest 2026-10-04 12:07:36 -04:00
parent 276d43613d
commit 4298caf5cb
552 changed files with 42990 additions and 776 deletions

138
game/COOP.md Normal file
View file

@ -0,0 +1,138 @@
# Harvest Season — co-op
Two players keep the farm together: each has a scarecrow, and both play the same vacation.
Co-op runs on [GD-Sync](https://www.gd-sync.com) (`addons/GD-Sync/`, version 1.0.2), the
multiplayer plugin; its autoload is `GDSync`.
## Playing together
Main menu → **Play with a friend**. Enter your name (shown over your scarecrow), then pick how to
connect:
| Connect | What it needs | How the friend finds you |
|---|---|---|
| **Same network (LAN)** | Nothing: GD-Sync's local mode is peer to peer, with no account or keys | Join lists the games announced on the network |
| **LAN by address** | The host's address (shown in the host's status line: "or by address: 192.168.1.20") | Join → type the address → Join. Use it when the list stays empty: some firewalls drop the announcements, and VPNs like Tailscale or ZeroTier don't carry them, but connect fine by address |
| **Online** | The project's GD-Sync API keys (below) | Join lists the open games, or type the game's name ("Ana's farm") |
- **Host a game:** pick the vacation (continue your save, or a new one), and the farm opens to
your friend. You play right away; your friend can join, leave, and rejoin at any time.
- **Join a game:** pick it from the list (or type its address or name). You arrive on the host's
farm as player 2, mid-day or mid-night, wherever the host is.
### Online play: the API keys
Online lobbies go through GD-Sync's servers, which need the project's keys (a free account at
gd-sync.com gives them):
1. In the Godot editor, open **Project → Tools → GD-Sync**.
2. Paste the public and private keys.
GD-Sync saves them to `addons/GD-Sync/keys.cfg`. That file is in `.gitignore`; never commit it.
The keys can also come from the `GDSYNC_PUBLIC_KEY` and `GDSYNC_PRIVATE_KEY` environment
variables. Without keys, the menu says so and LAN still works.
Exported builds get the keys automatically: GD-Sync's export plugin writes `keys.cfg` into
every export. Anyone with a build can read them, which is how GD-Sync works for every game. If
the keys leak somewhere they shouldn't, make new ones at gd-sync.com.
### Voice chat
On by default when both are in: your microphone is sent whenever it's above room noise (GD-Sync's
`VoiceChat`), and your friend's voice plays on the Voice bus.
- **[M]** mutes and unmutes your microphone; Settings → Co-op does the same.
- Settings → Audio → "Voice chat (your friend)" sets their volume.
- While your friend is talking, a speaker mark shows on their panel.
- Use headphones: an open microphone picks up the game's sound from speakers.
## In the game
- **Tags and colors.** Name tags over both scarecrows: P1 (the host) in gold, P2 in blue. Player
2's scarecrow is tinted blue.
- **Partner panel** (above your own health):
- their name, health, and what they're doing (down until morning, patching, gathering, fear
ready);
- "talking" while their voice comes through, and the ping;
- your microphone's state.
- **Edge arrow:** when your friend is off screen, an arrow at the edge points to them, with the
distance.
- **Everything is shared:** the shed, the pouch, upgrades, structures, and the vacation itself.
Either player can gather, build, repair, buy upgrades, and start the day.
- **Health is your own.** Upgrades to max health apply to both scarecrows.
- **A scarecrow at 0 HP is out until the morning.** It lies there and the camera follows the
other one. It comes back each morning at half health. **Game Over only when both are down at
once.**
- **Enemies go for the nearer scarecrow.** Animals follow whoever picked them up.
- **The host's game is the real one and it saves** (the partner's doesn't). Retry, starting the
night early, and the end screens work from either side; only the host can restart the night
from the pause menu.
- **Menus don't pause co-op.** Your scarecrow stands still while your menu is up.
- **Leaving:**
- If the partner leaves, the host plays on alone.
- If the host leaves, the partner is back at the main menu, which says why.
- A co-op save continued alone plays by the solo rules.
## How it works
The host's farm simulates everything: both scarecrows, every enemy, the loot, the animals, and the
campaign. The partner's farm is a replica (`FarmSim.replica`). It simulates nothing and shows what
the host sends, except the partner's own scarecrow. The partner moves that scarecrow itself, so
moving never waits on the network, and sends its position, facing, and buttons to the host, where
it acts.
| Piece | File | Does |
|---|---|---|
| `CoopSession` | `game/scripts/coop_session.gd` | The protocol, on both sides: the welcome, snapshots (the clock, both scarecrows with the weapon in hand and the bomb's recharge, animals, enemies in 16-byte records, shots) 20 times a second, the farm state and the loot when they change, news in order (phase changes, the end, sounds, toasts, loot news, breaches, fear bursts, attacks, pumpkin bombs thrown, gather popups), and the partner's input (with its pick of weapon) and requests. The partner's own weapons only aim and show their motion: the host attacks for it, so nothing is hit twice |
| `CoopLink`, `GDSyncLink` | `coop_link.gd`, `gdsync_link.gd` | The wire: GD-Sync remote calls, reliable or not; a loopback pair for tests |
| `CoopLobby` | `coop_lobby.gd` | GD-Sync's LAN and online modes, lobbies, join by address |
| `RemoteControls` | `remote_controls.gd` | The partner's buttons as the host sees them: held state, press counts (a lost packet never loses a press), aim, build mode, menus |
| `Avatar` | `avatar.gd` | One scarecrow and its kit, weapons, and hands; `FarmSim.avatars` holds both |
| `CoopVoice` | `coop_voice.gd` | GD-Sync's `VoiceChat`, one per player, owned by that player |
| `CoopHud`, `CoopMenu` | `coop_hud.gd`, `coop_menu.gd` | The partner panel and arrow; the menu |
Messages that may be lost (snapshots, input) stay under 1,100 bytes. GD-Sync splits datagrams at
1,200. Nothing depends on any one of them arriving: an enemy missed by a snapshot appears in the
next, and removals are reliable.
Measured on the loopback test with 90 enemies and a third of the snapshots dropped: about 31 KB/s
from the host and 10 KB/s from the partner, with the largest message under the limit. That's
nothing on a LAN. Online, check it against your GD-Sync plan's data allowance.
## Testing
- **`game/tests/test_coop.gd`** (in the main suite) runs host and partner in one process: the
partner's farm sits in its own world, over the loopback link. It covers the join, requests,
the partner moving, gathering, and shooting (and its pick of weapon), the host's stabs and
pumpkin bombs drawn on the partner's farm (harmless there), enemies, loot, and shots arriving, the fall rule
and Retry, a crowd with dropped packets, message sizes, and either side leaving.
- **`game/tools/coop_smoke.gd`** plays a real GD-Sync LAN game between two processes on one
machine. The partner joins by address, since broadcasts don't loop back on every machine;
`--discover` uses the network announcements instead. `--online` plays through GD-Sync's
servers (needs the keys): the partner finds the host's lobby in the online list. Give both
sides the same `--host-name`, so an old lobby from an earlier run isn't picked by mistake.
```sh
godot --headless --path . --script res://game/tools/coop_smoke.gd -- --role=host &
godot --headless --path . --script res://game/tools/coop_smoke.gd -- --role=join
# online:
godot --headless --path . --script res://game/tools/coop_smoke.gd -- --role=host --online --host-name=Smoke1 &
godot --headless --path . --script res://game/tools/coop_smoke.gd -- --role=join --online --host-name=Smoke1
```
**Online, tested (2026-10-04):** both sides passed. The partner found and joined the lobby in
about 2 s, and played the day and the night with 24 enemies.
**Not tested here:** discovery between two machines (this one's firewall drops broadcasts),
online play between two machines on different networks, and voice with real microphones
(headless has none).
## Patches to GD-Sync
Four small patches, each marked `Harvest Season patch` in the code. Re-apply them after updating
the plugin.
| File | Patch | Why |
|---|---|---|
| `Scripts/ConnectionController.gd` | LAN client ids fit in 30 bits | Targeted calls carry the id in 30 bits (`RequestProcessor.encode_target_client`). A random 32-bit LAN id got cut off, and calls to that player reached nobody. |
| `Scripts/RequestProcessor.gd` | A fixed HMAC key in LAN mode | Without API keys the key is empty, and Godot logs an error for every unreliable packet |
| `Scripts/SessionController.gd`, `Scripts/Types/NodeInstantiator.gd` | Null checks for the current scene | Tests and tools run without one (`--script`) |
| `Scripts/Logger.gd` | Only talk to the debugger when one is attached | Same |

View file

@ -7,11 +7,15 @@ The playable farm built in Step 2 of `first-game-plan.md`. All numbers here are
- **Playable area: 60 × 60 m**, x −13…47 and z −45…15 (`FarmZones.playable`). The rest of the
old farm is out-of-bounds scenery.
- **Perimeter:** a wooden fence (`fence_005`, 101 segments) with **6 gaps**. Ground enemies enter
and escape through the gaps. Crows (Step 9) fly over the fence.
- **Scarecrow bounds:** invisible walls on the fence lines (`Zones/Perimeter/PlayerBounds`, physics
layer 3 `player_bounds`). Only the scarecrow collides with them (its mask is 1 + 3), so the
scarecrow can step into a gap but not leave the farm. Enemy navigation ignores them.
- **Perimeter:** what's left of the wooden fence (`fence_005`, 52 segments): the north side and
the east side, with **3 gaps**. The south side and most of the west side were taken out, so the
farm is open ground there.
- **The farm's edge** is where enemies come from and go: every enemy arrives at its own random
point along it, and carriers escape across it (see "The farm's edge" below).
- **Scarecrow bounds:** invisible walls on the old farm's outer fences (`Zones/Perimeter/PlayerBounds`,
physics layer 3 `player_bounds`). Only the scarecrow collides with them (its mask is 1 + 3). It
walks off the farm to the gathering areas outside (see "Outside the fence" below), but not off
the map. Enemy navigation ignores them.
- **Scarecrow start:** (3, −13), between the barn apron and the animal pen.
Top-down picture with zone outlines:
@ -30,13 +34,49 @@ name when the scarecrow walks in.
| Zone | Rectangle (x, z) | What's there | Purpose |
|---|---|---|---|
| Crop Field | 14…46, −18.6…11.4 | The sunflower field: 6 plots, 30 crop units, two 2 m walkways between the plot bands | Exposed asset; crows' target |
| Supply Shed | −6…8, −24…−14 | The red barn's south doors and the apron in front of them, with stock piles: crates and sacks (west of the doors), logs, hay, and barrels (east of the doors) | Stored materials; ground thieves' target (Step 8) |
| Supply Shed | −6…8, −24…−14 | The red barn's south doors and the apron in front of them, with stock piles that grow and shrink with the stock (`ShedStock`): crates for scrap (west of the doors), logs for wood and hay bales for straw (east of the doors); also sacks and barrels | Stored materials; supply thieves' target |
| Work Area | 8…14, −24…−15 | Tool table, workbench, chair, bucket, between the barn and the house | Crafting, repairs, and upgrades |
| Animal Pen | −10…4, −11…−1 | Brown paddock fence, gate opening on the east side (panel swung open), henhouse, 4 chickens, 2 pigs, 2 sheep | Livestock (Step 8). Enemies can only reach the inside through the gate |
| Animal Pen | −10…4, −11…−1 | Brown paddock fence, a gate in the opening on the east side (a gate structure, standing from the start), henhouse, 4 chickens, 2 pigs, 2 sheep | Livestock; animal thieves' target. Enemies can only reach the inside by breaking the gate |
| Woodlot | 37.5…46.5, −35…−21 | The fir tree line, dead trees and branches, log piles | Wood |
| Scrap Heap | 25.5…36.5, −44…−33 | Old pickup, wagon, wheelbarrow, lawn mower, barrels, crate, on the farmyard dirt | Scrap |
| Haystacks | 14…22, −44…−35 | The old hay stack (moved in from beyond the north fence) and 3 round bales | Straw |
### The shed's stock piles (Step 8)
`ShedStock` (`game/scripts/shed_stock.gd`) takes over some of the shed zone's props and adds more
next to them. One prop shows per few units stored:
| Pile | Props | Units per prop | Thieves' spot |
|---|---|---|---|
| Wood | 7 log stacks east of the doors (2 from the scene) | 4 | (2.6, −18.6), beside the doors |
| Scrap | 10 crates and barrels west of the doors and along the barn wall (4 from the scene) | 3 | (−3.0, −15.1), in front |
| Straw | 6 hay bales east of the doors (1 from the scene) | 4 | (6.75, −16.25), in front |
Every prop collides and is in place when the navigation is built, so enemies always route around
a pile's full footprint. A hidden prop stops colliding for the scarecrow and shots. Each spot has
its own flow field, so a supply thief goes to the pile it wants even when another is nearer.
### Gather points and the workbench (Step 5)
Each point is a `GatherNode` under its zone, holding the props it is made of.
| Zone | Point | Props | Charges | Gathering clip |
|---|---|---|---|---|
| Woodlot | DeadTree, Snag | dead trees | 2 each | Chopping |
| Woodlot | Deadfall | big dead tree | 3 | Chopping |
| Woodlot | LogPile | stump with logs | 2 | PickUp |
| Scrap Heap | Wreck | old pickup | 3 | Hammering |
| Scrap Heap | Wagon | wagon | 2 | Hammering |
| Scrap Heap | Mower | lawn mower | 2 | PickUp |
| Scrap Heap | OldBarrels | two barrels | 2 | PickUp |
| Haystacks | Haystack | the 12-bale stack | 4 | PickUp |
| Haystacks | BaleA, BaleB, BaleC | round bales | 2 each | PickUp |
- Every point yields 2 per charge and grows back fully overnight.
- `Workbench` (the work area's tool table) sells Straw Stuffing.
- `test_economy` checks that the scarecrow's body can stand within reach of every point and the
workbench.
The middle and south-west of the map (x −13…14, z −1…15) are deliberately open ground for
building defenses.
@ -54,22 +94,29 @@ visible.
| Middle band (z −6.5…0.4) | Plot 3: units 11–15 | Plot 4: units 16–20 |
| South band (z 2.4…9.4) | Plot 5: units 21–25 | Plot 6: units 26–30 |
## Perimeter gaps and approach directions
## The farm's edge and the fence's gaps
Each gap is 3 m wide (the driveway is 4 m) and marked inside by a signpost. A `FarmMarker` (kind
GAP) sits 3 m outside each gap, where ground enemies spawn and escape.
**Arrivals.** Every enemy arrives at its own random point along the farm's edge
(`FarmZones.edge`, `WaveDirector`), not at fixed gates:
- On foot: 3 m outside the map (`GameConfig.spawn_margin`), at any free navigation cell along that
line that has a route onto the farm (`WaveDirector.ground_spawns`, nearly all of it). The same
line is where carriers escape and loose animals are lost.
- Crows: 8 m outside the map (`flyer_spawn_margin`), anywhere along it. They leave straight out
the nearest side.
**The gaps** in what's left of the fence are each 3 m wide (the driveway is 4 m) and marked inside
by a signpost. A `FarmMarker` sits 3 m outside each one. Enemies arriving behind the fence walk in
through them (or around the fence's ends); nothing can be built in them, so the scarecrow can
always walk out to the gathering areas.
| Gap | Fence side, position | Leads to |
|---|---|---|
| GapNorth | north, x 10.5…13.5 | Haystacks, work area, barn apron |
| GapDriveway | east, z −41.5…−37.5 (the farm road) | Scrap heap and farmyard. The farmers' truck uses it in the ending (Step 11) |
| GapDriveway | east, z −41.5…−37.5 (the farm road) | Scrap heap and farmyard. The farmers' car comes in here in the ending (Step 11) |
| GapEast | east, z −20…−17 | Woodlot and the crop field's north-east corner |
| GapSouthEast | south, x 29.5…32.5 | Crop field, south side |
| GapSouthWest | south, x −5.5…−2.5 | Open south-west ground, pen (south side) |
| GapWest | west, z −7.5…−4.5 | Pen's west fence: enemies must go round it to the gate |
Crow approach markers (kind CROW, about 8 m outside the fence): CrowNorth (17, −53),
CrowEast (55, −5), CrowSouth (17, 23), CrowWest (−21, −15).
The signposts of the three gaps that were in the removed south and west fence (SignSouthEast,
SignSouthWest, SignWest) still stand.
## Travel times
@ -80,29 +127,31 @@ routes to it go through the gate.
| From \ to | Crop Field | Supply Shed | Work Area | Animal Pen | Woodlot | Scrap Heap | Haystacks |
|---|---|---|---|---|---|---|---|
| **Crop Field** | — | 7.2 s | 5.4 s | 6.8 s | 5.9 s | 7.3 s | 8.0 s |
| **Supply Shed** | 7.2 s | — | 2.8 s | 4.7 s | 9.7 s | 9.1 s | 8.3 s |
| **Work Area** | 5.4 s | 2.8 s | — | 4.8 s | 7.1 s | 6.6 s | 5.7 s |
| **Animal Pen** | 6.8 s | 4.7 s | 4.8 s | — | 10.8 s | 11.0 s | 10.4 s |
| **Supply Shed** | 7.2 s | — | 2.8 s | 4.3 s | 9.7 s | 9.1 s | 8.3 s |
| **Work Area** | 5.4 s | 2.8 s | — | 4.7 s | 7.1 s | 6.6 s | 5.7 s |
| **Animal Pen** | 6.8 s | 4.3 s | 4.7 s | — | 10.8 s | 11.0 s | 10.3 s |
| **Woodlot** | 5.9 s | 9.7 s | 7.1 s | 10.8 s | — | 3.5 s | 5.3 s |
| **Scrap Heap** | 7.3 s | 9.1 s | 6.6 s | 11.0 s | 3.5 s | — | 2.3 s |
| **Haystacks** | 8.0 s | 8.3 s | 5.7 s | 10.4 s | 5.3 s | 2.3 s | — |
| **Haystacks** | 8.0 s | 8.3 s | 5.7 s | 10.3 s | 5.3 s | 2.3 s | — |
The longest trip is 11.0 s (Animal Pen ↔ Scrap Heap). The rule is no key area more than 12 s from
another. The two defended fronts sit 6–7 s apart: the crop field in the south-east, and the pen
and shed in the west. Holding one leaves the other exposed. The gathering spots are in the north,
so a day of gathering pulls the scarecrow away from both fronts.
Ground-enemy path from each gap to the nearest edge of each zone, in meters (enemy radius 0.35 m):
Ground-enemy path from the middle of each side of the farm's edge (3 m out) to the nearest edge of
each zone, in meters (enemy radius 0.35 m). Enemies arrive anywhere along the edge, so these are
samples, not routes everyone takes; arriving behind the north fence means walking round to a gap.
| Zone | North | Driveway | East | South-east | South-west | West |
|---|---|---|---|---|---|---|
| Crop Field | 30 | 23 | 4 | 7 | 24 | 34 |
| Supply Shed | 26 | 49 | 43 | 42 | 36 | 16 |
| Work Area | 24 | 46 | 37 | 40 | 38 | 30 |
| Animal Pen (inside) | 46 | 63 | 51 | 39 | 28 | 32 |
| Woodlot | 39 | 10 | 7 | 42 | 60 | 62 |
| Scrap Heap | 26 | 14 | 24 | 52 | 63 | 56 |
| Haystacks | 6 | 32 | 35 | 57 | 62 | 49 |
| Zone | North | East | South | West |
|---|---|---|---|---|
| Crop Field | 35 | 6 | 7 | 30 |
| Supply Shed | 31 | 45 | 36 | 10 |
| Work Area | 29 | 39 | 35 | 24 |
| Animal Pen (inside) | 51 | 53 | 30 | 28 |
| Woodlot | 44 | 9 | 48 | 56 |
| Scrap Heap | 30 | 26 | 55 | 50 |
| Haystacks | 11 | 37 | 55 | 43 |
## Navigation
@ -113,10 +162,10 @@ Ground-enemy path from each gap to the nearest edge of each zone, in meters (ene
- Obstacles are inflated by the mover's radius.
- Distance fields use octile Dijkstra with no corner cutting.
For enemies: the playable area plus a 5 m margin is 20,164 cells. 423 shapes are rasterized, and
For enemies: the playable area plus a 5 m margin is 20,164 cells. 390 shapes are rasterized, and
the grid builds in about 25 ms (headless, editor binary). Because the grid comes from the same
collision the player walks against, physics and navigation can't drift apart. Step 3 adds flow
fields toward the crop plots and the gaps on top of it.
fields toward the crop plots and the farm's edge on top of it.
## What changed from the old farm
@ -128,9 +177,10 @@ fields toward the crop plots and the gaps on top of it.
- **Moved:** the hay stack from beyond the north fence into the farmyard (Haystacks).
- **Collision:**
- `build_prop_collision.gd` generated collision for the newly placed prop types.
- Animals get none (they become moving entities in Step 8).
- The open gate (`fence_018`) has a hand-made thin box along its panel, so the pen opening stays
clear.
- Animals get none: they are moving entities (`AnimalSystem`).
- Step 8 removed the pen's propped-open gate panel (`fence_018`). The opening is shut by a
gate structure instead: `GameConfig.start_structures` puts it at (4, −6), turned to run north
to south. It can be broken, repaired, or rebuilt like any gate.
- **Rendering cost:**
| View | Draw calls before | Draw calls after |
@ -149,3 +199,41 @@ fields toward the crop plots and the gaps on top of it.
- Run `godot --headless --path . --script res://game/tests/run_tests.gd -- --suite=test_farm_layout`
to check the result: zones, fence integrity, reachability, and travel times. It prints the
tables above.
## The farmers' return (Step 11)
`FarmersReturn` (`game/scripts/farmers_return.gd`) uses fixed points on this map:
- **The car's route:** the station wagon (`car_002`) comes north up the road east of the fence
(x 52), turns in at GapDriveway (z ≈ −39.5), and runs west along the yard road. It turns south
past the wagon and parks at (32.8, −29.5), facing south.
- **The farmers:** they get out on both sides of the car and walk to the porch steps on the
house's north side (the house is x 15.8…25.2, z −29.6…−21.3; the steps are at about (19.6, −29.8)).
They stop at (18.9, −31.4) and (20.5, −31.5).
- **The scarecrow** waits at (24.6, −34.0), beside their way.
- **The yard shot** looks south at the porch from (28, 10, −45.5).
- **What to avoid:** the tractor parked east of the house (about (30, −25)) hides anything at the
house's east side from the south-east.
## Outside the fence
The scarecrow can leave through the fence's gaps or across the open south and west sides. The invisible walls (`Zones/Perimeter/PlayerBounds`)
now stand on the old farm's outer fences, not on the farm's own fence: x −27.6…54.8, z −59.6…47
(`FarmZones.roam`). Building, the enemies' navigation grid, and the night stay inside the fence
(`FarmZones.playable`).
Four outside zones (`FarmZone.outside`) hold more to gather. Every point there yields 3 per charge.
| Zone | Rectangle center, size | Points | Nearest gaps |
|---|---|---|---|
| North Grove (wood) | (12, −52), 16 × 12 | GroveDeadTree, GroveSnag, GroveDeadfall (dead trees, 3 charges), GroveLogs (log pile, 3) | GapNorth |
| Old Hangar (scrap) | (38, −53), 18 × 13 | HangarWreck (old SUV, 4), HangarBarrels (3), HangarCart (3) | GapNorth, GapDriveway |
| East Road (scrap) | (51.5, −15), 6 × 14 | RoadsideCar (the abandoned red car, moved in from `Level/`, 4), RoadsideBarrels (3) | GapEast |
| South Fields (straw) | (9.5, 31), 66 × 30 | FieldStackWest, FieldStackEast (4-bale stacks, 4), FieldBaleWest, FieldBaleEast (round bales, 3) | none: the south side is open |
`FarmZones.zone(kind)` only ever returns the farm's own zone, and `zones()` lists only the farm's.
`outside_zones()` lists these, and `zone_at()` finds both (the zone banner says "North Grove
(outside the fence)").
**Placing outside points:** the North Grove sits east of the tall barn on purpose. Behind the barn
(x < 9), the game camera can't see the scarecrow. The semi-trucks west of the farm are beyond the
old west fence (x ≈ −28.5), so they're out of reach.

362
game/PLAYTEST.md Normal file
View file

@ -0,0 +1,362 @@
# Harvest Season — playtest notes
Running notes on how the game plays, starting at Step 7 (the first complete day and night).
Scripted runs come from `game/tools/soak_night.gd`. Its scarecrow aims perfectly and never
hesitates, so real players will do worse at night and differently by day. Human playtest
findings go in the last section.
## Step 7: the first complete cycle (2026-10-03)
Every night currently plays night 1's plan, "Crop thieves": 9 thieves over the 150 s night, in
pairs and singles, through the east, south-east, north, and south-west gaps. Step 10 gives each
night its own plan.
### Full cycles
```sh
godot --headless --path . --script res://game/tools/soak_night.gd -- --mode=cycle --cycles=4 [--build=0] [--guard=0]
```
- **By day** the scripted scarecrow gathers until 115 s, storing at the shed, then builds this
plan in order, as far as it can afford: 2 automated defenses at the east and south-east gaps, 2
slowing traps, a third automated defense, 6 fences down the field's east side, and a fourth
automated defense.
- **At night** it guards (`--mode=guard`), or with `--guard=0` stands aside.
| Scarecrow at night | Defenses | Crops lost, nights 1-3 | Notes |
|---|---|---|---|
| away | none | 9, 9, 9 (3 left after night 3) | Every thief gets away with a crop. The farm is stripped on night 4. |
| guarding | none | 1, 0, 0 | One crop lost on night 1 |
| away | built | 0, 0, 0 | 1 crop stolen and dropped on night 1. The automated defenses cover the gaps the plan uses. |
| guarding | built | 0, 0, 0, 0 (4 nights) | |
Carry-over checks passed in every run: structures only go down by breaks overnight, wood and
scrap don't change overnight, and the scarecrow's health and the losses persist.
### A day of gathering
- Gathering everything takes about **106 s** of the 180 s day: 18 wood, 18 scrap, 20 straw, in 4
trips to the shed.
- That leaves about 70 s, plus the 30 s dusk, for building, repairs, and getting into position.
### What to tune (carry into Steps 10 and 12)
1. **Night 1 alone is not a threat once anything is defended.** A guarding scarecrow, or three
automated defenses, stop all 9 thieves.
- This is the intended difficulty for a first night.
- Nights 2-5 (Step 10) must escalate through new pressures (new targets, fence breakers,
simultaneous gaps), not only bigger numbers.
2. **Materials pile up.**
- By day 4 the shed holds 55 wood, 47 scrap, and 76 straw.
- Straw has almost no use: patches, plus one Straw Stuffing.
- Options: upgrades as a sink (Step 10); lower yields or slower regrowth; costs that rise with
each structure; straw-based buildables.
3. **The automated defense may be too strong for 6 scrap.**
- Placed at a gap the plan uses, it kills most thieves alone (1 shot/s, 7 m, 3 HP thieves).
- Night plans that spread over more gaps, tougher enemies (Step 9), or a scrap price increase
would rein it in.
4. **Thieves don't threaten the scarecrow.** It took no damage in any run. Health and patching
only start to matter with fence breakers (Step 9).
5. **The day may be long once everything is gathered.** The scripted scarecrow is done with
everything at 106 s plus building.
- Check with people whether the rest of the day feels like waiting.
- If it does, turn on `allow_early_night` (D1) or shorten `day_length` (D3).
6. **Dawn is quiet.** Thieves retreat and few remain, so the 20 s grace mostly passes uneventfully.
Shortening it is a Step 12 call.
### For a human playtest
Run the game (F5), play two or three full cycles, and note answers here.
- Is the morning review readable, and does "Start the day" feel natural?
- Does the dusk warning (banner, "Thieves tonight" rings, red arrows, HUD line) land before night
falls?
- Is the night dark but readable (the lantern pool, glowing thieves, markers)? Too dark anywhere?
- Is the day too long, too short, or right? Did you run out of things to do?
- Gathering, storing, building: any control friction (E to gather, B to build, rotate, place,
RMB to dismantle)?
- Night 1: too easy, about right, or too hard, with and without defenses?
- Anything that broke or felt wrong after a night (structures, materials, health)?
Debug keys help: F1 shows the readout, F6 skips a phase, F7 speeds time up 5x / 20x, and T sends
in a thief.
#### Findings
_(none yet)_
## Step 8: all three farm targets (2026-10-03)
Night 1's plan, "Thieves at the farm", now has 11 thieves:
- 7 crop thieves through the east and south-east gaps;
- 2 supply thieves from the north at 40 s;
- an animal thief from the south-west at 60 s, as a crop thief comes in at the east (two fronts);
- an animal thief from the west at 112 s.
### Full cycles
Same tool as Step 7: `--mode=cycle --cycles=4`. By day the scripted scarecrow also puts a gate back
in the pen opening if it's gone. Its build plan now ends with an automated defense by the pen
(7, −3.5) and one by the shed (9.5, −14). At night it guards all three targets and leads loose
animals home.
Losses per night, as crops / animals / supply units:
| Scarecrow at night | Defenses | Night 1 | Nights 2–4 | Left after night 4 |
|---|---|---|---|---|
| away | none | 7 / 6 / 10 (the gate broken; 6 animals wandered out and were lost) | 7 / 2 / 20, 9 / 0 / 10, 7 / 0 / 20 | 0 crops, 0 animals (the shed keeps refilling) |
| guarding | none | 0 / 0 / 0 | 0 / 0 / 0 each | everything |
| away | built | 0 / 6 / 10 (the pen and shed defenses come last in the plan, so not on day 1) | 0 / 0 / 0 each (1 crop stolen and dropped on night 4) | 30 crops, 2 animals |
| guarding | built | 0 / 0 / 0 | 0 / 0 / 0 each | everything |
`test_cycle`, scarecrow away, a fence and one automated defense by the crops: 4 crops lost, 5
animals lost (2 grabbed, 6 wandered out), 10 supplies carried off, the pen's gate broken. Carry-over
checks passed in every run: structures go down only by breaks, wood and scrap only by what was
carried off, and no sack is left in transit.
### What to tune (carry into Steps 10 and 12)
1. **A broken pen gate is the costliest event.** Undefended, the animal thief breaks the gate
(about 18 s), and the pen then empties: 6 of 8 animals wandered out and were lost in one night.
- That's a strong reason to defend the pen. It may be too punishing for night 1.
- Options: a longer `animal_wander_interval`, a slower `stray_speed`, or only the animals near
the breach wandering out.
2. **The scripted guard still loses nothing.** It aims perfectly, and the animal thief's 18 s at the
gate leaves time to deal with the crop thief first. Whether the two-front moment at 60 s forces
a choice is for people to say (the exit gate).
3. **Supply theft is small next to the surplus.** Ten units a night, against 56 gathered a day.
It only starts to matter once materials are tighter (Step 7, item 2).
4. **A farm is hard to strip.** With every crop and animal gone, gathering keeps refilling the
shed, so the vacation goes on (D2 as decided). Check in Step 12 that this feels right, and not
like a pointless last few nights.
5. **Defenses at the pen and shed shut those threats down.** Once those two automated defenses
stand, nothing is lost there (see Step 7, item 3, on the automated defense's strength).
6. **Look:** followers bunch up after a sharp turn, and a carried animal hangs under its thief
and can be hard to see near the screen edge (its badge shows). Placeholders; the visual pass
comes later.
### For a human playtest (add to the Step 7 list)
- Can you tell what each thief is after: the dusk warnings, the beacons, the outlines and badges,
the arrows' rims?
- When the animal thief at the pen and a crop thief arrive together (60 s into the night), do you
have to choose? Which did you pick, and why?
- Is leading animals back to the pen fun or fiddly? Is 3 at a time right?
- Do you notice when the pen is open (the toast, the morning review)? Did you rebuild the gate?
- Do the shed piles read as "how much is stored"?
## Step 9: the first enemy roster (2026-10-03)
Three types (`GameConfig.enemy_types`):
- crows (crops only; fly over fences);
- ground thieves (animals and supplies);
- fence breakers (smash the barriers guarding valuables, then fight the scarecrow).
Night 1 now has 10 crows, 4 thieves, and a breaker at 90 s. Six debug scenarios (F2) introduce
the types one at a time, then pairs, then all three.
### Same attack, different defenses
From `test_structures`, two enemies at a time all night, scarecrow away:
| Attack | Undefended | Fenced | Fenced + automated defenses |
|---|---|---|---|
| Crows on the crops | 15 crops | 15 (nothing broken) | 2 (6 defenses) |
| Thieves after supplies | 40 units | 35 (2 fences broken) | 0 (3 defenses) |
Fences are now an answer to thieves, not crows. For crows it's shooting and automated defenses.
### Full cycles
`--mode=cycle --cycles=4`, losses per night as crops / animals / supply units:
| Scarecrow at night | Defenses | Result |
|---|---|---|
| away | none | **Game over on night 1.** With the pen gate down and nothing left to break, the fence breaker hunts the idle scarecrow down. |
| guarding | none | 1 / 0 / 0 on night 1, then nothing; but the breaker costs it 2–4 HP each night (HP 8, 6, 7, 8 after patching) |
| away | built | 7 / 6 / 10 on night 1 (the pen and shed defenses come last in the plan), then 0–4 crops (to crows) and 0–1 animals a night. The breaker brings the idle scarecrow to 2 HP by night 4. |
| guarding | built | nothing lost in 4 nights; 8 of 10 HP |
`test_cycle`, scarecrow away, a fence and one automated defense by the crops:
- 10 crops lost to crows;
- 4 animals lost (2 grabbed, 6 wandered out after the breaker and a thief broke the pen's gate);
- 10 supplies carried off.
### What to tune (carry into Steps 10 and 12)
1. **The fence breaker can end a run by itself.** At 2 HP per hit it kills an idle scarecrow in
about 7 s. A player who shoots it from range (6 shots, about 1 s of fire) is fine.
- Check with people whether "turns on you within 4 m" reads, or whether it feels unfair when a
breaker walks up from off screen.
- Its hunt is announced by no alert yet.
- Options: a lower `damage`, a shorter hunt, or a "Fence breaker coming for you!" alert.
2. **Crows are now the only crop threat, and fast.** At 5.5 m/s with a 2 s steal they're in and
out in under 10 s. Against a perfect-aim bot they're harmless; people will lose more. The
automated defense handles them well (2 lost with 6), so crop defense may become "build
turrets" (see Step 7, item 3).
3. **Fences around the crops are pointless now.** That's by design: the field is defended by
shooting, the pen and shed by fences. The build HUD doesn't say so yet.
4. **Two-front pressure.** At 60–62 s an animal thief arrives at the pen as three crows reach the
field. The scripted guard still copes. This is the playtest's main question.
5. **Alerts.**
- Up to 5 labeled arrows. Check they help rather than clutter.
- Grouping by zone means two crows escaping from different zones show as two arrows.
- Escape alerts escalate as the carrier nears its exit.
6. **Look:** dark-tinted and rust-red mannequins and a primitive club are placeholders (the visual
pass comes later). At night the overlay makes them pale purple; readable, but not pretty.
### For a human playtest (add to the earlier lists)
- Use F2 to try each scenario, one type at a time, then the pairs and all three. Does each type
ask for something different (shoot crows, fence or trap thieves, kill breakers early)?
- When a breaker turns on you, can you see it coming? Is it fair?
- Do the alert arrows tell you where to go and what's most urgent? Too many, too few?
- In "All three", which threat did you deal with first, and why?
## Step 10: the five-night progression (2026-10-03)
The five nights:
1. Crows at the crops: 12 crows.
2. Thieves in the yard: 11 crows, 5 thieves.
3. Breakers at the fences: 2 breakers, 5 thieves, 6 crows.
4. From both sides: three opposite-sides moments, 19 enemies.
5. The last night: three waves, 23 enemies, 180 s.
Eight upgrades are on sale at the workbench (176 materials in all, 58 of them scrap).
### The whole vacation, scripted
`--mode=cycle --cycles=5`. Crops lost per night (animals and supplies lost were 0 unless noted):
| Scarecrow | Builds | Upgrades | Night 1 | 2 | 3 | 4 | 5 | Left at the end | Scarecrow HP at the end |
|---|---|---|---|---|---|---|---|---|---|
| guarding | plan | yes (0, 2, 3, 5, 6 owned) | 0 | 0 | 0 | 1 | 1 | 28 crops, 8 animals | 11 of 12 |
| guarding | plan | no | 0 | 0 | 0 | 2 | 0 | 28 crops, 8 animals | 10 of 10 |
| guarding | nothing | no | 1 | 1 | 0 | 3 (and 5 supplies taken, all recovered) | 3 | 22 crops, 8 animals | 7 of 10 |
| away | plan | yes | 7 | 3 (and 10 supplies lost) | 1 | 2 | 0 | 17 crops, 8 animals | 12 of 12 |
| away | nothing | no | 12 | 11, plus all 8 animals and 15 supplies | Game over: the breaker kills the idle scarecrow | | | | |
Carry-over checks passed in every run. Unspent materials keep piling up without building or
upgrades: 94 wood, 92 scrap, and 104 straw after five days of guarding only. With the build plan
and upgrades, little is left (22 wood, 4 scrap, 50 straw).
### What to tune (carry into Step 12)
1. **Upgrades now compete with building**, so a run makes choices. The scripted player got 6 of
8, and scrap is the bottleneck. Straw still piles up (50 left), so it could buy more.
2. **The nights don't get much harder for a good defense.** With the build plan, nights 4 and 5
cost 1–2 crops. The scripted guard is perfect, so people will feel it more. Check with people
whether night 5 feels like a finale.
3. **An undefended farm falls apart on night 2** (all animals and most crops), then the breaker
kills a scarecrow that doesn't fight back. A real player always fights back; the question is
how far behind a weak night 1 leaves you (Step 12, "recover after a bad night").
4. **The day is the same every day.** Gathering takes about 106 s of the 180 s. With upgrades to
buy, there's more to do with the rest of the day, but the build phase hasn't changed.
### For a human playtest (add to the earlier lists)
- Play all five nights. Does each night feel different from the one before?
- Did the dusk hint (under the banner) tell you what you needed? Did you prepare differently for
night 3's breakers or night 4's two fronts?
- Which upgrades did you buy, in what order, and did any feel useless?
- Did you run short of anything? Of scrap?
- Did the last night feel like a finale, and was it fair (announced, no surprises)?
## Step 11: the complete campaign experience (2026-10-03)
What's checked without a person (`test_save`, `test_flow`, screenshots):
- The title screen shows over the paused farm.
- New vacation, Continue, and their questions work, and a damaged save is refused with the reason.
- Pausing freezes the tick.
- Settings apply and persist.
- Restart the night, and Save & quit, leave the save untouched.
- The failure screen leads to Retry.
- The farmers' return plays (about 21 s, skippable) into the final assessment.
- The first-day tips show in order.
- Every sound cue has its sounds and bus, and the game's events play them.
The scripted five-night run of the assessment screen: 27 of 30 crops, 7 of 8 animals, and 95% of
supplies kept rate "Bumper crop, 90 points".
**Not checked by ear.** Every cue was chosen from file names and a pitch analysis, and the
synthesized sounds were checked as waveforms only.
### The hallway test (the exit gate)
Give the game to someone who hasn't seen it. Start from the title screen. Don't explain
anything; note where they stall.
- Do they start a vacation and understand the first morning screen?
- Do they follow the tips through day 1 (move, gather, store, build) and night 1 (shoot, fear,
recover)? Which tip was unclear or came at the wrong time? Did anyone hide them?
- Can they find pause (Escape / Start), quit to the menu, and Continue? Is it clear they come
back to the morning, not where they left off?
- Do they read the morning results? Which line do they look at first?
- On a Game Over, is the cause clear, and do they press Retry?
- Do they reach the farmers' return? Does the assessment make sense: points, rating, bars?
- **Sound:** is anything too loud, annoying, or wrong for what happened? Do the crow caws and
alarms help them find threats? Note any cue to swap (`FarmAudio.CUES`).
- **Settings:** do the volume sliders work as expected? Are the stick dead zones fine on a real
gamepad?
### Feedback after Step 10, for the scale pass
From the user (2026-10-03): the game is "extraordinarily easy". There are too few enemies, they
come too spread out, and the game feels slow. The vacation should grow from 5 days to 30, with
the scale following. That rework comes next, before or as part of Step 12. Step 11's screens
read the night count from `GameConfig.campaign_nights` (range now 1–60): the menus, results,
saves, and ending aren't tied to five nights. The night plans are still a list of five files in
`FarmSim.NIGHT_PLANS`, and the last one repeats for any nights after it.
## After Step 11: 5x enemies, outside gathering, co-op, music (2026-10-03)
**Five times the enemies.** Every night plan plays at 5 times its groups' size, 2.5 times as often
(`GameConfig.wave_count_scale`, `wave_spacing_scale`). Up to 160 enemies on the farm, 68 of them
on foot. Measured:
- **Night 5 unguarded:** 27 enemies on the farm at the peak (17 on foot). `FarmSim.step` takes
0.45 ms on average, 4.4 ms at worst. The farm was stripped about 90 s into the night.
- **The scripted player** (perfect aim, the build plan, upgrades; `--mode=cycle --cycles=5`): it
lost 1, 1, and 0 crops on nights 1–3, but its health ran down (7 of 12 after night 3), and it
fell on night 4.
- **No guard, defenses only** (`test_nights`): 10 crops on night 1; all 8 animals on night 2;
14 crops and 60 supplies on night 3; 90 supplies on nights 4 and 5.
**For the playtest:** is 5x the right amount, solo and in co-op? The two numbers above are the
dials. Does one scarecrow need more health, or the dusk warning more time, at this pressure?
**Outside the fence.** Four gathering areas: the North Grove, the Old Hangar, the East Road, and
the South Fields (`game/LAYOUT.md`). Every point there yields 3 per charge.
- **For the playtest:** is the walk worth it? Does anyone get caught outside at dusk?
**Co-op** (`game/COOP.md`):
- **Tested:** in one process (test_coop, 36 checks), and over real GD-Sync LAN between two
processes on this machine, joining by address (coop_smoke: the join, moves, shots, 24 enemies,
leaving).
- **Not tested:** two machines on a real network, online play (needs the API keys), and voice
with real microphones.
- **For the playtest:** does the partner's scarecrow feel responsive? Does anything look
different on the two screens: enemies, loot, the morning screen, the ending?
**Music:** "On the Farm" on the title screen, in the morning, and by day; "Purgatory" at night;
only ambience at dusk and dawn.
## A smaller first night (2026-10-04)
With the scarecrow starting on the pitchfork alone, night 1 at 7x (84 crows, one every 0.6–0.9 s)
was overwhelming. The scripted guard, with no builds or upgrades, lost 28 of 30 crops. Night 1 now plays its plan
unscaled (`NightPlan.count_scale` / `spacing_scale` 1). It sends 11 crows:
- single crows at 6 s and 22 s;
- pairs at 40 s and 62 s;
- three at 86 s;
- a last pair at 115 s.
Nights 2–5 still use the config's 7x / 0.3. `--mode=cycle --cycles=1 --build=0 --upgrades=0`:
| Scarecrow | Crops lost on night 1 |
|---|---|
| guarding, pitchfork only | 1, 2, 1 (seeds 1–3) |
| away | 11 (every crow got one) |
**For the playtest:**
- Is night 1 now a fair place to learn the stab, or too quiet over 150 s?
- Night 2 is the cliff: 112 enemies, about ten times night 1. Does it need its own scale too, given
the corn shooter costs 10 scrap and 4 wood from day 2?

View file

@ -5,8 +5,16 @@ The rule set every other system follows. Decision numbers (D1–D10) refer to
`res://game/resources/game_config.tres` (`GameConfig`) and gets tuned during balancing.
Enforced in code: phases, timers, outcomes, loss records, and the retry snapshot
(`CampaignController`, `FarmState`). Theft, combat, and building rules are written here first,
and later steps implement them as shown in the last column of each table.
(`CampaignController`, `FarmState`); theft and recovery of crops, animals, and supplies, the
sunrise retreat, and the end of the dawn grace (`FarmSim`, `ThiefBehavior`, `LootSystem`,
`AnimalSystem`, `ShedStock`; Steps 3 and 8); the scarecrow, gathering, and building (Steps 4–6);
the night plans, dusk warnings, morning review, and lighting (Step 7: `WaveDirector`,
`ReviewPanel`, `PhaseHud`, `DayNight`); the enemy roster and the alerts (Step 9: `EnemySystem`,
`ThiefBehavior`, `EnemyCharacters`, `AlertManager`); the five nights and the upgrades (Step 10:
`NightPlan`, `Upgrades`, `UpgradePanel`); the menus, saving, settings, results, endings, tips, and
sound (Step 11: `Main`, `SaveGame`, `GameSettings`, `ReviewPanel`, `EndPanel`, `Assessment`,
`FarmersReturn`, `Tutorial`, `FarmAudio`). Rules for later steps are written here first and
marked with the step that implements them.
## The vacation
@ -20,11 +28,53 @@ and later steps implement them as shown in the last column of each table.
| Phase | Length | What happens | Enforced |
|---|---|---|---|
| Morning | Untimed | Review last night's losses and damage. The day starts when the player dismisses the review. | Now |
| Morning | Untimed | The morning screen: last night's results (taken, recovered, and lost per category; enemies defeated; damage; materials gathered and spent); what's left; what needs repair (and whether the pen is open); materials; tonight. Autosaved. The day starts when the player presses "Start the day". | Now |
| Day | 180 s | Safe. Gather, build, repair, upgrade. | Now (timer) |
| Dusk | 30 s | Still safe. Warning of the coming attack; last chance to prepare. | Now (timer) |
| Night | 150 s | Enemies attack to steal farm assets or damage defenses. | Now (timer), enemies in Step 3 |
| Dawn | 20 s | Sunrise: no more enemies arrive and all of them retreat (D4). Carriers can still be stopped. Then remaining enemies leave and the night's losses are recorded. | Now (timer and record), retreat in Step 7 |
| Dusk | 30 s | Still safe. The banner names tonight ("Dusk: Breakers at the fences"), with tonight's hint under it. The phase HUD lists what tonight brings ("Tonight, from every side: crows and supply thieves"), not where: they arrive anywhere along the farm's edge. Nothing is marked on the farm itself. Last chance to prepare. | Now |
| Night | 150 s (the last night 180 s) | Enemies attack to steal farm assets or damage defenses. They arrive as the night's plan says (below). The HUD list and the hint stay up for the first 12 s of the night. | Now |
| Dawn | 20 s | Sunrise: no more enemies arrive and all of them retreat (D4). Carriers can still be stopped. Then remaining enemies leave, any still carrying loot take it with them (lost), and the night's losses are recorded. | Now |
**Night plans.** Each night has a plan (`NightPlan`, `game/resources/nights/`). A plan is a list of
groups of enemies. Each group has:
- an arrival time into the night, a count, and the spacing between them;
- the enemy type: thief, crow, or fence breaker (below);
- what they're after: crops, animals, supplies, or any of the type's targets.
**Where they arrive** isn't planned: every enemy comes in at its own random point along the farm's
edge, so a group spreads out all around the farm instead of filing in through one spot. Enemies on
foot arrive 3 m outside the map (`GameConfig.spawn_margin`), anywhere with a route onto the farm;
crows arrive 8 m out (`flyer_spawn_margin`). The south and west sides are open ground; on the north
and east, what's left of the old perimeter fence still stands, so enemies arriving behind it walk
in through its gaps (or around its ends).
A plan also has a title, a dusk hint, and optionally its own night length and scales (below).
Nothing arrives by day, at dusk, or after sunrise.
**The five nights** (Step 10). Each one tests something new. The plans are the nights' designs.
From night 2 on, every group plays at **7 times its size, about 3.3 times as often**
(`GameConfig.wave_count_scale` 7, `wave_spacing_scale` 0.3): each group's enemies come in a
stream twice as long, and the quiet stretches between groups are short. **Night 1 plays as
designed** (its plan's own `count_scale` and `spacing_scale` are 1): with only the pitchfork, it
is a few crows at a time to learn the stab on. The counts below are as played:
| Night | Title | What it tests | Who comes |
|---|---|---|---|
| 1 | Crows at the crops | Intercepting crop thieves | 11 crows: one at a time at first, then pairs, a group of three at 86 s |
| 2 | Thieves in the yard | Protecting a second target | 77 crows, plus 35 thieves after the shed and the pen |
| 3 | Breakers at the fences | Responding to damage and breaches | 14 fence breakers with 35 thieves behind them, 42 crows |
| 4 | From both sides | Dividing attention | 3 moments when two groups arrive at once: 77 crows, 42 thieves, 14 breakers |
| 5 | The last night | The whole farm layout | 3 announced waves over a 180 s night: 84 crows, 56 thieves, 21 breakers |
Up to 160 enemies can be on the farm at once (`enemy_capacity`): 48 thieves and 20 fence
breakers on foot (the character pool), and the rest in the air.
Every kind of enemy in tonight's plan shows up in the dusk warning in the phase HUD, so nothing
unannounced arrives (the last night's hint spells out its three waves). Nothing marks where they'll
arrive: anywhere along the edge. Debug scenarios (F2) replace tonight's plan for testing.
**Light.** Day is bright. Dusk turns to sunset, night falls over its first 8 s to moonlight, and
dawn brightens back to sunrise. At night the scarecrow carries a lantern and enemies glow
faintly, so the farm stays readable.
**Starting the night early (D1).** The player can skip the rest of the day or dusk straight to
the night, but only when `allow_early_night` is on. It is **off by default**.
@ -39,19 +89,23 @@ the night, but only when `allow_early_night` is on. It is **off by default**.
## Farm assets
Three kinds of asset can be stolen: **crops**, **animals**, and **supplies** (stored
construction materials in the shed). A kind is "in play" once the farm has any of it; until
Step 8 only crops are in play.
Three kinds of asset can be stolen, and all three are in play from the start:
- **crops**: the crop field's 30 units;
- **animals**: the 8 in the pen;
- **supplies**: the construction materials stored in the supply shed (the pouch can't be stolen).
A kind with nothing in it at the start is not in play. The asset HUD (top center) shows what's
left of each, and a count flashes red when it drops and green when it rises.
### Theft lifecycle
| State | Meaning | Feedback |
|---|---|---|
| Targeted | An enemy is heading for the asset | Marker over it; arrow at the screen edge if off screen |
| Being stolen | The enemy is taking it, which takes visible time (crops: 2.5 s). Damage resets the timer. | Progress ring |
| Carried | The enemy is heading for the nearest escape point, slower than usual | The asset shown on the enemy |
| Dropped | The carrier was stopped | The asset lies on the ground, glowing |
| Recovered | The scarecrow got it back | It returns home |
| Being stolen | The enemy is taking it, which takes visible time (crops 2.5 s, animals 2 s, a sack of supplies 3 s). Damage resets the timer. | Progress ring |
| Carried | The enemy is heading for the nearest escape point, slower than usual | The asset shown on the enemy, outlined in its category's color (crops gold, animals pink, supplies blue), with a badge |
| Dropped | The carrier was stopped | A crop or sack lies on the ground, glowing; an animal runs loose (below) |
| Recovered | The scarecrow got it back | It returns home (an animal follows the scarecrow home) |
| Lost | The carrier escaped off the farm | Permanently gone |
- **Stopping a carrier (D5).** Killing a carrier drops its loot. Fear also makes carriers drop
@ -64,23 +118,301 @@ Step 8 only crops are in play.
(`loot_returns_at_dawn`).
- Animals can also escape through a breach in the pen. An animal that leaves the farm is lost.
Implemented in Steps 3 (crops), 4 (fear), and 8 (animals and supplies).
Implemented for all three (Steps 3 and 8). The arrows at the screen edge are filled by state
(orange targeted, red carried, yellow dropped) and ringed in the category's color.
How enemies steal (the enemy types are in **The enemies**, below):
- **Targets.** Each enemy takes only its type's categories: crows take crops; thieves take
animals and supplies.
- It comes for one of them (its night-plan group's), or any.
- A dropped item of those it can see within 12 m comes first (crows see 20 m from above).
- If nothing in its category is left at home, it goes for another of its own, picked by
`target_weights`.
- With nothing of its own left, it leaves.
- **Crops.** A crow claims a random unit still in its plot and flies straight to it, over
anything in the way. It lands on it, takes it (2 s), and flies straight off the farm with it, out its
nearest side. Only one enemy claims an item at a time.
- **Animals.** A thief claims a random animal in the pen. The pen's gate keeps it out, so it
breaks the gate (30 HP: about 18 s). Then it walks in and catches the animal, which freezes, in
2 s. It carries the animal off, held under it, at 70 % speed to the **nearest** point of the farm's edge.
- **Supplies.** A thief goes to the shed pile of the material the shed holds most of (logs,
crates, or hay bales; each pile has a spot in front).
- There it fills a sack (3 s) with up to 5 units of that material, never more than the shed has.
- If the shed has run out by then, it takes nothing and goes for something else.
- If its claim disappears (the scarecrow recovered it, or an animal followed the scarecrow
away), it claims another.
## The enemies
Implemented in Step 9. The type table is `GameConfig.enemy_types`.
| | Crow | Thief | Fence breaker |
|---|---|---|---|
| Moves | Flies at 5.5 m/s | Walks at 3 m/s | Walks at 1.9 m/s |
| HP (hits) | 1 | 3 | 6 |
| Goes for | Crops | Animals and supplies | Barriers guarding valuables |
| Structures | Flies over fences and gates; traps don't touch it | Routes around barriers, breaks through when it must (2 per hit) | Smashes them (8 per hit, every 1.5 s): a fence in 3 hits, a gate in 4 |
| The scarecrow | Never fights | Hits on contact (1 HP) | Turns on it within 4 m or when shot, and hunts it when nothing is left to break (2 HP per hit) |
| Best answer | Stab or shoot it (one hit), or automated defenses by the crops | Fences and gates to slow it, traps, defenses | Shoot it from range before it reaches you (or bomb it), and keep repairing what it smashes |
- **Crows** cruise at a visual altitude and come down to land on their crop. Altitude is only
visual: shots at combat height and automated defenses hit them anywhere.
- **Fence breakers** steal nothing. They walk to the nearest barrier within 6 m of the crop
field, the pen, or the shed, smash it, and go for the next. The pen's gate is always one of
those.
- Their breaches open the way for thieves, who walk through without stopping.
- With no guarding barriers left, they go for any barrier, then for the scarecrow.
- A breaker that comes within 4 m of the scarecrow, or is shot, turns on it. It gives up the
chase beyond 12 m while there's still something to break.
- **Fear** scares every type.
**Alerts.** Arrows at the screen edge point at whatever is happening off screen:
- Each arrow is labeled ("3 crows — Crop Field", "Thief escaping with an animal!", "Breach! —
Animal Pen"), filled by kind, and ringed in the loot's category color.
- **Kinds, in priority order:** escapes; breaches (a barrier being smashed, or just broken);
thefts; loose animals and dropped loot.
- Alerts of the same kind, type, and loot in the same zone are grouped.
- An escape escalates as its carrier nears the exit: the arrow grows, pulses faster, and turns
red.
- At most 5 arrows show at once.
## Animals and the pen
Implemented in Step 8.
- **In the pen.** The 8 animals (4 chickens, 2 pigs, 2 sheep) wander inside the pen and stop to
graze. The pen's gate on its east side is a normal gate structure, standing from the start: the
scarecrow (and animals following it) walk through, but wandering animals and enemies can't.
- **The pen is open** when there's a way out that crosses no structure: its gate is broken or taken
down.
- A toast says so when it happens, and so does the morning review.
- At night (night and dawn), one calm animal walks out of an open pen every 10 s.
- By day they stay in.
- Building a gate (or a fence) back in the opening shuts the pen.
- **Loose animals** (dropped by a thief, or wandered out) walk toward the farm's nearest edge at
1.1 m/s, stopping to graze now and then.
- Structures stop them, so a fence line can hold them.
- One that reaches the edge is lost.
- One that gets back inside the pen is home.
- Any thief can grab a loose animal it sees.
- **Leading animals home (D6).**
- Walk up to a loose animal and it follows the scarecrow, walking its trail in line, gates
included. At most 3 follow at once; a toast says so when the line is full.
- Inside the pen it's home and stays calm for 30 s (it won't wander out of an open pen).
- Thieves can't take an animal that's following the scarecrow.
- At the end of the dawn grace, loose and following animals are back in the pen.
## Supplies
Implemented in Step 8.
- The shed's stock is shown by its piles: logs (wood) and hay bales (straw) east of the barn
doors, crates (scrap) west of them.
- Each pile shows one prop per few units (4 wood, 3 scrap, 4 straw), up to its full size.
- A label gives the amount while the scarecrow is near.
- A hidden prop doesn't block the scarecrow or shots. Enemies always route around a pile's
full footprint.
- A supply thief's sack holds up to 5 units, never more than the shed has.
- Killed (or scared), it drops the sack. Walk up to the sack and its contents go back to the
shed.
- A carried or dropped sack still counts as on the farm. Carried off, its contents are gone.
- Supplies lost in the night's record are the units carried off. Storing and spending don't
count.
## The scarecrow
- Starts with **10 HP**. HP **carries over between nights** (D7).
- **Patching** restores HP. It costs straw, takes a 2 s channel, can be done in any phase, and
damage interrupts it (Steps 4–5).
- **0 HP is an immediate Game Over.**
Implemented in Step 4. The numbers are in `GameConfig`.
- **Health:** starts with **10 HP**, and HP **carries over between nights** (D7).
- After a hit is accepted, the scarecrow ignores further hits for 1 s, so several hits on
the same tick cost one.
- A hit blinks the scarecrow red and tints the screen.
- **Thieves fight back on contact.** A thief hits the scarecrow for 1 HP when all of these
hold:
- it is close enough to touch;
- it is seeking, stealing, carrying, or breaking (not fleeing or retreating);
- it has a clear line (not through a fence or wall);
- its own 1.2 s cooldown is over. The cooldown starts on every attempt.
- Fence breakers hit for 2 HP every 1.5 s, but only while fighting the scarecrow. Crows
never fight.
- **Weapons** (fire: left mouse / RT; hold to keep attacking). Every scarecrow starts with the
**pitchfork**; the **corn shooter** and **pumpkin bombs** are bought at the workbench (below).
Switch with **Tab / d-pad down** (the next one owned) or **1 / 2 / 3**, outside build mode
(there those keys pick structures). The weapon in hand shows on the scarecrow and in the HUD's
weapon panel (bottom right), which also lists the ones still to buy. Numbers in `GameConfig`.
| Weapon | What it does | Damage | How often |
|---|---|---|---|
| Pitchfork | A stab at the aim: the nearest 3 enemies within 2.2 m (plus their size) and 50° either side of the aim, with a clear line (not through walls); crows too | 2 (a thief in 2 stabs, a crow in 1, a fence breaker in 3) | Every 0.5 s |
| Corn shooter | The gun: kernels flying at combat height, stopped by walls | 1 (2 with heavy seeds) | 6 a second (8 with rapid fire) |
| Pumpkin bombs | Thrown at the cursor (or 7 m ahead with the stick), 2–10 m away, in an arc; bursts on landing, hurting every enemy within 3 m (crows too; walls don't stop it; never the scarecrows, animals, or structures). An orange ring shows where it will land and how far it reaches | 3 (a thief at once, half a fence breaker) | One every 4 s; the next grows back in the hand. Every morning one is ready |
- Each weapon keeps its own wait, so switching doesn't skip one. A weapon no longer owned (a
retry from a morning before it was bought) goes back to the pitchfork. One bought from the
workbench menu goes straight into the hand.
- **Fear** (Q / left shoulder): every enemy within **6 m** flees straight away for **2 s**.
- Carriers drop their loot (D5).
- Enemies in the middle of a steal lose their progress and their claim.
- Afterwards they go back to stealing, or carrying if they kept their loot.
- Fear then needs **12 s** to recharge. A ring at the scarecrow's feet, and the HUD, show
when it's ready.
- **Sprint** (hold Shift / L3 while moving), once the **Sprint** upgrade is bought: the scarecrow
runs **1.6 times** as fast (8 m/s) for up to **3 s**. When the sprint ends (time's up, let go, or
stopped) it needs **10 s** to recharge; still holding, the next sprint starts as soon as it's
back. The HUD shows it ready, running, or recharging. Each new morning it's ready again.
- **Patching up** (hold F / Y): stand still, unable to shoot, for **2 s**, then **+3 HP** for
**2 straw**. The straw is paid when the patch completes.
- Releasing early, taking a hit, or using fear cancels it.
- Keep holding to patch again.
- It isn't available at full health, while gathering, or without the straw (a message says
what's missing).
- It works in any phase (D8).
- **Defeat:** at **0 HP** the scarecrow falls and the game is over at once (scarecrow first,
ahead of a stripped farm). A Game Over panel offers **Retry the night** (D9) and **New
vacation**. Every new morning, also after a retry, revives the scarecrow with fear ready.
## Materials and gathering
Implemented in Step 5. The numbers are in `GameConfig`; the gather points are listed in
`game/LAYOUT.md`.
- **Three materials:** wood, scrap, and straw.
- The supply shed's stock starts at 4 wood, 2 scrap, 4 straw.
- The scarecrow's **pouch** holds **15 units** in total.
- Walking into the Supply Shed zone empties the pouch into the shed, in any phase.
- **Paying:** costs come from the pouch first, then the shed, and are all-or-nothing.
- **Patch:** 2 straw.
- **Buildables:** fence 2 wood; gate 4 wood + 1 scrap; slowing trap 3 scrap + 1 wood; automated
defense 6 scrap + 2 wood + 2 straw.
- **Upgrades:** below.
- **Gathering** (hold E / X at a gather point), by day only (day and dusk, D8):
- Each gather takes **1.5 s** (rooted, no shooting) and puts the point's yield (2) into the
pouch, using one charge.
- Keep holding to gather again. Letting go, a hit, fear, or nightfall cancels it.
- The pouch needs room for the whole yield, so no charge is ever half wasted.
- Used-up points fade grey. They grow back overnight, at the end of the dawn grace.
- There are 4 points per material on the farm: about 18 wood, 18 scrap, and 20 straw a day.
- **Outside the fence:** the scarecrow can walk off the farm (through the gaps in the north and east
fence, or straight off the open south and west sides), as far as the old farm's
outer fences (the invisible walls are there now, not on the farm's fence).
- Four gathering areas wait outside, each point yielding **3** per charge with 3–4 charges:
- the North Grove: wood, north of the barn;
- the Old Hangar: scrap, north-east;
- the East Road: scrap, the abandoned car;
- the South Fields: straw, on the old plowed fields.
- They grow back overnight like the others. Gathering is still daytime only.
- Building, the enemies' paths, and the night stay inside the fence. At dusk and at nightfall,
a scarecrow still outside gets a warning.
- **Work area:** press E / X at the tool table, by day, to open the upgrade menu (below).
- **Persistence:** materials (shed and pouch), used gather points, and upgrades carry over
between nights and are restored by a retry.
- **Measured** (`soak_night.gd --mode=gather`): gathering everything and storing it takes about
**106 s** of the 180 s day, with 4 shed trips. That leaves about 70 s of day plus the 30 s of
dusk for building (Step 6).
## Upgrades
Implemented in Step 10. Bought once each, by day, from the menu at the work area's tool table. The
menu works with mouse, keyboard (arrows and Enter), or gamepad (d-pad and A). Close it with
Escape / B, interact again, or by walking off. The scarecrow stands still while it's open.
| Track | Upgrade | Effect | Cost |
|---|---|---|---|
| Weapon | Corn shooter | The gun: corn kernels from afar (below) | 10 scrap, 4 wood |
| Weapon | Rapid fire | The corn shooter fires a third faster (needs the corn shooter) | 12 scrap, 8 wood |
| Weapon | Heavy seeds | Each kernel does 2 damage (needs the corn shooter) | 14 scrap, 10 straw |
| Weapon | Pumpkin bombs | Thrown bombs that burst over 3 m, one every 4 s (below) | 12 straw, 6 scrap |
| Fear | Wide fear | Fear reaches 30% farther | 20 straw, 4 wood |
| Fear | Quick fear | Fear recharges 20% faster | 16 straw, 6 scrap |
| Scarecrow | Straw stuffing | +2 max health | 12 straw, 4 wood |
| Scarecrow | Sprint | Hold Shift / L3 to sprint: 1.6 times as fast for 3 s, then 10 s to recharge | 8 wood, 6 straw |
| Defenses | Reinforced fences | Fences and gates +50% health (standing ones keep their share) | 20 wood, 6 scrap |
| Defenses | Long-range defenses | Automated defenses reach 30% farther | 14 scrap, 10 wood |
| Defenses | Sticky tar | Slowing traps hold 50% longer | 14 straw, 6 scrap |
- **Cost:** all eleven cost 222 materials (74 scrap, 58 wood, 90 straw), drawing on the same
stock as building. Measured (before Sprint and the weapons were added): the scripted
scarecrow, building its plan, could afford 6 of the 8 over the five days.
- **Needs:** rapid fire and heavy seeds can't be bought before the corn shooter ("Needs the corn
shooter first").
- **Persistence:** upgrades carry over between nights and come back with a retry. The automated
defense's shots don't get heavy seeds.
## Construction
Implemented in Step 6. The numbers are in `GameConfig`.
- **Build mode** (B / d-pad up):
- Pick with 1–4 (or Tab / d-pad down), rotate with Z / C (d-pad) in 45° steps, and build with
LMB / RT.
- Positions snap to a 0.5 m grid. Building is instant, by day only (D8), and within 9 m of the
scarecrow.
- RMB / B over a built structure dismantles it, refunding half its cost, rounded down, into
the shed. Anywhere else it leaves build mode.
- The scarecrow doesn't shoot or gather in build mode.
| Buildable | Cost | HP | What it does |
|---|---|---|---|
| Fence | 2 wood | 20 | 2 m segment (1.5 × 1.5 m on the diagonal); ground enemies can't pass |
| Gate | 4 wood, 1 scrap | 30 | A fence the scarecrow walks through (it swings open); enemies can't |
| Slowing trap | 3 scrap, 1 wood | 10 triggers | A ground enemy stepping on it moves at half speed for 2 s; each crossing uses a trigger |
| Automated defense | 6 scrap, 2 wood, 2 straw | 25 | Shoots the nearest enemy within 7 m with a clear line, once a second (it leads the target) |
- **Placement:** a ghost shows green, or red with the reason. A structure can't go:
- outside the farm, within 2.5 m of a gap in the remaining perimeter fence (the scarecrow's way
out to the gathering areas), or in front of the barn doors;
- on a crop row, or into anything solid;
- onto another structure (fences may touch end to end, for corners);
- onto the scarecrow or an enemy (a gate may go where the scarecrow stands).
- It also needs daytime and the materials.
- **Blocked routes:** a barrier is never a wall to navigation, just expensive. Each barrier cell
counts as an 18 m detour.
- Enemies walk around a short fence but break through a long one.
- A fully enclosed target always has a route, which ends at the cheapest barrier. The thief
stops there and hits it (2 damage every 1.2 s, so about 12 s for a fence) until it breaks,
then carries on. A fence breaker does the same at 8 damage every 1.5 s.
- A broken structure leaves debris and a **"Breach!"** toast.
- Enemy routes are rebuilt over a few ticks whenever structures change. There are six routes:
the farm's edge, the pen, the three shed piles, and the fence breakers' targets. Measured: about
120 ms in total over 47 ticks, at most 2.6 ms in one tick.
- **Flying enemies** (crows) ignore fences, gates, and traps. The automated defense and the
scarecrow still hit them.
- **Damage and repair:**
- Damaged structures show an HP bar and a red tint, and wobble when hit.
- Hold E / X next to one (any phase) to repair it fully in 1.5 s. The cost is the build cost
times the missing share of HP (or triggers), rounded up.
- Damaged structures come first in the interact focus.
- **Persistence:** structures (position, rotation, HP) carry over between nights and are
restored by a retry.
## How the vacation ends
| Outcome | Condition | Result |
|---|---|---|
| Scarecrow destroyed | Scarecrow HP reaches 0, in any phase | Game Over |
| Farm stripped (D2) | **Every** kind of asset in play is gone: crops, animals, and stored supplies all at zero. Losing one kind isn't enough. | Game Over |
| Farm stripped (D2) | **Every** kind of asset in play is gone: crops, animals, and stored supplies all at zero. Losing one kind isn't enough. Supplies only count as gone when thieves emptied the shed (and no sack is still on the farm). Spending the last materials doesn't strip the farm. | Game Over |
| Vacation complete | The fifth night's dawn ends | The farmers return; final assessment |
- **The failure screen** names the cause and the night it happened on (with its plan's title),
then what was kept, what's left, what the night had cost so far, and the vacation's totals.
Retry the night is focused; Main menu goes back to the title screen.
- **The farmers' return** plays after the last dawn: their station wagon drives in at the
driveway gap and parks by the house, and the farmers walk to the porch, wave to the scarecrow,
and cheer. Fire, interact, or Enter / A skips it.
- **The final assessment** follows:
- Crops and animals count the share still on the farm.
- Supplies are also spent on building, so they count by theft instead: the share of
everything that passed through the farm (the shed's starting stock plus everything
gathered) that thieves didn't carry off.
- The score is the weighted share kept, as 0–100 points. Weights: crops 0.5, animals 0.3,
supplies 0.2, renormalized over the categories in play.
| Points | Rating |
|---|---|
| 95+ | Blue-ribbon harvest |
| 80+ | Bumper crop |
| 60+ | Fair season |
| 40+ | Lean season |
| below 40 | Hanging by a thread |
- **Order of checks.** The outcome is checked every tick, after gameplay and before any phase
change. A destroyed scarecrow is checked first, then a stripped farm, then completion. If a
failure and the end of the final dawn happen on the same tick, the result is a **loss**.
@ -90,8 +422,102 @@ Implemented in Steps 3 (crops), 4 (fear), and 8 (animals and supplies).
## Night record
When a night's dawn ends, the losses of that night (night and dawn together) are recorded per
asset kind. The morning review (Step 7) and nightly results (Step 11) read from this record.
Counted from each morning to the end of its dawn grace, and recorded when the dawn ends
(`FarmState.night_log`):
- crops and animals lost, supply units carried off;
- what was taken, recovered, and wandered out, per category;
- enemies killed per type, and those that got away with loot;
- the scarecrow's damage taken and patches;
- structures built, damage dealt to them, structures broken, and repairs;
- upgrades bought;
- materials gathered (into the pouch) and spent (building, repairs, patching, upgrades), per
material.
Open item for Step 8: supplies spent on building also reduce stored supplies. Decide then
whether a farm whose supplies were *spent* rather than stolen counts as stripped.
The morning screen opens with the last night's record. Its table shows taken, recovered, and
lost per category; animals taken include those that wandered out of an open pen. Under the
table come the enemies, the damage, and the materials. The final assessment adds up all the
nights.
Decided in Step 8: a farm whose supplies were *spent* rather than stolen is not stripped. The
shed counts as raided when a thief takes the last of its stock, and storing anything clears that
(`FarmState.shed_raided`).
## Saving and continuing
- **Autosave.** Every morning is saved to `user://savegame.json` (the farm state with a version
number). A new vacation is saved at once.
- **Continue** resumes at the saved morning. After a Game Over that's the failed night's morning,
the same as Retry. Finishing the vacation deletes the save.
- **Nothing else saves.** Quitting mid-day or mid-night (Save & quit, Quit, closing the window)
keeps the morning's save, so the pause menu says what Continue picks up. Going back to the
menu puts the farm behind it at that morning without writing anything.
- **Bad saves.** A missing, damaged, or newer save can't be continued, and the main menu says
why. An older save is upgraded when there's a known way (version 2 to 3: the new nightly
records start at zero) and refused otherwise. New vacation replaces any save; it asks first
only when the save is a good one.
## Menus, pause, and settings
- **Title screen:** Continue, New vacation, Settings, Quit, over the farm standing still.
- **Pause** (Escape / Start, any phase) freezes the whole simulation: timers, enemies, shots,
and game sounds. The menus and the ambience keep running. Its options are Resume, Restart the
night, Settings, Save & quit to menu, and Quit the game. Restarting and quitting ask first, with
Cancel focused.
- **Settings** apply at once and are saved to `user://settings.cfg`, apart from the save game.
Bad or missing values fall back to the defaults.
| Setting | Default | Range |
|---|---|---|
| Master / music and stingers / sound effects / ambience volume | 80 / 70 / 80 / 60 % | 0–100 % (0 mutes) |
| Move stick dead zone | 20 % | 5–90 % |
| Aim stick dead zone | 30 % | 5–90 % |
| Fullscreen | off | |
| VSync | on | |
| 3D resolution scale | 100 % | 50–100 % (the HUD stays sharp) |
| Tips on the first day and night | on | |
- Mouse aim follows the cursor directly, so there's no mouse sensitivity setting. The settings
list every binding; there's no remapping.
## First-day tips
On night 1 a short tip shows above the hotbar when it's useful, one at a time, and goes away
once it's done:
- **By day:** move, gather, store at the shed (once the pouch has something), and build (after
storing, or once half the day has gone).
- **At dusk:** when the thieves come (from every side).
- **At night:** fight with the pitchfork, and where to get the other weapons (once enemies are in), fear (when two or more are close), recover (when
something is dropped), and patch up (when hurt).
The most urgent tip wins. Backspace / Back hides them, and Settings turns them off. A finished
tip doesn't come back on a retry.
## Sound
- **Buses:** Master, then Music (stingers and outcome jingles), SFX, and Ambience.
- **Positional sounds** are heard from the scarecrow, facing the way the camera does, so a crow
cawing in from the east is heard on the right.
- **No pile-ups:** each cue has a minimum gap between plays and a voice limit, so a flock
arriving is a few caws, not twenty.
- **Coverage:** gathering, building, repairs, hits, deaths, fear, theft, breach and loss
alarms, the dusk bell, stingers at dusk, nightfall, sunrise, and morning, the outcome jingles,
and day and night ambience that crossfades through dusk and dawn.
- **Music**, crossfading between phases:
- "On the Farm" on the title screen, in the morning, by day, and when the farmers are back;
- "Purgatory" at night;
- nothing at dusk, at dawn, or after a Game Over: only the ambience.
## Co-op
Two players, each with a scarecrow, keep one farm (Main menu → Play with a friend; the details are
in `game/COOP.md`):
- **What's shared:** the shed, the pouch, upgrades, and structures. Either player can gather,
build, repair, buy upgrades, and start the day.
- **What's your own:** your scarecrow's health, and the weapon in your hands: a weapon bought
is there for both, and each player picks their own. Upgrades to max health apply to both.
- **Falling:** a scarecrow at 0 HP is out until the morning, when it comes back at half health.
**Game Over only when both are down at once.**
- **Enemies** go for the nearer scarecrow.
- **Saving:** the host's game saves; the partner's doesn't. A co-op save continued alone plays by
the solo rules.
- **Menus** don't pause the farm in co-op.

View file

@ -0,0 +1,27 @@
[gd_resource type="AudioBusLayout" format=3]
[resource]
bus/1/name = &"Music"
bus/1/solo = false
bus/1/mute = false
bus/1/bypass_fx = false
bus/1/volume_db = 0.0
bus/1/send = &"Master"
bus/2/name = &"SFX"
bus/2/solo = false
bus/2/mute = false
bus/2/bypass_fx = false
bus/2/volume_db = 0.0
bus/2/send = &"Master"
bus/3/name = &"Ambience"
bus/3/solo = false
bus/3/mute = false
bus/3/bypass_fx = false
bus/3/volume_db = 0.0
bus/3/send = &"Master"
bus/4/name = &"Voice"
bus/4/solo = false
bus/4/mute = false
bus/4/bypass_fx = false
bus/4/volume_db = 0.0
bus/4/send = &"Master"

Binary file not shown.

View file

@ -0,0 +1,12 @@
shader_type spatial;
// Overlay on a ground enemy's character (EnemyCharacters): a white hit flash (flash, 1 on a hit,
// fading) and, at night, a faint purple glow (night_glow, set by DayNight) so enemies stay
// readable in the dark, matching the crows' shader.
render_mode unshaded, blend_add, depth_draw_never, cull_back;
uniform float flash : hint_range(0.0, 1.0) = 0.0;
uniform float night_glow : hint_range(0.0, 1.0) = 0.0;
void fragment() {
ALBEDO = vec3(1.0, 0.95, 0.9) * flash * 0.8 + vec3(0.5, 0.28, 0.75) * night_glow * 0.22;
}

View file

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

View file

@ -0,0 +1,23 @@
shader_type spatial;
// The scarecrow's fear burst: a flat ring on the ground racing out to the fear radius (the
// plane is sized to it) with a faint fill behind it, fading as it goes. t runs 0 -> 1 over the
// burst. Drawn over the scene so raised ground tiles and crops don't hide it.
render_mode unshaded, cull_disabled, depth_test_disabled, shadows_disabled;
uniform float t : hint_range(0.0, 1.0) = 0.0;
uniform vec4 color : source_color = vec4(0.7, 0.92, 1.0, 1.0);
void fragment() {
vec2 p = UV * 2.0 - 1.0;
float r = length(p);
float front = sqrt(t); // fast at first, easing out
float width = 0.05 + 0.08 * t;
float fade = 1.0 - t;
float a = smoothstep(width, 0.0, abs(r - front)) * fade;
a += step(r, front) * 0.16 * fade;
if (r > 1.0 || a <= 0.002) {
discard;
}
ALBEDO = color.rgb;
ALPHA = a * color.a;
}

View file

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

View file

@ -10,10 +10,218 @@ dusk_length = 30.0
night_length = 150.0
dawn_grace = 20.0
allow_early_night = false
scarecrow_max_hp = 10
scarecrow_max_hp = 3
start_crops = 30
start_animals = 0
start_supplies = 0
start_animals = 8
start_structures = Array[Dictionary]([{
"rot": 2,
"type": "gate",
"x": 4.0,
"z": -6.0
}])
fear_drops_loot = true
loot_returns_at_dawn = true
max_following_animals = 3
max_following_animals = 5
crop_steal_time = 2.5
animal_capture_time = 2.0
supply_steal_time = 1.0
supply_bundle = 5
stray_speed = 1.1
animal_wander_interval = 10.0
animal_calm_time = 30.0
follow_speed = 6.0
target_weights = {
"animals": 1.0,
"crops": 2.0,
"supplies": 1.0
}
pickup_radius = 1.3
combat_height = 1.8
pitchfork_reach = 2.2
pitchfork_arc = 100.0
pitchfork_damage = 2
pitchfork_targets = 3
pitchfork_interval = 0.5
bomb_range = 10.0
bomb_min_range = 2.0
bomb_speed = 12.0
bomb_radius = 3.0
bomb_damage = 3
bomb_cooldown = 4.0
fire_rate = 6.0
projectile_speed = 24.0
projectile_lifetime = 2.0
projectile_capacity = 64
muzzle_distance = 1.05
aim_dead_zone = 0.3
mouse_switch_threshold = 12.0
enemy_capacity = 800
enemy_radius = 0.3
nav_cell_size = 0.5
nav_inflate_margin = 0.05
separation_radius = 0.8
separation_weight = 1.4
max_correction_per_tick = 0.15
direct_seek_distance = 12.0
night_thieves = 0
thief_spawn_interval = 6.0
trickle_type = "crow"
trickle_target = "any"
enemy_types = {
"breaker": {
"acceleration": 8.0,
"aggression": "fight",
"aggro_range": 4.0,
"carry_speed": 0.0,
"damage": 2,
"flying": false,
"hit_interval": 1.5,
"hit_radius": 0.55,
"hp": 6,
"speed": 1.9,
"steal_time": 0.0,
"structure_damage": 8,
"targets": ["structures"]
},
"crow": {
"acceleration": 18.0,
"aggression": "none",
"aggro_range": 0.0,
"carry_speed": 0.75,
"damage": 0,
"flying": true,
"hit_interval": 1.0,
"hit_radius": 0.45,
"hp": 1,
"speed": 5.5,
"steal_time": 0.8,
"structure_damage": 0,
"targets": ["crops"]
},
"thief": {
"acceleration": 14.0,
"aggression": "contact",
"aggro_range": 0.0,
"carry_speed": 0.7,
"damage": 1,
"flying": false,
"hit_interval": 1.2,
"hit_radius": 0.4,
"hp": 3,
"speed": 3.0,
"steal_time": 1.0,
"structure_damage": 2,
"targets": ["animals", "supplies"]
}
}
cruise_altitude = 3.2
land_altitude = 1.55
guard_range = 6.0
invulnerability_time = 1.0
fear_radius = 6.0
fear_cooldown = 12.0
fear_duration = 2.0
patch_time = 2.0
patch_heal = 3
sprint_speed_mult = 1.6
sprint_time = 3.0
sprint_cooldown = 10.0
enemy_attack_reach = 0.25
flee_speed_factor = 1.15
start_wood = 4
start_scrap = 2
start_straw = 4
pouch_capacity = 16
gather_time = 1.5
costs = {
"automated_defense": {
"scrap": 6,
"straw": 2,
"wood": 2
},
"fence": {
"wood": 2
},
"gate": {
"scrap": 1,
"wood": 4
},
"patch": {
"straw": 2
},
"slowing_trap": {
"scrap": 3,
"wood": 1
},
"straw_stuffing": {
"straw": 12,
"wood": 4
},
"sprint": {
"straw": 6,
"wood": 8
},
"corn_shooter": {
"scrap": 10,
"wood": 4
},
"pumpkin_bomb": {
"scrap": 6,
"straw": 12
},
"rapid_fire": {
"scrap": 12,
"wood": 8
},
"heavy_seeds": {
"scrap": 14,
"straw": 10
},
"wide_fear": {
"straw": 20,
"wood": 4
},
"quick_fear": {
"scrap": 6,
"straw": 16
},
"reinforced_fences": {
"scrap": 6,
"wood": 20
},
"long_range": {
"scrap": 14,
"wood": 10
},
"sticky_tar": {
"scrap": 6,
"straw": 14
}
}
shot_damage = 1
upgrades = {
"corn_shooter": {"name": "Corn shooter", "text": "A gun that fires corn kernels, from afar", "track": "Weapon"},
"heavy_seeds": {"add": 1, "name": "Heavy seeds", "requires": "corn_shooter", "stat": "shot_damage", "text": "Each kernel does 2 damage", "track": "Weapon"},
"long_range": {"mult": 1.3, "name": "Long-range defenses", "stat": "turret_range", "text": "Automated defenses reach 30% farther", "track": "Defenses"},
"pumpkin_bomb": {"name": "Pumpkin bombs", "text": "Throw a pumpkin that bursts, hurting everything within 3 m (one every 4 s)", "track": "Weapon"},
"quick_fear": {"mult": 0.8, "name": "Quick fear", "stat": "fear_cooldown", "text": "Fear recharges 20% faster", "track": "Fear"},
"rapid_fire": {"mult": 1.333, "name": "Rapid fire", "requires": "corn_shooter", "stat": "fire_rate", "text": "The corn shooter fires a third faster", "track": "Weapon"},
"reinforced_fences": {"mult": 1.5, "name": "Reinforced fences", "stat": "barrier_hp", "text": "Fences and gates +50% health", "track": "Defenses"},
"sprint": {"name": "Sprint", "text": "Sprint 60% faster for 3 s at a time, every 10 s", "track": "Scarecrow"},
"sticky_tar": {"mult": 1.5, "name": "Sticky tar", "stat": "trap_slow_time", "text": "Slowing traps hold 50% longer", "track": "Defenses"},
"straw_stuffing": {"add": 2, "name": "Straw stuffing", "stat": "scarecrow_max_hp", "text": "+2 max health", "track": "Scarecrow"},
"wide_fear": {"mult": 1.3, "name": "Wide fear", "stat": "fear_radius", "text": "Fear reaches 30% farther", "track": "Fear"}
}
fence_hp = 20
gate_hp = 30
trap_triggers = 10
turret_hp = 25
trap_slow_factor = 0.5
trap_slow_time = 2.0
turret_range = 7.0
turret_fire_interval = 1.0
build_range = 9.0
barrier_detour = 18.0
repair_time = 1.5
dismantle_refund = 0.5
flow_slice_cells = 2000

View file

@ -0,0 +1,23 @@
shader_type spatial;
// Billboarded health bar over a damaged structure: fills from the left by `fill`, green at full
// through yellow to red, on a dark backing. Drawn over the scene so the structure can't hide it.
render_mode unshaded, cull_disabled, depth_test_disabled, shadows_disabled;
uniform float fill : hint_range(0.0, 1.0) = 1.0;
void vertex() {
MODELVIEW_MATRIX = VIEW_MATRIX * mat4(INV_VIEW_MATRIX[0], INV_VIEW_MATRIX[1], INV_VIEW_MATRIX[2], MODEL_MATRIX[3]);
}
void fragment() {
vec2 p = UV;
float edge = 0.08;
bool border = p.x < edge * 0.25 || p.x > 1.0 - edge * 0.25 || p.y < edge || p.y > 1.0 - edge;
vec3 good = vec3(0.4, 0.9, 0.3);
vec3 mid = vec3(1.0, 0.8, 0.2);
vec3 bad = vec3(1.0, 0.25, 0.15);
vec3 bar = fill > 0.5 ? mix(mid, good, (fill - 0.5) * 2.0) : mix(bad, mid, fill * 2.0);
vec3 col = border ? vec3(0.02) : (p.x <= fill ? bar : vec3(0.12));
ALBEDO = col;
ALPHA = 0.95;
}

View file

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

View file

@ -0,0 +1,31 @@
shader_type spatial;
// Billboarded badge over carried or dropped loot: a center and a fill in the loot's category
// colors (crops: a sunflower; animals: pink; supplies: a sack) and a colored rim (red = carried
// off, yellow = dropped, pulsing toward white so it reads as "pick me up"). Drawn over the scene
// so a carrier behind a building can still be tracked.
render_mode unshaded, cull_disabled, depth_test_disabled, shadows_disabled;
uniform vec4 edge_color : source_color = vec4(1.0, 0.22, 0.15, 1.0);
uniform vec4 fill_color : source_color = vec4(1.0, 0.82, 0.18, 1.0);
uniform vec4 center_color : source_color = vec4(0.32, 0.18, 0.07, 1.0);
uniform float pulse : hint_range(0.0, 1.0) = 0.0;
void vertex() {
MODELVIEW_MATRIX = VIEW_MATRIX * mat4(INV_VIEW_MATRIX[0], INV_VIEW_MATRIX[1], INV_VIEW_MATRIX[2], MODEL_MATRIX[3]);
}
void fragment() {
vec2 p = UV * 2.0 - 1.0;
float r = length(p);
if (r > 1.0) {
discard;
}
vec3 col = fill_color.rgb;
if (r < 0.34) {
col = center_color.rgb;
} else if (r > 0.74) {
col = mix(edge_color.rgb, vec3(1.0), pulse * 0.7);
}
ALBEDO = col;
ALPHA = 0.95;
}

View file

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

View file

@ -0,0 +1,47 @@
[gd_resource type="Resource" script_class="NightPlan" format=3 uid="uid://14uhnrybetil"]
[ext_resource type="Script" uid="uid://bx3jd1naaa7iu" path="res://game/scripts/night_plan.gd" id="1_plan"]
[resource]
script = ExtResource("1_plan")
title = "Crows at the crops"
dusk_hint = "The crows are coming for the crops....."
count_scale = 1.0
spacing_scale = 1.0
groups = Array[Dictionary]([{
"count": 1,
"every": 3.0,
"target": "crops",
"time": 6.0,
"type": "crow"
}, {
"count": 1,
"every": 3.0,
"target": "crops",
"time": 22.0,
"type": "crow"
}, {
"count": 2,
"every": 4.0,
"target": "crops",
"time": 40.0,
"type": "crow"
}, {
"count": 2,
"every": 3.0,
"target": "crops",
"time": 62.0,
"type": "crow"
}, {
"count": 3,
"every": 3.0,
"target": "crops",
"time": 86.0,
"type": "crow"
}, {
"count": 2,
"every": 3.0,
"target": "crops",
"time": 115.0,
"type": "crow"
}])

View file

@ -0,0 +1,57 @@
[gd_resource type="Resource" script_class="NightPlan" format=3 uid="uid://dpc1nd7ihxmgh"]
[ext_resource type="Script" uid="uid://bx3jd1naaa7iu" path="res://game/scripts/night_plan.gd" id="1_plan"]
[resource]
script = ExtResource("1_plan")
title = "Thieves in the yard"
dusk_hint = "The Crows are coming again...... and what are those things?!"
groups = Array[Dictionary]([{
"count": 3,
"every": 2.0,
"target": "crops",
"time": 5.0,
"type": "crow"
}, {
"count": 2,
"every": 4.0,
"target": "supplies",
"time": 20.0,
"type": "thief"
}, {
"count": 3,
"every": 2.0,
"target": "crops",
"time": 40.0,
"type": "crow"
}, {
"count": 1,
"every": 2.0,
"target": "animals",
"time": 55.0,
"type": "thief"
}, {
"count": 3,
"every": 2.0,
"target": "crops",
"time": 90.0,
"type": "crow"
}, {
"count": 1,
"every": 2.0,
"target": "supplies",
"time": 100.0,
"type": "thief"
}, {
"count": 1,
"every": 2.0,
"target": "animals",
"time": 110.0,
"type": "thief"
}, {
"count": 2,
"every": 2.0,
"target": "crops",
"time": 120.0,
"type": "crow"
}])

View file

@ -0,0 +1,51 @@
[gd_resource type="Resource" script_class="NightPlan" format=3 uid="uid://c1euh8r1ek74x"]
[ext_resource type="Script" uid="uid://bx3jd1naaa7iu" path="res://game/scripts/night_plan.gd" id="1_plan"]
[resource]
script = ExtResource("1_plan")
title = "Breakers at the fences"
dusk_hint = "You guessed it. Crows. Thieves. And.... Oh no..."
groups = Array[Dictionary]([{
"count": 1,
"every": 2.0,
"target": "any",
"time": 5.0,
"type": "breaker"
}, {
"count": 2,
"every": 4.0,
"target": "animals",
"time": 20.0,
"type": "thief"
}, {
"count": 3,
"every": 2.0,
"target": "crops",
"time": 40.0,
"type": "crow"
}, {
"count": 1,
"every": 2.0,
"target": "any",
"time": 60.0,
"type": "breaker"
}, {
"count": 2,
"every": 4.0,
"target": "supplies",
"time": 75.0,
"type": "thief"
}, {
"count": 3,
"every": 2.0,
"target": "crops",
"time": 100.0,
"type": "crow"
}, {
"count": 1,
"every": 2.0,
"target": "any",
"time": 120.0,
"type": "thief"
}])

View file

@ -0,0 +1,57 @@
[gd_resource type="Resource" script_class="NightPlan" format=3 uid="uid://cl3uvraq82hbi"]
[ext_resource type="Script" uid="uid://bx3jd1naaa7iu" path="res://game/scripts/night_plan.gd" id="1_plan"]
[resource]
script = ExtResource("1_plan")
title = "From both sides"
dusk_hint = "AHHHHHHH....."
groups = Array[Dictionary]([{
"count": 4,
"every": 1.5,
"target": "crops",
"time": 10.0,
"type": "crow"
}, {
"count": 2,
"every": 3.0,
"target": "animals",
"time": 10.0,
"type": "thief"
}, {
"count": 3,
"every": 1.5,
"target": "crops",
"time": 55.0,
"type": "crow"
}, {
"count": 1,
"every": 2.0,
"target": "any",
"time": 55.0,
"type": "breaker"
}, {
"count": 2,
"every": 3.0,
"target": "animals",
"time": 57.0,
"type": "thief"
}, {
"count": 4,
"every": 1.5,
"target": "crops",
"time": 100.0,
"type": "crow"
}, {
"count": 2,
"every": 3.0,
"target": "supplies",
"time": 100.0,
"type": "thief"
}, {
"count": 1,
"every": 2.0,
"target": "any",
"time": 102.0,
"type": "breaker"
}])

View file

@ -0,0 +1,76 @@
[gd_resource type="Resource" script_class="NightPlan" format=3 uid="uid://b27he0p0joyl0"]
[ext_resource type="Script" uid="uid://bx3jd1naaa7iu" path="res://game/scripts/night_plan.gd" id="1_plan"]
[resource]
script = ExtResource("1_plan")
title = "The last night"
dusk_hint = "The farmers are back in the morning. It's gonna be a long night...."
night_length = 180.0
groups = Array[Dictionary]([{
"count": 4,
"every": 2.0,
"target": "crops",
"time": 5.0,
"type": "crow"
}, {
"count": 2,
"every": 3.0,
"target": "animals",
"time": 8.0,
"type": "thief"
}, {
"count": 1,
"every": 2.0,
"target": "any",
"time": 55.0,
"type": "breaker"
}, {
"count": 1,
"every": 2.0,
"target": "any",
"time": 58.0,
"type": "breaker"
}, {
"count": 3,
"every": 3.0,
"target": "supplies",
"time": 65.0,
"type": "thief"
}, {
"count": 3,
"every": 2.0,
"target": "crops",
"time": 70.0,
"type": "crow"
}, {
"count": 3,
"every": 1.5,
"target": "crops",
"time": 115.0,
"type": "crow"
}, {
"count": 2,
"every": 1.5,
"target": "crops",
"time": 115.0,
"type": "crow"
}, {
"count": 2,
"every": 3.0,
"target": "any",
"time": 118.0,
"type": "thief"
}, {
"count": 1,
"every": 3.0,
"target": "any",
"time": 120.0,
"type": "thief"
}, {
"count": 1,
"every": 2.0,
"target": "any",
"time": 125.0,
"type": "breaker"
}])

Binary file not shown.

View file

@ -0,0 +1,38 @@
[gd_resource type="Resource" script_class="NightPlan" format=3]
[ext_resource type="Script" path="res://game/scripts/night_plan.gd" id="1_plan"]
[resource]
script = ExtResource("1_plan")
title = "All three"
groups = Array[Dictionary]([{
"count": 1,
"every": 2.0,
"target": "any",
"time": 3.0,
"type": "breaker"
}, {
"count": 3,
"every": 1.5,
"target": "crops",
"time": 8.0,
"type": "crow"
}, {
"count": 2,
"every": 3.0,
"target": "animals",
"time": 12.0,
"type": "thief"
}, {
"count": 3,
"every": 1.5,
"target": "crops",
"time": 35.0,
"type": "crow"
}, {
"count": 2,
"every": 3.0,
"target": "supplies",
"time": 40.0,
"type": "thief"
}])

View file

@ -0,0 +1,20 @@
[gd_resource type="Resource" script_class="NightPlan" format=3]
[ext_resource type="Script" path="res://game/scripts/night_plan.gd" id="1_plan"]
[resource]
script = ExtResource("1_plan")
title = "Fence breakers only"
groups = Array[Dictionary]([{
"count": 1,
"every": 2.0,
"target": "any",
"time": 3.0,
"type": "breaker"
}, {
"count": 1,
"every": 2.0,
"target": "any",
"time": 40.0,
"type": "breaker"
}])

View file

@ -0,0 +1,26 @@
[gd_resource type="Resource" script_class="NightPlan" format=3]
[ext_resource type="Script" path="res://game/scripts/night_plan.gd" id="1_plan"]
[resource]
script = ExtResource("1_plan")
title = "Crows only"
groups = Array[Dictionary]([{
"count": 3,
"every": 1.5,
"target": "crops",
"time": 3.0,
"type": "crow"
}, {
"count": 3,
"every": 1.5,
"target": "crops",
"time": 25.0,
"type": "crow"
}, {
"count": 4,
"every": 1.0,
"target": "crops",
"time": 50.0,
"type": "crow"
}])

View file

@ -0,0 +1,32 @@
[gd_resource type="Resource" script_class="NightPlan" format=3]
[ext_resource type="Script" path="res://game/scripts/night_plan.gd" id="1_plan"]
[resource]
script = ExtResource("1_plan")
title = "Crows and thieves"
groups = Array[Dictionary]([{
"count": 3,
"every": 1.5,
"target": "crops",
"time": 3.0,
"type": "crow"
}, {
"count": 2,
"every": 3.0,
"target": "animals",
"time": 5.0,
"type": "thief"
}, {
"count": 3,
"every": 1.5,
"target": "crops",
"time": 35.0,
"type": "crow"
}, {
"count": 2,
"every": 3.0,
"target": "supplies",
"time": 38.0,
"type": "thief"
}])

View file

@ -0,0 +1,26 @@
[gd_resource type="Resource" script_class="NightPlan" format=3]
[ext_resource type="Script" path="res://game/scripts/night_plan.gd" id="1_plan"]
[resource]
script = ExtResource("1_plan")
title = "Ground thieves only"
groups = Array[Dictionary]([{
"count": 2,
"every": 3.0,
"target": "supplies",
"time": 3.0,
"type": "thief"
}, {
"count": 2,
"every": 3.0,
"target": "animals",
"time": 20.0,
"type": "thief"
}, {
"count": 2,
"every": 3.0,
"target": "any",
"time": 45.0,
"type": "thief"
}])

View file

@ -0,0 +1,26 @@
[gd_resource type="Resource" script_class="NightPlan" format=3]
[ext_resource type="Script" path="res://game/scripts/night_plan.gd" id="1_plan"]
[resource]
script = ExtResource("1_plan")
title = "Thieves behind a fence breaker"
groups = Array[Dictionary]([{
"count": 1,
"every": 2.0,
"target": "any",
"time": 3.0,
"type": "breaker"
}, {
"count": 2,
"every": 4.0,
"target": "animals",
"time": 15.0,
"type": "thief"
}, {
"count": 2,
"every": 3.0,
"target": "supplies",
"time": 40.0,
"type": "thief"
}])

View file

@ -0,0 +1,24 @@
shader_type spatial;
// Billboarded radial progress ring above a crop unit while a thief takes it. Fills clockwise
// from the top; drawn over the scene so crops and buildings never hide it.
render_mode unshaded, cull_disabled, depth_test_disabled, shadows_disabled;
uniform float progress : hint_range(0.0, 1.0) = 0.0;
uniform vec4 fill_color : source_color = vec4(1.0, 0.45, 0.1, 1.0);
uniform vec4 back_color : source_color = vec4(0.05, 0.05, 0.05, 0.6);
void vertex() {
MODELVIEW_MATRIX = VIEW_MATRIX * mat4(INV_VIEW_MATRIX[0], INV_VIEW_MATRIX[1], INV_VIEW_MATRIX[2], MODEL_MATRIX[3]);
}
void fragment() {
vec2 p = UV * 2.0 - 1.0;
float r = length(p);
if (r > 1.0 || r < 0.58) {
discard;
}
float a = fract(atan(p.x, -p.y) / 6.2831853 + 1.0);
vec4 c = a <= progress ? fill_color : back_color;
ALBEDO = c.rgb;
ALPHA = c.a;
}

View file

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

View file

@ -0,0 +1,30 @@
shader_type spatial;
// Shared enemy material (one MultiMesh batch), from the prototype's bird shader: wings (local
// |x|) flap with a per-enemy phase from INSTANCE_CUSTOM.r, and a hit flashes the enemy white
// through INSTANCE_CUSTOM.g (1 on the hit, fading). Rim light keeps the near-black crow
// readable against the grass and crops, and night_glow (set by DayNight) adds a faint purple glow
// at night.
render_mode cull_disabled;
uniform vec3 base_color : source_color = vec3(0.07, 0.07, 0.09);
uniform float flap_speed = 11.0;
uniform float flap_amount = 0.55;
uniform float night_glow : hint_range(0.0, 1.0) = 0.0;
varying float flash;
void vertex() {
float span = abs(VERTEX.x);
float phase = INSTANCE_CUSTOM.r * 6.2831853;
VERTEX.y += sin(TIME * flap_speed + phase) * span * flap_amount;
flash = INSTANCE_CUSTOM.g;
}
void fragment() {
ALBEDO = mix(base_color, vec3(1.0), clamp(flash, 0.0, 1.0));
EMISSION = vec3(1.0, 0.9, 0.8) * flash * 0.6 + vec3(0.5, 0.28, 0.75) * night_glow * 0.35;
ROUGHNESS = 0.55;
SPECULAR = 0.4;
RIM = 0.8;
RIM_TINT = 0.3;
}

View file

@ -0,0 +1 @@
uid://5vlqyyk1u75v

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

66
game/scenes/main.tscn Normal file
View file

@ -0,0 +1,66 @@
[gd_scene format=3]
[ext_resource type="Script" path="res://game/scripts/main.gd" id="1_main"]
[ext_resource type="PackedScene" uid="uid://dfg4ba00jby52" path="res://game/scenes/farm.tscn" id="2_farm"]
[ext_resource type="Script" path="res://game/scripts/main_menu.gd" id="3_main_menu"]
[ext_resource type="Script" path="res://game/scripts/pause_menu.gd" id="4_pause_menu"]
[ext_resource type="Script" path="res://game/scripts/settings_menu.gd" id="5_settings_menu"]
[ext_resource type="Script" path="res://game/scripts/confirm_box.gd" id="6_confirm_box"]
[ext_resource type="Script" path="res://game/scripts/coop_menu.gd" id="7_coop_menu"]
[node name="Main" type="Node"]
script = ExtResource("1_main")
[node name="Farm" parent="." instance=ExtResource("2_farm")]
[node name="Menus" type="CanvasLayer" parent="."]
layer = 10
[node name="MainMenu" type="Control" parent="Menus"]
layout_mode = 3
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
script = ExtResource("3_main_menu")
[node name="PauseMenu" type="CenterContainer" parent="Menus"]
layout_mode = 3
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
mouse_filter = 2
script = ExtResource("4_pause_menu")
[node name="SettingsMenu" type="CenterContainer" parent="Menus"]
layout_mode = 3
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
mouse_filter = 2
script = ExtResource("5_settings_menu")
[node name="CoopMenu" type="CenterContainer" parent="Menus"]
layout_mode = 3
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
mouse_filter = 2
script = ExtResource("7_coop_menu")
[node name="ConfirmBox" type="CenterContainer" parent="Menus"]
layout_mode = 3
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
mouse_filter = 2
script = ExtResource("6_confirm_box")

View file

@ -0,0 +1,23 @@
class_name ActionEdges
extends RefCounted
## Per-tick "just pressed" for input actions. A press counts once, either from its input event
## (note(), so a tap between two ticks still registers) or from the action turning pressed since
## the previous poll (which also covers simulated input). Poll every action once per tick.
var _held := {}
var _requested := {}
func note(event: InputEvent, actions: Array) -> void:
for a in actions:
if event.is_action_pressed(a, false):
_requested[a] = true
func pressed(action: StringName) -> bool:
var held := Input.is_action_pressed(action)
var was: bool = _held.get(action, false)
_held[action] = held
var requested: bool = _requested.get(action, false)
_requested.erase(action)
return requested or (held and not was)

View file

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

View file

@ -0,0 +1,289 @@
class_name AlertManager
extends Control
## What's going wrong on the farm, as labeled arrows at the screen edge for whatever is off
## screen (on-screen threats already have their world markers). Every frame it collects alerts:
## ESCAPE a carrier making off with loot. It escalates as the carrier nears its exit (the
## farm's nearest edge, on foot or flying): the arrow grows, pulses faster, and
## turns from orange to red, and the label ends in "!".
## BREACH a barrier being smashed, or one just broken (for BREACH_TIME)
## THEFT loot being taken, or an enemy on its way to it
## LOOSE an animal loose on the farm, or loot lying dropped
## Alerts of the same kind, enemy type, and loot category in the same zone are grouped into one
## ("3 crows — Crop Field"). They're ordered by priority (kind, then escalation, then distance to
## the scarecrow), and at most MAX_SHOWN arrows are drawn at once.
enum Kind { ESCAPE, BREACH, THEFT, LOOSE }
const PRIORITY := {Kind.ESCAPE: 100.0, Kind.BREACH: 70.0, Kind.THEFT: 60.0, Kind.LOOSE: 45.0}
const FILL := {
Kind.ESCAPE: Color(1.0, 0.22, 0.15),
Kind.BREACH: Color(1.0, 0.45, 0.2),
Kind.THEFT: Color(1.0, 0.6, 0.1),
Kind.LOOSE: Color(1.0, 0.9, 0.25),
}
const MAX_SHOWN := 5
const MARGIN := 46.0
const BREACH_TIME := 6.0
## Escape alerts start escalating this far from the exit.
const ESCALATE_FROM := 20.0
var loot: LootSystem
var waves: WaveDirector
var enemies: EnemySystem
var structures: StructureSystem
var zones: FarmZones
var player: Node3D
## Set by FarmSim: the field to the farm's edge (how far a carrier on foot has left to go).
var sim: FarmSim
## Alerts drawn last frame (tests and debugging).
var last_shown: Array[Dictionary] = []
var _breaches: Array = [] # [seconds left, position, type name]
var _time: float = 0.0
var _font: Font
func setup(p_sim: FarmSim) -> void:
sim = p_sim
loot = sim.loot
waves = sim.waves
enemies = sim.enemies
structures = sim.structures
zones = sim.zones
player = sim.player
structures.destroyed.connect(func(_id: int, t: String, at: Vector3) -> void: _breaches.append([BREACH_TIME, at, t]))
sim.campaign.phase_changed.connect(func(phase: CampaignController.Phase, _p: CampaignController.Phase) -> void:
if phase == CampaignController.Phase.MORNING:
_breaches.clear())
func _ready() -> void:
set_anchors_preset(Control.PRESET_FULL_RECT)
mouse_filter = Control.MOUSE_FILTER_IGNORE
_font = ThemeDB.fallback_font
func _process(delta: float) -> void:
_time += delta
for b in _breaches:
b[0] = float(b[0]) - delta
_breaches = _breaches.filter(func(b: Array) -> bool: return float(b[0]) > 0.0)
queue_redraw()
## Every alert right now, grouped and sorted by priority (highest first). Each is a dictionary:
## kind, type (EnemySystem type or -1), category (LootSystem.Category or -1), zone (name or ""),
## position (Vector3, the group's center), count, escalation (0..1), priority, label.
func collect() -> Array[Dictionary]:
var raw: Array[Dictionary] = []
if loot != null:
for id in range(1, loot.item_count + 1):
match loot.status[id]:
LootSystem.Status.CARRIED:
var d := enemies.resolve_handle(loot.holder[id])
if d < 0:
continue
var p := Vector2(enemies.pos_x[d], enemies.pos_z[d])
raw.append(_alert(Kind.ESCAPE, enemies.type[d], loot.category[id], p, _escalation(d, p)))
LootSystem.Status.HOME:
var d := enemies.resolve_handle(loot.holder[id]) if loot.holder[id] >= 0 else -1
if d >= 0:
raw.append(_alert(Kind.THEFT, enemies.type[d], loot.category[id], loot.position_of(id), 0.0))
LootSystem.Status.DROPPED:
raw.append(_alert(Kind.LOOSE, -1, loot.category[id], loot.position_of(id), 0.0))
if enemies != null and structures != null:
for d in enemies.active_count:
if enemies.alive[d] == 1 and enemies.state[d] == ThiefBehavior.State.BREAK:
var e := structures.campaign.state.structure(enemies.barrier[d])
if not e.is_empty():
raw.append(_alert(Kind.BREACH, enemies.type[d], -1, Vector2(e["x"], e["z"]), 0.0))
for b in _breaches:
var at: Vector3 = b[1]
raw.append(_alert(Kind.BREACH, -1, -1, Vector2(at.x, at.z), 1.0))
return sort_alerts(group_alerts(raw))
## Merges alerts of the same kind, type, category, and zone.
static func group_alerts(raw: Array[Dictionary]) -> Array[Dictionary]:
var groups := {}
var order: Array[String] = []
for a in raw:
var key := "%d|%d|%d|%s" % [a["kind"], a["type"], a["category"], a["zone"]]
if not groups.has(key):
groups[key] = a.duplicate()
groups[key]["sum"] = a["position"]
order.append(key)
else:
var g: Dictionary = groups[key]
g["count"] = int(g["count"]) + 1
g["sum"] = (g["sum"] as Vector3) + (a["position"] as Vector3)
g["escalation"] = maxf(float(g["escalation"]), float(a["escalation"]))
var out: Array[Dictionary] = []
for key in order:
var g: Dictionary = groups[key]
g["position"] = (g["sum"] as Vector3) / float(g["count"])
g.erase("sum")
g["priority"] = float(PRIORITY[g["kind"]]) + 20.0 * float(g["escalation"]) + minf(float(g["count"]) - 1.0, 5.0)
g["label"] = label_for(g)
out.append(g)
return out
static func sort_alerts(list: Array[Dictionary]) -> Array[Dictionary]:
list.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
if not is_equal_approx(float(a["priority"]), float(b["priority"])):
return float(a["priority"]) > float(b["priority"])
return float(a.get("distance", 0.0)) < float(b.get("distance", 0.0)))
return list
## The first `cap` alerts that pass the filter (on the HUD: those off screen).
static func cap(list: Array[Dictionary], limit: int, keep: Callable = Callable()) -> Array[Dictionary]:
var out: Array[Dictionary] = []
for a in list:
if out.size() >= limit:
break
if not keep.is_valid() or keep.call(a):
out.append(a)
return out
## "3 crows — Crop Field", "Crow escaping with a crop!", "Breach! — Animal Pen".
static func label_for(a: Dictionary) -> String:
var n := int(a["count"])
var t := int(a["type"])
var who := ""
if t >= 0:
who = "%d %s" % [n, EnemySystem.PLURALS[t]] if n > 1 else EnemySystem.NAMES[t].capitalize()
var what := ""
var c := int(a["category"])
if c >= 0:
what = ["crop", "animal", "supplies"][c]
if n > 1 and c != LootSystem.Category.SUPPLY:
what += "s"
var text := ""
match int(a["kind"]):
Kind.ESCAPE:
var article := ("an " if what.begins_with("a") else "a ") if n == 1 and c != LootSystem.Category.SUPPLY else ""
text = "%s escaping with %s%s" % [who, article, what]
if float(a["escalation"]) >= 0.7:
text += "!"
Kind.BREACH:
text = "Breach!" if t < 0 else "%s smashing a barrier" % who
Kind.THEFT:
text = who
Kind.LOOSE:
text = ("%d loose animals" % n if n > 1 else "Loose animal") if c == LootSystem.Category.ANIMAL \
else ("%d dropped %s" % [n, what] if n > 1 else "Dropped %s" % what)
return "%s — %s" % [text, a["zone"]] if String(a["zone"]) != "" else text
func _alert(kind: Kind, type: int, category: int, p: Vector2, escalation: float) -> Dictionary:
var zone := zones.zone_at(Vector3(p.x, 0.0, p.y)) if zones != null else null
var me := Vector2(player.global_position.x, player.global_position.z) if player != null else p
return {"kind": kind, "type": type, "category": category, "zone": zone.display_name if zone != null else "",
"position": Vector3(p.x, 1.0, p.y), "count": 1, "escalation": escalation, "distance": p.distance_to(me)}
## How close a carrier is to getting away (0 far .. 1 at the exit): on foot by the escape field,
## a flyer by its distance to the fence.
func _escalation(d: int, p: Vector2) -> float:
var left := ESCALATE_FROM
if enemies.t_flying[enemies.type[d]] == 1:
var r := zones.playable
left = maxf(minf(minf(p.x - r.position.x, r.end.x - p.x), minf(p.y - r.position.y, r.end.y - p.y)), 0.0)
elif sim != null and not sim.escape_field.is_empty():
left = sim.nav.meters(sim.escape_field[sim.nav.cell_of(p.x, p.y)])
return clampf(1.0 - left / ESCALATE_FROM, 0.0, 1.0)
func _draw() -> void:
var cam := get_viewport().get_camera_3d()
if cam == null or loot == null:
return
var view := get_viewport_rect()
var inner := view.grow(-MARGIN)
var center := inner.get_center()
var to_canvas := get_viewport().get_screen_transform().affine_inverse()
var offscreen := func(a: Dictionary) -> bool:
var world: Vector3 = a["position"]
return cam.is_position_behind(world) or not view.has_point(to_canvas * cam.unproject_position(world))
last_shown = cap(collect(), MAX_SHOWN, offscreen)
var labels: Array[Rect2] = []
for a in last_shown:
var world: Vector3 = a["position"]
var behind := cam.is_position_behind(world)
var p := to_canvas * cam.unproject_position(world)
var dir := (p - center) * (-1.0 if behind else 1.0)
dir = dir.normalized() if dir.length_squared() > 1.0 else Vector2.DOWN
var t := INF
if absf(dir.x) > 1e-4:
t = minf(t, inner.size.x * 0.5 / absf(dir.x))
if absf(dir.y) > 1e-4:
t = minf(t, inner.size.y * 0.5 / absf(dir.y))
_arrow(_clear_of_hud(center + dir * t, inner), dir, a, labels)
## The HUD's corner panels (phase, materials, scarecrow), which arrows and labels keep out of.
func _hud_rects() -> Array[Rect2]:
var v := size_px()
return [Rect2(0.0, 0.0, 600.0, 140.0), Rect2(v.x - 540.0, 0.0, 540.0, 130.0), Rect2(0.0, v.y - 180.0, 370.0, 180.0)]
## Slides a point on the arrow border along that border, out of any HUD panel.
func _clear_of_hud(p: Vector2, inner: Rect2) -> Vector2:
for r in _hud_rects():
var g := r.grow(24.0)
if not g.has_point(p):
continue
var on_side := absf(p.x - inner.position.x) < 1.0 or absf(p.x - inner.end.x) < 1.0
if on_side:
p.y = g.end.y if g.position.y <= 0.0 else g.position.y
else:
p.x = g.end.x if g.position.x <= 0.0 else g.position.x
return p
func _arrow(at: Vector2, dir: Vector2, a: Dictionary, labels: Array[Rect2]) -> void:
var e := float(a["escalation"])
var color: Color = FILL[a["kind"]]
if int(a["kind"]) == Kind.ESCAPE:
color = Color(1.0, 0.6, 0.15).lerp(Color(1.0, 0.1, 0.08), e)
var pulse := 0.5 + 0.5 * sin(_time * (5.0 + 10.0 * e))
var size := 1.0 + 0.45 * e * pulse
var side := Vector2(-dir.y, dir.x)
var tip := at + dir * 28.0 * size
var back := at - dir * 16.0 * size
var points := PackedVector2Array([tip, back + side * 22.0 * size, back - side * 22.0 * size])
draw_colored_polygon(points, color)
points.append(tip)
var rim: Color = LootSystem.CATEGORY_COLORS[a["category"]] if int(a["category"]) >= 0 else Color(0.05, 0.03, 0.0)
draw_polyline(points, rim, 5.0, true)
draw_polyline(points, Color(0.05, 0.03, 0.0), 1.5, true)
var text := String(a["label"])
var fs := 20
var w := _font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x
var anchor := at - dir * 44.0 - Vector2(w * 0.5, -fs * 0.35)
anchor.x = clampf(anchor.x, 8.0, size_px().x - w - 8.0)
anchor.y = clampf(anchor.y, fs + 4.0, size_px().y - 8.0)
# Stack labels instead of overlapping them (moving toward the middle of the screen).
var step := Vector2(0.0, -26.0 if anchor.y > size_px().y * 0.5 else 26.0)
var box := Rect2(anchor + Vector2(-6.0, -fs - 2.0), Vector2(w + 12.0, fs + 10.0))
for k in 6:
var hit := false
for other in labels:
if other.intersects(box):
hit = true
break
if not hit:
break
anchor += step
box.position += step
labels.append(box)
draw_rect(box, Color(0.0, 0.0, 0.0, 0.45))
draw_string_outline(_font, anchor, text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, 6, Color.BLACK)
draw_string(_font, anchor, text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, color.lerp(Color.WHITE, 0.35))
func size_px() -> Vector2:
return get_viewport_rect().size

View file

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

View file

@ -0,0 +1,469 @@
class_name AnimalSystem
extends Node3D
## The pen's animals as moving entities. Their theft state lives in LootSystem; this moves and
## shows them:
## in the pen (HOME) wander between random spots in the pen, pausing to graze; one a thief is
## catching stands still. At night (night and dawn), while the pen is open (a
## way out that crosses no structure: its gate broken or taken down), one calm
## animal wanders out every animal_wander_interval and is loose.
## loose (DROPPED) dropped by its thief, or wandered out: walks toward the farm's nearest edge
## along the escape field at stray_speed, stopping to graze now and then, and
## can't pass structures. At the edge it is lost; inside the pen it is home
## again.
## following walks the scarecrow's trail (so it goes wherever the scarecrow went, gates
## included), in line behind it. Inside the pen it is home (returned) and calm
## for animal_calm_time.
## carried held under its thief, wriggling.
## The farm pack's animals are static meshes, so walking is procedural: chickens hop, pigs and
## sheep waddle. Each scene animal (a farm-pack prefab under the pen zone) is reparented under a
## pivot at the middle of its body.
const WANDER_SPEED := {"chicken": 0.9, "pig": 0.6, "sheep": 0.7}
const TRAIL_STEP := 0.25
const TRAIL_POINTS := 160
const FOLLOW_GAP := 1.0
const FOLLOW_FIRST := 1.5
## A follower whose scarecrow got this far away (a retry, a fall) is loose again.
const FOLLOW_LEASH := 20.0
## The pen opened (its gate broken or taken down) or was shut again.
signal pen_changed(open: bool)
var config: GameConfig
var campaign: CampaignController
var nav: FarmNavigation
var loot: LootSystem
var enemies: EnemySystem
var player: Node3D
var pen: Rect2
## Set by FarmSim: the field loose animals walk along, toward the farm's nearest edge.
var escape_field := PackedInt32Array()
var count: int = 0
## There's a way out of the pen that crosses no structure.
var pen_open := false
# Per animal, indexed 1..count.
var pos := PackedVector2Array()
var prev := PackedVector2Array()
var yaw := PackedFloat32Array()
var speed := PackedFloat32Array()
var goal := PackedVector2Array()
var timer := PackedFloat32Array()
var calm := PackedFloat32Array()
var phase := PackedFloat32Array()
## Order in the line behind the scarecrow (0 = first), -1 when not following.
var slot := PackedInt32Array()
## Wandering out of the open pen and not out yet (so being inside doesn't count as home).
var leaving := PackedByteArray()
var kinds: Array[String] = []
var _start := PackedVector2Array()
var _start_yaw := PackedFloat32Array()
var _pivots: Array[Node3D] = []
var _meshes: Array = [] # per animal: Array[MeshInstance3D]
## Co-op: the scarecrows animals can follow (player 1's, player 2's), each with its trail, and
## which one each following animal follows.
var leaders: Array[Node3D] = []
var leader := PackedInt32Array()
var _trails: Array[PackedVector2Array] = [PackedVector2Array(), PackedVector2Array()]
var _wander_wait: float = 0.0
var _rng := RandomNumberGenerator.new()
var _dir := PackedFloat32Array([0.0, 0.0])
## Takes over the farm-pack animals under the pen zone (in name order: animal ids 1..count).
static func find_animals(pen_zone: Node3D) -> Array[Node3D]:
var out: Array[Node3D] = []
for child in pen_zone.get_children():
if child is Node3D and String(child.scene_file_path).contains("/animal/"):
out.append(child)
out.sort_custom(func(a: Node3D, b: Node3D) -> bool: return String(a.name) < String(b.name))
return out
func setup(p_campaign: CampaignController, pen_zone: FarmZone, p_nav: FarmNavigation, p_loot: LootSystem,
p_enemies: EnemySystem, p_player: Node3D) -> void:
campaign = p_campaign
config = p_campaign.config
nav = p_nav
loot = p_loot
enemies = p_enemies
player = p_player
leaders = [p_player]
pen = pen_zone.rect()
_rng.seed = 8061
var found := find_animals(pen_zone)
count = found.size()
var n := count + 1
for a: PackedVector2Array in [pos, prev, goal, _start]:
a.resize(n)
for a: PackedFloat32Array in [yaw, speed, timer, calm, phase, _start_yaw]:
a.resize(n)
slot.resize(n)
leader.resize(n)
leaving.resize(n)
kinds.resize(n)
_pivots.resize(n)
_meshes.resize(n)
for i in count:
var node := found[i]
var id := i + 1
kinds[id] = String(node.scene_file_path.get_file().get_basename()).get_slice("_", 0)
var center := _local_center(node)
var world := node.global_transform * center
var forward := node.global_transform.basis.z
var pivot := Node3D.new()
pivot.name = "Animal%d_%s" % [id, kinds[id]]
pivot.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(pivot)
node.reparent(pivot, false)
node.transform = Transform3D(Basis(), Vector3(-center.x, 0.0, -center.z))
_pivots[id] = pivot
var meshes: Array[MeshInstance3D] = []
for mi in node.find_children("*", "MeshInstance3D", true, false):
meshes.append(mi)
_meshes[id] = meshes
_start[id] = Vector2(world.x, world.z)
_start_yaw[id] = atan2(forward.x, forward.z)
phase[id] = _rng.randf() * TAU
sync_from_state()
## Every animal back at its spot in the pen (or hidden if lost), nobody following (new morning,
## retry).
func sync_from_state() -> void:
for k in _trails.size():
_trails[k] = PackedVector2Array()
_wander_wait = config.animal_wander_interval * 0.3
for id in range(1, count + 1):
pos[id] = _start[id]
prev[id] = _start[id]
yaw[id] = _start_yaw[id]
speed[id] = 0.0
goal[id] = _start[id]
timer[id] = _rng.randf_range(0.5, 3.0)
calm[id] = 0.0
slot[id] = -1
leaving[id] = 0
_apply_visuals(1.0)
## Co-op host: every animal's [x, z, yaw, speed].
func replica_record() -> PackedFloat32Array:
var out := PackedFloat32Array()
for id in range(1, count + 1):
out.append_array([pos[id].x, pos[id].y, yaw[id], speed[id]])
return out
## Co-op partner: the host's animals (drawn between this and the last, like a physics tick).
func apply_replica(rec: PackedFloat32Array) -> void:
if rec.size() != count * 4:
return
for id in range(1, count + 1):
var k := (id - 1) * 4
prev[id] = pos[id]
pos[id] = Vector2(rec[k], rec[k + 1])
yaw[id] = rec[k + 2]
speed[id] = rec[k + 3]
func kind(id: int) -> String:
return kinds[id] if id >= 1 and id <= count else "animal"
func position(id: int) -> Vector2:
return pos[id] if id >= 1 and id <= count else Vector2.ZERO
func in_pen(p: Vector2) -> bool:
return pen.grow(-0.6).has_point(p)
## Puts a loose animal where its carrier was stopped.
func place(id: int, p: Vector2) -> void:
pos[id] = p
prev[id] = p
speed[id] = 0.0
timer[id] = _rng.randf_range(0.6, 1.2) # a moment's shock before it bolts
func start_following(id: int) -> void:
var who := clampi(loot.recoverer if loot != null else 0, 0, maxi(leaders.size() - 1, 0))
var taken := 0
for other in range(1, count + 1):
if slot[other] >= 0 and leader[other] == who:
taken = maxi(taken, slot[other] + 1)
slot[id] = taken
leader[id] = who
## Whether there's a way out of the pen that crosses no structure (flood fill from inside the pen
## over walkable cells, reaching past the pen fence). Run whenever the structures change.
func update_pen_open() -> void:
var limit := pen.grow(2.0)
var outside := pen.grow(0.75)
var start := nav.cell_of(pen.get_center().x, pen.get_center().y)
var seen := {}
var queue: Array[int] = []
for c in nav.free_cells_in(pen.grow(-1.2)):
if nav.is_walkable(c):
queue.append(c)
seen[c] = true
if queue.is_empty():
queue.append(start)
var head := 0
var was := pen_open
pen_open = false
while head < queue.size():
var c := queue[head]
head += 1
var p := nav.cell_center(c)
if not outside.has_point(p):
pen_open = true
break
for k in 4:
var nb: int = c + nav._offsets[k]
if seen.has(nb) or not nav.is_walkable(nb) or not limit.has_point(nav.cell_center(nb)):
continue
seen[nb] = true
queue.append(nb)
if pen_open and not was:
_wander_wait = config.animal_wander_interval * 0.3
if pen_open != was:
pen_changed.emit(pen_open)
## Physics tick, after the loot system (recoveries) and before the night's arrivals.
func step(dt: float) -> void:
var at: Array[Vector2] = []
for k in leaders.size():
var body := leaders[k]
at.append(Vector2(body.global_position.x, body.global_position.z) if body != null else Vector2(INF, INF))
if body != null:
_record_trail(k, at[k])
_wander_out(dt)
for id in range(1, count + 1):
prev[id] = pos[id]
calm[id] = maxf(calm[id] - dt, 0.0)
var item := loot.animal_item(id)
match loot.status[item]:
LootSystem.Status.HOME:
slot[id] = -1
_wander(id, item, dt)
LootSystem.Status.DROPPED:
slot[id] = -1
if not in_pen(pos[id]):
leaving[id] = 0
if in_pen(pos[id]) and leaving[id] == 0:
loot.animal_home(item)
_rest(id)
else:
_stray(id, item, dt)
LootSystem.Status.FOLLOWING:
var k := clampi(leader[id], 0, at.size() - 1)
_follow(id, item, at[k], dt)
LootSystem.Status.CARRIED:
slot[id] = -1
var d := enemies.resolve_handle(loot.holder[item])
if d >= 0:
pos[id] = Vector2(enemies.pos_x[d], enemies.pos_z[d])
speed[id] = 0.0
_:
slot[id] = -1
speed[id] = 0.0
func _process(_delta: float) -> void:
_apply_visuals(Engine.get_physics_interpolation_fraction())
func _wander(id: int, item: int, dt: float) -> void:
# Stand still while a thief is catching it.
var d := enemies.resolve_handle(loot.holder[item]) if loot.holder[item] >= 0 else -1
if d >= 0 and Vector2(enemies.pos_x[d], enemies.pos_z[d]).distance_to(pos[id]) < 2.0:
speed[id] = 0.0
var to := Vector2(enemies.pos_x[d], enemies.pos_z[d]) - pos[id]
if to.length_squared() > 1e-4:
yaw[id] = lerp_angle(yaw[id], atan2(-to.x, -to.y), 0.1) # facing away, cowering
return
timer[id] -= dt
if speed[id] == 0.0:
if timer[id] <= 0.0:
goal[id] = _wander_goal()
speed[id] = float(WANDER_SPEED.get(kinds[id], 0.7))
timer[id] = 8.0 # give up on a goal it can't reach
return
var to := goal[id] - pos[id]
if to.length() < 0.2 or timer[id] <= 0.0:
_rest(id)
return
_move(id, to.normalized(), speed[id], dt)
func _stray(id: int, item: int, dt: float) -> void:
if escape_field.size() > 0 and escape_field[nav.cell_of(pos[id].x, pos[id].y)] == 0:
loot.animal_escaped(item)
speed[id] = 0.0
return
timer[id] -= dt
if timer[id] <= 0.0:
if speed[id] > 0.0:
speed[id] = 0.0 # graze a moment
timer[id] = _rng.randf_range(0.8, 1.8)
else:
speed[id] = config.stray_speed
timer[id] = _rng.randf_range(3.0, 5.0)
if speed[id] > 0.0 and escape_field.size() > 0 and nav.flow_direction(escape_field, pos[id].x, pos[id].y, _dir):
_move(id, Vector2(_dir[0], _dir[1]), speed[id], dt)
func _follow(id: int, item: int, sc: Vector2, dt: float) -> void:
if in_pen(pos[id]):
loot.animal_home(item)
calm[id] = config.animal_calm_time
slot[id] = -1
_rest(id)
return
if pos[id].distance_to(sc) > FOLLOW_LEASH:
loot.status[item] = LootSystem.Status.DROPPED
loot.ground[item] = pos[id]
slot[id] = -1
_rest(id)
return
var target := _trail_point(clampi(leader[id], 0, _trails.size() - 1), sc, FOLLOW_FIRST + FOLLOW_GAP * maxi(slot[id], 0))
var to := target - pos[id]
var dist := to.length()
speed[id] = clampf(dist * 3.0, 0.0, config.follow_speed)
if dist < 0.05:
speed[id] = 0.0
return
var step_len := minf(speed[id] * dt, dist)
pos[id] += to / dist * step_len
yaw[id] = lerp_angle(yaw[id], atan2(to.x, to.y), 0.2)
## Moves with the grid's collision (static obstacles and structures), sliding along an axis
## when blocked.
func _move(id: int, dir: Vector2, v: float, dt: float) -> void:
var p := pos[id]
var n := p + dir * v * dt
if not nav.is_walkable(nav.cell_of(n.x, n.y)):
if nav.is_walkable(nav.cell_of(n.x, p.y)):
n.y = p.y
elif nav.is_walkable(nav.cell_of(p.x, n.y)):
n.x = p.x
else:
n = p
pos[id] = n
if n.distance_squared_to(p) > 1e-8:
var moved := n - p
yaw[id] = lerp_angle(yaw[id], atan2(moved.x, moved.y), 0.15)
func _rest(id: int) -> void:
speed[id] = 0.0
timer[id] = _rng.randf_range(1.5, 4.0)
func _wander_goal() -> Vector2:
var area := pen.grow(-1.2)
for attempt in 12:
var p := Vector2(_rng.randf_range(area.position.x, area.end.x), _rng.randf_range(area.position.y, area.end.y))
if nav.is_walkable(nav.cell_of(p.x, p.y)):
return p
return area.get_center()
## At night, while the pen is open, a calm animal walks out now and then.
func _wander_out(dt: float) -> void:
var ph := campaign.state.phase
if not pen_open or (ph != CampaignController.Phase.NIGHT and ph != CampaignController.Phase.DAWN):
return
_wander_wait -= dt
if _wander_wait > 0.0:
return
_wander_wait = config.animal_wander_interval
var calm_ones: Array[int] = []
for id in range(1, count + 1):
var item := loot.animal_item(id)
if loot.status[item] == LootSystem.Status.HOME and loot.holder[item] == -1 and calm[id] == 0.0:
calm_ones.append(id)
if not calm_ones.is_empty():
var id := calm_ones[_rng.randi() % calm_ones.size()]
loot.animal_strays(loot.animal_item(id))
leaving[id] = 1
speed[id] = config.stray_speed
timer[id] = 4.0
func _record_trail(k: int, sc: Vector2) -> void:
var trail := _trails[k]
if trail.is_empty() or trail[trail.size() - 1].distance_to(sc) >= TRAIL_STEP:
trail.append(sc)
if trail.size() > TRAIL_POINTS:
trail.remove_at(0)
_trails[k] = trail # packed arrays are values: store the changed one back
## The point `back` meters behind a scarecrow along the path it walked.
func _trail_point(k: int, sc: Vector2, back: float) -> Vector2:
var trail := _trails[k]
var at := sc
var left := back
for i in range(trail.size() - 1, -1, -1):
var p := trail[i]
var seg := at.distance_to(p)
if seg >= left:
return at.lerp(p, left / seg) if seg > 1e-5 else p
left -= seg
at = p
return at
func _apply_visuals(f: float) -> void:
for id in range(1, count + 1):
var pivot := _pivots[id]
var item := loot.animal_item(id)
var st := loot.status[item]
pivot.visible = st != LootSystem.Status.LOST
if not pivot.visible:
continue
var outline: Material = loot.outline_for(LootSystem.Category.ANIMAL) \
if st == LootSystem.Status.CARRIED or st == LootSystem.Status.DROPPED else null
for mi: MeshInstance3D in _meshes[id]:
if mi.material_overlay != outline:
mi.material_overlay = outline
if st == LootSystem.Status.CARRIED:
var d := enemies.resolve_handle(loot.holder[item])
var p := enemies.visual_position(d) if d >= 0 else pos[id]
var t := Time.get_ticks_msec() / 1000.0
pivot.position = Vector3(p.x, config.combat_height - 1.05, p.y)
pivot.rotation = Vector3(sin(t * 9.0) * 0.25, yaw[id] + sin(t * 4.0) * 0.4, sin(t * 11.0) * 0.2)
continue
var p := prev[id].lerp(pos[id], f)
var moving := speed[id] > 0.05
phase[id] += (get_process_delta_time() if is_inside_tree() else 0.0) * (6.0 + speed[id] * 6.0) * (1.0 if moving else 0.0)
var y := 0.0
var roll := 0.0
if moving:
if kinds[id] == "chicken":
y = absf(sin(phase[id])) * 0.12
else:
y = absf(sin(phase[id])) * 0.03
roll = sin(phase[id]) * 0.07
pivot.position = Vector3(p.x, y, p.y)
pivot.rotation = Vector3(0.0, yaw[id], roll)
## The middle of a model's body, in its own coordinates (from its meshes' bounds).
static func _local_center(node: Node3D) -> Vector3:
var box := AABB()
var first := true
for mi in node.find_children("*", "MeshInstance3D", true, false):
var m := mi as MeshInstance3D
var local := node.global_transform.affine_inverse() * m.global_transform
var a: AABB = local * m.get_aabb()
box = a if first else box.merge(a)
first = false
return box.get_center() if not first else Vector3.ZERO

View file

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

View file

@ -0,0 +1,59 @@
class_name Assessment
extends RefCounted
## The final assessment once the farmers are back: the share of each category kept, a weighted
## score, its rating tier (GameConfig.assessment_weights, rating_tiers), and the vacation's totals.
## * Crops and animals: what's still on the farm of what was there at the start.
## * Supplies are also spent on building, so they count by theft instead: of everything that
## passed through the farm (the shed's starting stock plus everything gathered), the share
## thieves didn't carry off.
## Categories not in play are left out and the weights renormalized.
## {"parts": category -> share kept (0..1), "score": 0..100, "tier", "text" (the tier's
## line), "totals": FarmState.totals(), "supplies_handled", "supplies_lost"}.
static func of(s: FarmState, cfg: GameConfig) -> Dictionary:
var t := s.totals()
var parts := {}
if s.crops_total > 0:
parts["crops"] = float(s.crops) / s.crops_total
if s.animals_total > 0:
parts["animals"] = float(s.animals) / s.animals_total
var handled: int = s.supplies_total + int(t["gathered_wood"]) + int(t["gathered_scrap"]) + int(t["gathered_straw"])
if handled > 0:
parts["supplies"] = 1.0 - minf(float(t["supplies_lost"]) / handled, 1.0)
var weight := 0.0
var sum := 0.0
for k: String in parts:
var w := float(cfg.assessment_weights.get(k, 0.0))
weight += w
sum += w * float(parts[k])
var score := roundi(100.0 * sum / weight) if weight > 0.0 else 0
var tier := {}
for row in cfg.rating_tiers:
if score >= int(row.get("min", 0)):
tier = row
break
return {"parts": parts, "score": score, "tier": String(tier.get("name", "")), "text": String(tier.get("text", "")),
"totals": t, "supplies_handled": handled, "supplies_lost": int(t["supplies_lost"])}
## "50 crows, 20 thieves and 6 fence breakers" (or "none").
static func enemies_line(t: Dictionary) -> String:
var parts := PackedStringArray()
for type in [EnemySystem.TYPE_CROW, EnemySystem.TYPE_THIEF, EnemySystem.TYPE_BREAKER]:
var n := int(t.get("killed_" + EnemySystem.TYPE_NAMES[type], 0))
if n == 1:
parts.append("1 " + EnemySystem.NAMES[type])
elif n > 1:
parts.append("%d %s" % [n, EnemySystem.PLURALS[type]])
return PhaseHud.join_words(parts) if not parts.is_empty() else "none"
## "18 wood, 6 scrap, 12 straw" from the gathered_ or spent_ counts (or "nothing").
static func materials_line(t: Dictionary, prefix: String) -> String:
var amounts := {}
for m in ResourceStore.MATERIALS:
if int(t.get(prefix + m, 0)) > 0:
amounts[m] = int(t[prefix + m])
var text := ResourceStore.describe(amounts)
return text if text != "" else "nothing"

View file

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

89
game/scripts/asset_hud.gd Normal file
View file

@ -0,0 +1,89 @@
class_name AssetHud
extends Control
## Top-center readout of what's left to protect: "Crops 28/30 · Animals 7/8 · Supplies 23" (the
## shed's stock plus any sacks still on the farm), each in its category's color. A count flashes
## red when it drops and green when it rises. Categories not in play are left out.
const FLASH_TIME := 1.2
const LOSS := Color(1.0, 0.3, 0.25)
const GAIN := Color(0.5, 1.0, 0.45)
var campaign: CampaignController
var _box: HBoxContainer
var _panel: PanelContainer
var _labels: Array[Label] = []
var _last := PackedInt32Array([-1, -1, -1])
var _flash := PackedFloat32Array([0.0, 0.0, 0.0])
var _flash_color: Array[Color] = [Color.WHITE, Color.WHITE, Color.WHITE]
func setup(p_campaign: CampaignController) -> void:
campaign = p_campaign
_last = _counts()
func _ready() -> void:
set_anchors_preset(Control.PRESET_FULL_RECT)
mouse_filter = Control.MOUSE_FILTER_IGNORE
_panel = PanelContainer.new()
var bg := StyleBoxFlat.new()
bg.bg_color = Color(0.0, 0.0, 0.0, 0.42)
bg.content_margin_left = 18.0
bg.content_margin_right = 18.0
bg.content_margin_top = 4.0
bg.content_margin_bottom = 4.0
_panel.add_theme_stylebox_override("panel", bg)
_panel.mouse_filter = Control.MOUSE_FILTER_IGNORE
add_child(_panel)
_box = HBoxContainer.new()
_box.add_theme_constant_override("separation", 28)
_box.mouse_filter = Control.MOUSE_FILTER_IGNORE
_panel.add_child(_box)
for c in 3:
var l := Label.new()
l.add_theme_font_size_override("font_size", 24)
l.add_theme_color_override("font_color", LootSystem.CATEGORY_COLORS[c])
l.add_theme_color_override("font_outline_color", Color.BLACK)
l.add_theme_constant_override("outline_size", 6)
l.mouse_filter = Control.MOUSE_FILTER_IGNORE
_box.add_child(l)
_labels.append(l)
## "Crops 28/30 · Animals 7/8 · Supplies 23", as the HUD shows it (also used by tests).
func describe() -> String:
var parts: Array[String] = []
for l in _labels:
if l.visible:
parts.append(l.text)
return " · ".join(parts)
func _process(delta: float) -> void:
if campaign == null:
return
var s := campaign.state
var now := _counts()
var texts := ["Crops %d/%d" % [s.crops, s.crops_total], "Animals %d/%d" % [s.animals, s.animals_total],
"Supplies %d" % s.supplies]
var in_play := [s.crops_total > 0, s.animals_total > 0, s.supplies_total > 0]
for c in 3:
var l := _labels[c]
l.visible = in_play[c]
l.text = texts[c]
if _last[c] >= 0 and now[c] != _last[c]:
_flash[c] = FLASH_TIME
_flash_color[c] = LOSS if now[c] < _last[c] else GAIN
_last[c] = now[c]
_flash[c] = maxf(_flash[c] - delta, 0.0)
var k := _flash[c] / FLASH_TIME
var pulse := (0.5 + 0.5 * sin(_flash[c] * 18.0)) * k
l.modulate = Color.WHITE.lerp(_flash_color[c] * 1.4, pulse)
_panel.reset_size()
_panel.position = Vector2((size.x - _panel.size.x) * 0.5, 14.0)
func _counts() -> PackedInt32Array:
var s := campaign.state
return PackedInt32Array([s.crops, s.animals, s.supplies])

View file

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

32
game/scripts/avatar.gd Normal file
View file

@ -0,0 +1,32 @@
class_name Avatar
extends RefCounted
## One scarecrow in play and everything that acts for it: its body, its kit (health, fear,
## patching), its gun, and its hands (Interactions). Solo there is one (player 1). In co-op
## FarmSim holds two: slot 0 is player 1 (the host's), slot 1 player 2 (the partner's). The one
## this machine plays is local; on the host the partner's reads RemoteControls (remote), and on
## the partner's machine player 1's is moved by the network.
const NAMES: Array[String] = ["P1", "P2"]
const COLORS: Array[Color] = [Color(1.0, 0.85, 0.35), Color(0.45, 0.8, 1.0)]
var slot: int = 0
var body: PlayerCharacter
var kit: Scarecrow
var combat: ScarecrowCombat
var interactions: Interactions
var remote: RemoteControls
var is_local := true
## The player's name (co-op), shown on the tag over the head and the partner HUD.
var player_name := ""
func position() -> Vector2:
return Vector2(body.global_position.x, body.global_position.z)
func label() -> String:
return "%s %s" % [NAMES[slot], player_name] if player_name != "" else NAMES[slot]
func color() -> Color:
return COLORS[slot]

View file

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

76
game/scripts/build_hud.gd Normal file
View file

@ -0,0 +1,76 @@
class_name BuildHud
extends Control
## The build hotbar, shown in build mode: one slot per buildable with its key, name, and cost
## (red when it can't be afforded), the selected one highlighted, the controls, and how many
## structures stand on the farm.
const SLOT := Vector2(230.0, 76.0)
const GAP := 12.0
var build: BuildMode
var campaign: CampaignController
var _names: Array[Label] = []
var _costs: Array[Label] = []
var _help: Label
func setup(p_build: BuildMode, p_campaign: CampaignController) -> void:
build = p_build
campaign = p_campaign
func _ready() -> void:
set_anchors_preset(Control.PRESET_FULL_RECT)
mouse_filter = Control.MOUSE_FILTER_IGNORE
for i in StructureSystem.ORDER.size():
_names.append(_label(22))
_costs.append(_label(18))
_help = _label(19)
func _process(_delta: float) -> void:
visible = build != null and build.active
if not visible:
return
var r := campaign.state.resources
var origin := _origin()
for i in StructureSystem.ORDER.size():
var t: String = StructureSystem.ORDER[i]
var cost: Dictionary = campaign.config.costs.get(t, {})
var pos := origin + Vector2(i * (SLOT.x + GAP), 0.0)
_names[i].text = "%d %s" % [i + 1, StructureSystem.NAMES[t]]
_names[i].position = pos + Vector2(12.0, 8.0)
_costs[i].text = ResourceStore.describe(cost)
_costs[i].position = pos + Vector2(12.0, 42.0)
_costs[i].add_theme_color_override("font_color", Color(0.9, 0.95, 0.9) if r.can_afford(cost) else Color(1.0, 0.45, 0.4))
_help.text = "Build mode · LMB / RT build · Z C / d-pad rotate · 1-4 / Tab pick · RMB / B dismantle or leave · %d built" % \
build.structures.count()
_help.position = origin + Vector2(0.0, -34.0)
queue_redraw()
func _draw() -> void:
if build == null or not build.active:
return
var origin := _origin()
for i in StructureSystem.ORDER.size():
var rect := Rect2(origin + Vector2(i * (SLOT.x + GAP), 0.0), SLOT)
draw_rect(rect, Color(0.0, 0.0, 0.0, 0.55))
draw_rect(rect, Color(1.0, 0.9, 0.4) if i == build.selected else Color(1.0, 1.0, 1.0, 0.25), false, 3.0 if i == build.selected else 1.5)
func _origin() -> Vector2:
var n := StructureSystem.ORDER.size()
var width := n * SLOT.x + (n - 1) * GAP
return Vector2((size.x - width) * 0.5, size.y - SLOT.y - 28.0)
func _label(font_size: int) -> Label:
var l := Label.new()
l.add_theme_font_size_override("font_size", font_size)
l.add_theme_color_override("font_outline_color", Color.BLACK)
l.add_theme_constant_override("outline_size", 6)
l.mouse_filter = Control.MOUSE_FILTER_IGNORE
add_child(l)
return l

View file

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

208
game/scripts/build_mode.gd Normal file
View file

@ -0,0 +1,208 @@
class_name BuildMode
extends Node3D
## The scarecrow's build mode (build_mode: B / d-pad up toggles it):
## * Pick what to build with 1-4, or cycle with build_next (Tab / d-pad down).
## * A ghost follows the cursor, snapped to the 0.5 m grid: the ground point under the mouse,
## or GAMEPAD_REACH ahead along the right stick. rotate_left / rotate_right (Z / C, d-pad)
## turn it by 45 degrees.
## * The ghost is green where it can go and red where it can't, with the reason above it.
## * fire (LMB / RT) builds it (StructureSystem.validate, then place).
## * Over a built structure, cancel (RMB / B) dismantles it for its refund; anywhere else
## cancel leaves build mode.
## The scarecrow doesn't shoot, gather, or repair while building (FarmSim, Interactions).
## Co-op, on the partner's machine: placing and dismantling are sent to the host (place_request,
## dismantle_request), which checks them again and does them; the result comes back as a message.
signal message(text: String, color: Color)
signal toggled(on: bool)
## A placement was refused (the reason); a structure was taken down.
signal refused(reason: String)
signal dismantled(type: String)
const ACTIONS: Array[StringName] = [&"build_mode", &"build_next", &"build_1", &"build_2", &"build_3",
&"build_4", &"rotate_left", &"rotate_right", &"fire", &"cancel"]
const GAMEPAD_REACH := 3.0
var active := false
var selected: int = 0
var rot: int = 0
var cursor := Vector2.ZERO
## Built structure under the cursor (-1 = none) and why the ghost can't be placed ("" = it can).
var hover: int = -1
var reason := ""
var config: GameConfig
var campaign: CampaignController
var player: PlayerCharacter
var camera: Camera3D
var structures: StructureSystem
var combat: ScarecrowCombat
var kit: Scarecrow
## Co-op partner: ask the host instead (type, x, z, rot) / (structure id).
var place_request: Callable
var dismantle_request: Callable
var _edges := ActionEdges.new()
var _ghost: Node3D
var _ghost_key := ""
var _ok_mat: StandardMaterial3D
var _bad_mat: StandardMaterial3D
var _label: Label3D
var _stick_dir := Vector2(0.0, -1.0)
func setup(cfg: GameConfig, p_campaign: CampaignController, p_player: PlayerCharacter, p_camera: Camera3D,
p_structures: StructureSystem, p_combat: ScarecrowCombat, p_kit: Scarecrow) -> void:
config = cfg
campaign = p_campaign
player = p_player
camera = p_camera
structures = p_structures
combat = p_combat
kit = p_kit
_ok_mat = _ghost_material(Color(0.3, 1.0, 0.4, 0.45))
_bad_mat = _ghost_material(Color(1.0, 0.25, 0.2, 0.45))
_label = Label3D.new()
_label.billboard = BaseMaterial3D.BILLBOARD_ENABLED
_label.no_depth_test = true
_label.shaded = false
_label.font_size = 40
_label.outline_size = 10
_label.pixel_size = 0.0075
_label.top_level = true
_label.visible = false
_label.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(_label)
func type() -> String:
return StructureSystem.ORDER[selected]
func set_active(on: bool) -> void:
if on == active:
return
active = on
if _ghost != null:
_ghost.visible = on
_label.visible = on
toggled.emit(on)
## One physics tick. Every action is polled each tick so presses are seen exactly once.
func step(_dt: float) -> void:
var p := {}
for a in ACTIONS:
p[a] = _edges.pressed(a)
if not kit.alive:
set_active(false)
return
if p[&"build_mode"]:
set_active(not active)
if not active:
return
for k in 4:
if p[StringName("build_%d" % (k + 1))]:
selected = k
if p[&"build_next"]:
selected = (selected + 1) % StructureSystem.ORDER.size()
if p[&"rotate_left"]:
rot = (rot + 7) % 8
if p[&"rotate_right"]:
rot = (rot + 1) % 8
_update_cursor()
var me := Vector2(player.global_position.x, player.global_position.z)
hover = structures.structure_near(cursor, 0.3)
if hover >= 0:
reason = ""
if p[&"cancel"]:
if dismantle_request.is_valid():
dismantle_request.call(hover)
hover = -1
return
var e := campaign.state.structure(hover)
var back := structures.dismantle(hover)
dismantled.emit(String(e["type"]))
message.emit("Dismantled the %s%s" % [StructureSystem.NAMES[e["type"]].to_lower(),
(": %s back in the shed" % ResourceStore.describe(back)) if not back.is_empty() else ""], Color(0.85, 0.95, 1.0))
hover = -1
return
reason = structures.validate(type(), cursor.x, cursor.y, rot, me)
if p[&"fire"]:
if reason == "" and place_request.is_valid():
place_request.call(type(), cursor.x, cursor.y, rot)
elif reason == "":
structures.place(type(), cursor.x, cursor.y, rot)
message.emit("Built a %s" % StructureSystem.NAMES[type()].to_lower(), Color(0.6, 1.0, 0.55))
else:
message.emit(reason, Color(1.0, 0.8, 0.5))
refused.emit(reason)
elif p[&"cancel"]:
set_active(false)
func _unhandled_input(event: InputEvent) -> void:
_edges.note(event, ACTIONS)
func _update_cursor() -> void:
var at: Vector2
if combat.device == ScarecrowCombat.Device.GAMEPAD:
var b := camera.global_transform.basis
var fwd := Vector2(-b.z.x, -b.z.z).normalized()
var right := Vector2(b.x.x, b.x.z).normalized()
var stick := Input.get_vector("aim_left", "aim_right", "aim_down", "aim_up", config.aim_dead_zone)
if stick != Vector2.ZERO:
_stick_dir = (right * stick.x + fwd * stick.y).normalized()
at = Vector2(player.global_position.x, player.global_position.z) + _stick_dir * GAMEPAD_REACH
else:
var screen := camera.get_viewport().get_mouse_position()
var o := camera.project_ray_origin(screen)
var d := camera.project_ray_normal(screen)
var t := -o.y / d.y if absf(d.y) > 1e-5 else 0.0
at = Vector2(o.x + d.x * t, o.z + d.z * t)
cursor = StructureSystem.snap(at)
func _process(_delta: float) -> void:
if not active:
return
var key := "%s/%d" % [type(), rot]
if key != _ghost_key:
_ghost_key = key
if _ghost != null:
_ghost.queue_free()
_ghost = structures.make_ghost(type(), rot)
_ghost.top_level = true
add_child(_ghost)
var ok := reason == "" and hover < 0
for mi in _ghost.find_children("*", "MeshInstance3D", true, false):
(mi as MeshInstance3D).material_override = _ok_mat if ok else _bad_mat
_ghost.visible = hover < 0
_ghost.global_position = Vector3(cursor.x, structures._ground_y(cursor), cursor.y)
_label.global_position = Vector3(cursor.x, 2.4, cursor.y)
if hover >= 0:
var e := campaign.state.structure(hover)
var refund := {}
var cost: Dictionary = config.costs.get(e.get("type", ""), {})
for m in cost:
if floori(int(cost[m]) * config.dismantle_refund) > 0:
refund[m] = floori(int(cost[m]) * config.dismantle_refund)
_label.text = "%s %d/%d\n[RMB / B] Dismantle%s" % [StructureSystem.NAMES.get(e.get("type", ""), ""), int(e.get("hp", 0)),
structures.max_hp(e.get("type", "fence")), (" (+%s)" % ResourceStore.describe(refund)) if not refund.is_empty() else ""]
_label.modulate = Color(0.85, 0.95, 1.0)
elif ok:
_label.text = "%s %s\n[LMB / RT] Build" % [StructureSystem.NAMES[type()], ResourceStore.describe(config.costs.get(type(), {}))]
_label.modulate = Color(0.7, 1.0, 0.7)
else:
_label.text = "%s\n%s" % [StructureSystem.NAMES[type()], reason]
_label.modulate = Color(1.0, 0.7, 0.6)
func _ghost_material(color: Color) -> StandardMaterial3D:
var m := StandardMaterial3D.new()
m.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
m.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
m.albedo_color = color
m.no_depth_test = false
return m

View file

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

View file

@ -1,7 +1,9 @@
class_name CampaignController
extends Node
## Owns the five-night vacation: the phase state machine, phase timers, the outcome rules, and
## the morning snapshot used to retry a failed night (rules: game/RULES.md).
## Owns the vacation (GameConfig.campaign_nights nights): the phase state machine, phase timers,
## the outcome rules, and the morning snapshot used to retry a failed night (rules:
## game/RULES.md). With save_path set, every morning is also saved to disk (SaveGame), and
## finishing the vacation deletes the save.
##
## MORNING -> DAY -> DUSK -> NIGHT -> DAWN -> MORNING of the next night; after the final dawn,
## FARMERS_RETURN. GAME_OVER can follow any phase. Both are terminal. The morning review is
@ -17,11 +19,24 @@ enum Outcome { CONTINUE, GAME_OVER_SCARECROW, GAME_OVER_STRIPPED, VACATION_COMPL
signal phase_changed(phase: Phase, previous: Phase)
signal campaign_ended(outcome: Outcome)
## The dawn grace is over: listeners settle the night (enemies leave, loot on the ground returns)
## before its losses are recorded and the outcome is checked.
signal night_ending
@export var config: GameConfig
var state: FarmState
var outcome: Outcome = Outcome.CONTINUE
## Set by FarmSim: night -> its plan's length, when the plan overrides GameConfig.night_length
## (returns 0 or less for "no override").
var night_length_for: Callable
## Co-op, on the partner's machine (a replica of the host's farm): what the player asks for
## (begin_day, retry_night, start_night_early) goes to the host instead ("begin_day" etc.).
var remote_request: Callable
## Where every morning is autosaved ("" = not saved; Main sets SaveGame.PATH).
var save_path := ""
## The last autosave's result.
var last_save_error: Error = OK
var _morning_snapshot: Dictionary = {}
var _night_start := PackedInt32Array()
@ -59,6 +74,9 @@ func tick(delta: float) -> void:
func begin_day() -> bool:
if state.phase != Phase.MORNING:
return false
if remote_request.is_valid():
remote_request.call("begin_day")
return true
_resolve(true)
return true
@ -67,6 +85,9 @@ func begin_day() -> bool:
func start_night_early() -> bool:
if not can_start_night_early():
return false
if remote_request.is_valid():
remote_request.call("start_night_early")
return true
_enter(Phase.NIGHT)
return true
@ -81,8 +102,23 @@ func advance_phase() -> void:
_resolve(true)
## D9: restarts the current night from its morning (the autosave point once saving exists).
## Continues a saved vacation (SaveGame.read): its morning becomes the current one.
func load_state(saved: FarmState) -> void:
state = saved
outcome = Outcome.CONTINUE
_enter(Phase.MORNING)
## The latest morning's state (what retry_night() restores and what was saved).
func morning_snapshot() -> Dictionary:
return _morning_snapshot.duplicate(true)
## D9: restarts the current night from its morning (the autosave point).
func retry_night() -> bool:
if remote_request.is_valid():
remote_request.call("retry_night")
return true
var restored := FarmState.from_dict(_morning_snapshot)
if restored == null:
return false
@ -92,18 +128,33 @@ func retry_night() -> bool:
return true
## D8: gathering, building, and upgrades happen by day (day and dusk), not at night or during
## the morning review.
func is_daytime() -> bool:
return state.phase == Phase.DAY or state.phase == Phase.DUSK
func is_over() -> bool:
return state.phase == Phase.GAME_OVER or state.phase == Phase.FARMERS_RETURN
func is_timed(phase: Phase) -> bool:
return is_finite(config.phase_length(phase))
return is_finite(phase_length(phase))
## Seconds a phase lasts tonight (the night can be longer or shorter than usual), or INF.
func phase_length(phase: Phase) -> float:
if phase == Phase.NIGHT and night_length_for.is_valid():
var override: float = night_length_for.call(state.night)
if override > 0.0:
return override
return config.phase_length(phase)
## The outcome rules as a pure function of the farm state. Scarecrow destruction is checked
## first, then a stripped farm, and only then completing the vacation.
static func check_outcome(s: FarmState, campaign_nights: int) -> Outcome:
if s.scarecrow_hp <= 0:
if s.scarecrow_hp <= 0 and (not s.coop or s.partner_hp <= 0): # in co-op, both down
return Outcome.GAME_OVER_SCARECROW
if s.is_stripped():
return Outcome.GAME_OVER_STRIPPED
@ -115,11 +166,15 @@ static func check_outcome(s: FarmState, campaign_nights: int) -> Outcome:
func _resolve(phase_finished: bool) -> void:
var finished_phase := state.phase
if phase_finished and finished_phase == Phase.DAWN:
night_ending.emit()
state.nights_survived = state.night
state.log_night(_night_start)
state.settle_supplies()
var result := check_outcome(state, config.campaign_nights)
if result != Outcome.CONTINUE:
outcome = result
if result == Outcome.VACATION_COMPLETE and save_path != "":
SaveGame.delete(save_path)
_enter(Phase.FARMERS_RETURN if result == Outcome.VACATION_COMPLETE else Phase.GAME_OVER)
campaign_ended.emit(result)
return
@ -133,11 +188,21 @@ func _resolve(phase_finished: bool) -> void:
func _enter(phase: Phase) -> void:
var previous := state.phase
state.phase = phase
var length := config.phase_length(phase)
var length := phase_length(phase)
state.phase_time_left = length if is_finite(length) else 0.0
match phase:
Phase.MORNING:
state.night_events.clear() # the day's and night's counts start now
if state.coop: # a scarecrow that fell in the night is back, at half health
if state.scarecrow_hp <= 0:
state.scarecrow_hp = ceili(state.scarecrow_max_hp / 2.0)
if state.partner_hp <= 0:
state.partner_hp = ceili(state.partner_max_hp / 2.0)
_morning_snapshot = state.to_dict()
if save_path != "":
last_save_error = SaveGame.write(_morning_snapshot, save_path)
if last_save_error != OK:
push_warning("Autosave to %s failed: %s" % [save_path, error_string(last_save_error)])
Phase.NIGHT:
_night_start = state.asset_counts()
phase_changed.emit(phase, previous)

View file

@ -1,16 +1,19 @@
class_name CampaignDebug
extends CanvasLayer
## Temporary campaign readout and debug keys, until the phase HUD (Step 7) and menus (Step 11)
## replace it.
## Enter / Space / A begin the day (ends the untimed morning review)
## Debug readout and keys (debug builds). The readout is hidden until F1; the keys always work.
## F1 show / hide this readout
## F2 cycle tonight's plan through the debug scenarios (one enemy type, then
## pairs, then all three; game/resources/scenarios/) and back to the real one
## N start the night early (only when GameConfig.allow_early_night is on)
## R / Start after Game Over: retry the night; after the farmers return: new vacation
## R after Game Over: retry the night; after the farmers return: new vacation
## F6 end the current phase now
## F7 cycle game speed 1x / 5x / 20x
## F9 debug: scarecrow to 0 HP
## F10 debug: strip every farm asset
## T / G / H debug: send in a thief / a crow / a fence breaker (FarmSim)
const SPEEDS: Array[float] = [1.0, 5.0, 20.0]
const SCENARIOS: Array[String] = ["crows", "thieves", "breakers", "crows_thieves", "thieves_breakers", "all_three"]
const ENDINGS := {
CampaignController.Outcome.GAME_OVER_SCARECROW: "GAME OVER: the scarecrow was destroyed",
CampaignController.Outcome.GAME_OVER_STRIPPED: "GAME OVER: the farm was stripped bare",
@ -18,17 +21,21 @@ const ENDINGS := {
}
@export var campaign: CampaignController
## Optional: shows thieves and crops in flight.
@export var sim: FarmSim
var _label: Label
var _speed_index: int = 0
var _scenario: int = -1
func _ready() -> void:
_label = Label.new()
_label.position = Vector2(24.0, 20.0)
_label.position = Vector2(24.0, 140.0)
_label.add_theme_font_size_override("font_size", 22)
_label.add_theme_color_override("font_outline_color", Color.BLACK)
_label.add_theme_constant_override("outline_size", 6)
_label.visible = false
add_child(_label)
@ -42,9 +49,7 @@ func _process(_delta: float) -> void:
func _unhandled_input(event: InputEvent) -> void:
var s := campaign.state
if event.is_action_pressed("ui_accept") and s.phase == CampaignController.Phase.MORNING:
campaign.begin_day()
elif event.is_action_pressed("restart"):
if event.is_action_pressed("restart") and event is InputEventKey:
if s.phase == CampaignController.Phase.GAME_OVER:
campaign.retry_night()
elif s.phase == CampaignController.Phase.FARMERS_RETURN:
@ -53,6 +58,10 @@ func _unhandled_input(event: InputEvent) -> void:
if key == null or not key.pressed or key.echo:
return
match key.physical_keycode:
KEY_F1:
_label.visible = not _label.visible
KEY_F2:
cycle_scenario()
KEY_N:
campaign.start_night_early()
KEY_F6:
@ -63,9 +72,20 @@ func _unhandled_input(event: InputEvent) -> void:
KEY_F9:
s.scarecrow_hp = 0
KEY_F10:
s.crops = 0
s.animals = 0
s.supplies = 0
s.strip()
## Next debug scenario as tonight's plan (after the last, the real plan again).
func cycle_scenario() -> void:
if sim == null:
return
_scenario = _scenario + 1 if _scenario + 1 < SCENARIOS.size() else -1
var plan: NightPlan = null
if _scenario >= 0:
plan = load("res://game/resources/scenarios/%s.tres" % SCENARIOS[_scenario]) as NightPlan
sim.waves.debug_plan = plan
if sim.toasts != null:
sim.toasts.push("Tonight (debug): %s" % (plan.title if plan != null else "the night's own plan"), Color(0.8, 0.9, 1.0))
func _describe() -> String:
@ -81,11 +101,13 @@ func _describe() -> String:
if s.animals_total > 0:
farm += " · Animals %d/%d" % [s.animals, s.animals_total]
if s.supplies_total > 0:
farm += " · Supplies %d" % s.supplies
farm += " · Supplies %d%s" % [s.supplies, " (raided)" if s.shed_raided else ""]
lines.append(farm)
if sim != null and sim.loot != null:
lines.append("Thieves %d · carried %d, dropped %d, following %d · pen %s" % [sim.enemies.alive_count(),
sim.loot.count(LootSystem.Status.CARRIED), sim.loot.count(LootSystem.Status.DROPPED),
sim.loot.followers(), "open" if sim.animals.pen_open else "closed"])
match s.phase:
CampaignController.Phase.MORNING:
lines.append("[Enter] begin the day")
CampaignController.Phase.GAME_OVER:
lines.append(ENDINGS[campaign.outcome] + " · [R] retry the night")
CampaignController.Phase.FARMERS_RETURN:
@ -93,5 +115,7 @@ func _describe() -> String:
_:
if campaign.can_start_night_early():
lines.append("[N] start the night early")
lines.append("F6 next phase · F7 speed · F9 scarecrow to 0 HP · F10 strip farm")
if sim != null and sim.waves.debug_plan != null:
lines.append("Scenario: %s (F2 next)" % sim.waves.debug_plan.title)
lines.append("F1 hide · F2 scenario · F6 next phase · F7 speed · F9 scarecrow to 0 HP · F10 strip farm · T/G/H thief/crow/breaker")
return "\n".join(lines)

View file

@ -0,0 +1,80 @@
class_name ConfirmBox
extends CenterContainer
## A yes / no question over the menus (Main): the message, the confirming button, and Cancel
## (focused, so a stray Enter / A never throws progress away). Escape / B cancels.
var message: Label
var yes_button: Button
var no_button: Button
var is_open := false
var _on_yes: Callable
func _ready() -> void:
set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
var panel := PanelContainer.new()
add_child(panel)
var margin := MarginContainer.new()
for side in ["left", "right", "top", "bottom"]:
margin.add_theme_constant_override("margin_" + side, 30)
panel.add_child(margin)
var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 22)
margin.add_child(box)
message = Label.new()
message.custom_minimum_size = Vector2(560.0, 0.0)
message.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
message.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
message.add_theme_font_size_override("font_size", 24)
box.add_child(message)
var row := HBoxContainer.new()
row.alignment = BoxContainer.ALIGNMENT_CENTER
row.add_theme_constant_override("separation", 24)
box.add_child(row)
yes_button = Button.new()
yes_button.custom_minimum_size = Vector2(240.0, 54.0)
yes_button.pressed.connect(_yes)
row.add_child(yes_button)
no_button = Button.new()
no_button.text = "Cancel"
no_button.custom_minimum_size = Vector2(200.0, 54.0)
no_button.pressed.connect(close)
row.add_child(no_button)
visible = false
mouse_filter = Control.MOUSE_FILTER_IGNORE
func ask(text: String, confirm_text: String, on_yes: Callable) -> void:
message.text = text
yes_button.text = confirm_text
_on_yes = on_yes
is_open = true
visible = true
mouse_filter = Control.MOUSE_FILTER_STOP
no_button.grab_focus.call_deferred()
func close() -> void:
if not is_open:
return
is_open = false
visible = false
mouse_filter = Control.MOUSE_FILTER_IGNORE
func _draw() -> void:
draw_rect(Rect2(Vector2.ZERO, size), Color(0.0, 0.0, 0.0, 0.45)) # dims what's behind
func _yes() -> void:
var then := _on_yes
close()
if then.is_valid():
then.call()
func _unhandled_input(event: InputEvent) -> void:
if is_open and event.is_action_pressed("ui_cancel"):
close()
get_viewport().set_input_as_handled()

View file

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

171
game/scripts/coop_hud.gd Normal file
View file

@ -0,0 +1,171 @@
class_name CoopHud
extends Control
## The co-op part of the HUD (Main adds it to the farm's HUD layer):
## * the partner panel, above your own health: their name in their color (P1 gold, P2 blue),
## their health pips, what they're doing (down until morning, patching, gathering, fear
## ready), a speaker mark while their voice comes through, and the ping; plus your
## microphone (on / muted, [M])
## * an arrow at the screen edge toward the partner when they're off screen, with the distance
## * the lobby's status while hosting with nobody in yet ("Waiting for a friend to join ...")
## Both scarecrows also wear name tags (PlayerCharacter.set_tag).
const PANEL := Rect2(22.0, -318.0, 336.0, 104.0) # from the bottom left
const PIP := Vector2(14.0, 9.0)
const ARROW_MARGIN := 60.0
var sim: FarmSim
var session: CoopSession
var lobby: CoopLobby
var _name: Label
var _state: Label
var _mic: Label
var _status: Label
var _arrow_label: Label
var _arrow_at := Vector2.ZERO
var _arrow_dir := Vector2.ZERO
var _arrow_on := false
var _ping: float = -1.0
var _ping_wait: float = 0.0
var _pinging := false
func setup(p_sim: FarmSim, p_session: CoopSession, p_lobby: CoopLobby) -> void:
sim = p_sim
session = p_session
lobby = p_lobby
func _ready() -> void:
set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
mouse_filter = Control.MOUSE_FILTER_IGNORE
_name = _label(22)
_state = _label(18)
_mic = _label(16)
_status = _label(20)
_status.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
_status.add_theme_color_override("font_color", Avatar.COLORS[1])
_arrow_label = _label(17)
func _process(delta: float) -> void:
queue_redraw()
_ping_wait -= delta
if _ping_wait <= 0.0 and not _pinging and lobby != null and lobby.gdsync != null and lobby.other_id >= 0 and lobby.gdsync.is_active():
_ping_wait = 2.0
_measure_ping()
var active := session != null and session.is_active() and sim != null and sim.partner != null
var other: Avatar = null
if active:
other = sim.avatars[0] if session.is_client() else sim.partner
for l: Label in [_name, _state, _mic]:
l.visible = other != null
var waiting := lobby != null and lobby.stage == CoopLobby.Stage.HOSTING and not active
_status.visible = waiting and lobby.status != ""
_status.text = "Co-op: " + lobby.status if lobby != null else ""
_status.position = Vector2((size.x - 900.0) * 0.5, 64.0)
_status.size = Vector2(900.0, 30.0)
_arrow_on = false
_arrow_label.visible = false
if other == null:
return
var base := Vector2(PANEL.position.x, size.y + PANEL.position.y)
_name.text = other.label()
_name.add_theme_color_override("font_color", other.color())
_name.position = base + Vector2(14.0, 6.0)
var k := other.kit
var what := ""
if not k.alive:
what = "Down until morning"
elif k.patching:
what = "Patching up"
elif other.interactions.gathering != null:
what = "Gathering"
elif k.fear_left == 0.0:
what = "Fear ready"
if session.partner_speaking():
what = ("%s · talking" % what) if what != "" else "Talking"
if _ping >= 0.0:
what += " %d ms" % roundi(_ping * 1000.0 if _ping < 10.0 else _ping)
_state.text = what
_state.add_theme_color_override("font_color", Color(1.0, 0.5, 0.42) if not k.alive else Color(0.85, 0.88, 0.82))
_state.position = base + Vector2(14.0, 58.0)
_mic.visible = not session.voices.is_empty()
_mic.text = "Your mic: %s [M]" % ("on" if session.microphone else "muted")
_mic.position = base + Vector2(14.0, PANEL.size.y + 2.0)
# The arrow toward the partner when they're off screen.
var cam := get_viewport().get_camera_3d()
if cam == null:
return
var world := other.body.global_position + Vector3(0.0, 1.2, 0.0)
var on_screen := cam.unproject_position(world)
var view := Rect2(Vector2.ZERO, size).grow(-ARROW_MARGIN)
if not cam.is_position_behind(world) and view.has_point(on_screen):
return
var center := size * 0.5
var dir := (on_screen - center)
if cam.is_position_behind(world):
dir = -dir
if dir.length_squared() < 1.0:
return
dir = dir.normalized()
var t := INF
var half := view.size * 0.5
if absf(dir.x) > 1e-4:
t = minf(t, half.x / absf(dir.x))
if absf(dir.y) > 1e-4:
t = minf(t, half.y / absf(dir.y))
_arrow_at = center + dir * t
_arrow_dir = dir
_arrow_on = true
var meters := sim.local_avatar.position().distance_to(other.position())
_arrow_label.visible = true
_arrow_label.text = "%s %d m" % [other.label(), roundi(meters)]
_arrow_label.add_theme_color_override("font_color", other.color())
_arrow_label.position = _arrow_at - dir * 46.0 - Vector2(60.0, 10.0)
func _draw() -> void:
if session == null or not session.is_active() or sim == null or sim.partner == null:
return
var other := sim.avatars[0] if session.is_client() else sim.partner
var base := Vector2(PANEL.position.x, size.y + PANEL.position.y)
draw_rect(Rect2(base, PANEL.size), Color(0.0, 0.0, 0.0, 0.45))
draw_rect(Rect2(base, Vector2(5.0, PANEL.size.y)), other.color())
var hp := other.kit.hp()
var top := other.kit.max_hp()
for i in top:
var r := Rect2(base + Vector2(14.0 + i * (PIP.x + 4.0), 40.0), PIP)
draw_rect(r, other.color() if i < hp else Color(0.15, 0.15, 0.15, 0.8))
if session.partner_speaking():
var c := base + Vector2(PANEL.size.x - 34.0, 22.0)
draw_rect(Rect2(c + Vector2(-8.0, -5.0), Vector2(6.0, 10.0)), other.color())
draw_colored_polygon(PackedVector2Array([c + Vector2(-2.0, -5.0), c + Vector2(6.0, -11.0), c + Vector2(6.0, 11.0),
c + Vector2(-2.0, 5.0)]), other.color())
draw_arc(c + Vector2(6.0, 0.0), 8.0, -0.9, 0.9, 8, other.color(), 2.0)
draw_arc(c + Vector2(6.0, 0.0), 13.0, -0.9, 0.9, 8, other.color(), 2.0)
if _arrow_on:
var tip := _arrow_at + _arrow_dir * 18.0
var side := Vector2(-_arrow_dir.y, _arrow_dir.x) * 13.0
var back := _arrow_at - _arrow_dir * 14.0
draw_colored_polygon(PackedVector2Array([tip, back + side, back - side]), other.color())
draw_polyline(PackedVector2Array([tip, back + side, back - side, tip]), Color.BLACK, 2.0)
## GD-Sync's ping (it sends a message and waits for the answer).
func _measure_ping() -> void:
_pinging = true
var p: float = await lobby.gdsync.get_client_ping(lobby.other_id)
_ping = p
_pinging = false
func _label(font_size: int) -> Label:
var l := Label.new()
l.add_theme_font_size_override("font_size", font_size)
l.add_theme_color_override("font_outline_color", Color.BLACK)
l.add_theme_constant_override("outline_size", 6)
l.mouse_filter = Control.MOUSE_FILTER_IGNORE
l.visible = false
add_child(l)
return l

View file

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

85
game/scripts/coop_link.gd Normal file
View file

@ -0,0 +1,85 @@
class_name CoopLink
extends RefCounted
## The wire between the two machines of a co-op game (CoopSession talks only to this). send()
## delivers one message (a kind and a Variant) to the other side, reliably (in order, never
## lost) or not (may be dropped; for the 20 Hz snapshots and the partner's input, which the next
## one replaces). received is emitted on the other side.
## GDSyncLink is the real one (GD-Sync, LAN or online). CoopLink.pair() makes two loopback links
## for tests: messages go through var_to_bytes / bytes_to_var like on the wire, and are delivered
## when the receiving side polls. Every link counts what it sends; unreliable messages over
## UNRELIABLE_LIMIT bytes are counted as too big (GD-Sync splits datagrams at 1200 bytes).
signal received(kind: String, data: Variant)
const UNRELIABLE_LIMIT := 1100
var sent_messages: int = 0
var sent_bytes: int = 0
## The largest unreliable message so far (bytes) and how many were over the limit.
var largest_unreliable: int = 0
var oversized: int = 0
## Set when the other side went away.
var closed := false
func send(kind: String, data: Variant, reliable: bool) -> void:
var size := var_to_bytes([kind, data]).size()
sent_messages += 1
sent_bytes += size
if not reliable:
largest_unreliable = maxi(largest_unreliable, size)
if size > UNRELIABLE_LIMIT:
oversized += 1
_deliver(kind, data, reliable)
## Delivers what has arrived (loopback links; GD-Sync delivers on its own).
func poll() -> void:
pass
func close() -> void:
closed = true
func _deliver(_kind: String, _data: Variant, _reliable: bool) -> void:
pass
## Two loopback links, each the other's far end.
static func pair() -> Array[CoopLink]:
var a := Loopback.new()
var b := Loopback.new()
a.other = b
b.other = a
return [a, b]
class Loopback extends CoopLink:
var other: Loopback
## Drops every n-th unreliable message (0 = none), to test that nothing depends on them.
var drop_every: int = 0
var _inbox: Array = []
var _count: int = 0
func _deliver(kind: String, data: Variant, reliable: bool) -> void:
if other == null or other.closed:
return
_count += 1
if not reliable and drop_every > 0 and _count % drop_every == 0:
return
other._inbox.append(var_to_bytes([kind, data])) # as on the wire
func poll() -> void:
var batch := _inbox
_inbox = []
for bytes: PackedByteArray in batch:
var m: Array = bytes_to_var(bytes)
received.emit(String(m[0]), m[1])
func close() -> void:
closed = true
if other != null:
other.closed = true
other.other = null # the pair refers to each other: break the cycle
other = null

View file

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

304
game/scripts/coop_lobby.gd Normal file
View file

@ -0,0 +1,304 @@
class_name CoopLobby
extends Node
## Finding each other over GD-Sync (the GDSync autoload), for co-op:
## LAN GD-Sync's local mode: peer to peer on the same network, no account or keys. Games
## announce themselves on the network; Join lists them.
## ONLINE GD-Sync's servers, across the internet: needs the project's GD-Sync API keys
## (Project > Tools > GD-Sync in the editor, saved to addons/GD-Sync/keys.cfg, or the
## GDSYNC_PUBLIC_KEY / GDSYNC_PRIVATE_KEY environment variables).
## The host opens a lobby named after its player ("Ana's farm") for two; the partner lists the
## open lobbies (or types one's name, online) and joins. On a LAN that doesn't pass GD-Sync's
## announcements (some firewalls; VPNs like Tailscale or ZeroTier) the partner can join by the
## host's address instead (join_address; the host's waiting status shows its addresses). Once both are in, partner_arrived (on the
## host) and joined (on the partner) give the other side's GD-Sync client id, and CoopSession
## takes over over a GDSyncLink. If the other side leaves, other_left. GD-Sync keeps running
## while the game is paused (the menus).
enum Mode { LAN, ONLINE }
enum Stage { IDLE, CONNECTING, HOSTING, SEARCHING, JOINING, IN_LOBBY }
signal status_changed(text: String)
## Join's list: [{"name", "players"}] of open lobbies with room.
signal lobbies_found(lobbies: Array)
signal partner_arrived(client_id: int)
signal joined(host_id: int)
signal other_left(client_id: int)
signal failed(text: String)
const SEARCH_EVERY := 2.0
const GAME_PORT := 42400
const GAME_TAG := "harvest-season"
var gdsync: Node
var mode: Mode = Mode.LAN
var stage: Stage = Stage.IDLE
var lobby_name := ""
var my_name := ""
var other_id: int = -1
var status := ""
var _after_connect := "" # "host" or "search"
var _join_target := ""
var _search_left: float = 0.0
func _ready() -> void:
process_mode = Node.PROCESS_MODE_ALWAYS
gdsync = get_node_or_null("/root/GDSync")
if gdsync == null:
return
gdsync.process_mode = Node.PROCESS_MODE_ALWAYS # the lobby works behind the paused menus
gdsync.connected.connect(_on_connected)
gdsync.connection_failed.connect(_on_connection_failed)
gdsync.disconnected.connect(_on_disconnected)
gdsync.lobby_created.connect(_on_lobby_created)
gdsync.lobby_creation_failed.connect(_on_lobby_creation_failed)
gdsync.lobby_joined.connect(_on_lobby_joined)
gdsync.lobby_join_failed.connect(_on_lobby_join_failed)
gdsync.lobbies_received.connect(_on_lobbies_received)
gdsync.client_joined.connect(_on_client_joined)
gdsync.client_left.connect(_on_client_left)
func available() -> bool:
return gdsync != null
## Whether online play can be tried (the API keys are there).
static func has_online_keys() -> bool:
var ks: Variant = load("res://addons/GD-Sync/Scripts/KeyStore.gd")
return ks != null and bool(ks.has_keys())
func my_id() -> int:
return int(gdsync.get_client_id()) if gdsync != null else -1
## Opens a lobby for a partner to join.
func host(p_mode: Mode, p_name: String) -> void:
if not _begin(p_mode, p_name):
return
lobby_name = ("%s's farm" % my_name).left(32)
_after_connect = "host"
_start()
## Looks for open lobbies (LAN: on the network, every SEARCH_EVERY seconds; online: on the server).
func search(p_mode: Mode, p_name: String) -> void:
if not _begin(p_mode, p_name):
return
_after_connect = "search"
_start()
func join(lobby: String) -> void:
if gdsync == null or not gdsync.is_active():
return
_join_target = lobby
stage = Stage.JOINING
_say("Joining %s..." % lobby)
gdsync.lobby_join(lobby)
## LAN: joins the game at a host's address ("192.168.1.20", or with ":port" when it isn't the
## first game port). Starts GD-Sync's local mode first if needed.
func join_address(address: String, p_name: String = "") -> void:
if gdsync == null:
failed.emit("GD-Sync isn't installed")
return
var a := address.strip_edges()
if a == "":
return
if not gdsync.is_active() or mode != Mode.LAN:
if not _begin(Mode.LAN, p_name if p_name != "" else my_name):
return
_after_connect = "address"
_join_target = a
_start()
return
var ip := a
var port := GAME_PORT
if a.count(":") == 1:
ip = a.get_slice(":", 0)
port = int(a.get_slice(":", 1))
var local_server: Node = gdsync.get("_local_server")
if local_server == null:
failed.emit("This GD-Sync version can't join by address")
return
var key := "%s:%d" % [ip, port]
# GD-Sync joins a LAN game it has heard announced; this one is "announced" by hand (and
# never expires).
(local_server.get("found_lobbies") as Dictionary)[key] = {"Name": key, "IP": ip, "Port": port, "Public": false,
"Open": true, "PlayerCount": 1, "PlayerLimit": 2, "Tags": {}, "DetectionTime": Time.get_unix_time_from_system() + 1e9}
_after_connect = "join"
join(key)
## This machine's addresses on the local network (and VPNs), for joining by address.
static func host_addresses() -> PackedStringArray:
var out := PackedStringArray()
for ip in IP.get_local_addresses():
if ip.contains(":"):
continue # IPv6
var parts := ip.split(".")
var a := int(parts[0])
var b := int(parts[1])
if a == 10 or (a == 192 and b == 168) or (a == 172 and b >= 16 and b <= 31) or (a == 100 and b >= 64 and b <= 127):
out.append(ip)
return out
## Leaves the lobby and stops GD-Sync.
func leave() -> void:
if gdsync == null:
return
var was := stage
stage = Stage.IDLE # first: stopping emits disconnected, which isn't a failure now
other_id = -1
_after_connect = ""
if was == Stage.HOSTING or was == Stage.IN_LOBBY or was == Stage.JOINING:
gdsync.lobby_leave()
if gdsync.is_active():
gdsync.stop_multiplayer()
_say("")
func _process(delta: float) -> void:
if stage == Stage.SEARCHING and gdsync != null and gdsync.is_active():
_search_left -= delta
if _search_left <= 0.0:
_search_left = SEARCH_EVERY
gdsync.get_public_lobbies()
func _begin(p_mode: Mode, p_name: String) -> bool:
if gdsync == null:
failed.emit("GD-Sync isn't installed")
return false
if p_mode == Mode.ONLINE and not has_online_keys():
failed.emit("Online play needs the GD-Sync API keys: in the editor, Project > Tools > GD-Sync (see game/COOP.md). LAN works without them.")
return false
leave()
mode = p_mode
my_name = p_name.strip_edges() if p_name.strip_edges() != "" else "Player %d" % (randi() % 900 + 100)
return true
func _start() -> void:
stage = Stage.CONNECTING
_say("Connecting%s..." % (" on the local network" if mode == Mode.LAN else " to GD-Sync"))
if mode == Mode.LAN:
gdsync.start_local_multiplayer()
else:
gdsync.start_multiplayer()
func _on_connected() -> void:
gdsync.player_set_username(my_name)
match _after_connect:
"host":
_say("Opening the lobby...")
gdsync.lobby_create(lobby_name, "", true, 2, {"game": GAME_TAG})
"search":
stage = Stage.SEARCHING
_search_left = 0.0
_say("Looking for games%s..." % (" on the local network" if mode == Mode.LAN else ""))
"address":
join_address(_join_target)
func _on_connection_failed(error: int) -> void:
stage = Stage.IDLE
var why := "the connection failed"
match error:
0:
why = "the GD-Sync API keys were refused"
1:
why = "it timed out"
2:
why = "no network port was free"
failed.emit("Couldn't connect: %s." % why)
_say("")
func _on_disconnected() -> void:
if stage != Stage.IDLE:
var was := other_id
stage = Stage.IDLE
other_id = -1
if was >= 0:
other_left.emit(was)
failed.emit("Disconnected from GD-Sync.")
func _on_lobby_created(created: String) -> void:
gdsync.lobby_join(created)
func _on_lobby_creation_failed(_n: String, error: int) -> void:
stage = Stage.IDLE
var why := ["a lobby with that name exists", "the name is too short", "the name is too long", "", "", "",
"wait a few seconds and try again", "no network port was free"]
failed.emit("Couldn't open the lobby: %s." % (why[error] if error < why.size() and why[error] != "" else "error %d" % error))
func _on_lobby_joined(n: String) -> void:
if _after_connect == "host":
stage = Stage.HOSTING
if mode == Mode.LAN:
var at := host_addresses()
_say("Waiting for a friend to join \"%s\" (same network%s)" % [n,
(", or by address: " + ", ".join(at)) if not at.is_empty() else ""])
else:
_say("Waiting for a friend to join \"%s\" (online)" % n)
else:
stage = Stage.IN_LOBBY
_say("Joined \"%s\": waiting for the farm..." % n)
func _on_lobby_join_failed(n: String, error: int) -> void:
stage = Stage.SEARCHING
var why := ["it doesn't exist any more", "it's closed", "it's full", "the password is wrong", "your name is the same as the host's"]
failed.emit("Couldn't join %s: %s." % [n, why[error] if error < why.size() else "error %d" % error])
func _on_lobbies_received(lobbies: Array) -> void:
var out: Array = []
for l: Variant in lobbies:
if not l is Dictionary:
continue
var d := l as Dictionary
var tags: Variant = d.get("Tags", {})
if tags is Dictionary and (tags as Dictionary).has("game") and String(tags["game"]) != GAME_TAG:
continue
var players := int(d.get("PlayerCount", 0))
var limit := int(d.get("PlayerLimit", 2))
if limit > 0 and players >= limit:
continue
out.append({"name": String(d.get("Name", "")), "players": players})
lobbies_found.emit(out)
func _on_client_joined(id: int) -> void:
if id == my_id() or other_id >= 0:
return
if stage == Stage.HOSTING:
other_id = id
partner_arrived.emit(id)
elif stage == Stage.IN_LOBBY or stage == Stage.JOINING:
other_id = id
joined.emit(id)
func _on_client_left(id: int) -> void:
if id != other_id:
return
other_id = -1
other_left.emit(id)
if stage == Stage.HOSTING:
_say("Your friend left. Waiting for someone to join \"%s\"" % lobby_name)
func _say(text: String) -> void:
status = text
status_changed.emit(text)

View file

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

234
game/scripts/coop_menu.gd Normal file
View file

@ -0,0 +1,234 @@
class_name CoopMenu
extends CenterContainer
## "Play with a friend" from the main menu (Main does the rest):
## * your name, and how to connect: on the same network (LAN, no account) or online (GD-Sync's
## servers; needs the project's API keys, see game/COOP.md)
## * Host: continue your saved vacation or start a new one; the farm opens to your friend
## * Join: the games found (LAN: announced on the network; online: open lobbies), or a lobby's
## name typed in (online)
## The status line says what's happening and why something failed.
signal host_requested(mode: CoopLobby.Mode, player_name: String, resume: bool)
signal search_requested(mode: CoopLobby.Mode, player_name: String)
signal join_requested(lobby: String)
signal join_address_requested(address: String)
signal back_requested
var is_open := false
var mode: CoopLobby.Mode = CoopLobby.Mode.LAN
var name_edit: LineEdit
var lan_button: Button
var online_button: Button
var host_button: Button
var join_button: Button
var continue_button: Button
var new_button: Button
var back_button: Button
var lobby_edit: LineEdit
var lobby_join_button: Button
var status: Label
var list: VBoxContainer
## "home", "host" (which vacation), "join" (the list)
var view := "home"
var _host_box: VBoxContainer
var _join_box: VBoxContainer
var _online_row: HBoxContainer
func _ready() -> void:
set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
var panel := PanelContainer.new()
add_child(panel)
var margin := MarginContainer.new()
for side in ["left", "right", "top", "bottom"]:
margin.add_theme_constant_override("margin_" + side, 30)
panel.add_child(margin)
var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 14)
box.custom_minimum_size = Vector2(760.0, 0.0)
margin.add_child(box)
var title := Label.new()
title.text = "Play with a friend"
title.add_theme_font_size_override("font_size", 44)
title.add_theme_color_override("font_color", UiTheme.GOLD)
box.add_child(title)
var name_row := HBoxContainer.new()
name_row.add_theme_constant_override("separation", 16)
box.add_child(name_row)
var nl := Label.new()
nl.text = "Your name"
nl.custom_minimum_size = Vector2(170.0, 0.0)
name_row.add_child(nl)
name_edit = LineEdit.new()
name_edit.max_length = 20
name_edit.custom_minimum_size = Vector2(420.0, 44.0)
name_edit.placeholder_text = "Shown over your scarecrow"
name_row.add_child(name_edit)
var mode_row := HBoxContainer.new()
mode_row.add_theme_constant_override("separation", 16)
box.add_child(mode_row)
var ml := Label.new()
ml.text = "Connect"
ml.custom_minimum_size = Vector2(170.0, 0.0)
mode_row.add_child(ml)
var group := ButtonGroup.new()
lan_button = _toggle(mode_row, "Same network (LAN)", group)
lan_button.button_pressed = true
lan_button.pressed.connect(func() -> void: _set_mode(CoopLobby.Mode.LAN))
online_button = _toggle(mode_row, "Online", group)
online_button.pressed.connect(func() -> void: _set_mode(CoopLobby.Mode.ONLINE))
var actions := HBoxContainer.new()
actions.add_theme_constant_override("separation", 16)
box.add_child(actions)
host_button = _button(actions, "Host a game")
host_button.pressed.connect(func() -> void: _show("host"))
join_button = _button(actions, "Join a game")
join_button.pressed.connect(func() -> void:
_show("join")
search_requested.emit(mode, player_name()))
_host_box = VBoxContainer.new()
_host_box.add_theme_constant_override("separation", 10)
box.add_child(_host_box)
var hl := Label.new()
hl.text = "Which vacation? Your friend joins your farm."
_host_box.add_child(hl)
var host_row := HBoxContainer.new()
host_row.add_theme_constant_override("separation", 16)
_host_box.add_child(host_row)
continue_button = _button(host_row, "Continue")
continue_button.pressed.connect(func() -> void: host_requested.emit(mode, player_name(), true))
new_button = _button(host_row, "New vacation")
new_button.pressed.connect(func() -> void: host_requested.emit(mode, player_name(), false))
_join_box = VBoxContainer.new()
_join_box.add_theme_constant_override("separation", 8)
box.add_child(_join_box)
var jl := Label.new()
jl.text = "Games found:"
_join_box.add_child(jl)
list = VBoxContainer.new()
list.add_theme_constant_override("separation", 6)
_join_box.add_child(list)
_online_row = HBoxContainer.new()
_online_row.add_theme_constant_override("separation", 12)
_join_box.add_child(_online_row)
lobby_edit = LineEdit.new()
lobby_edit.custom_minimum_size = Vector2(440.0, 44.0)
_online_row.add_child(lobby_edit)
lobby_join_button = _button(_online_row, "Join")
lobby_join_button.pressed.connect(func() -> void:
var t := lobby_edit.text.strip_edges()
if t == "":
return
if mode == CoopLobby.Mode.LAN:
join_address_requested.emit(t)
else:
join_requested.emit(t))
status = Label.new()
status.custom_minimum_size = Vector2(740.0, 0.0)
status.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
status.add_theme_font_size_override("font_size", 19)
status.add_theme_color_override("font_color", Color(0.78, 0.8, 0.72))
box.add_child(status)
back_button = _button(box, "Back")
back_button.pressed.connect(func() -> void: back_requested.emit())
visible = false
mouse_filter = Control.MOUSE_FILTER_IGNORE
func open(saved: SaveGame.Loaded, nights: int, p_name: String) -> void:
is_open = true
visible = true
mouse_filter = Control.MOUSE_FILTER_STOP
if name_edit.text == "":
name_edit.text = p_name
var ok := saved != null and saved.status == SaveGame.Status.OK
continue_button.disabled = not ok
continue_button.text = "Continue (morning of day %d of %d)" % [saved.state.night, nights] if ok else "Continue"
status.text = ""
_show("home")
host_button.grab_focus.call_deferred()
func close() -> void:
is_open = false
visible = false
mouse_filter = Control.MOUSE_FILTER_IGNORE
func player_name() -> String:
return name_edit.text.strip_edges()
func set_status(text: String) -> void:
status.text = text
func show_lobbies(lobbies: Array) -> void:
for c in list.get_children():
c.queue_free()
if lobbies.is_empty():
var l := Label.new()
l.text = "None yet. (Ask your friend to host; on a LAN you need to be on the same network.)"
l.add_theme_font_size_override("font_size", 18)
l.add_theme_color_override("font_color", Color(0.7, 0.72, 0.66))
list.add_child(l)
return
for lob: Dictionary in lobbies:
var b := _button(list, "%s (%d/2)" % [lob["name"], int(lob["players"])])
b.alignment = HORIZONTAL_ALIGNMENT_LEFT
var n := String(lob["name"])
b.pressed.connect(func() -> void: join_requested.emit(n))
func _show(v: String) -> void:
view = v
_host_box.visible = v == "host"
_join_box.visible = v == "join"
_online_row.visible = v == "join"
_placeholder()
if v == "host":
(continue_button if not continue_button.disabled else new_button).grab_focus.call_deferred()
if v == "join":
show_lobbies([])
func _set_mode(m: CoopLobby.Mode) -> void:
mode = m
if m == CoopLobby.Mode.ONLINE and not CoopLobby.has_online_keys():
status.text = "Online play needs the GD-Sync API keys (free at gd-sync.com): in the editor, Project > Tools > GD-Sync. Until then, play on the same network (LAN)."
else:
status.text = ""
_placeholder()
if view == "join":
search_requested.emit(mode, player_name())
func _placeholder() -> void:
lobby_edit.placeholder_text = "Or the host's address, e.g. 192.168.1.20" if mode == CoopLobby.Mode.LAN \
else "Or type the game's name, e.g. Ana's farm"
func _button(parent: Control, text: String) -> Button:
var b := Button.new()
b.text = text
b.custom_minimum_size = Vector2(240.0, 50.0)
parent.add_child(b)
return b
func _toggle(parent: Control, text: String, group: ButtonGroup) -> Button:
var b := _button(parent, text)
b.toggle_mode = true
b.button_group = group
return b
func _draw() -> void:
draw_rect(Rect2(Vector2.ZERO, size), Color(0.0, 0.0, 0.0, 0.4))
func _unhandled_input(event: InputEvent) -> void:
if is_open and event.is_action_pressed("ui_cancel"):
back_requested.emit()
get_viewport().set_input_as_handled()

View file

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

View file

@ -0,0 +1,756 @@
class_name CoopSession
extends Node
## Co-op for two over a CoopLink (GD-Sync, or loopback in tests). The host's farm is the real
## one: it simulates both scarecrows, every enemy, all the loot, and the campaign, and saves.
## The partner's farm is a replica (FarmSim.replica): it simulates nothing and shows what the
## host sends, except its own scarecrow, which it moves itself (so moving never waits on the
## network) and whose buttons it sends to the host.
##
## Host -> partner
## welcome (reliable, once) the farm state, the phase, tonight's time, the loot, the names
## batch (reliable, each tick with news) events in order: phase changes (with the state),
## the end of the campaign, sounds, toasts for the partner, loot and arrival news,
## breaches, fear bursts, gather popups, the workbench; enemies removed
## state (reliable, at most STATE_HZ, when it changed) the farm state
## loot (reliable, at most LOOT_HZ, when it changed) every item
## snap (unreliable, SNAP_HZ) the phase clock, both scarecrows, the animals
## foes (unreliable, SNAP_HZ, in chunks) every enemy, 16 bytes each
## shots (unreliable, SNAP_HZ) the shots in flight
## Partner -> host
## hello (reliable) its player's name
## input (unreliable, INPUT_HZ) its scarecrow's position and facing, held buttons and press
## counts, aim, build mode, the upgrade menu (RemoteControls)
## req (reliable) start the day, start the night early, retry the night, build,
## dismantle, buy an upgrade
## Unreliable messages stay under CoopLink.UNRELIABLE_LIMIT; nothing depends on any single one
## arriving (enemies missed by a snapshot appear in the next; removals are reliable).
## Voice chat (GD-Sync only, start_voice): a CoopVoice per player, owned by that player's client.
enum Role { SOLO, HOST, CLIENT }
signal partner_joined(name: String)
signal partner_left(name: String)
## Partner: the host went away (or the session was closed).
signal ended(reason: String)
## Partner: the first full state arrived; the game is on.
signal welcomed
const SNAP_EVERY := 3 # physics ticks: 20 Hz
const INPUT_EVERY := 2 # 30 Hz
const STATE_EVERY := 15 # 4 Hz
const LOOT_EVERY := 6 # 10 Hz
const ENEMY_CHUNK := 56
const MAX_SHOTS := 60
## Partner: seconds without a word from the host before it counts as gone.
const TIMEOUT := 8.0
var role: Role = Role.SOLO
var sim: FarmSim
var link: CoopLink
var my_name := ""
var partner_name := ""
## Ticks since the session started, and seconds since the other side was last heard.
var ticks: int = 0
var quiet: float = 0.0
## Voice chat: one per player (slot), and whether this machine's microphone is on.
var voices: Array[CoopVoice] = []
var microphone := true
# Host
var _events: Array = []
var _removed: Array = []
var _state_hash: int = 0
var _loot_hash: int = 0
var _connections: Array = [] # [Signal, Callable] to undo
# Partner
var _map := {} # host enemy handle -> local handle
var _gone := {} # host handles already removed (a late snapshot mustn't bring them back)
var _targets := {} # local handle -> PackedFloat32Array [x, z, hx, hz, vx, vz, alt]
var _sender := RemoteControls.Sender.new()
var _snap_tick: int = -1
var _structures_json := ""
var _shed_json := ""
var _is_welcomed := false
var _welcome_sent := false
var _hello_wait: float = 0.0
func is_active() -> bool:
return role != Role.SOLO
func is_host() -> bool:
return role == Role.HOST
func is_client() -> bool:
return role == Role.CLIENT
## The host's side: the partner (name) is in; their scarecrow joins the farm.
func start_host(p_sim: FarmSim, p_link: CoopLink, p_my_name: String, p_partner_name: String) -> void:
sim = p_sim
link = p_link
role = Role.HOST
my_name = p_my_name
partner_name = p_partner_name
ticks = 0
quiet = 0.0
link.received.connect(_on_message)
sim.avatars[0].player_name = my_name
var a := sim.add_partner(false, partner_name)
a.body.remote_driven = true
a.body.snap_to_net(a.body.global_position, 0.0)
_tag_all()
_hook(sim.campaign.phase_changed, func(phase: CampaignController.Phase, previous: CampaignController.Phase) -> void:
_events.append(["phase", int(phase), int(previous), sim.campaign.state.to_dict(), sim.campaign.state.phase_time_left])
if phase == CampaignController.Phase.MORNING and sim.partner != null:
_ensure_coop())
_hook(sim.campaign.campaign_ended, func(outcome: CampaignController.Outcome) -> void:
_events.append(["ended", int(outcome), sim.campaign.state.to_dict()]))
_hook(sim.enemies.enemy_removed, func(h: int, reason: EnemySystem.Removal, x: float, z: float, _c: int, _t: int) -> void:
_removed.append([h, int(reason), x, z]))
_hook(sim.waves.arrived, func(h: int, at: Vector2) -> void:
var d := sim.enemies.resolve_handle(h)
_events.append(["arrived", sim.enemies.type[d] if d >= 0 else 0, at]))
_hook(sim.loot.loot_event, func(kind: StringName, id: int, at: Vector3) -> void:
_events.append(["loot", String(kind), id, at]))
_hook(sim.structures.destroyed, func(id: int, type: String, at: Vector3) -> void:
_events.append(["destroyed", id, type, at]))
for av in sim.avatars:
var slot := av.slot
_hook(av.kit.fear_used, func(_p: Vector3, _n: int) -> void: _events.append(["fear", slot]))
_hook(av.combat.attacked, func(w: ScarecrowCombat.Weapon) -> void: _events.append(["attack", slot, int(w)]))
_hook(sim.bombs.thrown, func(from: Vector3, to: Vector3) -> void: _events.append(["bomb", from, to]))
_hook(a.interactions.message, func(text: String, color: Color) -> void: _events.append(["toast", text, color]))
_hook(a.interactions.workbench_requested, func() -> void: _events.append(["workbench"]))
_hook(a.interactions.gathered, func(m: String, amount: int, n: GatherNode) -> void:
_events.append(["popup", "+%d %s" % [amount, m], n.global_position + Vector3(0.0, n.top() + 1.4, 0.0), GatherNode.COLORS[m]]))
_hook(a.kit.patch_denied, func(missing: Dictionary) -> void:
_events.append(["toast", "Not enough straw to patch up: need %s more" % ResourceStore.describe(missing), Color(1.0, 0.8, 0.5)]))
if sim.audio != null:
sim.audio.forward = func(cue: String, at: Vector3) -> void: _events.append(["sound", cue, at])
_ensure_coop()
_state_hash = 0
_loot_hash = 0
_welcome_sent = false # sent when the partner says hello (then it is surely listening)
if sim.toasts != null:
sim.toasts.push("%s joined: player 2's scarecrow is on the farm" % _display(partner_name, "P2"), Avatar.COLORS[1])
partner_joined.emit(partner_name)
## The partner's side: the farm becomes a replica of the host's; player 2's scarecrow is ours.
func start_client(p_sim: FarmSim, p_link: CoopLink, p_my_name: String) -> void:
sim = p_sim
link = p_link
role = Role.CLIENT
my_name = p_my_name
ticks = 0
quiet = 0.0
_is_welcomed = false
link.received.connect(_on_message)
var c := sim.campaign
c.save_path = "" # only the host saves
c.remote_request = func(what: String) -> void: _request([what])
sim.replica = true
sim.replica_step = _replica_tick
var a := sim.add_partner(true, my_name)
sim.set_local(a)
a.combat.replica = true # it only aims and shows its attacks: the host attacks for it
sim.bombs.replica = true
var first := sim.avatars[0]
first.is_local = false
first.body.remote_driven = true
sim.build.place_request = func(type: String, x: float, z: float, rot: int) -> void: _request(["place", type, x, z, rot])
sim.build.dismantle_request = func(id: int) -> void: _request(["dismantle", id])
if sim.upgrade_panel != null:
sim.upgrade_panel.buy_request = func(id: String) -> void: _request(["buy", id])
if sim.audio != null:
sim.audio.remote_cues = true
if sim.tutorial != null:
sim.tutorial.enabled = false # the partner joins a game in progress
_hello_wait = 0.0 # hello goes out (again every second) until the welcome arrives
## Ends the session on this side. The host carries on alone; the partner's game is left as a
## replica for Main to reset (it reloads the scene).
func stop(reason: String = "") -> void:
if role == Role.SOLO:
return
var was := role
role = Role.SOLO
for pair: Array in _connections:
if (pair[0] as Signal).is_connected(pair[1]):
(pair[0] as Signal).disconnect(pair[1])
_connections.clear()
if link != null:
if link.received.is_connected(_on_message):
link.received.disconnect(_on_message)
link.close()
for v in voices:
if is_instance_valid(v):
v.queue_free()
voices.clear()
if sim != null and sim.audio != null:
sim.audio.forward = Callable()
if was == Role.HOST:
var gone_name := partner_name
sim.remove_partner()
sim.avatars[0].player_name = ""
sim.player.set_tag("", Color.WHITE)
if sim.toasts != null:
sim.toasts.push("%s left: you're on your own" % _display(gone_name, "Player 2"), Color(1.0, 0.8, 0.5))
partner_left.emit(gone_name)
else:
ended.emit(reason)
## Voice chat over GD-Sync: owners[slot] is each player's GD-Sync client id.
func start_voice(gdsync: Node, owners: Array, mic_on: bool) -> void:
for v in voices:
v.queue_free()
voices.clear()
for slot in owners.size():
var v := CoopVoice.make(slot)
add_child(v)
gdsync.set_gdsync_owner(v, int(owners[slot]))
voices.append(v)
set_microphone(mic_on)
func set_microphone(on: bool) -> void:
microphone = on
for v in voices:
if on:
v.unmute_microphone()
else:
v.mute_microphone()
## Whether the other player's voice is coming through now.
func partner_speaking() -> bool:
var other := 1 if role == Role.HOST else 0
return other < voices.size() and voices[other].speaking()
## GD-Sync calls this on the other machine (GDSyncLink).
func net_receive(kind: String, data: Variant) -> void:
if link != null:
link.received.emit(kind, data)
func _physics_process(dt: float) -> void:
if role == Role.SOLO or link == null:
return
ticks += 1
quiet += dt
if role == Role.HOST:
link.poll()
if _welcome_sent:
_host_tick()
elif quiet > TIMEOUT * 2.0:
stop("Your friend didn't answer")
else:
if not _is_welcomed:
link.poll()
_hello_wait -= dt
if _hello_wait <= 0.0:
_hello_wait = 1.0
link.send("hello", {"name": my_name}, true)
elif ticks % INPUT_EVERY == 0:
_send_input()
if link.closed or (role == Role.CLIENT and quiet > TIMEOUT):
stop("The host left the game" if link.closed else "Lost the connection to the host")
# --- Host -----------------------------------------------------------------------------------
func _host_tick() -> void:
if ticks % SNAP_EVERY == 0:
_send_snapshot()
if ticks % STATE_EVERY == 0:
var d := sim.campaign.state.to_dict()
var h := hash(d)
if h != _state_hash:
_state_hash = h
link.send("state", d, true)
if ticks % LOOT_EVERY == 0:
var rec := sim.loot.replica_record()
var h := hash(rec)
if h != _loot_hash:
_loot_hash = h
link.send("loot", rec, true)
if not _events.is_empty() or not _removed.is_empty():
link.send("batch", {"events": _events, "removed": _removed}, true)
_events = []
_removed = []
func _welcome() -> Dictionary:
var c := sim.campaign
return {"state": c.state.to_dict(), "phase": int(c.state.phase), "time": c.state.phase_time_left, "outcome": int(c.outcome),
"night_time": sim.waves.night_time, "loot": sim.loot.replica_record(), "host": my_name}
func _send_snapshot() -> void:
var avs: Array = []
for a in sim.avatars:
avs.append(_avatar_record(a))
link.send("snap", {"t": ticks, "time": sim.campaign.state.phase_time_left, "night": sim.waves.night_time, "av": avs,
"an": sim.animals.replica_record()}, false)
var es := sim.enemies
var chunk := PackedByteArray()
for d in es.active_count:
if es.alive[d] == 0:
continue
chunk.append_array(_enemy_bytes(es, d))
if chunk.size() >= ENEMY_CHUNK * 16:
link.send("foes", chunk, false)
chunk = PackedByteArray()
if not chunk.is_empty():
link.send("foes", chunk, false)
link.send("shots", sim.projectiles.replica_record(MAX_SHOTS), false)
static func _enemy_bytes(es: EnemySystem, d: int) -> PackedByteArray:
var b := PackedByteArray()
b.resize(16)
b.encode_s32(0, es.handle_of(d))
b[4] = es.type[d]
b[5] = es.state[d]
b[6] = clampi(roundi(es.hurt[d] * 255.0), 0, 255)
b[7] = clampi(roundi(es.alt[d] * 40.0), 0, 255)
b.encode_s16(8, clampi(roundi(es.pos_x[d] * 100.0), -32768, 32767))
b.encode_s16(10, clampi(roundi(es.pos_z[d] * 100.0), -32768, 32767))
b.encode_s8(12, clampi(roundi(es.head_x[d] * 127.0), -127, 127))
b.encode_s8(13, clampi(roundi(es.head_z[d] * 127.0), -127, 127))
b.encode_s8(14, clampi(roundi(es.vel_x[d] * 20.0), -127, 127))
b.encode_s8(15, clampi(roundi(es.vel_z[d] * 20.0), -127, 127))
return b
func _avatar_record(a: Avatar) -> Dictionary:
var it := a.interactions
var k := a.kit
return {"s": a.slot, "p": a.body.global_position, "y": a.body.model.rotation.y, "v": a.body.move_strength(),
"a": k.alive, "hp": k.hp(), "inv": k.invulnerable_left, "fl": k.fear_left,
"w": int(a.combat.weapon), "bl": a.combat.bomb_left,
"pt": k.patch_elapsed if k.patching else -1.0, "ch": String(a.body.channel_clip) if a.body.rooted else "",
"fo": String(it.focus.name) if it.focus != null else "", "ga": String(it.gathering.name) if it.gathering != null else "",
"ge": it.gather_elapsed, "rt": it.repair_target, "rp": it.repairing, "re": it.repair_elapsed}
func _on_message(kind: String, data: Variant) -> void:
quiet = 0.0
if role == Role.HOST:
_host_message(kind, data)
elif role == Role.CLIENT:
_client_message(kind, data)
func _host_message(kind: String, data: Variant) -> void:
var a := sim.partner
if a == null:
return
match kind:
"hello":
partner_name = String((data as Dictionary).get("name", partner_name))
a.player_name = partner_name
_tag_all()
if not _welcome_sent:
_welcome_sent = true
_events.clear()
_removed.clear()
link.send("welcome", _welcome(), true)
"input":
var rec := data as Dictionary
a.remote.apply(rec)
a.body.net_position = rec.get("p", a.body.net_position)
a.body.net_yaw = float(rec.get("y", a.body.net_yaw))
a.body.net_speed = float(rec.get("v", 0.0))
"req":
_do_request(data as Array)
func _do_request(r: Array) -> void:
var c := sim.campaign
var a := sim.partner
match String(r[0]):
"begin_day":
c.begin_day()
"start_night_early":
c.start_night_early()
"retry_night":
if c.state.phase == CampaignController.Phase.GAME_OVER:
c.retry_night()
"place":
var type := String(r[1])
var x := float(r[2])
var z := float(r[3])
var rot := int(r[4])
if not StructureSystem.ORDER.has(type):
return
var why := sim.structures.validate(type, x, z, rot, a.position())
if why == "":
sim.structures.place(type, x, z, rot)
_events.append(["toast", "Built a %s" % StructureSystem.NAMES[type].to_lower(), Color(0.6, 1.0, 0.55)])
else:
_events.append(["toast", why, Color(1.0, 0.8, 0.5)])
_events.append(["sound", "error", Vector3.INF])
"dismantle":
var e := c.state.structure(int(r[1]))
if e.is_empty() or a.position().distance_to(Vector2(e["x"], e["z"])) > sim.config.build_range:
return
var back := sim.structures.dismantle(int(r[1]))
_events.append(["toast", "Dismantled the %s%s" % [StructureSystem.NAMES[e["type"]].to_lower(),
(": %s back in the shed" % ResourceStore.describe(back)) if not back.is_empty() else ""], Color(0.85, 0.95, 1.0)])
"buy":
var text := Upgrades.buy(c, String(r[1]), sim.structures)
_events.append(["toast", text, Color(0.85, 0.75, 1.0) if text.contains("done:") else Color(1.0, 0.8, 0.5)])
## Co-op is on for the farm state (after a retry, a new vacation, or a morning).
func _ensure_coop() -> void:
var s := sim.campaign.state
if not s.coop:
s.coop = true
s.partner_max_hp = s.scarecrow_max_hp
s.partner_hp = s.scarecrow_max_hp
# --- Partner ----------------------------------------------------------------------------------
func _client_message(kind: String, data: Variant) -> void:
match kind:
"welcome":
_welcome_received(data as Dictionary)
"state":
_apply_state(data as Dictionary)
"loot":
sim.loot.apply_replica(data as Dictionary, _local_handle)
"snap":
_apply_snap(data as Dictionary)
"foes":
_apply_foes(data as PackedByteArray)
"shots":
sim.projectiles.apply_replica(data as PackedFloat32Array)
"batch":
var b := data as Dictionary
for r: Array in b.get("removed", []):
_remove_foe(int(r[0]), int(r[1]))
for e: Array in b.get("events", []):
_apply_event(e)
func _welcome_received(w: Dictionary) -> void:
var c := sim.campaign
partner_name = String(w.get("host", ""))
sim.avatars[0].player_name = partner_name
_tag_all()
var previous := c.state.phase
_apply_state(w["state"], true)
c.state.phase = int(w["phase"]) as CampaignController.Phase
c.state.phase_time_left = float(w["time"])
c.outcome = int(w["outcome"]) as CampaignController.Outcome
sim.waves.night_time = float(w["night_time"])
_reset_world()
sim.loot.apply_replica(w["loot"], _local_handle)
c.phase_changed.emit(c.state.phase, previous)
if sim.day_night != null:
sim.day_night.snap()
_is_welcomed = true
if sim.toasts != null:
sim.toasts.push("Joined %s's farm: you're player 2" % _display(partner_name, "the host"), Avatar.COLORS[1])
welcomed.emit()
## The host's farm state, keeping this machine's phase until the phase news arrives (in order).
func _apply_state(d: Dictionary, everything: bool = false) -> void:
var s := FarmState.from_dict(d)
if s == null:
return
var c := sim.campaign
if not everything:
s.phase = c.state.phase
s.phase_time_left = c.state.phase_time_left
c.state = s
var structures_json := JSON.stringify(d["structures"])
if everything or structures_json != _structures_json:
_structures_json = structures_json
sim.structures.sync_from_state()
sim.animals.update_pen_open()
var shed_json := JSON.stringify(d["resources"])
if everything or shed_json != _shed_json:
_shed_json = shed_json
sim.shed_stock.refresh()
if sim.upgrade_panel != null and sim.upgrade_panel.is_open:
sim.upgrade_panel.refresh()
if c.state.phase == CampaignController.Phase.MORNING and sim.review_panel != null:
sim.review_panel.refresh()
func _apply_event(e: Array) -> void:
var c := sim.campaign
match String(e[0]):
"phase":
var previous := c.state.phase
_apply_state(e[3], true)
c.state.phase = int(e[1]) as CampaignController.Phase
c.state.phase_time_left = float(e[4])
if c.state.phase == CampaignController.Phase.MORNING:
_map.clear()
_gone.clear()
_targets.clear()
c.phase_changed.emit(c.state.phase, previous)
"ended":
_apply_state(e[2], true)
c.outcome = int(e[1]) as CampaignController.Outcome
var terminal := CampaignController.Phase.FARMERS_RETURN if c.outcome == CampaignController.Outcome.VACATION_COMPLETE \
else CampaignController.Phase.GAME_OVER
if c.state.phase != terminal:
var previous := c.state.phase
c.state.phase = terminal
c.phase_changed.emit(terminal, previous)
c.campaign_ended.emit(c.outcome)
"sound":
if sim.audio != null:
sim.audio.play_remote(String(e[1]), e[2])
"toast":
if sim.toasts != null:
sim.toasts.push(String(e[1]), e[2])
"loot":
sim.loot.loot_event.emit(StringName(e[1]), int(e[2]), e[3])
"arrived":
if sim.toasts != null:
sim.toasts.push(FarmSim.arrival_message(int(e[1]), sim.zones.side_of(e[2])), Color(1.0, 0.75, 0.55))
"destroyed":
sim.structures.show_debris(e[3])
sim.structures.destroyed.emit(int(e[1]), String(e[2]), e[3])
"fear":
var slot := int(e[1])
if slot < sim.avatars.size():
sim.avatars[slot].kit.play_burst()
"attack": # our own scarecrow's attacks already show here
var slot := int(e[1])
if slot < sim.avatars.size() and not sim.avatars[slot].is_local:
var combat := sim.avatars[slot].combat
combat.show_weapon(int(e[2]))
combat.models.attack(int(e[2]))
"bomb":
sim.bombs.throw(e[1], e[2], 0, 0.0) # drawn only (replica)
"popup":
sim.interactions._popup(String(e[1]), e[2], e[3])
"workbench":
if sim.upgrade_panel != null and c.is_daytime():
sim.upgrade_panel.open()
func _apply_snap(snap: Dictionary) -> void:
var t := int(snap.get("t", 0))
if t <= _snap_tick:
return # an older one, out of order
_snap_tick = t
sim.campaign.state.phase_time_left = float(snap["time"])
sim.waves.night_time = float(snap["night"])
for rec: Dictionary in snap["av"]:
var slot := int(rec["s"])
if slot >= sim.avatars.size():
continue
_apply_avatar(sim.avatars[slot], rec)
sim.animals.apply_replica(snap["an"])
func _apply_avatar(a: Avatar, rec: Dictionary) -> void:
var k := a.kit
var body := a.body
if not a.is_local:
body.net_position = rec["p"]
body.net_yaw = float(rec["y"])
body.net_speed = float(rec["v"])
var s := sim.campaign.state
if a.slot == 0:
s.scarecrow_hp = clampi(int(rec["hp"]), 0, s.scarecrow_max_hp)
else:
s.partner_hp = clampi(int(rec["hp"]), 0, s.partner_max_hp)
var alive := bool(rec["a"])
if alive != k.alive:
k.alive = alive
if alive:
body.revive()
else:
body.die()
k.invulnerable_left = float(rec["inv"])
k.fear_left = float(rec["fl"])
a.combat.bomb_left = float(rec.get("bl", 0.0))
if not a.is_local:
a.combat.show_weapon(int(rec.get("w", 0)))
var pt := float(rec["pt"])
k.patching = pt >= 0.0
k.patch_elapsed = maxf(pt, 0.0)
if a.is_local:
var ch := String(rec["ch"])
if ch != "" and (not body.rooted or body.channel_clip != StringName(ch)):
body.start_channel(StringName(ch))
elif ch == "" and body.rooted and not (sim.upgrade_panel != null and sim.upgrade_panel.is_open):
body.stop_channel()
var it := a.interactions
it.focus = _gather_node(String(rec["fo"]))
it.gathering = _gather_node(String(rec["ga"])) as GatherNode
it.gather_elapsed = float(rec["ge"])
it.repair_target = int(rec["rt"])
it.repairing = int(rec["rp"])
it.repair_elapsed = float(rec["re"])
func _gather_node(node_name: String) -> Node3D:
if node_name == "":
return null
var it := sim.interactions
if it.workbench != null and String(it.workbench.name) == node_name:
return it.workbench
for n in it.nodes:
if String(n.name) == node_name:
return n
return null
func _apply_foes(chunk: PackedByteArray) -> void:
var es := sim.enemies
for o in range(0, chunk.size() - 15, 16):
var host := chunk.decode_s32(o)
if _gone.has(host):
continue
var type := chunk[o + 4]
var x := chunk.decode_s16(o + 8) / 100.0
var z := chunk.decode_s16(o + 10) / 100.0
var h: int = _map.get(host, -1)
var d := es.resolve_handle(h) if h >= 0 else -1
if d < 0:
h = es.spawn(type, x, z, Vector2(chunk.decode_s8(o + 12), chunk.decode_s8(o + 13)))
if h < 0:
continue
_map[host] = h
d = es.resolve_handle(h)
es.state[d] = chunk[o + 5]
es.hurt[d] = chunk[o + 6] / 255.0
var t := PackedFloat32Array([x, z, chunk.decode_s8(o + 12) / 127.0, chunk.decode_s8(o + 13) / 127.0,
chunk.decode_s8(o + 14) / 20.0, chunk.decode_s8(o + 15) / 20.0, chunk[o + 7] / 40.0])
_targets[h] = t
func _remove_foe(host: int, reason: int) -> void:
_gone[host] = true
var h: int = _map.get(host, -1)
_map.erase(host)
if h < 0:
return
_targets.erase(h)
var es := sim.enemies
var d := es.resolve_handle(h)
if d < 0:
return
es.carry[d] = -1 # the host settles the loot; here it's only for show
es.target[d] = -1
es.queue_removal(d, reason as EnemySystem.Removal)
es.commit_removals()
## This machine's handle for a host enemy (-1 if it isn't here).
func _local_handle(host: int) -> int:
return int(_map.get(host, -1))
## Each partner tick (FarmSim._step_replica): the news, then the enemies and shots move on
## toward where the host last had them.
func _replica_tick(dt: float) -> void:
if link != null:
link.poll()
var es := sim.enemies
for h: int in _targets:
var d := es.resolve_handle(h)
if d < 0:
continue
var t: PackedFloat32Array = _targets[h]
t[0] += t[4] * dt # carry on as the host said it was moving
t[1] += t[5] * dt
_targets[h] = t
es.prev_x[d] = es.pos_x[d]
es.prev_z[d] = es.pos_z[d]
var k := 0.35
if Vector2(t[0] - es.pos_x[d], t[1] - es.pos_z[d]).length() > 5.0:
k = 1.0
es.pos_x[d] = lerpf(es.pos_x[d], t[0], k)
es.pos_z[d] = lerpf(es.pos_z[d], t[1], k)
var hv := Vector2(t[2], t[3])
if hv.length_squared() > 1e-4:
hv = hv.normalized()
es.head_x[d] = hv.x
es.head_z[d] = hv.y
es.vel_x[d] = t[4]
es.vel_z[d] = t[5]
es.alt[d] = lerpf(es.alt[d], t[6], 0.3)
sim.projectiles.advance_replica(dt)
func _reset_world() -> void:
sim.enemies.clear()
sim.projectiles.clear()
_map.clear()
_gone.clear()
_targets.clear()
func _send_input() -> void:
var a := sim.local_avatar
var build_on := sim.build.active
var ui := sim.upgrade_panel != null and sim.upgrade_panel.is_open
var rec := _sender.record(a.combat.aim, a.combat.aim_point, int(a.combat.device), build_on, ui)
if sim.local_frozen:
rec["held"] = 0 # a menu is up
rec["p"] = a.body.global_position
rec["y"] = a.body.model.rotation.y
rec["v"] = a.body.move_strength()
rec["weapon"] = int(a.combat.weapon)
rec["ground"] = a.combat.ground_point
link.send("input", rec, false)
_close_menu_if_needed()
func _unhandled_input(event: InputEvent) -> void:
if role == Role.CLIENT:
_sender.note(event)
## The upgrade menu closes here on the same rules as solo (Interactions): walking off,
## nightfall, build mode.
func _close_menu_if_needed() -> void:
var panel := sim.upgrade_panel
if panel == null or not panel.is_open:
return
var bench := sim.interactions.workbench
var p := sim.local_avatar.position()
if not sim.campaign.is_daytime() or sim.build.active or bench == null \
or Vector2(bench.global_position.x, bench.global_position.z).distance_to(p) > bench.reach + 0.5:
panel.close()
func _request(r: Array) -> void:
if link != null and role == Role.CLIENT:
link.send("req", r, true)
# --- Both -------------------------------------------------------------------------------------
func _hook(sig: Signal, callable: Callable) -> void:
sig.connect(callable)
_connections.append([sig, callable])
## Name tags over both scarecrows ("P1 Ana", "P2 Ben").
func _tag_all() -> void:
for a in sim.avatars:
a.body.set_tag(a.label(), a.color())
static func _display(n: String, fallback: String) -> String:
return n if n != "" else fallback

View file

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

View file

@ -0,0 +1,31 @@
class_name CoopVoice
extends VoiceChat
## Voice chat in co-op: GD-Sync's VoiceChat, one per player at the same path on both machines
## (CoopSession/Voice1 for player 1, Voice2 for player 2). Each is owned by its player's GD-Sync
## client: the owner's microphone is recorded (above GD-Sync's volume threshold) and sent, and
## the other machine plays it on the Voice bus. This adds when the voice was last heard, for the
## "speaking" mark on the partner HUD and the name tag.
## Seconds of the game clock when audio last arrived (-1000 = never).
var last_heard: float = -1000.0
static func make(slot: int) -> CoopVoice:
var v := CoopVoice.new()
v.name = "Voice%d" % (slot + 1)
v.input_volume_threshold = 0.025 # above room noise (GD-Sync's default is 0.01)
var out := AudioStreamPlayer.new()
out.name = "Out"
out.bus = &"Voice"
v.add_child(out)
v.set_output_player(out)
return v
func speaking() -> bool:
return Time.get_ticks_msec() / 1000.0 - last_heard < 0.35
func _process_audio(audio: PackedFloat32Array, mixrate: float) -> void:
last_heard = Time.get_ticks_msec() / 1000.0
super(audio, mixrate)

View file

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

127
game/scripts/day_night.gd Normal file
View file

@ -0,0 +1,127 @@
class_name DayNight
extends Node
## Lighting through the vacation's phases. Four keyed looks (day, sunset, night, sunrise) set
## the sun's angle, color, and strength, the ambient and sky light, and a whole-picture
## brightness and saturation (Environment adjustments, which leave the HUD alone):
## morning review -> mostly day; day -> day; dusk -> day turning to sunset over the dusk;
## night -> sunset to night in the first NIGHTFALL seconds (the sun becomes the moon);
## dawn -> night to sunrise over the dawn grace (brightening early: by the square root).
## The scarecrow carries a lantern that lights up as it gets dark, and enemies glow faintly at
## night (thief.gdshader night_glow) so they stay readable. The current look eases toward the
## target, so phase changes never pop.
const NIGHTFALL := 8.0
const EASE := 2.5
const DAY := {"elev": 55.0, "yaw": -35.0, "color": Color(1.0, 0.96, 0.88), "energy": 1.1, "ambient": 1.0,
"sky": 1.0, "bright": 1.0, "sat": 1.0, "lantern": 0.0, "glow": 0.0}
const SUNSET := {"elev": 9.0, "yaw": -70.0, "color": Color(1.0, 0.55, 0.3), "energy": 0.8, "ambient": 0.6,
"sky": 0.55, "bright": 0.92, "sat": 1.05, "lantern": 0.6, "glow": 0.3}
const NIGHT := {"elev": 48.0, "yaw": 25.0, "color": Color(0.55, 0.66, 1.0), "energy": 0.38, "ambient": 0.35,
"sky": 0.12, "bright": 0.78, "sat": 0.62, "lantern": 1.9, "glow": 1.0}
const SUNRISE := {"elev": 10.0, "yaw": 150.0, "color": Color(1.0, 0.72, 0.58), "energy": 0.75, "ambient": 0.6,
"sky": 0.6, "bright": 0.94, "sat": 1.0, "lantern": 0.5, "glow": 0.2}
var campaign: CampaignController
var sun: DirectionalLight3D
var env: Environment
var enemy_material: ShaderMaterial
## Set by FarmSim: the ground enemies' characters glow too.
var characters: EnemyCharacters
var lantern: OmniLight3D
## Co-op: player 2's lantern (add_lantern), lit the same.
var lanterns: Array[OmniLight3D] = []
var current := DAY.duplicate()
func setup(p_campaign: CampaignController, p_sun: DirectionalLight3D, p_env: Environment, player: Node3D,
p_enemy_material: ShaderMaterial) -> void:
campaign = p_campaign
sun = p_sun
env = p_env
enemy_material = p_enemy_material
env.adjustment_enabled = true
lantern = add_lantern(player)
snap()
## A lantern carried by a scarecrow (the first is player 1's).
func add_lantern(body: Node3D) -> OmniLight3D:
var l := OmniLight3D.new()
l.name = "Lantern"
l.light_color = Color(1.0, 0.8, 0.5)
l.omni_range = 9.0
l.omni_attenuation = 1.4
l.shadow_enabled = false
l.position = Vector3(0.0, 2.6, 0.0)
body.add_child(l)
lanterns.append(l)
return l
## 0 in daylight .. 1 at full night.
func darkness() -> float:
return clampf(float(current["glow"]), 0.0, 1.0)
## Jumps straight to the current phase's look (new vacation, retry, tests).
func snap() -> void:
current = target()
_apply()
func target() -> Dictionary:
var s := campaign.state
var cfg := campaign.config
var length := campaign.phase_length(s.phase)
var elapsed := length - s.phase_time_left if is_finite(length) else 0.0
var p := clampf(elapsed / length, 0.0, 1.0) if is_finite(length) and length > 0.0 else 0.0
match s.phase:
CampaignController.Phase.MORNING:
return _mix(SUNRISE, DAY, 0.7)
CampaignController.Phase.DUSK:
return _mix(DAY, SUNSET, p)
CampaignController.Phase.NIGHT:
return _mix(SUNSET, NIGHT, clampf(elapsed / NIGHTFALL, 0.0, 1.0))
CampaignController.Phase.DAWN:
return _mix(NIGHT, SUNRISE, sqrt(p))
CampaignController.Phase.GAME_OVER:
return current
return DAY
func _process(delta: float) -> void:
if campaign == null:
return
current = _mix(current, target(), 1.0 - exp(-EASE * delta))
_apply()
func _apply() -> void:
sun.rotation = Vector3(deg_to_rad(-float(current["elev"])), deg_to_rad(float(current["yaw"])), 0.0)
sun.light_color = current["color"]
sun.light_energy = current["energy"]
env.ambient_light_energy = current["ambient"]
env.background_energy_multiplier = current["sky"]
env.adjustment_brightness = current["bright"]
env.adjustment_saturation = current["sat"]
for l in lanterns:
if is_instance_valid(l):
l.light_energy = current["lantern"]
if enemy_material != null:
enemy_material.set_shader_parameter("night_glow", current["glow"])
if characters != null:
characters.set_night_glow(current["glow"])
static func _mix(a: Dictionary, b: Dictionary, t: float) -> Dictionary:
var out := {}
for k in a:
var va: Variant = a[k]
if va is Color:
out[k] = (va as Color).lerp(b[k], t)
elif k == "yaw":
out[k] = rad_to_deg(lerp_angle(deg_to_rad(va), deg_to_rad(b[k]), t))
else:
out[k] = lerpf(va, b[k], t)
return out

View file

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

251
game/scripts/end_panel.gd Normal file
View file

@ -0,0 +1,251 @@
class_name EndPanel
extends CenterContainer
## The two end screens. Works with mouse, keyboard (arrows + Enter), and gamepad (d-pad + A)
## through focus.
## * Failure, a moment after a Game Over (so the fall can play): the cause (the scarecrow
## destroyed, or the farm stripped bare), the night reached and its plan, what's left and
## what the night cost so far, the vacation's totals, and Retry the night (D9, focused: back
## to that morning) and Main menu (New vacation when there's no menu, e.g. the farm scene on
## its own).
## * The final assessment, once the farmers' return (FarmersReturn) has played or been
## skipped: the rating and score (Assessment), the share kept per category with a bar, and
## the vacation's totals, with Main menu (or New vacation).
signal menu_requested
const DELAY := 1.4
const GOLD := Color(0.95, 0.82, 0.45)
const GREY := Color(0.75, 0.77, 0.72)
var campaign: CampaignController
## Set by Main: the Main menu button shows instead of New vacation.
var has_menu := false
## Set by FarmSim: the final assessment waits for the farmers' return to finish.
var ending: FarmersReturn
var waves: WaveDirector
## Set when the screen is up: "failure" or "assessment".
var mode := ""
var _title: Label
var _rating: Label
var _detail: Label
var _bars: GridContainer
var _bar_rows := {} # category -> [ProgressBar, Label]
var _stats: Label
var _retry: Button
var _menu: Button
var _new: Button
var _wait: float = -1.0
var _pending_mode := ""
func setup(p_campaign: CampaignController) -> void:
campaign = p_campaign
campaign.campaign_ended.connect(_on_ended)
campaign.phase_changed.connect(func(phase: CampaignController.Phase, _previous: CampaignController.Phase) -> void:
if phase == CampaignController.Phase.MORNING:
hide_panel())
func _ready() -> void:
set_anchors_preset(Control.PRESET_FULL_RECT)
var panel := PanelContainer.new()
panel.add_theme_stylebox_override("panel", ReviewPanel.backing())
add_child(panel)
var margin := MarginContainer.new()
for side in ["left", "right", "top", "bottom"]:
margin.add_theme_constant_override("margin_" + side, 34)
panel.add_child(margin)
var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 16)
margin.add_child(box)
_title = _label(box, 46)
_rating = _label(box, 30, GOLD)
_detail = _label(box, 22)
_bars = GridContainer.new()
_bars.columns = 3
_bars.add_theme_constant_override("h_separation", 18)
_bars.add_theme_constant_override("v_separation", 8)
_bars.size_flags_horizontal = Control.SIZE_SHRINK_CENTER
box.add_child(_bars)
for cat in ["crops", "animals", "supplies"]:
var name_label := _label(_bars, 22)
name_label.text = cat.capitalize()
name_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_LEFT
var bar := ProgressBar.new()
bar.custom_minimum_size = Vector2(320.0, 26.0)
bar.show_percentage = false
bar.max_value = 1.0
var fill := StyleBoxFlat.new()
fill.bg_color = Color(0.55, 0.78, 0.4)
fill.set_corner_radius_all(4)
var back := StyleBoxFlat.new()
back.bg_color = Color(0.22, 0.24, 0.2)
back.set_corner_radius_all(4)
bar.add_theme_stylebox_override("fill", fill)
bar.add_theme_stylebox_override("background", back)
_bars.add_child(bar)
var text := _label(_bars, 20, GREY)
text.horizontal_alignment = HORIZONTAL_ALIGNMENT_LEFT
_bar_rows[cat] = [bar, text, name_label]
_stats = _label(box, 20, GREY)
var buttons := HBoxContainer.new()
buttons.alignment = BoxContainer.ALIGNMENT_CENTER
buttons.add_theme_constant_override("separation", 24)
box.add_child(buttons)
_retry = _button(buttons, "Retry the night")
_retry.pressed.connect(func() -> void: campaign.retry_night())
_menu = _button(buttons, "Main menu")
_menu.pressed.connect(func() -> void: menu_requested.emit())
_new = _button(buttons, "New vacation")
_new.pressed.connect(func() -> void: campaign.new_campaign())
hide_panel()
func hide_panel() -> void:
visible = false
mode = ""
_wait = -1.0
_pending_mode = ""
mouse_filter = Control.MOUSE_FILTER_IGNORE
func _on_ended(outcome: CampaignController.Outcome) -> void:
if outcome == CampaignController.Outcome.VACATION_COMPLETE:
if ending != null:
if not ending.finished.is_connected(_on_ending_finished):
ending.finished.connect(_on_ending_finished)
return
_pending_mode = "assessment"
else:
_pending_mode = "failure"
_wait = DELAY
func _on_ending_finished() -> void:
_pending_mode = "assessment"
_wait = 0.01
func _process(delta: float) -> void:
if _wait < 0.0:
return
_wait -= delta
if _wait <= 0.0:
_wait = -1.0
if _pending_mode == "assessment":
show_assessment()
else:
show_failure()
func show_failure() -> void:
var s := campaign.state
var cfg := campaign.config
mode = "failure"
var plan := waves.plan_for(s.night) if waves != null else null
var night := "Night %d of %d%s" % [s.night, cfg.campaign_nights, (": " + plan.title) if plan != null and plan.title != "" else ""]
if campaign.outcome == CampaignController.Outcome.GAME_OVER_SCARECROW:
_title.text = "The scarecrow has fallen"
_rating.text = "%s. Its straw gave out." % night
else:
_title.text = "The farm was stripped bare"
_rating.text = "%s. Every crop, animal, and supply is gone." % night
var e := s.night_events
var lines: Array[String] = []
lines.append("You kept the farm for %d %s." % [s.nights_survived, "night" if s.nights_survived == 1 else "nights"])
lines.append("Left: %d of %d crops, %d of %d animals, %d supplies." % [s.crops, s.crops_total, s.animals, s.animals_total, s.supplies])
lines.append("Tonight: %s defeated; %d crops, %d animals, and %d supplies snatched." % [Assessment.enemies_line(e),
int(e.get("crops_stolen", 0)), int(e.get("animals_stolen", 0)), int(e.get("supplies_stolen", 0))])
_detail.text = "\n".join(lines)
_bars.visible = false
_stats.text = _totals_text(s.totals(), false)
_stats.visible = not s.night_log.is_empty()
_retry.visible = true
_retry.text = "Retry the night (from the morning of day %d)" % s.night
_show_buttons()
_open(_retry)
func show_assessment() -> void:
var s := campaign.state
var cfg := campaign.config
mode = "assessment"
var a := Assessment.of(s, cfg)
_title.text = "The farmers are home!"
_rating.text = "%s · %d points" % [a["tier"], a["score"]]
_detail.text = "%s\nYou kept the farm for all %d nights." % [a["text"], s.nights_survived]
_bars.visible = true
var parts: Dictionary = a["parts"]
for cat: String in _bar_rows:
var row: Array = _bar_rows[cat]
var shown := parts.has(cat)
for c: Control in row:
c.visible = shown
if not shown:
continue
(row[0] as ProgressBar).value = float(parts[cat])
var pct := roundi(100.0 * float(parts[cat]))
match cat:
"crops":
(row[1] as Label).text = "%d%% (%d of %d)" % [pct, s.crops, s.crops_total]
"animals":
(row[1] as Label).text = "%d%% (%d of %d)" % [pct, s.animals, s.animals_total]
_:
(row[1] as Label).text = "%d%% kept from thieves (%d of %d carried off)" % [pct, a["supplies_lost"], a["supplies_handled"]]
_stats.text = _totals_text(a["totals"], true)
_stats.visible = true
_retry.visible = false
_show_buttons()
_open(_menu if has_menu else _new)
## The vacation's totals, a few lines.
func _totals_text(t: Dictionary, finished: bool) -> String:
var s := campaign.state
var lines: Array[String] = []
if not finished:
lines.append("Over the vacation so far:")
lines.append("Enemies defeated: %s. Got away with loot: %d." % [Assessment.enemies_line(t), int(t["escaped"])])
lines.append("Recovered: %s, %s, %d supplies. Carried off: %s, %s, %d supplies." % [
_count(t["crops_recovered"], "crop"), _count(t["animals_recovered"], "animal"), int(t["supplies_recovered"]),
_count(t["crops_lost"], "crop"), _count(t["animals_lost"], "animal"), int(t["supplies_lost"])])
lines.append("Built %d, repaired %d, broken %d. Upgrades: %d of %d. Patched up %s, %d damage taken." % [
int(t["structures_built"]), int(t["repairs"]), int(t["structures_destroyed"]), s.upgrades.size(),
Upgrades.ORDER.size(), _count(t["patches"], "time"), int(t["scarecrow_damage"])])
lines.append("Gathered %s. Spent %s." % [Assessment.materials_line(t, "gathered_"), Assessment.materials_line(t, "spent_")])
return "\n".join(lines)
## "1 crop", "3 crops".
static func _count(n: Variant, word: String) -> String:
return "%d %s%s" % [int(n), word, "" if int(n) == 1 else "s"]
func _show_buttons() -> void:
_menu.visible = has_menu
_new.visible = not has_menu
func _open(focus: Button) -> void:
visible = true
mouse_filter = Control.MOUSE_FILTER_STOP
focus.grab_focus()
func _label(parent: Node, font_size: int, color: Color = Color(0.92, 0.92, 0.88)) -> Label:
var l := Label.new()
l.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
l.add_theme_font_size_override("font_size", font_size)
l.add_theme_color_override("font_color", color)
parent.add_child(l)
return l
func _button(parent: Control, text: String) -> Button:
var b := Button.new()
b.text = text
b.custom_minimum_size = Vector2(230.0, 56.0)
b.add_theme_font_size_override("font_size", 24)
parent.add_child(b)
return b

View file

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

View file

@ -0,0 +1,259 @@
class_name EnemyCharacters
extends Node3D
## The KayKit characters that draw ground enemies (EnemySystem keeps the simulation; flyers stay
## in its MultiMesh). A fixed pool per type is created at load and never grows: a ground enemy
## only spawns while its type has a free character.
## thief Mannequin_Medium, tinted dark, Rig_Medium clips (player_animations.res)
## breaker Mannequin_Large, rust red, scaled down, a club in its right hand, Rig_Large clips
## (breaker_animations.res)
## Each frame a character takes its enemy's interpolated position and heading and a clip for what
## it's doing (walking or running by speed, taking loot, breaking, fighting), flashes white on a
## hit, and glows faintly at night. A killed enemy's character plays its death clip where it fell
## for CORPSE_TIME; a corpse is only for show, so a new enemy can take it over at once when no
## other character is free.
const POOL := {EnemySystem.TYPE_THIEF: 48, EnemySystem.TYPE_BREAKER: 20}
const CORPSE_TIME := 1.6
const HIT_TIME := 0.35
const KIT := "res://assets/kaykit_characters/characters/"
const SCENES := {EnemySystem.TYPE_THIEF: KIT + "Mannequin_Medium.glb", EnemySystem.TYPE_BREAKER: KIT + "Mannequin_Large.glb"}
const LIBRARIES := {
EnemySystem.TYPE_THIEF: "res://game/resources/player_animations.res",
EnemySystem.TYPE_BREAKER: "res://game/resources/breaker_animations.res",
}
const SCALES := {EnemySystem.TYPE_THIEF: 0.86, EnemySystem.TYPE_BREAKER: 0.62}
const TINTS := {EnemySystem.TYPE_THIEF: Color(0.3, 0.27, 0.36), EnemySystem.TYPE_BREAKER: Color(0.72, 0.32, 0.2)}
## Clips by what the character is doing: idle, walk, run, steal (crops and animals), steal
## (supplies), break, fight, hit, death.
const CLIPS := {
EnemySystem.TYPE_THIEF: {"idle": &"Idle_A", "walk": &"Walking_A", "run": &"Running_A", "steal": &"PickUp",
"steal_supply": &"Lockpicking", "break": &"Melee_Unarmed_Attack_Punch_A", "fight": &"Melee_Unarmed_Attack_Punch_A",
"hit": &"Hit_A", "death": &"Death_A"},
EnemySystem.TYPE_BREAKER: {"idle": &"Melee_2H_Idle", "walk": &"Walking_A", "run": &"Running_A", "steal": &"Melee_2H_Idle",
"steal_supply": &"Melee_2H_Idle", "break": &"Melee_2H_Slam", "fight": &"Melee_2H_Attack",
"hit": &"Hit_A", "death": &"Death_A"},
}
var enemies: EnemySystem
var config: GameConfig
## Per character (index into the arrays below): its type, the enemy id it draws (-1 when free),
## and timers.
var type := PackedByteArray()
var enemy_id := PackedInt32Array()
var corpse := PackedFloat32Array()
var hit_left := PackedFloat32Array()
var _roots: Array[Node3D] = []
var _anims: Array[AnimationPlayer] = []
var _overlays: Array[ShaderMaterial] = []
var _clip: Array[StringName] = []
var _by_id := {} # enemy id -> character index
var _night_glow: float = 0.0
func setup(p_enemies: EnemySystem, p_config: GameConfig) -> void:
enemies = p_enemies
config = p_config
var shader := load("res://game/resources/enemy_overlay.gdshader") as Shader
for t: int in POOL:
var scene := load(SCENES[t]) as PackedScene
var library := load(LIBRARIES[t]) as AnimationLibrary
for k in POOL[t]:
var root := Node3D.new()
root.name = "%s_%d" % [EnemySystem.TYPE_NAMES[t], k]
root.visible = false
root.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(root)
var model := scene.instantiate() as Node3D
model.scale = Vector3.ONE * float(SCALES[t])
root.add_child(model)
var overlay := ShaderMaterial.new()
overlay.shader = shader
for mi in model.find_children("*", "MeshInstance3D", true, false):
var m := mi as MeshInstance3D
var base := m.get_active_material(0)
if base is BaseMaterial3D:
var tinted := (base as BaseMaterial3D).duplicate() as BaseMaterial3D
tinted.albedo_color = TINTS[t]
m.material_override = tinted
m.material_overlay = overlay
if t == EnemySystem.TYPE_BREAKER:
_add_club(model)
var anim := AnimationPlayer.new()
root.add_child(anim)
anim.root_node = anim.get_path_to(model)
anim.add_animation_library(&"", library)
_roots.append(root)
_anims.append(anim)
_overlays.append(overlay)
_clip.append(&"")
type.append(t)
enemy_id.append(-1)
corpse.append(0.0)
hit_left.append(0.0)
## Characters of the type not drawing a live enemy (corpses included: they can be taken over).
func free_count(t: int) -> int:
var n := 0
for c in type.size():
if type[c] == t and enemy_id[c] < 0:
n += 1
return n
func corpses() -> int:
var n := 0
for c in type.size():
if enemy_id[c] < 0 and corpse[c] > 0.0:
n += 1
return n
## Takes a character of the type for enemy id: a free one, else the corpse closest to fading.
## Returns false if every one is drawing a live enemy.
func acquire(t: int, id: int) -> bool:
var pick := -1
for c in type.size():
if type[c] != t or enemy_id[c] >= 0:
continue
if corpse[c] <= 0.0:
pick = c
break
if pick < 0 or corpse[c] < corpse[pick]:
pick = c
if pick < 0:
return false
enemy_id[pick] = id
corpse[pick] = 0.0
_by_id[id] = pick
hit_left[pick] = 0.0
_clip[pick] = &""
_roots[pick].visible = true
_overlays[pick].set_shader_parameter("flash", 0.0)
return true
## The enemy is gone: a killed one's character plays its death clip where it fell for a moment.
func release(id: int, killed: bool) -> void:
if not _by_id.has(id):
return
var c: int = _by_id[id]
_by_id.erase(id)
enemy_id[c] = -1
if killed:
corpse[c] = CORPSE_TIME
_play(c, CLIPS[type[c]]["death"], 0.1)
else:
_roots[c].visible = false
func hit(id: int) -> void:
if _by_id.has(id):
hit_left[_by_id[id]] = HIT_TIME
## Every character back to the pool, hidden (new morning, retry).
func clear() -> void:
_by_id.clear()
for c in type.size():
enemy_id[c] = -1
corpse[c] = 0.0
_roots[c].visible = false
## How many characters are drawing an enemy right now (tests).
func in_use() -> int:
return _by_id.size()
func set_night_glow(glow: float) -> void:
_night_glow = glow
func _process(delta: float) -> void:
if enemies == null:
return
for c in type.size():
var root := _roots[c]
if corpse[c] > 0.0:
corpse[c] = maxf(corpse[c] - delta, 0.0)
if corpse[c] == 0.0:
root.visible = false
continue
if enemy_id[c] < 0:
continue
var d: int = enemies.id_dense[enemy_id[c]]
if d < 0:
continue
var p := enemies.visual_position(d)
root.position = Vector3(p.x, 0.0, p.y)
root.rotation.y = lerp_angle(root.rotation.y, atan2(enemies.head_x[d], enemies.head_z[d]), 1.0 - exp(-14.0 * delta))
hit_left[c] = maxf(hit_left[c] - delta, 0.0)
_overlays[c].set_shader_parameter("flash", enemies.hurt[d])
_overlays[c].set_shader_parameter("night_glow", _night_glow)
_animate(c, d)
func _animate(c: int, d: int) -> void:
var clips: Dictionary = CLIPS[type[c]]
var speed := Vector2(enemies.vel_x[d], enemies.vel_z[d]).length()
var clip: StringName = clips["idle"]
var scale := 1.0
match enemies.state[d]:
ThiefBehavior.State.STEAL:
var tg := enemies.target[d]
var supply := tg > 0 and enemies.behavior != null and enemies.behavior.loot.category[tg] == LootSystem.Category.SUPPLY
clip = clips["steal_supply"] if supply else clips["steal"]
ThiefBehavior.State.BREAK:
clip = clips["break"]
ThiefBehavior.State.FIGHT:
clip = clips["fight"] if speed < 0.3 else clips["walk"]
_:
if speed > 2.2:
clip = clips["run"]
scale = clampf(speed / 4.5, 0.6, 1.3)
elif speed > 0.25:
clip = clips["walk"]
scale = clampf(speed / 1.6, 0.6, 1.4)
if hit_left[c] > 0.0:
clip = clips["hit"]
_anims[c].speed_scale = scale
if clip != _clip[c] or not _anims[c].is_playing():
_play(c, clip, 0.15)
func _play(c: int, clip: StringName, blend: float) -> void:
_clip[c] = clip
if _anims[c].has_animation(clip):
_anims[c].play(clip, blend)
## A club built from primitives in the large mannequin's right hand.
func _add_club(model: Node3D) -> void:
var skel := model.find_children("*", "Skeleton3D", true, false)
if skel.is_empty():
return
var attach := BoneAttachment3D.new()
attach.bone_name = "handslot.r"
(skel[0] as Skeleton3D).add_child(attach)
var wood := StandardMaterial3D.new()
wood.albedo_color = Color(0.42, 0.27, 0.15)
var handle := MeshInstance3D.new()
var cyl := CylinderMesh.new()
cyl.top_radius = 0.07
cyl.bottom_radius = 0.06
cyl.height = 1.1
cyl.material = wood
handle.mesh = cyl
handle.position = Vector3(0.0, 0.45, 0.0)
attach.add_child(handle)
var head := MeshInstance3D.new()
var knob := CylinderMesh.new()
knob.top_radius = 0.2
knob.bottom_radius = 0.16
knob.height = 0.45
knob.material = wood
head.mesh = knob
head.position = Vector3(0.0, 1.05, 0.0)
attach.add_child(head)

View file

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

View file

@ -0,0 +1,620 @@
class_name EnemySystem
extends Node3D
## Pooled enemy simulation for the farm, forked from the prototype's HordeSystem: dense slots
## with stable ids and generation counters (handles that go stale when a slot is reused),
## swap-removal, removals deferred to the end of the tick, and one shared MultiMesh batch
## (HordeRenderer) for the flyers. Adds per-slot type, behavior state, target and carried loot,
## and a state timer. Each type's stats come from GameConfig.enemy_types (cached per type here).
## Ground enemies collide with the farm through the FarmNavigation grid: an enemy's center stays
## in walkable cells (free of static obstacles and of player-built structures, both already
## inflated by its radius), so it keeps clear of every shape the scarecrow collides with and
## can't pass a fence or gate without breaking it; slowing traps (StructureSystem.try_trap) slow
## it down; it is drawn by a pooled KayKit character (EnemyCharacters). Flyers ignore all of
## that, keep apart only from each other, and fly at a visual altitude (alt) in the MultiMesh;
## their hit proxy stays at combat height. What each enemy wants is decided by the behavior
## policy (ThiefBehavior); motion, damage, removal, and rendering live here.
enum Removal { KILLED, ESCAPED, LEFT }
enum Aggression { NONE, CONTACT, FIGHT }
const ID_BITS := 16
const ID_MASK := (1 << ID_BITS) - 1
const TYPE_THIEF := 0
const TYPE_CROW := 1
const TYPE_BREAKER := 2
## GameConfig.enemy_types keys, by type id.
const TYPE_NAMES: Array[String] = ["thief", "crow", "breaker"]
## Display names, singular and plural.
const NAMES: Array[String] = ["thief", "crow", "fence breaker"]
const PLURALS: Array[String] = ["thieves", "crows", "fence breakers"]
const NB_DX: Array[int] = [0, -1, 0, 1, -1, 1, -1, 0, 1]
const NB_DZ: Array[int] = [0, -1, -1, -1, 0, 0, 1, 1, 1]
## Emitted for every removal at the end of the tick, while the handle is still valid, with the
## loot item the enemy carried and the one it targeted (-1 for none).
signal enemy_removed(handle: int, reason: Removal, x: float, z: float, carry: int, target: int)
var config: GameConfig
var nav: FarmNavigation
var behavior: ThiefBehavior
## Set by FarmSim: slowing traps, and the characters that draw ground enemies.
var structures: StructureSystem
var characters: EnemyCharacters
var grid := SpatialGrid.new()
var renderer: HordeRenderer
# Per type (index = type id), from GameConfig.enemy_types.
var t_speed := PackedFloat32Array()
var t_accel := PackedFloat32Array()
var t_hp := PackedInt32Array()
var t_flying := PackedByteArray()
## Loot categories it takes (bit per LootSystem.Category); t_breaks for "structures".
var t_targets := PackedInt32Array()
var t_breaks := PackedByteArray()
var t_steal := PackedFloat32Array()
var t_carry := PackedFloat32Array()
var t_structure_damage := PackedInt32Array()
var t_damage := PackedInt32Array()
var t_hit_interval := PackedFloat32Array()
var t_aggression := PackedByteArray()
var t_aggro_range := PackedFloat32Array()
var t_hit_radius := PackedFloat32Array()
var capacity: int = 0
var active_count: int = 0
# Dense per-slot state (index = slot in [0, active_count)).
var pos_x := PackedFloat32Array()
var pos_z := PackedFloat32Array()
var prev_x := PackedFloat32Array()
var prev_z := PackedFloat32Array()
var vel_x := PackedFloat32Array()
var vel_z := PackedFloat32Array()
## Desired unit direction and pace (share of full speed) written by the behavior each tick.
var desire_x := PackedFloat32Array()
var desire_z := PackedFloat32Array()
var pace := PackedFloat32Array()
var head_x := PackedFloat32Array()
var head_z := PackedFloat32Array()
var flap_phase := PackedFloat32Array()
## Hit flash (1 on a hit, fading), shown by the shader.
var hurt := PackedFloat32Array()
var timer := PackedFloat32Array()
## Flyers: visual altitude.
var alt := PackedFloat32Array()
## Seconds until the enemy can attack again.
var attack_cd := PackedFloat32Array()
## Seconds of slowing-trap slowdown left.
var slow_left := PackedFloat32Array()
## Structure being broken (BREAK) and the state to resume after it (-1 / 0 when none).
var barrier := PackedInt32Array()
var resume := PackedByteArray()
var health := PackedInt32Array()
## Loot item the enemy is after and the one it carries (-1 for none).
var target := PackedInt32Array()
var carry := PackedInt32Array()
## The loot category it goes for (LootSystem.Category, or LootSystem.ANY).
var want := PackedByteArray()
var type := PackedByteArray()
var state := PackedByteArray()
var alive := PackedByteArray()
var removal := PackedByteArray()
var dense_id := PackedInt32Array()
# Stable ids: slot of each id (-1 when free) and its generation.
var id_dense := PackedInt32Array()
var id_generation := PackedInt32Array()
var _free_ids := PackedInt32Array()
var _free_top: int = 0
var _pending := PackedInt32Array()
var _pending_count: int = 0
# Diagnostics.
var spawn_skipped: int = 0
var kills: int = 0
var escapes: int = 0
var attacks_attempted: int = 0
var attacks_blocked_by_cover: int = 0
## Fraction along the last sweep_hit() segment where the nearest hit happened.
var hit_t: float = 0.0
func setup(cfg: GameConfig, p_nav: FarmNavigation, p_behavior: ThiefBehavior, mesh: Mesh,
material: Material, area: Rect2) -> void:
config = cfg
nav = p_nav
behavior = p_behavior
capacity = cfg.enemy_capacity
_load_types(cfg)
for a: PackedFloat32Array in [pos_x, pos_z, prev_x, prev_z, vel_x, vel_z, desire_x, desire_z,
pace, head_x, head_z, flap_phase, hurt, timer, attack_cd, slow_left, alt]:
a.resize(capacity)
a.fill(0.0)
for a: PackedInt32Array in [health, target, carry, barrier, dense_id, id_dense, id_generation, _free_ids, _pending]:
a.resize(capacity)
a.fill(0)
for a: PackedByteArray in [type, state, alive, removal, resume, want]:
a.resize(capacity)
a.fill(0)
id_dense.fill(-1)
grid.setup(area, 1.0, capacity)
renderer = HordeRenderer.new()
renderer.name = "EnemyRenderer"
add_child(renderer)
var aabb := AABB(Vector3(area.position.x, 0.0, area.position.y), Vector3(area.size.x, 4.0, area.size.y))
renderer.setup(mesh, material, capacity, cfg.combat_height, aabb)
clear()
func _load_types(cfg: GameConfig) -> void:
var n := TYPE_NAMES.size()
for a: PackedFloat32Array in [t_speed, t_accel, t_steal, t_carry, t_hit_interval, t_aggro_range, t_hit_radius]:
a.resize(n)
for a: PackedInt32Array in [t_hp, t_targets, t_structure_damage, t_damage]:
a.resize(n)
for a: PackedByteArray in [t_flying, t_breaks, t_aggression]:
a.resize(n)
for t in n:
var row := cfg.enemy(TYPE_NAMES[t])
t_speed[t] = float(row.get("speed", 3.0))
t_accel[t] = float(row.get("acceleration", 14.0))
t_hp[t] = int(row.get("hp", 1))
t_flying[t] = 1 if bool(row.get("flying", false)) else 0
var mask := 0
for target in row.get("targets", []):
var c := LootSystem.CATEGORY_KEYS.find(String(target))
if c >= 0:
mask |= 1 << c
t_targets[t] = mask
t_breaks[t] = 1 if (row.get("targets", []) as Array).has("structures") else 0
t_steal[t] = float(row.get("steal_time", 1.0))
t_carry[t] = float(row.get("carry_speed", 0.7))
t_structure_damage[t] = int(row.get("structure_damage", 0))
t_damage[t] = int(row.get("damage", 0))
t_hit_interval[t] = float(row.get("hit_interval", 1.2))
t_aggression[t] = maxi(["none", "contact", "fight"].find(String(row.get("aggression", "none"))), 0)
t_aggro_range[t] = float(row.get("aggro_range", 0.0))
t_hit_radius[t] = float(row.get("hit_radius", 0.4))
func is_flying(d: int) -> bool:
return t_flying[type[d]] == 1
func max_speed() -> float:
var best := 0.0
for v in t_speed:
best = maxf(best, v)
return best
## Releases every enemy at once, without removal events (used when the farm state is replaced,
## e.g. on retry: the loot system resyncs from the new state).
func clear() -> void:
active_count = 0
_pending_count = 0
_free_top = capacity
for id in capacity:
_free_ids[id] = capacity - 1 - id # pop order 0, 1, 2, ...
if id_dense[id] >= 0:
id_generation[id] += 1
id_dense[id] = -1
if renderer:
renderer.clear()
renderer.commit(0)
if characters:
characters.clear()
## Acquires a slot and initializes every state field. Returns a handle, or -1 if the pool is
## exhausted, or for a ground enemy there's no free character to draw it (the spawn is skipped
## and counted; nothing grows).
func spawn(enemy_type: int, x: float, z: float, heading: Vector2, p_want: int = LootSystem.ANY) -> int:
if active_count >= capacity or _free_top <= 0:
spawn_skipped += 1
return -1
var id := _free_ids[_free_top - 1]
if characters != null and t_flying[enemy_type] == 0 and not characters.acquire(enemy_type, id):
spawn_skipped += 1
return -1
_free_top -= 1
var d := active_count
active_count += 1
var h := heading.normalized() if heading.length_squared() > 1e-6 else Vector2(0.0, -1.0)
pos_x[d] = x
pos_z[d] = z
prev_x[d] = x
prev_z[d] = z
vel_x[d] = 0.0
vel_z[d] = 0.0
desire_x[d] = 0.0
desire_z[d] = 0.0
pace[d] = 0.0
head_x[d] = h.x
head_z[d] = h.y
flap_phase[d] = randf()
hurt[d] = 0.0
timer[d] = 0.0
attack_cd[d] = 0.0
slow_left[d] = 0.0
alt[d] = config.cruise_altitude
health[d] = t_hp[enemy_type]
target[d] = -1
carry[d] = -1
barrier[d] = -1
resume[d] = 0
type[d] = enemy_type
want[d] = p_want
state[d] = 0
alive[d] = 1
removal[d] = 0
dense_id[d] = id
id_dense[id] = d
renderer.write_new(d, x, z, h.x, h.y, flap_phase[d])
return handle_of(d)
func handle_of(d: int) -> int:
var id := dense_id[d]
return id | (id_generation[id] << ID_BITS)
## Returns the dense slot for a handle, or -1 if the handle is stale or released.
func resolve_handle(handle: int) -> int:
if handle < 0:
return -1
var id := handle & ID_MASK
if id >= capacity or id_generation[id] != (handle >> ID_BITS):
return -1
return id_dense[id]
func is_alive_slot(d: int) -> bool:
return d >= 0 and d < active_count and alive[d] == 1
func alive_count() -> int:
return active_count - _pending_count
## Interpolated render-time position of a slot (between the last two ticks).
func visual_position(d: int) -> Vector2:
var f := Engine.get_physics_interpolation_fraction()
return Vector2(lerpf(prev_x[d], pos_x[d], f), lerpf(prev_z[d], pos_z[d], f))
## Applies one hit. Returns false for dead or pending slots (no double kills).
func apply_hit(d: int, damage: int = 1) -> bool:
if not is_alive_slot(d):
return false
health[d] -= damage
hurt[d] = 1.0
if characters != null and t_flying[type[d]] == 0:
characters.hit(dense_id[d])
if health[d] <= 0:
kills += 1
queue_removal(d, Removal.KILLED)
elif behavior != null:
behavior.on_hit(self, d)
return true
func apply_hit_handle(handle: int, damage: int = 1) -> bool:
return apply_hit(resolve_handle(handle), damage)
## Takes a living enemy out of the simulation now; its slot is released (and enemy_removed
## emitted) at the end of the tick by commit_removals().
func queue_removal(d: int, reason: Removal) -> void:
if not is_alive_slot(d):
return
alive[d] = 0
removal[d] = reason
if reason == Removal.ESCAPED:
escapes += 1
_pending[_pending_count] = dense_id[d]
_pending_count += 1
## Every living enemy leaves now (end of the night): removal reason LEFT.
func remove_all() -> void:
for d in active_count:
queue_removal(d, Removal.LEFT)
commit_removals()
## One tick: behavior decides desired directions, then steering (desire plus separation from
## nearby enemies of the same kind, ground or air) and motion. Ground enemies collide with the
## grid and yield to the scarecrow; flyers do neither and ease toward their altitude.
## Co-op: player 2's scarecrow, which ground enemies yield to as well (INF when there's none).
var scarecrow2 := Vector2(INF, INF)
func step(dt: float, scarecrow: Vector2, scarecrow_radius: float) -> void:
var scarecrows: Array[Vector2] = [scarecrow, scarecrow2]
if behavior != null:
behavior.update(self, dt)
var cfg := config
var sep_r := cfg.separation_radius
var contact := cfg.enemy_radius + scarecrow_radius
var max_corr := cfg.max_correction_per_tick
var g := grid
for i in active_count:
hurt[i] = maxf(hurt[i] - dt * 4.0, 0.0)
attack_cd[i] = maxf(attack_cd[i] - dt, 0.0)
slow_left[i] = maxf(slow_left[i] - dt, 0.0)
var x := pos_x[i]
var z := pos_z[i]
prev_x[i] = x
prev_z[i] = z
if alive[i] == 0:
continue
var t := type[i]
var flying := t_flying[t] == 1
var speed := t_speed[t]
var accel := t_accel[t] * dt
if flying:
var want_alt := behavior.altitude_for(self, i) if behavior != null else cfg.cruise_altitude
alt[i] = move_toward(alt[i], want_alt, dt * 2.5)
elif structures != null and slow_left[i] == 0.0 and structures.try_trap(x, z):
slow_left[i] = structures.trap_slow_time()
# Separation from neighbors (previous tick's buckets).
var sx := 0.0
var sz := 0.0
var gx := g.cell_x(x)
var gz := g.cell_z(z)
for n in 9:
var ncx := gx + NB_DX[n]
var ncz := gz + NB_DZ[n]
if ncx < 0 or ncz < 0 or ncx >= g.width or ncz >= g.height:
continue
var c := ncz * g.width + ncx
for k in range(g.cell_start[c], g.cell_start[c + 1]):
var o := g.items[k]
if o == i or o >= active_count or alive[o] == 0 or t_flying[type[o]] != t_flying[t]:
continue
var dx := x - pos_x[o]
var dz := z - pos_z[o]
var d2 := dx * dx + dz * dz
if d2 >= sep_r * sep_r or d2 < 1e-8:
continue
var d := sqrt(d2)
sx += dx / d * (sep_r - d) / sep_r
sz += dz / d * (sep_r - d) / sep_r
var top := speed * pace[i] * (cfg.trap_slow_factor if slow_left[i] > 0.0 else 1.0)
var tx := desire_x[i] * top + sx * cfg.separation_weight * speed * 0.5
var tz := desire_z[i] * top + sz * cfg.separation_weight * speed * 0.5
var vx := vel_x[i]
var vz := vel_z[i]
var dvx := tx - vx
var dvz := tz - vz
var dl2 := dvx * dvx + dvz * dvz
if dl2 > accel * accel:
var kk := accel / sqrt(dl2)
dvx *= kk
dvz *= kk
vx += dvx
vz += dvz
var nx := x + vx * dt
var nz := z + vz * dt
if flying:
pos_x[i] = nx
pos_z[i] = nz
vel_x[i] = vx
vel_z[i] = vz
_turn(i, vx, vz)
continue
# Yield to the scarecrow (bounded push), and stop pressing into it.
for sc: Vector2 in scarecrows:
if not sc.is_finite():
continue
var ox := nx - sc.x
var oz := nz - sc.y
var od2 := ox * ox + oz * oz
if od2 < contact * contact and od2 > 1e-8:
var od := sqrt(od2)
var push := minf(contact - od, max_corr)
nx += ox / od * push
nz += oz / od * push
var vn := (vx * ox + vz * oz) / od
if vn < 0.0:
vx -= vn * ox / od
vz -= vn * oz / od
# Grid collision: keep the center in walkable cells, sliding along an axis when blocked.
if not nav.is_walkable(nav.cell_of(nx, nz)):
if nav.is_walkable(nav.cell_of(nx, z)):
nz = z
vz = 0.0
elif nav.is_walkable(nav.cell_of(x, nz)):
nx = x
vx = 0.0
else:
nx = x
nz = z
vx = 0.0
vz = 0.0
pos_x[i] = nx
pos_z[i] = nz
vel_x[i] = vx
vel_z[i] = vz
_turn(i, vx, vz)
grid.rebuild(pos_x, pos_z, active_count)
## Turns the heading toward the velocity (or the desire, when nearly still).
func _turn(i: int, vx: float, vz: float) -> void:
var sp2 := vx * vx + vz * vz
var fx := vx if sp2 > 0.04 else desire_x[i]
var fz := vz if sp2 > 0.04 else desire_z[i]
var fl := sqrt(fx * fx + fz * fz)
if fl > 1e-4:
var hx := head_x[i] + (fx / fl - head_x[i]) * 0.25
var hz := head_z[i] + (fz / fl - head_z[i]) * 0.25
var hl := sqrt(hx * hx + hz * hz)
if hl > 1e-4:
head_x[i] = hx / hl
head_z[i] = hz / hl
## Melee: enemies the behavior allows to attack, touching the scarecrow (within
## enemy_attack_reach of contact), off cooldown, and with a clear line to it, attack for their
## type's damage. The scarecrow's invulnerability decides whether a hit lands, so several attacks
## on one tick cost at most one hit. The cooldown (the type's hit_interval) starts on every
## attempt.
func evaluate_attacks(scarecrow_pos: Vector2, scarecrow_radius: float, target_kit: Scarecrow) -> void:
var cfg := config
var reach := cfg.enemy_radius + scarecrow_radius + cfg.enemy_attack_reach
var g := grid
var cx0 := g.cell_x(scarecrow_pos.x - reach)
var cx1 := g.cell_x(scarecrow_pos.x + reach)
var cz0 := g.cell_z(scarecrow_pos.y - reach)
var cz1 := g.cell_z(scarecrow_pos.y + reach)
for cz in range(cz0, cz1 + 1):
for cx in range(cx0, cx1 + 1):
var c := cz * g.width + cx
for k in range(g.cell_start[c], g.cell_start[c + 1]):
var i := g.items[k]
if i >= active_count or alive[i] == 0 or attack_cd[i] > 0.0:
continue
if behavior != null and not behavior.can_attack(self, i):
continue
var dx := pos_x[i] - scarecrow_pos.x
var dz := pos_z[i] - scarecrow_pos.y
if dx * dx + dz * dz > reach * reach:
continue
attack_cd[i] = t_hit_interval[type[i]]
attacks_attempted += 1
if not nav.line_clear(pos_x[i], pos_z[i], scarecrow_pos.x, scarecrow_pos.y):
attacks_blocked_by_cover += 1
continue
target_kit.try_damage(t_damage[type[i]])
## Swept projectile test against enemy hit proxies (vertical cylinders of the type's hit_radius;
## shots fly horizontally at combat height, so it is a 2D circle test, flyers included), using
## each enemy's motion across the tick relative to the shot's (the prototype's exact
## relative-motion test). Returns the dense slot of the nearest hit (fraction in hit_t) or -1.
func sweep_hit(x0: float, z0: float, x1: float, z1: float, use_motion: bool) -> int:
var widest := 0.0
for v in t_hit_radius:
widest = maxf(widest, v)
var margin := widest + max_speed() / float(Engine.physics_ticks_per_second) + config.max_correction_per_tick * 2.0
var g := grid
var cx0 := g.cell_x(minf(x0, x1) - margin)
var cx1 := g.cell_x(maxf(x0, x1) + margin)
var cz0 := g.cell_z(minf(z0, z1) - margin)
var cz1 := g.cell_z(maxf(z0, z1) + margin)
var best := -1
var best_t := 2.0
var mbx := x1 - x0
var mbz := z1 - z0
for cz in range(cz0, cz1 + 1):
for cx in range(cx0, cx1 + 1):
var c := cz * g.width + cx
for k in range(g.cell_start[c], g.cell_start[c + 1]):
var i := g.items[k]
if i >= active_count or alive[i] == 0:
continue
var rr := t_hit_radius[type[i]]
var ex0 := prev_x[i] if use_motion else pos_x[i]
var ez0 := prev_z[i] if use_motion else pos_z[i]
var sx := x0 - ex0
var sz := z0 - ez0
var mx := mbx - (pos_x[i] - ex0)
var mz := mbz - (pos_z[i] - ez0)
var cc := sx * sx + sz * sz - rr * rr
var t := 2.0
if cc <= 0.0:
t = 0.0
else:
var a := mx * mx + mz * mz
var bb := sx * mx + sz * mz
if a > 1e-12 and bb < 0.0:
var disc := bb * bb - a * cc
if disc >= 0.0:
t = (-bb - sqrt(disc)) / a
if t <= 1.0 and t < best_t:
best_t = t
best = i
hit_t = best_t
return best
## Releases this tick's removals: emits enemy_removed (handle still valid), then swaps the last
## active enemy into each freed slot and updates every mapping.
func commit_removals() -> void:
var n := _pending_count
_pending_count = 0
for k in n:
var id := _pending[k]
var d := id_dense[id]
if d < 0:
continue
enemy_removed.emit(handle_of(d), removal[d] as Removal, pos_x[d], pos_z[d], carry[d], target[d])
if characters != null and t_flying[type[d]] == 0:
characters.release(id, removal[d] == Removal.KILLED)
_release_slot(d)
## Uploads the flyers' poses (with their altitude) to the MultiMesh; ground enemies are drawn by
## their characters, so their instances are scaled to nothing.
func commit_render() -> void:
var b := renderer.buffer
var o := 0
for i in active_count:
var on := 1.0 if t_flying[type[i]] == 1 else 0.0
var c := -head_z[i] * on
var s := -head_x[i] * on
b[o] = c
b[o + 2] = s
b[o + 3] = pos_x[i]
b[o + 5] = on
b[o + 7] = alt[i]
b[o + 8] = -s
b[o + 10] = c
b[o + 11] = pos_z[i]
b[o + 13] = hurt[i]
o += HordeRenderer.STRIDE
renderer.commit(active_count)
func _release_slot(d: int) -> void:
var id := dense_id[d]
var last := active_count - 1
if d != last:
for a: PackedFloat32Array in [pos_x, pos_z, prev_x, prev_z, vel_x, vel_z, desire_x, desire_z,
pace, head_x, head_z, flap_phase, hurt, timer, attack_cd, slow_left, alt]:
a[d] = a[last]
for a: PackedInt32Array in [health, target, carry, barrier]:
a[d] = a[last]
for a: PackedByteArray in [type, state, alive, removal, resume, want]:
a[d] = a[last]
var moved := dense_id[last]
dense_id[d] = moved
id_dense[moved] = d
renderer.move_slot(last, d)
alive[last] = 0
id_dense[id] = -1
id_generation[id] += 1
_free_ids[_free_top] = id
_free_top += 1
active_count -= 1
## The prototype's bird, re-centered on the torso and scaled to meters, beak along -Z.
static func build_bird_mesh(scale: float) -> ArrayMesh:
var src := load(AssetCatalog.BIRD_PATH) as Mesh
var basis := Basis(Vector3(0, 0, -1), Vector3(-1, 0, 0), Vector3(0, 1, 0))
var mesh := ArrayMesh.new()
for surface in src.get_surface_count():
var arrays := src.surface_get_arrays(surface)
var verts: PackedVector3Array = arrays[Mesh.ARRAY_VERTEX]
var normals: PackedVector3Array = arrays[Mesh.ARRAY_NORMAL]
for i in verts.size():
verts[i] = basis * ((verts[i] - AssetCatalog.BIRD_SOURCE_PIVOT) * scale)
for i in normals.size():
normals[i] = basis * normals[i]
arrays[Mesh.ARRAY_VERTEX] = verts
arrays[Mesh.ARRAY_NORMAL] = normals
arrays[Mesh.ARRAY_TANGENT] = null
mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
return mesh

View file

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

504
game/scripts/farm_audio.gd Normal file
View file

@ -0,0 +1,504 @@
class_name FarmAudio
extends Node3D
## Every sound in the game, by cue name (CUES), routed through the audio buses (Music: phase
## stingers and outcomes; SFX: everything else; Ambience: the day and night loops). FarmSim
## creates it and setup() connects it to the farm's systems:
## * scarecrow: footsteps, its weapons (a pitchfork's whoosh and what it strikes, corn shots,
## a pumpkin bomb's toss and burst), hurt, fall, fear and fear ready, patching and patched
## * enemies: crow caws and thieves' / fence breakers' arrivals (from where they come in), hits
## and deaths by type
## * theft: grabbed, dropped, recovered, carried off (with an alarm tone), animals following
## * building: placed, refused, dismantled, hit, broken (with a breach alarm), repaired,
## automated defenses firing, traps springing, the repair hammering
## * gathering: chopping, rustling straw, clanking scrap; stored at the shed; upgrades bought
## * phases: the dusk bell, stingers at dusk, nightfall, sunrise, and morning; game over;
## the day and night ambience (crossfading through dusk and dawn)
## * UI: hover, click, back, open, close, error (ui(), also from the menus)
## * Music (the Music bus), by phase: "On the Farm" on the title screen (the farm's morning
## behind it), the morning, and by day, and when the farmers are back; "Purgatory" at night;
## none at dusk, at dawn, or after a Game Over (only the ambience). Tracks crossfade.
## Positional cues play where they happen and are heard from an AudioListener3D at the
## scarecrow (or the cutscene's focus) facing the way the camera does, so left and right on
## screen are left and right in the ears. Each cue has a volume, a random pitch spread, a
## minimum gap between plays, and a voice limit, so twenty crows don't make twenty caws.
## UI, stinger, and ambience players keep playing while the game is paused; the rest pause.
## Co-op: every world sound the host plays is also sent to the partner (forward), whose game
## plays only those (remote_cues) plus what it makes itself: its footsteps and channels, the UI,
## the phase stingers, and the music (LOCAL_CUES).
## Sources: Kenney's CC0 packs (assets/audio/kenney/, with their licenses) and sounds made by
## game/tools/synth_audio.gd (assets/audio/synth/). A '*' in a file name stands for 0..9.
const ROOT := "res://assets/audio/"
const CUES := {
# UI
"ui_hover": {"files": ["kenney/ui/rollover2.ogg"], "db": -16.0, "gap": 0.03, "ui": true},
"ui_click": {"files": ["kenney/interface/click_002.ogg"], "db": -8.0, "ui": true},
"ui_back": {"files": ["kenney/interface/back_001.ogg"], "db": -8.0, "ui": true},
"ui_open": {"files": ["kenney/interface/open_001.ogg"], "db": -10.0, "ui": true},
"ui_close": {"files": ["kenney/interface/close_001.ogg"], "db": -10.0, "ui": true},
"error": {"files": ["kenney/interface/error_004.ogg"], "db": -8.0, "gap": 0.25, "ui": true},
# Scarecrow
"step": {"files": ["kenney/impact/footstep_grass_00*.ogg"], "db": -15.0, "pitch": 0.08},
"shot": {"files": ["kenney/interface/pluck_00*.ogg"], "db": -9.0, "pitch": 0.12, "max": 3},
"stab": {"files": ["synth/pitchfork_whoosh.wav"], "db": -6.0, "pitch": 0.12, "max": 3},
"throw": {"files": ["kenney/rpg/cloth*.ogg"], "db": -4.0, "pitch": 0.1},
"boom": {"files": ["synth/pumpkin_boom.wav"], "db": 0.0, "pitch": 0.08, "gap": 0.05, "max": 4},
"hurt": {"files": ["kenney/impact/impactSoft_heavy_00*.ogg"], "db": -1.0, "pitch": 0.1, "gap": 0.1},
"fall": {"files": ["kenney/impact/impactSoft_heavy_004.ogg"], "db": 0.0, "pitch": 0.0},
"fear": {"files": ["kenney/digital/phaserDown2.ogg"], "db": -5.0, "pitch": 0.05},
"fear_ready": {"files": ["kenney/interface/maximize_003.ogg"], "db": -12.0},
"patching": {"files": ["kenney/rpg/cloth*.ogg"], "db": -10.0, "pitch": 0.1},
"patched": {"files": ["kenney/rpg/clothBelt.ogg"], "db": -4.0},
# Weapon and enemies
"hit": {"files": ["kenney/impact/impactPunch_medium_00*.ogg"], "db": -8.0, "pitch": 0.1, "gap": 0.03, "max": 4},
"hit_crow": {"files": ["kenney/impact/impactSoft_medium_00*.ogg"], "db": -6.0, "pitch": 0.15, "gap": 0.03, "max": 4},
"hit_world": {"files": ["kenney/impact/impactGeneric_light_00*.ogg"], "db": -14.0, "pitch": 0.15, "gap": 0.05, "max": 3},
"crow_arrive": {"files": ["synth/crow_caw_1.wav", "synth/crow_caw_2.wav"], "db": 2.0, "pitch": 0.08, "gap": 0.7, "max": 2},
"crow_die": {"files": ["synth/crow_squawk.wav"], "db": -2.0, "pitch": 0.1, "gap": 0.05, "max": 3},
"thief_arrive": {"files": ["kenney/rpg/creak*.ogg"], "db": 0.0, "pitch": 0.1, "gap": 0.8},
"breaker_arrive": {"files": ["kenney/impact/impactWood_heavy_000.ogg"], "db": 4.0, "pitch": 0.0, "gap": 0.8},
"enemy_die": {"files": ["kenney/impact/impactPunch_heavy_00*.ogg"], "db": -3.0, "pitch": 0.1, "gap": 0.05, "max": 3},
# Theft and alerts
"grab": {"files": ["kenney/rpg/handleSmallLeather.ogg"], "db": -4.0, "pitch": 0.1, "gap": 0.1},
"theft_alert": {"files": ["kenney/digital/lowThreeTone.ogg"], "db": -10.0, "gap": 2.5, "ui": true},
"drop": {"files": ["kenney/rpg/dropLeather.ogg"], "db": -4.0, "pitch": 0.1, "gap": 0.05},
"recover": {"files": ["kenney/interface/confirmation_002.ogg"], "db": -6.0, "pitch": 0.05, "gap": 0.08},
"follow": {"files": ["kenney/interface/confirmation_001.ogg"], "db": -8.0, "pitch": 0.1, "gap": 0.08},
"lost": {"files": ["kenney/digital/lowDown.ogg"], "db": -6.0, "gap": 1.0, "ui": true},
"breach": {"files": ["kenney/digital/twoTone1.ogg"], "db": -8.0, "gap": 2.0, "ui": true},
# Building
"build": {"files": ["kenney/impact/impactPlank_medium_00*.ogg"], "db": -3.0, "pitch": 0.08},
"dismantle": {"files": ["kenney/impact/impactWood_light_00*.ogg"], "db": -4.0, "pitch": 0.1},
"structure_hit": {"files": ["kenney/impact/impactWood_medium_00*.ogg"], "db": -4.0, "pitch": 0.1, "gap": 0.12, "max": 3},
"smash": {"files": ["kenney/impact/impactWood_heavy_00*.ogg"], "db": 2.0, "pitch": 0.08},
"hammer": {"files": ["kenney/impact/impactWood_light_00*.ogg"], "db": -7.0, "pitch": 0.12},
"repaired": {"files": ["kenney/interface/confirmation_001.ogg"], "db": -6.0},
"turret": {"files": ["kenney/interface/drop_00*.ogg"], "db": -11.0, "pitch": 0.1, "gap": 0.05, "max": 3},
"trap": {"files": ["kenney/impact/impactSoft_medium_00*.ogg"], "db": -4.0, "pitch": 0.2, "gap": 0.1},
# Gathering and upgrades
"chop": {"files": ["kenney/rpg/chop.ogg"], "db": -4.0, "pitch": 0.1},
"rustle": {"files": ["kenney/rpg/cloth*.ogg"], "db": -6.0, "pitch": 0.15},
"clank": {"files": ["kenney/impact/impactMetal_light_00*.ogg"], "db": -8.0, "pitch": 0.1},
"gathered": {"files": ["kenney/rpg/handleSmallLeather2.ogg"], "db": -8.0, "pitch": 0.05},
"deposit": {"files": ["kenney/rpg/bookPlace*.ogg"], "db": -4.0, "pitch": 0.08, "gap": 0.3},
"upgrade": {"files": ["kenney/jingles/jingles_PIZZI16.ogg"], "db": -6.0, "ui": true},
# Phases and outcomes (stingers on the Music bus)
"bell": {"files": ["kenney/impact/impactBell_heavy_00*.ogg"], "db": -4.0, "pitch": 0.0, "ui": true},
"dusk": {"files": ["kenney/jingles/jingles_PIZZI07.ogg"], "db": -6.0, "bus": "Music", "ui": true},
"night": {"files": ["kenney/jingles/jingles_PIZZI14.ogg"], "db": -6.0, "bus": "Music", "ui": true},
"dawn": {"files": ["kenney/jingles/jingles_PIZZI10.ogg"], "db": -6.0, "bus": "Music", "ui": true},
"morning": {"files": ["kenney/jingles/jingles_PIZZI12.ogg"], "db": -9.0, "bus": "Music", "ui": true},
"game_over": {"files": ["kenney/jingles/jingles_PIZZI01.ogg"], "db": -4.0, "bus": "Music", "ui": true},
"victory": {"files": ["kenney/jingles/jingles_PIZZI02.ogg"], "db": -4.0, "bus": "Music", "ui": true},
"assessment": {"files": ["kenney/jingles/jingles_PIZZI15.ogg"], "db": -5.0, "bus": "Music", "ui": true},
"horn": {"files": ["synth/truck_horn.wav"], "db": -4.0},
"truck_engine": {"files": ["synth/truck_engine.wav"], "db": -6.0},
"day_ambience": {"files": ["synth/day_ambience.wav"], "bus": "Ambience"},
"night_ambience": {"files": ["synth/night_ambience.wav"], "bus": "Ambience"},
}
## Cues each machine plays for itself in co-op (never sent, never skipped).
const LOCAL_CUES: Array[String] = ["ui_hover", "ui_click", "ui_back", "ui_open", "ui_close", "error", "step", "chop",
"rustle", "clank", "hammer", "patching", "bell", "dusk", "night", "dawn", "morning", "game_over", "victory",
"assessment", "horn", "truck_engine", "day_ambience", "night_ambience", "upgrade", "fear_ready"]
const VOICES_3D := 20
const VOICES_UI := 10
## Seconds of channel between repeats of the gather / repair / patch sounds, and meters per
## footstep.
const CHANNEL_REPEAT := 0.5
const STRIDE := 1.55
## Ambience levels (day, night) per phase, and the crossfade speed (share per second).
const AMBIENCE := {
CampaignController.Phase.MORNING: Vector2(1.0, 0.0), CampaignController.Phase.DAY: Vector2(1.0, 0.0),
CampaignController.Phase.DUSK: Vector2(0.55, 0.45), CampaignController.Phase.NIGHT: Vector2(0.0, 1.0),
CampaignController.Phase.DAWN: Vector2(0.6, 0.4), CampaignController.Phase.FARMERS_RETURN: Vector2(1.0, 0.0),
CampaignController.Phase.GAME_OVER: Vector2(0.0, 0.6),
}
const FADE_RATE := 0.25
const MUSIC := {"farm": "music/on_the_farm.wav", "night": "music/purgatory.ogg"}
const MUSIC_FOR := {
CampaignController.Phase.MORNING: "farm", CampaignController.Phase.DAY: "farm", CampaignController.Phase.DUSK: "",
CampaignController.Phase.NIGHT: "night", CampaignController.Phase.DAWN: "", CampaignController.Phase.FARMERS_RETURN: "farm",
CampaignController.Phase.GAME_OVER: "",
}
const MUSIC_DB := -5.0
const MUSIC_FADE := 2.5
var sim: FarmSim
## Where the listener sits (the scarecrow; the cutscene moves it).
var focus: Node3D
## Cue name -> streams, and cue name -> how many times it played (tests read this).
var streams := {}
var played := {}
## Co-op host: called with (cue, at) for every world sound, to send it to the partner.
var forward: Callable
## Co-op partner: world sounds come only from the host (play_remote).
var remote_cues := false
var _voices_3d: Array[AudioStreamPlayer3D] = []
var _voices_ui: Array[AudioStreamPlayer] = []
var _voices_game: Array[AudioStreamPlayer] = []
var _last := {} # cue -> msec of the last play
var _listener: AudioListener3D
var _day: AudioStreamPlayer
var _night: AudioStreamPlayer
var _ambience := Vector2.ZERO
var _ambience_target := Vector2(1.0, 0.0)
var _channel_left: float = 0.0
var _stride_left: float = STRIDE
var _bell_left: float = -1.0
## The track playing or fading in ("" = none), and each track's player and level (0..1).
var music_track := ""
var _music := {}
var _music_level := {}
func _ready() -> void:
process_mode = Node.PROCESS_MODE_ALWAYS # music and ambience fade on the paused title screen
for track: String in MUSIC:
var m := AudioStreamPlayer.new()
m.bus = &"Music"
m.stream = load(ROOT + MUSIC[track]) as AudioStream
m.volume_db = -80.0
add_child(m)
_music[track] = m
_music_level[track] = 0.0
for cue: String in CUES:
var list: Array[AudioStream] = []
for f: String in CUES[cue]["files"]:
for path in _expand(ROOT + f):
var s := load(path) as AudioStream
if s != null:
list.append(s)
if list.is_empty():
push_warning("FarmAudio: no sound for cue '%s'" % cue)
streams[cue] = list
for i in VOICES_3D:
var p := AudioStreamPlayer3D.new()
p.bus = &"SFX"
p.unit_size = 9.0
p.max_distance = 90.0
p.panning_strength = 0.7
p.attenuation_filter_cutoff_hz = 20500.0 # no muffling with distance
p.process_mode = Node.PROCESS_MODE_PAUSABLE # game sounds stop while paused
add_child(p)
_voices_3d.append(p)
for i in VOICES_UI:
var p := AudioStreamPlayer.new()
p.process_mode = Node.PROCESS_MODE_ALWAYS
add_child(p)
_voices_ui.append(p)
var g := AudioStreamPlayer.new()
g.process_mode = Node.PROCESS_MODE_PAUSABLE
add_child(g)
_voices_game.append(g)
_day = _loop_player("day_ambience")
_night = _loop_player("night_ambience")
_listener = AudioListener3D.new()
_listener.top_level = true
add_child(_listener)
_listener.make_current()
func setup(p_sim: FarmSim) -> void:
sim = p_sim
focus = sim.player
var c := sim.campaign
c.phase_changed.connect(_on_phase)
c.campaign_ended.connect(func(outcome: CampaignController.Outcome) -> void:
if outcome != CampaignController.Outcome.VACATION_COMPLETE:
play("game_over"))
_ambience_target = AMBIENCE.get(c.state.phase, Vector2(1.0, 0.0))
_ambience = _ambience_target
music_track = MUSIC_FOR.get(c.state.phase, "")
_wire_weapons(sim.combat, Callable())
sim.bombs.burst.connect(func(at: Vector3, _n: int) -> void: play("boom", at))
sim.projectiles.hit.connect(func(at: Vector3, type: int) -> void:
play("hit_world" if type < 0 else "hit_crow" if type == EnemySystem.TYPE_CROW else "hit", at))
sim.enemies.enemy_removed.connect(_on_removed)
sim.waves.arrived.connect(func(h: int, at: Vector2) -> void:
var d := sim.enemies.resolve_handle(h)
var type := sim.enemies.type[d] if d >= 0 else EnemySystem.TYPE_THIEF
play(["thief_arrive", "crow_arrive", "breaker_arrive"][type], Vector3(at.x, 0.0, at.y)))
var kit := sim.scarecrow
kit.damaged.connect(func(hp: int) -> void: play("fall" if hp <= 0 else "hurt"))
kit.fear_used.connect(func(_p: Vector3, _n: int) -> void: play("fear"))
kit.fear_ready.connect(func() -> void: play("fear_ready"))
kit.patched.connect(func(_hp: int) -> void: play("patched"))
kit.patch_denied.connect(func(_m: Dictionary) -> void: play("error"))
sim.interactions.gathered.connect(func(_m: String, _a: int, n: GatherNode) -> void: play("gathered", n.global_position))
sim.interactions.deposited.connect(func(_moved: Dictionary) -> void: play("deposit", sim.player.global_position))
var st := sim.structures
st.built.connect(func(id: int, _type: String) -> void: play("build", _structure_at(id)))
st.destroyed.connect(func(_id: int, _type: String, at: Vector3) -> void:
play("smash", at)
play("breach"))
st.hurt.connect(func(_id: int, at: Vector3) -> void: play("structure_hit", at))
st.repaired.connect(func(id: int) -> void: play("repaired", _structure_at(id)))
st.turret_fired.connect(func(at: Vector3) -> void: play("turret", at))
st.trap_sprung.connect(func(at: Vector3) -> void: play("trap", at))
sim.build.refused.connect(func(_why: String) -> void: play("error"))
sim.build.dismantled.connect(func(_type: String) -> void: play("dismantle", Vector3(sim.build.cursor.x, 0.5, sim.build.cursor.y)))
sim.build.toggled.connect(func(on: bool) -> void: play("ui_open" if on else "ui_close"))
sim.loot.loot_event.connect(_on_loot)
if sim.upgrade_panel != null:
sim.upgrade_panel.bought.connect(func(_id: String) -> void: play("upgrade"))
wire_buttons(sim.upgrade_panel)
if sim.review_panel != null:
wire_buttons(sim.review_panel)
if sim.end_panel != null:
wire_buttons(sim.end_panel)
## Stops every voice, so no playback outlives the farm (the audio server holds on to playing
## ones until its next mix; Main.quit_game() gives it that moment).
func silence() -> void:
for p in get_children():
if p is AudioStreamPlayer or p is AudioStreamPlayer3D:
p.stop()
p.stream = null
func _exit_tree() -> void:
silence()
## Plays a cue: where it happens (positional) when at is given, else straight to the ears.
## Returns false when the cue is resting (its gap) or has no sound.
func play(cue: String, at: Vector3 = Vector3.INF) -> bool:
var local := LOCAL_CUES.has(cue)
if remote_cues and not local:
return false
if forward.is_valid() and not local:
forward.call(cue, at)
return _play(cue, at)
## A world sound the host played (co-op partner).
func play_remote(cue: String, at: Vector3 = Vector3.INF) -> bool:
return _play(cue, at)
## Sounds for a scarecrow other than the first (co-op): its gun, hurt, fall, fear, and patch,
## where it is.
func wire_avatar(a: Avatar) -> void:
_wire_weapons(a.combat, func() -> Vector3: return a.body.global_position)
a.kit.damaged.connect(func(hp: int) -> void: play("fall" if hp <= 0 else "hurt", a.body.global_position))
a.kit.fear_used.connect(func(_p: Vector3, _n: int) -> void: play("fear", a.body.global_position))
a.kit.patched.connect(func(_hp: int) -> void: play("patched", a.body.global_position))
## A scarecrow's weapons: where (at) for another scarecrow than this machine's, which is heard
## from right here.
func _wire_weapons(combat: ScarecrowCombat, at: Callable) -> void:
var where := func() -> Vector3: return at.call() if at.is_valid() else Vector3.INF
combat.fired.connect(func() -> void: play("shot", where.call()))
combat.stabbed.connect(func(_n: int) -> void: play("stab", where.call()))
combat.struck.connect(func(p: Vector3, type: int) -> void: play("hit_crow" if type == EnemySystem.TYPE_CROW else "hit", p))
combat.threw.connect(func(_to: Vector3) -> void: play("throw", where.call()))
func _play(cue: String, at: Vector3) -> bool:
var def: Dictionary = CUES.get(cue, {})
var list: Array = streams.get(cue, [])
if def.is_empty() or list.is_empty():
return false
var now := Time.get_ticks_msec()
if now - int(_last.get(cue, -1000000000)) < int(float(def.get("gap", 0.0)) * 1000.0):
return false
_last[cue] = now
played[cue] = int(played.get(cue, 0)) + 1
var stream: AudioStream = list[randi() % list.size()]
var pitch := 1.0 + randf_range(-1.0, 1.0) * float(def.get("pitch", 0.0))
var db := float(def.get("db", 0.0))
var bus := StringName(def.get("bus", "SFX"))
var limit := int(def.get("max", 4))
if is_finite(at.x) and not bool(def.get("ui", false)):
var p := _free_voice(_voices_3d, cue, limit) as AudioStreamPlayer3D
p.global_position = at
p.bus = bus
_start(p, stream, db, pitch, cue)
else:
var pool := _voices_ui if bool(def.get("ui", false)) else _voices_game
var p := _free_voice(pool, cue, limit) as AudioStreamPlayer
p.bus = bus
_start(p, stream, db, pitch, cue)
return true
## UI sounds (they play while paused).
func ui(cue: String) -> void:
play(cue)
## Gives every Button under node a hover and a click sound (call again after adding buttons).
func wire_buttons(node: Node) -> void:
for b in node.find_children("*", "BaseButton", true, false):
if b.has_meta(&"sounds"):
continue
b.set_meta(&"sounds", true)
var button := b as BaseButton
button.mouse_entered.connect(func() -> void:
if not button.disabled:
ui("ui_hover"))
button.focus_entered.connect(func() -> void: ui("ui_hover"))
button.pressed.connect(func() -> void: ui("ui_click"))
## The first stream of a cue (for looping players the cutscene owns).
func stream_of(cue: String) -> AudioStream:
var list: Array = streams.get(cue, [])
return list[0] if not list.is_empty() else null
func _physics_process(dt: float) -> void:
if sim == null or sim.campaign.is_over() or get_tree().paused:
return
var p := sim.player
if sim.scarecrow.alive and p.is_on_floor():
var v := Vector2(p.velocity.x, p.velocity.z).length()
if v > 1.0:
_stride_left -= v * dt
if _stride_left <= 0.0:
_stride_left = STRIDE
play("step", p.global_position)
else:
_stride_left = minf(_stride_left, STRIDE * 0.3)
var it := sim.interactions
var channel := ""
var at := p.global_position
if it.gathering != null:
channel = {"wood": "chop", "straw": "rustle", "scrap": "clank"}.get(it.gathering.material, "rustle")
at = it.gathering.global_position
elif it.repairing >= 0:
channel = "hammer"
at = _structure_at(it.repairing)
elif sim.scarecrow.patching:
channel = "patching"
if channel == "":
_channel_left = 0.15
return
_channel_left -= dt
if _channel_left <= 0.0:
_channel_left = CHANNEL_REPEAT
play(channel, at)
func _process(delta: float) -> void:
var cam := get_viewport().get_camera_3d()
if cam != null and focus != null and is_instance_valid(focus):
_listener.global_transform = Transform3D(cam.global_transform.basis, focus.global_position + Vector3(0.0, 1.5, 0.0))
for track: String in _music:
var m := _music[track] as AudioStreamPlayer
var level := move_toward(float(_music_level[track]), 1.0 if track == music_track else 0.0, delta / MUSIC_FADE)
_music_level[track] = level
m.volume_db = MUSIC_DB + linear_to_db(maxf(level, 0.0001))
if level > 0.0 and not m.playing and m.stream != null:
m.play()
elif level <= 0.0 and m.playing:
m.stop()
_ambience = _ambience.move_toward(_ambience_target, FADE_RATE * delta)
_day.volume_db = linear_to_db(maxf(_ambience.x, 0.0001))
_night.volume_db = linear_to_db(maxf(_ambience.y, 0.0001))
if _bell_left >= 0.0:
_bell_left -= delta
if _bell_left < 0.0:
_last.erase("bell")
play("bell")
func _on_phase(phase: CampaignController.Phase, _previous: CampaignController.Phase) -> void:
_ambience_target = AMBIENCE.get(phase, Vector2(1.0, 0.0))
music_track = MUSIC_FOR.get(phase, "")
match phase:
CampaignController.Phase.MORNING:
_ambience = _ambience_target # a retry or a load jumps straight to morning
play("morning")
CampaignController.Phase.DUSK:
play("bell")
_bell_left = 1.3 # and a second strike
play("dusk")
CampaignController.Phase.NIGHT:
play("night")
CampaignController.Phase.DAWN:
play("dawn")
func _on_removed(handle: int, reason: EnemySystem.Removal, x: float, z: float, _carry: int, _target: int) -> void:
if reason != EnemySystem.Removal.KILLED:
return
var d := sim.enemies.resolve_handle(handle)
var crow := d >= 0 and sim.enemies.type[d] == EnemySystem.TYPE_CROW
play("crow_die" if crow else "enemy_die", Vector3(x, 1.0, z))
func _on_loot(kind: StringName, _id: int, at: Vector3) -> void:
match kind:
&"stolen":
play("grab", at)
play("theft_alert")
&"dropped":
play("drop", at)
&"recovered":
play("recover", at)
&"following":
play("follow", at)
&"lost":
play("lost")
&"follow_full":
play("error")
func _structure_at(id: int) -> Vector3:
var e := sim.campaign.state.structure(id)
return Vector3(e["x"], 0.5, e["z"]) if not e.is_empty() else sim.player.global_position
func _loop_player(cue: String) -> AudioStreamPlayer:
var p := AudioStreamPlayer.new()
p.process_mode = Node.PROCESS_MODE_ALWAYS
p.bus = &"Ambience"
p.stream = stream_of(cue)
p.volume_db = -80.0
add_child(p)
if p.stream != null:
p.play()
return p
## Prefers an idle voice; else the oldest of this cue's once it's at its limit; else the oldest.
func _free_voice(pool: Array, cue: String, limit: int) -> Node:
var oldest: Node = pool[0]
var oldest_same: Node = null
var same := 0
for v: Node in pool:
var playing: bool = v.playing
if not playing:
return v
if v.get_meta(&"cue", "") == cue:
same += 1
if oldest_same == null or int(v.get_meta(&"t")) < int(oldest_same.get_meta(&"t")):
oldest_same = v
if int(v.get_meta(&"t")) < int(oldest.get_meta(&"t")):
oldest = v
return oldest_same if same >= limit and oldest_same != null else oldest
func _start(p: Node, stream: AudioStream, db: float, pitch: float, cue: String) -> void:
p.set(&"stream", stream)
p.set(&"volume_db", db)
p.set(&"pitch_scale", pitch)
p.set_meta(&"cue", cue)
p.set_meta(&"t", Time.get_ticks_usec())
p.call(&"play")
static func _expand(path: String) -> Array[String]:
var out: Array[String] = []
if not path.contains("*"):
out.append(path)
return out
for i in 10:
var p := path.replace("*", str(i))
if ResourceLoader.exists(p):
out.append(p)
return out

View file

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

View file

@ -1,10 +1,7 @@
@tool
class_name FarmMarker
extends Marker3D
## A point on the farm perimeter. A GAP marker sits just outside a gap in the perimeter fence:
## ground enemies arrive and escape there. A CROW marker is a direction that flyers arrive from
## and leave toward.
enum Kind { GAP, CROW }
@export var kind: Kind = Kind.GAP
## A gap in what's left of the perimeter fence (the north and east sides), just outside it. The
## scarecrow walks out through the gaps to the gathering areas, so nothing can be built in them
## (StructureSystem). Enemies don't use them as entrances: they arrive anywhere along the farm's
## edge (WaveDirector), and route through a gap only when the fence is in their way.

View file

@ -8,15 +8,21 @@ extends RefCounted
## like the flat concrete pads). Every other shape that reaches into BAND_LOW..BAND_HIGH blocks
## the cells its XZ outline covers, inflated by the mover's radius. Bodies on other layers
## (the scarecrow-only PlayerBounds) are ignored. The grid has a 1-cell blocked border.
## * A structure layer on top (set_structures): the cells of player-built barriers (fences, gates,
## defenses), inflated like the static obstacles. Movers can't walk into them, but distance
## fields cross them at barrier_cost extra per cell, so a walled-in goal still has a route: it
## ends at the cheapest barrier, which barrier_ahead() reports so the mover can break it.
## * Distance fields toward a set of goal cells: Dijkstra over 8 neighbors with octile integer
## costs (orthogonal 5, diagonal 7 ~ 5 * sqrt(2)) and a circular bucket queue with lazy
## deletion, the scheme of the prototype's ArenaNavigation. Diagonal steps never cut a blocked
## corner. Unreachable cells keep UNREACHABLE.
## costs (orthogonal 5, diagonal 7 ~ 5 * sqrt(2)) plus barrier costs, with a circular bucket
## queue (Dial's algorithm, lazy deletion), run as a FieldJob that can be sliced over ticks.
## Diagonal steps never cut a blocked corner or slip between structure cells. Unreachable cells
## keep UNREACHABLE.
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
## Largest barrier_cost: every edge must cost less than FieldJob.BUCKET_COUNT.
const MAX_BARRIER_COST := 240
## Height band (meters above the farm floor at y = 0) in which a shape obstructs ground movement.
const BAND_LOW := 0.35
const BAND_HIGH := 2.0
@ -28,14 +34,17 @@ var origin_z: float
var width: int
var height: int
var blocked: PackedByteArray
## Structure id per cell (-1 = none), from set_structures().
var structure_at: PackedInt32Array
## Extra path cost of entering one structure cell (5 = half a meter).
var barrier_cost: int = 180
var shapes_rasterized: int = 0
var build_usec: int = 0
var _inflate: float = 0.0
var _offsets := PackedInt32Array()
var _side_a := PackedInt32Array()
var _side_b := PackedInt32Array()
var _bucket_buf := PackedInt32Array() # BUCKETS stacks of capacity cell_count()
var _bucket_cnt := PackedInt32Array()
func build(world: Node, bounds: Rect2, p_cell_size: float, inflate: float, layer_mask: int = 1) -> void:
@ -46,9 +55,13 @@ func build(world: Node, bounds: Rect2, p_cell_size: float, inflate: float, layer
height = ceili(bounds.size.y * inv_cell) + 2
origin_x = bounds.position.x - cell_size
origin_z = bounds.position.y - cell_size
_inflate = inflate
var n := width * height
blocked = PackedByteArray()
blocked.resize(n)
structure_at = PackedInt32Array()
structure_at.resize(n)
structure_at.fill(-1)
for cx in width:
blocked[cx] = 1
blocked[(height - 1) * width + cx] = 1
@ -72,13 +85,26 @@ func build(world: Node, bounds: Rect2, p_cell_size: float, inflate: float, layer
_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])
_bucket_buf = PackedInt32Array()
_bucket_buf.resize(n * BUCKETS)
_bucket_cnt = PackedInt32Array()
_bucket_cnt.resize(BUCKETS)
build_usec = Time.get_ticks_usec() - t0
## Replaces the structure layer: entries are {"id": int, "outline": PackedVector2Array (world
## XZ convex outline)}; each covers the cells within the build inflation of its outline.
func set_structures(entries: Array) -> void:
structure_at.fill(-1)
for e: Dictionary in entries:
_rasterize_into(e["outline"], _inflate, int(e["id"]))
func set_barrier_cost(cost: int) -> void:
barrier_cost = clampi(cost, 0, MAX_BARRIER_COST)
## Free of static obstacles and structures: a mover may stand here.
func is_walkable(i: int) -> bool:
return blocked[i] == 0 and structure_at[i] < 0
func cell_count() -> int:
return width * height
@ -135,56 +161,107 @@ func free_cells_in(rect: Rect2) -> PackedInt32Array:
return out
## Free cells within radius of any of the points (goal sets such as the shed's piles).
func free_cells_near(points: PackedVector2Array, radius: float) -> PackedInt32Array:
var out := PackedInt32Array()
for p in points:
for i in free_cells_in(Rect2(p - Vector2(radius, radius), Vector2(radius, radius) * 2.0)):
if cell_center(i).distance_to(p) <= radius and not out.has(i):
out.append(i)
return out
## Free cells whose centers lie within band of a rectangle's outline (the farm's edge, where
## enemies arrive and escape).
func free_cells_on_outline(rect: Rect2, band: float) -> PackedInt32Array:
var out := PackedInt32Array()
var inner := rect.grow(-band)
for i in free_cells_in(rect.grow(band)):
if not inner.has_point(cell_center(i)):
out.append(i)
return out
## True when a straight segment crosses no blocked cell (sampled every half cell); structure
## cells count as blocked too unless through_structures.
func line_clear(x0: float, z0: float, x1: float, z1: float, through_structures: bool = false) -> bool:
var dx := x1 - x0
var dz := z1 - z0
var steps := ceili(sqrt(dx * dx + dz * dz) * inv_cell * 2.0)
for k in steps + 1:
var t := k / float(maxi(steps, 1))
var c := cell_of(x0 + dx * t, z0 + dz * t)
if blocked[c] == 1 or (not through_structures and structure_at[c] >= 0):
return false
return true
## The structure a mover at (x, z) runs into next when going downhill in a field (its steepest-
## descent neighbor is a structure cell), or -1.
func barrier_ahead(field: PackedInt32Array, x: float, z: float) -> int:
var nb := _downhill(field, cell_of(x, z))
return structure_at[nb] if nb >= 0 else -1
## Unit direction (written to out[0], out[1]) for a mover at (x, z) heading downhill in a
## distance field: toward the center of the cell reached by up to `lookahead` legal steepest-
## descent steps, which smooths the 8-way grid moves. Returns false at a goal cell, or where the
## mover's cell (and every free cell near it) has no route.
func flow_direction(field: PackedInt32Array, x: float, z: float, out: PackedFloat32Array, lookahead: int = 3) -> bool:
var c := cell_of(x, z)
if blocked[c] == 1 or field[c] >= UNREACHABLE:
c = nearest_free(c, 64)
if c < 0 or field[c] >= UNREACHABLE:
return false
var cur := c
for step in lookahead:
var nxt := _downhill(field, cur)
if nxt < 0:
break
cur = nxt
if cur == c and field[c] == 0:
return false
var p := cell_center(cur)
var dx := p.x - x
var dz := p.y - z
var l := sqrt(dx * dx + dz * dz)
if l < 1e-4:
return false
out[0] = dx / l
out[1] = dz / l
return true
func _downhill(field: PackedInt32Array, c: int) -> int:
var best := -1
var best_d := field[c]
for k in 8:
var nb := c + _offsets[k]
if blocked[nb] == 1:
continue
if k >= 4:
var sa := c + _side_a[k]
var sb := c + _side_b[k]
if blocked[sa] == 1 or blocked[sb] == 1 or structure_at[sa] >= 0 or structure_at[sb] >= 0:
continue
if field[nb] < best_d:
best_d = field[nb]
best = nb
return best
## Path cost from distance_field() in meters.
func meters(cost: int) -> float:
return cost * cell_size / COST_ORTH
## Octile path cost from every cell to the nearest goal cell (blocked goals are ignored).
## Octile path cost from every cell to the nearest goal cell, computed at once (load, tests).
## Goals that aren't walkable are ignored.
func distance_field(goals: PackedInt32Array) -> PackedInt32Array:
var n := cell_count()
var dist := PackedInt32Array()
dist.resize(n)
dist.fill(UNREACHABLE)
var buf := _bucket_buf
var cnt := _bucket_cnt
cnt.fill(0)
var pending := 0
for g in goals:
if blocked[g] == 1 or dist[g] == 0:
continue
dist[g] = 0
buf[cnt[0]] = g
cnt[0] += 1
pending += 1
var cur := 0
while pending > 0:
var b := cur % BUCKETS
var base := b * n
while cnt[b] > 0:
cnt[b] -= 1
var c := buf[base + cnt[b]]
pending -= 1
if dist[c] != cur:
continue # superseded by a shorter path (lazy deletion)
for k in 8:
var nb := c + _offsets[k]
if blocked[nb] == 1:
continue
var cost := COST_ORTH
if k >= 4:
if blocked[c + _side_a[k]] == 1 or blocked[c + _side_b[k]] == 1:
continue
cost = COST_DIAG
var nd := cur + cost
if nd < dist[nb]:
dist[nb] = nd
var nk := nd % BUCKETS
buf[nk * n + cnt[nk]] = nb
cnt[nk] += 1
pending += 1
cur += 1
return dist
var job := FieldJob.new(self)
job.start(goals)
job.step(1 << 30)
return job.dist
## XZ convex outline of a shape (from its debug mesh in world space), or empty when the shape
@ -208,6 +285,12 @@ func _outline(cs: CollisionShape3D) -> PackedVector2Array:
func _rasterize(hull: PackedVector2Array, inflate: float) -> void:
_rasterize_into(hull, inflate, -1)
## Marks the cells within inflate of a convex outline: as blocked (id < 0) or, for free cells,
## as belonging to structure id.
func _rasterize_into(hull: PackedVector2Array, inflate: float, id: int) -> void:
var lo := hull[0]
var hi := hull[0]
for p in hull:
@ -225,7 +308,10 @@ func _rasterize(hull: PackedVector2Array, inflate: float) -> void:
continue
var p := cell_center(i)
if (solid and Geometry2D.is_point_in_polygon(p, hull)) or _dist2_to_outline(p, hull) <= r2:
blocked[i] = 1
if id < 0:
blocked[i] = 1
else:
structure_at[i] = id
static func _dist2_to_outline(p: Vector2, hull: PackedVector2Array) -> float:
@ -236,3 +322,99 @@ static func _dist2_to_outline(p: Vector2, hull: PackedVector2Array) -> float:
if hull.size() == 1:
best = p.distance_squared_to(hull[0])
return best
## A distance field computation that can run in slices (step) so a rebuild after a structure
## change spreads over several ticks; the old field stays in use until it finishes. Dial's
## algorithm: BUCKET_COUNT circular buckets as linked lists over an entry pool, valid because no
## edge costs BUCKET_COUNT or more.
class FieldJob:
extends RefCounted
const BUCKET_COUNT := 256
const BUCKET_MASK := BUCKET_COUNT - 1
var nav: FarmNavigation
var dist := PackedInt32Array()
var done := true
## Queue entries processed so far (the slice budget counts these).
var processed: int = 0
var _head := PackedInt32Array()
var _cell := PackedInt32Array()
var _next := PackedInt32Array()
var _top: int = 0
var _pending: int = 0
var _cur: int = 0
func _init(p_nav: FarmNavigation) -> void:
nav = p_nav
var n := nav.cell_count()
dist.resize(n)
_head.resize(BUCKET_COUNT)
_cell.resize(n * 9) # at most 8 relaxations per cell, plus the goals
_next.resize(n * 9)
func start(goals: PackedInt32Array) -> void:
dist.fill(UNREACHABLE)
_head.fill(-1)
_top = 0
_pending = 0
_cur = 0
processed = 0
for g in goals:
if nav.is_walkable(g) and dist[g] != 0:
dist[g] = 0
_push(g, 0)
done = _pending == 0
## Processes up to budget queue entries. Returns true once the field is complete.
func step(budget: int) -> bool:
var blk := nav.blocked
var st := nav.structure_at
var off := nav._offsets
var sa_off := nav._side_a
var sb_off := nav._side_b
var barrier := nav.barrier_cost
var d := dist
var popped := 0
while _pending > 0 and popped < budget:
var b := _cur & BUCKET_MASK
var e := _head[b]
if e == -1:
_cur += 1
continue
_head[b] = _next[e]
_pending -= 1
popped += 1
var c := _cell[e]
if d[c] != _cur:
continue # superseded by a shorter path (lazy deletion)
for k in 8:
var nb := c + off[k]
if blk[nb] == 1:
continue
var cost := COST_ORTH
if k >= 4:
var sa := c + sa_off[k]
var sb := c + sb_off[k]
if blk[sa] == 1 or blk[sb] == 1 or st[sa] >= 0 or st[sb] >= 0:
continue
cost = COST_DIAG
if st[nb] >= 0:
cost += barrier
var nd := _cur + cost
if nd < d[nb]:
d[nb] = nd
_push(nb, nd)
processed += popped
done = _pending == 0
return done
func _push(cell: int, distance: int) -> void:
var b := distance & BUCKET_MASK
_cell[_top] = cell
_next[_top] = _head[b]
_head[b] = _top
_top += 1
_pending += 1

View file

@ -0,0 +1,183 @@
class_name FarmProjectiles
extends Node3D
## Fixed-capacity pooled shots with shared instanced visuals, forked from the prototype's
## ProjectileSystem for the farm (GameConfig, EnemySystem): the corn shooter's kernels and the
## automated defenses' shots. Shots are zero-width rays drawn as a corn kernel streaking
## horizontally at combat height. Each physics tick a shot's whole
## segment is tested against the farm's collision (one physics ray on the world layer) and
## against enemy hit proxies (EnemySystem.sweep_hit); the nearest hit wins, so a building
## shields a thief behind it. No piercing: a hit damages once and frees the shot. Shots also
## expire, and leave when they fly out of the farm. Exhaustion skips the shot and is counted;
## the pool never grows.
const WORLD_LAYER := 1
## A shot struck an enemy (its type) or the farm (enemy_type -1), for sound and effects.
signal hit(at: Vector3, enemy_type: int)
var capacity: int = 0
var active_count: int = 0
# Diagnostics.
var exhausted: int = 0
var fired: int = 0
var hits_enemy: int = 0
var hits_world: int = 0
var blocked_at_muzzle: int = 0
var _px := PackedFloat32Array()
var _pz := PackedFloat32Array()
var _dx := PackedFloat32Array()
var _dz := PackedFloat32Array()
var _life := PackedFloat32Array()
var _damage := PackedInt32Array()
var _cfg: GameConfig
var _enemies: EnemySystem
var _bounds: Rect2
var _renderer: HordeRenderer
var _ray := PhysicsRayQueryParameters3D.new()
func setup(cfg: GameConfig, enemies: EnemySystem, bounds: Rect2, shooter: RID) -> void:
_cfg = cfg
_enemies = enemies
_bounds = bounds
capacity = cfg.projectile_capacity
for a: PackedFloat32Array in [_px, _pz, _dx, _dz, _life]:
a.resize(capacity)
a.fill(0.0)
_damage.resize(capacity)
_ray.collision_mask = 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.13, 0.11, 0.34)
var mat := StandardMaterial3D.new()
mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
mat.albedo_color = Color(1.0, 0.82, 0.18)
_renderer = HordeRenderer.new()
_renderer.name = "ShotRenderer"
add_child(_renderer)
var aabb := AABB(Vector3(bounds.position.x, 0.0, bounds.position.y), Vector3(bounds.size.x, 4.0, bounds.size.y))
_renderer.setup(mesh, mat, capacity, cfg.combat_height, aabb)
func clear() -> void:
active_count = 0
_renderer.clear()
_renderer.commit(0)
## Fires from the weapon origin (scarecrow center at combat height) through the muzzle. The
## origin -> muzzle segment is tested first, so a barrel poking through a wall resolves there
## instead of spawning the shot on the far side. Returns false if the shot was skipped.
func fire(origin: Vector3, muzzle: Vector3, dir: Vector3, damage: int = 1) -> bool:
if active_count >= capacity:
exhausted += 1
return false
fired += 1
if _resolve_segment(origin.x, origin.z, muzzle.x, muzzle.z, false, damage):
blocked_at_muzzle += 1
return false
var d := active_count
active_count += 1
_px[d] = muzzle.x
_pz[d] = muzzle.z
_dx[d] = dir.x
_dz[d] = dir.z
_life[d] = _cfg.projectile_lifetime
_damage[d] = damage
_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, _damage[i]):
_release(i)
continue
_px[i] = x1
_pz[i] = z1
_life[i] -= dt
if _life[i] <= 0.0 or not _bounds.has_point(Vector2(x1, z1)):
_release(i)
continue
i += 1
## Co-op host: every shot in flight as [x, z, dx, dz] (at most max_shots).
func replica_record(max_shots: int) -> PackedFloat32Array:
var out := PackedFloat32Array()
for i in mini(active_count, max_shots):
out.append_array([_px[i], _pz[i], _dx[i], _dz[i]])
return out
## Co-op partner: the host's shots, which then fly on here until the next update.
func apply_replica(rec: PackedFloat32Array) -> void:
active_count = mini(rec.size() / 4, capacity)
for i in active_count:
_px[i] = rec[i * 4]
_pz[i] = rec[i * 4 + 1]
_dx[i] = rec[i * 4 + 2]
_dz[i] = rec[i * 4 + 3]
_life[i] = _cfg.projectile_lifetime
func advance_replica(dt: float) -> void:
var step_len := _cfg.projectile_speed * dt
for i in active_count:
_px[i] += _dx[i] * step_len
_pz[i] += _dz[i] * step_len
func commit_render() -> void:
_renderer.write_poses(active_count, _px, _pz, _dx, _dz)
_renderer.commit(active_count)
## 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, damage: int) -> 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 := _enemies.sweep_hit(x0, z0, x1, z1, use_motion)
if e >= 0 and _enemies.hit_t <= world_t:
var t := _enemies.type[e]
_enemies.apply_hit(e, damage)
hits_enemy += 1
hit.emit(Vector3(lerpf(x0, x1, _enemies.hit_t), h, lerpf(z0, z1, _enemies.hit_t)), t)
return true
if world_t <= 1.0:
hits_world += 1
hit.emit(Vector3(lerpf(x0, x1, world_t), h, lerpf(z0, z1, world_t)), -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]
_damage[i] = _damage[last]
_renderer.move_slot(last, i)
active_count -= 1

View file

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

735
game/scripts/farm_sim.gd Normal file
View file

@ -0,0 +1,735 @@
class_name FarmSim
extends Node
## Drives the farm's simulation in a fixed order each physics tick, after the scarecrow has
## moved (PlayerCharacter runs earlier in the tree):
## scarecrow kit (fear, patch, timers) -> build mode -> interactions (gather, workbench,
## repair, shed drop-off) -> weapons (recharge, switching) -> aim and attack (pitchfork, corn
## shooter, pumpkin bombs) -> enemies (behavior, steering, motion, collision, traps) -> enemy
## melee -> automated defenses -> shots -> pumpkin bombs -> recovery by touch -> animals
## (wander, stray, follow) -> night arrivals (WaveDirector) -> deferred enemy removals ->
## flow-field rebuild slice -> render upload -> campaign phase timers and outcome.
## Whenever the structures change (built, broken, dismantled), the flow fields are rebuilt as
## FieldJobs in slices of flow_slice_cells per tick; thieves keep using the old fields until the
## new ones are complete.
## It builds the farm navigation and the theft flow fields at load (toward the crop rows, the
## inside of the pen, each of the shed's piles, and the farm's edge, where enemies arrive and
## escape: WaveDirector.ground_spawns are the edge cells with a route in), owns the combat and theft systems,
## and applies the phase rules: thieves arrive only at night (the night's NightPlan, run by
## WaveDirector), sunrise makes them retreat (carriers keep running), the end of the dawn grace
## sends the rest off the farm with whatever they carry, returns dropped loot (and loose animals)
## home, and regrows the gather points, and every new morning (also after a retry) resets the
## theft state from the farm state. DayNight lights the phases; PhaseHud, AssetHud, ReviewPanel,
## and the other HUD parts show them. Co-op (CoopSession): a second scarecrow (add_partner) is
## simulated alongside the first, and on the partner's machine the farm is a replica: nothing is
## simulated there, the host's state is applied instead (replica = true), and player, scarecrow,
## combat, and interactions are that machine's own scarecrow's (player 2's).
## FarmAudio plays every sound, Tutorial shows the first
## day's and night's tips, and FarmersReturn plays the ending. Debug: T / G / H send in a
## thief / a crow / a fence breaker at any time.
const SCARECROW_RADIUS := 0.4
const HUNT_INTERVAL := 0.4
const NIGHT_PLANS: Array[String] = [
"res://game/resources/nights/night_1.tres", "res://game/resources/nights/night_2.tres",
"res://game/resources/nights/night_3.tres", "res://game/resources/nights/night_4.tres",
"res://game/resources/nights/night_5.tres",
]
@export var campaign: CampaignController
@export var zones: FarmZones
@export var player: PlayerCharacter
@export var camera: Camera3D
@export var toasts: ToastFeed
@export var alerts: AlertManager
@export var hud: ScarecrowHud
@export var end_panel: EndPanel
@export var resource_hud: ResourceHud
@export var build_hud: BuildHud
@export var phase_hud: PhaseHud
@export var asset_hud: AssetHud
@export var review_panel: ReviewPanel
@export var upgrade_panel: UpgradePanel
@export var sun: DirectionalLight3D
@export var world_environment: WorldEnvironment
var config: GameConfig
var nav := FarmNavigation.new()
var crop_field := PackedInt32Array()
var escape_field := PackedInt32Array()
var animal_field := PackedInt32Array()
## Material -> the field toward that material's pile at the shed.
var supply_fields := {}
var enemies: EnemySystem
var behavior := ThiefBehavior.new()
var loot: LootSystem
var animals: AnimalSystem
var shed_stock: ShedStock
var projectiles: FarmProjectiles
var bombs: PumpkinBombs
var combat: ScarecrowCombat
var scarecrow: Scarecrow
var interactions: Interactions
var structures: StructureSystem
var build: BuildMode
var waves: WaveDirector
var day_night: DayNight
## Every scarecrow in play (player 1's first), the one this machine plays, and the other one
## (co-op; null solo). On the partner's machine the farm is a replica of the host's.
var avatars: Array[Avatar] = []
var local_avatar: Avatar
var partner: Avatar
var replica := false
## Co-op menus don't pause the farm: this machine's scarecrow ignores the input meanwhile.
var local_frozen := false
## Set by CoopSession on the partner's machine: applies the host's state each tick.
var replica_step: Callable
## Co-op: the session with the other machine (idle solo).
var coop: CoopSession
var audio: FarmAudio
var tutorial: Tutorial
var ending: FarmersReturn
## Flow-field rebuild after a structure change: running, and stats of the last one.
var rebuilding := false
var rebuilds: int = 0
var last_rebuild_usec: int = 0
var last_rebuild_ticks: int = 0
var max_rebuild_slice_usec: int = 0
var load_msec: int = 0
## Flow-field jobs by name: "escape" (the farm's edge), "pen" (inside the pen), one per shed pile (by
## material), "breaker" (barriers guarding valuables), and "crops" (the crop rows) only when a
## ground enemy type goes for crops.
var _jobs := {}
var _goals := {} # name -> goal cells (the breaker's are worked out at every rebuild)
var breaker_field := PackedInt32Array()
## Toward the scarecrow, for enemies hunting it: rebuilt in slices (HUNT_INTERVAL apart at most)
## while any enemy fights and the scarecrow has moved to another cell.
var hunt_field := PackedInt32Array()
var characters: EnemyCharacters
var _hunt_job: FarmNavigation.FieldJob
var _hunt_cell: int = -1
var _hunt_wait: float = 0.0
var _rebuild_usec: int = 0
var _rebuild_ticks: int = 0
func _ready() -> void:
var t0 := Time.get_ticks_msec()
config = campaign.config
campaign.set_physics_process(false) # ticked from step(), after the simulation
player.config = config # the sprint
player.campaign = campaign
var shed_zone := zones.zone(FarmZone.Kind.SUPPLY_SHED)
var pen_zone := zones.zone(FarmZone.Kind.ANIMAL_PEN)
shed_stock = ShedStock.new()
shed_stock.name = "ShedStock"
add_child(shed_stock)
shed_stock.setup(campaign, shed_zone, player) # every pile prop in place for the navigation
nav.build(get_parent(), zones.playable.grow(5.0), config.nav_cell_size, config.enemy_radius + config.nav_inflate_margin)
shed_stock.refresh()
var field := zones.zone(FarmZone.Kind.CROP_FIELD)
# Goals are the crop rows themselves (not the whole zone), so a fence around the crops
# encloses every goal and thieves have to break in. Likewise the inside of the pen.
var crop_goals := PackedInt32Array()
for u in zones.crop_units():
var lo := Vector2(INF, INF)
var hi := Vector2(-INF, -INF)
for plant in u.get_children():
var at := Vector2((plant as Node3D).global_position.x, (plant as Node3D).global_position.z)
lo = lo.min(at)
hi = hi.max(at)
crop_goals.append_array(nav.free_cells_in(Rect2(lo, hi - lo).grow(0.3)))
_goals = {"escape": nav.free_cells_on_outline(zones.edge(config.spawn_margin), nav.cell_size * 0.75),
"pen": nav.free_cells_in(pen_zone.rect().grow(-1.0)), "breaker": PackedInt32Array()}
for m in ResourceStore.MATERIALS:
_goals[m] = nav.free_cells_near(PackedVector2Array([shed_stock.spot(m)]), 0.8)
if _ground_takes_crops():
_goals["crops"] = crop_goals
for job_name in _goals:
_jobs[job_name] = FarmNavigation.FieldJob.new(nav)
_hunt_job = FarmNavigation.FieldJob.new(nav)
enemies = EnemySystem.new()
enemies.name = "Enemies"
add_child(enemies)
loot = LootSystem.new()
loot.name = "Loot"
add_child(loot)
animals = AnimalSystem.new()
animals.name = "Animals"
add_child(animals)
behavior.setup(config, nav, loot, crop_field, escape_field, field.rect())
behavior.pen_rect = pen_zone.rect()
behavior.shed_rect = shed_zone.rect()
behavior.farm_rect = zones.playable
characters = EnemyCharacters.new()
characters.name = "EnemyCharacters"
add_child(characters)
var mat := ShaderMaterial.new()
mat.shader = load("res://game/resources/thief.gdshader") as Shader
enemies.setup(config, nav, behavior, EnemySystem.build_bird_mesh(0.0055), mat, zones.playable.grow(12.0))
characters.setup(enemies, config)
enemies.characters = characters
loot.animals = animals
loot.shed_stock = shed_stock
loot.setup(campaign, zones.crop_units(), enemies, AnimalSystem.find_animals(pen_zone).size())
animals.setup(campaign, pen_zone, nav, loot, enemies, player)
if animals.count != config.start_animals:
push_warning("The pen holds %d animals but GameConfig.start_animals is %d" % [animals.count, config.start_animals])
enemies.enemy_removed.connect(loot.on_enemy_removed)
enemies.enemy_removed.connect(_count_removal)
projectiles = FarmProjectiles.new()
projectiles.name = "Shots"
add_child(projectiles)
projectiles.setup(config, enemies, zones.playable.grow(8.0), player.get_rid())
bombs = PumpkinBombs.new()
bombs.name = "Bombs"
add_child(bombs)
bombs.setup(config, enemies)
structures = StructureSystem.new()
structures.name = "Structures"
add_child(structures)
structures.setup(campaign, nav, zones, enemies, projectiles, player)
enemies.structures = structures
behavior.structures = structures
_start_field_rebuild()
_finish_field_rebuild(1 << 30) # at load, all at once
max_rebuild_slice_usec = 0
structures.layout_changed.connect(_start_field_rebuild)
structures.layout_changed.connect(animals.update_pen_open)
animals.update_pen_open()
combat = ScarecrowCombat.new()
combat.name = "Combat"
add_child(combat)
combat.setup(config, player, camera, projectiles)
combat.campaign = campaign
combat.enemies = enemies
combat.bombs = bombs
scarecrow = Scarecrow.new()
scarecrow.name = "Scarecrow"
add_child(scarecrow)
scarecrow.setup(config, campaign, player, enemies, behavior)
interactions = Interactions.new()
interactions.name = "Interactions"
add_child(interactions)
interactions.setup(config, campaign, player, scarecrow, zones)
scarecrow.interactions = interactions
interactions.gathered.connect(func(material: String, amount: int, _n: GatherNode) -> void:
campaign.state.record_event("gathered_" + material, amount))
var first := Avatar.new()
first.slot = 0
first.body = player
first.kit = scarecrow
first.combat = combat
first.interactions = interactions
avatars = [first]
local_avatar = first
waves = WaveDirector.new()
waves.name = "Waves"
add_child(waves)
var plans: Array[NightPlan] = []
for path in NIGHT_PLANS:
plans.append(load(path) as NightPlan)
waves.setup(campaign, enemies, zones, plans)
for c in _goals["escape"]:
if animal_field[c] < FarmNavigation.UNREACHABLE: # not shut in by the props around it
waves.ground_spawns.append(nav.cell_center(c))
campaign.night_length_for = waves.night_length
if sun != null and world_environment != null:
day_night = DayNight.new()
day_night.name = "DayNight"
add_child(day_night)
day_night.characters = characters
day_night.setup(campaign, sun, world_environment.environment, player, mat)
build = BuildMode.new()
build.name = "Build"
add_child(build)
build.setup(config, campaign, player, camera, structures, combat, scarecrow)
build.toggled.connect(func(_on: bool) -> void: combat.reset())
interactions.structures = structures
interactions.build = build
if upgrade_panel != null:
upgrade_panel.setup(campaign, structures, player)
interactions.upgrade_panel = upgrade_panel
upgrade_panel.bought.connect(func(id: String) -> void: # a new weapon goes into the hand
var w := ScarecrowCombat.WEAPON_IDS.find(id)
if w > 0:
combat.equip(w))
if resource_hud != null:
resource_hud.setup(campaign)
resource_hud.structures = structures
if build_hud != null:
build_hud.setup(build, campaign)
if phase_hud != null:
phase_hud.setup(campaign, waves, enemies)
if asset_hud != null:
asset_hud.setup(campaign)
if review_panel != null:
review_panel.setup(campaign, structures)
review_panel.animals = animals
review_panel.waves = waves
review_panel.refresh()
if hud != null:
hud.setup(scarecrow, campaign, combat)
ending = FarmersReturn.new()
ending.name = "FarmersReturn"
add_child(ending)
ending.setup(self)
if end_panel != null:
end_panel.setup(campaign)
end_panel.ending = ending
end_panel.waves = waves
if hud != null and hud.get_parent() != null:
tutorial = Tutorial.new()
tutorial.name = "Tutorial"
hud.get_parent().add_child(tutorial)
tutorial.setup(self)
if end_panel != null:
end_panel.get_parent().move_child(end_panel, -1) # over the banners and the tips
audio = FarmAudio.new()
audio.name = "Audio"
add_child(audio)
audio.setup(self)
coop = CoopSession.new()
coop.name = "Coop" # the same path on both machines (GD-Sync calls it by path)
add_child(coop)
campaign.phase_changed.connect(_on_phase_changed)
campaign.night_ending.connect(_on_night_ending)
if toasts != null:
toasts.loot = loot
loot.loot_event.connect(toasts.on_loot_event)
interactions.message.connect(toasts.push)
if upgrade_panel != null:
upgrade_panel.message.connect(toasts.push)
build.message.connect(toasts.push)
waves.arrived.connect(func(h: int, at: Vector2) -> void:
toasts.push(arrival_message(enemies.type[enemies.resolve_handle(h)], zones.side_of(at)), Color(1.0, 0.75, 0.55)))
structures.destroyed.connect(func(_id: int, type: String, _at: Vector3) -> void:
toasts.push("Breach! A %s was broken" % StructureSystem.NAMES[type].to_lower(), Color(1.0, 0.35, 0.3)))
animals.pen_changed.connect(func(open: bool) -> void:
if open and campaign.state.phase != CampaignController.Phase.MORNING:
toasts.push("The pen is open: animals will wander out at night", Color(1.0, 0.55, 0.35)))
scarecrow.patch_denied.connect(func(missing: Dictionary) -> void:
toasts.push("Not enough straw to patch up: need %s more" % ResourceStore.describe(missing), Color(1.0, 0.8, 0.5)))
if alerts != null:
alerts.setup(self)
load_msec = Time.get_ticks_msec() - t0
func _physics_process(dt: float) -> void:
step(dt)
func step(dt: float) -> void:
if replica:
_step_replica(dt)
return
if not campaign.is_over():
var first := avatars[0]
var p := first.position()
behavior.scarecrow = p if first.kit.alive else Vector2(INF, INF)
var second := avatars[1] if avatars.size() > 1 else null
behavior.scarecrow2 = second.position() if second != null and second.kit.alive else Vector2(INF, INF)
enemies.scarecrow2 = behavior.scarecrow2
for a in avatars:
a.kit.step(dt)
if not local_frozen:
build.step(dt)
for a in avatars:
a.interactions.step(dt)
for a in avatars:
a.combat.tick(dt, a.is_local and not build.active and not local_frozen and not _menu_open())
for a in avatars:
var building := build.active if a.is_local else (a.remote != null and a.remote.build_active)
if a.kit.can_shoot() and a.interactions.can_shoot() and not building:
a.combat.step(dt)
enemies.step(dt, p, SCARECROW_RADIUS)
for a in avatars:
if a.kit.alive:
enemies.evaluate_attacks(a.position(), SCARECROW_RADIUS, a.kit)
structures.step(dt)
projectiles.step(dt)
bombs.step(dt)
for a in avatars:
if a.kit.alive:
loot.step(a.position(), a.slot)
animals.step(dt)
waves.step(dt)
enemies.commit_removals()
if rebuilding:
_finish_field_rebuild(config.flow_slice_cells)
_update_hunt(dt)
enemies.commit_render()
projectiles.commit_render()
campaign.tick(dt)
## The partner's machine: only its own scarecrow acts locally (aiming, build mode as a UI); the
## host's state is applied (replica_step), then drawn.
func _step_replica(dt: float) -> void:
if replica_step.is_valid():
replica_step.call(dt)
combat.tick(dt, not build.active and not local_frozen and not _menu_open())
bombs.step(dt) # the host's throws, drawn
if not campaign.is_over() and scarecrow.alive and not local_frozen:
build.step(dt)
if interactions.can_shoot() and not build.active and not _menu_open():
combat.step(dt)
enemies.commit_render()
projectiles.commit_render()
func _menu_open() -> bool:
return upgrade_panel != null and upgrade_panel.is_open
## Co-op: while this machine's scarecrow is down, the camera watches the partner's.
func _process(_delta: float) -> void:
if partner == null or not (camera is FollowCamera):
return
var other := avatars[0] if local_avatar == partner else partner
var want := local_avatar.body if local_avatar.kit.alive or not other.kit.alive else other.body
if (camera as FollowCamera).target != want:
(camera as FollowCamera).target = want
## Co-op: while a menu is up, this machine's scarecrow takes no input (its kit, hands, and gun
## read an empty RemoteControls; its body doesn't move).
func freeze_local(on: bool) -> void:
local_frozen = on
var a := local_avatar
var none := RemoteControls.new() if on else null
a.kit.remote = none
a.interactions.remote = none
a.combat.remote = none
a.body.input_enabled = not on
if on:
build.set_active(false)
## Co-op: brings player 2's scarecrow onto the farm (next to player 1's): a second body with its
## own kit, gun, and hands. local: whether this machine plays it (the partner's machine) or the
## partner's game does (the host: then it reads remote). Returns it.
func add_partner(local: bool, name_text: String = "") -> Avatar:
if partner != null:
return partner
var a := Avatar.new()
a.slot = 1
a.is_local = local
a.player_name = name_text
var body := (load("res://game/scenes/player.tscn") as PackedScene).instantiate() as PlayerCharacter
body.name = "Player2"
get_parent().add_child(body)
body.global_position = player.global_position + Vector3(1.8, 0.0, 0.6)
body.set_tint(Color(0.55, 0.75, 1.0))
body.config = config
body.campaign = campaign
a.body = body
a.kit = Scarecrow.new()
a.kit.name = "Scarecrow2"
a.kit.slot = 1
add_child(a.kit)
a.kit.setup(config, campaign, body, enemies, behavior)
a.combat = ScarecrowCombat.new()
a.combat.name = "Combat2"
add_child(a.combat)
a.combat.setup(config, body, camera, projectiles)
a.combat.campaign = campaign
a.combat.enemies = enemies
a.combat.bombs = bombs
a.combat.show_marker = local
a.interactions = Interactions.new()
a.interactions.name = "Interactions2"
add_child(a.interactions)
a.interactions.setup(config, campaign, body, a.kit, zones)
a.interactions.structures = structures
a.interactions.show_labels = local
a.kit.interactions = a.interactions
a.interactions.gathered.connect(func(material: String, amount: int, _n: GatherNode) -> void:
if not replica:
campaign.state.record_event("gathered_" + material, amount))
if not local:
a.remote = RemoteControls.new()
a.kit.remote = a.remote
a.combat.remote = a.remote
a.interactions.remote = a.remote
avatars.append(a)
partner = a
animals.leaders.append(body)
structures.partner = body
if day_night != null:
day_night.add_lantern(body)
if audio != null:
audio.wire_avatar(a)
if not replica:
var s := campaign.state
if not s.coop:
s.coop = true
s.partner_max_hp = s.scarecrow_max_hp
s.partner_hp = s.scarecrow_max_hp
return a
## Co-op: player 2 left. Their scarecrow goes; if player 1's is down, that's the end of the night.
func remove_partner() -> void:
if partner == null:
return
var a := partner
partner = null
avatars.erase(a)
if camera is FollowCamera and (camera as FollowCamera).target == a.body:
(camera as FollowCamera).target = local_avatar.body
animals.leaders.erase(a.body)
if structures.partner == a.body:
structures.partner = null
for n: Node in [a.kit, a.combat, a.interactions, a.body]:
if is_instance_valid(n):
n.queue_free()
if not replica:
campaign.state.coop = false
behavior.scarecrow2 = Vector2(INF, INF)
enemies.scarecrow2 = Vector2(INF, INF)
## Makes another scarecrow this machine's own (the partner's machine plays player 2): the HUD,
## the camera, build mode, the upgrade menu, sounds, and tips follow it.
func set_local(a: Avatar) -> void:
for other in avatars:
other.is_local = other == a
other.combat.show_marker = other == a
other.interactions.show_labels = other == a
local_avatar = a
player = a.body
scarecrow = a.kit
combat = a.combat
interactions = a.interactions
interactions.structures = structures
interactions.build = build
interactions.upgrade_panel = upgrade_panel
build.player = a.body
build.combat = a.combat
build.kit = a.kit
if upgrade_panel != null:
upgrade_panel.player = a.body
if camera is FollowCamera:
(camera as FollowCamera).target = a.body
(camera as FollowCamera).snap_to_target()
if hud != null:
hud.retarget(a.kit, a.combat)
if audio != null:
audio.focus = a.body
if alerts != null:
alerts.player = a.body
shed_stock.player = a.body
## Restarts every flow-field job for the current structure layout.
func _start_field_rebuild() -> void:
_goals["breaker"] = _breaker_goals()
for job_name in _jobs:
(_jobs[job_name] as FarmNavigation.FieldJob).start(_goals[job_name])
rebuilding = true
_rebuild_usec = 0
_rebuild_ticks = 0
## Runs up to budget cells of the rebuild, one job after another; swaps the new fields in once
## all are complete.
func _finish_field_rebuild(budget: int) -> void:
var t0 := Time.get_ticks_usec()
var left := budget
for job: FarmNavigation.FieldJob in _jobs.values():
if left <= 0:
break
if not job.done:
var before := job.processed
job.step(left)
left -= job.processed - before
var slice := Time.get_ticks_usec() - t0
_rebuild_usec += slice
_rebuild_ticks += 1
max_rebuild_slice_usec = maxi(max_rebuild_slice_usec, slice)
if _jobs.values().all(func(j: FarmNavigation.FieldJob) -> bool: return j.done):
if _jobs.has("crops"):
crop_field = _jobs["crops"].dist.duplicate()
escape_field = _jobs["escape"].dist.duplicate()
animal_field = _jobs["pen"].dist.duplicate()
breaker_field = _jobs["breaker"].dist.duplicate()
for m in ResourceStore.MATERIALS:
supply_fields[m] = _jobs[m].dist.duplicate()
behavior.crop_field = crop_field
behavior.escape_field = escape_field
behavior.animal_field = animal_field
behavior.supply_fields = supply_fields
behavior.breaker_field = breaker_field
animals.escape_field = escape_field
rebuilding = false
rebuilds += 1
last_rebuild_usec = _rebuild_usec
last_rebuild_ticks = _rebuild_ticks
## Sends a ground thief in at a random point along the farm's edge (or at the given point), going
## for the given target (a LootSystem.Category, or LootSystem.ANY: its type's targets by weight).
## Returns its handle.
func spawn_thief(want: int = LootSystem.ANY, at: Vector2 = WaveDirector.ANYWHERE) -> int:
return spawn_enemy(EnemySystem.TYPE_THIEF, want, at)
## Sends an enemy of any type in at a random point along the farm's edge (or at the given
## point). Returns its handle.
func spawn_enemy(type: int, want: int = LootSystem.ANY, at: Vector2 = WaveDirector.ANYWHERE) -> int:
return waves.spawn(type, want, at)
## Counts the night's kills by type, and the enemies that got away with loot.
func _count_removal(handle: int, reason: EnemySystem.Removal, _x: float, _z: float, _carry: int, _target: int) -> void:
match reason:
EnemySystem.Removal.KILLED:
var d := enemies.resolve_handle(handle)
if d >= 0:
campaign.state.record_event("killed_" + EnemySystem.TYPE_NAMES[enemies.type[d]])
EnemySystem.Removal.ESCAPED:
campaign.state.record_event("escaped")
## Keeps the field toward the scarecrow fresh while anything is fighting it.
func _update_hunt(dt: float) -> void:
_hunt_wait = maxf(_hunt_wait - dt, 0.0)
if not _hunt_job.done:
if _hunt_job.step(config.flow_slice_cells):
hunt_field = _hunt_job.dist.duplicate()
behavior.hunt_field = hunt_field
return
var hunting := false
for d in enemies.active_count:
if enemies.alive[d] == 1 and enemies.state[d] == ThiefBehavior.State.FIGHT:
hunting = true
break
if not hunting:
return
# Toward every scarecrow standing (each enemy follows it to the nearer one).
var goals := PackedInt32Array()
var key := 0
for a in avatars:
if not a.kit.alive:
continue
var p := a.position()
var c := nav.nearest_free(nav.cell_of(p.x, p.y), 64)
if c >= 0:
goals.append(c)
key = key * 100003 + c + 1
if goals.is_empty() or (key == _hunt_cell and not hunt_field.is_empty()) or _hunt_wait > 0.0:
return
_hunt_cell = key
_hunt_wait = HUNT_INTERVAL
_hunt_job.start(goals)
## Whether any ground enemy type goes for crops (then the crop rows get a flow field).
func _ground_takes_crops() -> bool:
for type_name: String in config.enemy_types:
var row := config.enemy(type_name)
if not bool(row.get("flying", false)) and (row.get("targets", []) as Array).has("crops"):
return true
return false
## Where fence breakers head: the walkable cells next to every barrier within guard_range of the
## crop rows, the pen, or the shed (or next to any barrier, when none guards anything).
func _breaker_goals() -> PackedInt32Array:
if structures == null:
return PackedInt32Array()
var areas: Array[Rect2] = [zones.zone(FarmZone.Kind.CROP_FIELD).rect(), zones.zone(FarmZone.Kind.ANIMAL_PEN).rect(),
zones.zone(FarmZone.Kind.SUPPLY_SHED).rect()]
var guarding: Array[Dictionary] = []
var barriers: Array[Dictionary] = []
for e in campaign.state.structures:
if not structures.blocks(e["type"]):
continue
barriers.append(e)
var at := Vector2(e["x"], e["z"])
for a in areas:
if a.grow(config.guard_range).has_point(at):
guarding.append(e)
break
var out := PackedInt32Array()
for e in (guarding if not guarding.is_empty() else barriers):
var outline := StructureSystem.corners(structures.footprint(e["type"], e["x"], e["z"], e["rot"]))
var lo := outline[0]
var hi := outline[0]
for q in outline:
lo = lo.min(q)
hi = hi.max(q)
for c in nav.free_cells_in(Rect2(lo, hi - lo).grow(1.2)):
if nav.is_walkable(c) and StructureSystem._distance_to_outline(nav.cell_center(c), outline) <= 1.1:
out.append(c)
return out
## "A crow flew in from the east", "A fence breaker came in from the south-west" (side:
## FarmZones.side_of the arrival point).
static func arrival_message(type: int, side: String) -> String:
var from := " from the %s" % side if side != "" else ""
match type:
EnemySystem.TYPE_CROW:
return "A crow flew in" + from
EnemySystem.TYPE_BREAKER:
return "A fence breaker came in" + from
return "A thief slipped in" + from
func _on_phase_changed(phase: CampaignController.Phase, _previous: CampaignController.Phase) -> void:
match phase:
CampaignController.Phase.DUSK, CampaignController.Phase.NIGHT:
if toasts != null and scarecrow.alive and not zones.is_inside_fence(player.global_position):
toasts.push("You're outside the fence: get back in before nightfall!" if phase == CampaignController.Phase.DUSK
else "Night has fallen and you're outside the fence!", Color(1.0, 0.55, 0.35))
CampaignController.Phase.DAWN:
behavior.retreat_all(enemies)
if enemies.alive_count() > 0 and toasts != null:
toasts.push("Sunrise! The thieves are running for it", Color(1.0, 0.85, 0.6))
CampaignController.Phase.MORNING:
if partner == null and not replica:
campaign.state.coop = false # a co-op save continued alone: solo rules
enemies.clear()
projectiles.clear()
bombs.clear()
loot.sync_from_state()
animals.sync_from_state()
structures.sync_from_state()
shed_stock.refresh()
build.set_active(false)
for a in avatars:
a.combat.ready_for_morning()
a.kit.reset_for_morning()
a.interactions.cancel()
if a.remote != null:
a.remote.release()
if upgrade_panel != null:
upgrade_panel.close()
if review_panel != null:
review_panel.refresh() # after the farm is back in sync (the pen's gate)
## End of the dawn grace: whoever is still on the farm leaves (carrying their loot off), and
## loot still lying on the ground goes home (crops to their plots, sacks to the shed, loose
## animals to the pen).
func _on_night_ending() -> void:
enemies.remove_all()
loot.return_dropped()
interactions.regen_overnight()
func _unhandled_input(event: InputEvent) -> void:
var key := event as InputEventKey
if key == null or not key.pressed or key.echo or not OS.is_debug_build():
return
match key.physical_keycode:
KEY_T:
spawn_enemy(EnemySystem.TYPE_THIEF)
KEY_G:
spawn_enemy(EnemySystem.TYPE_CROW)
KEY_H:
spawn_enemy(EnemySystem.TYPE_BREAKER)

View file

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

View file

@ -1,16 +1,44 @@
class_name FarmState
extends RefCounted
## The single source of truth for everything that persists through the vacation: farm assets,
## scarecrow health, campaign progress, and the nightly loss records. Scene nodes only display
## it. to_dict() / from_dict() round-trip every field, also through JSON (the morning retry
## snapshot now, save games later). Plain asset counts become per-unit records in Step 3.
## scarecrow health, campaign progress, and the nightly records. Scene nodes only display it.
## to_dict() / from_dict() round-trip every field, also through JSON (the morning retry
## snapshot and the save game, SaveGame). Crops and animals are per-unit records (lost ids, 1..total);
## supplies are the supply shed's stock of construction materials (the shed and the scarecrow's
## pouch live in resources). Gather points below full, bought upgrades, and the built structures
## are kept too.
const VERSION := 1
const VERSION := 4
const KEYS: Array[String] = [
"night", "nights_survived", "phase", "phase_time_left", "scarecrow_max_hp", "scarecrow_hp",
"crops_total", "crops", "animals_total", "animals", "supplies_total", "supplies", "night_log",
"crops_total", "lost_crops", "animals_total", "lost_animals", "supplies_total", "shed_raided",
"resources", "gather_charges", "upgrades", "structures", "next_structure_id", "night_events",
"night_log", "coop", "partner_max_hp", "partner_hp",
]
const STRUCTURE_KEYS: Array[String] = ["id", "type", "x", "z", "rot", "hp"]
## Events counted from the morning to the end of the dawn grace, copied into the night's log
## entry when it closes. Theft: supply events count material units, the others crop units or
## animals. Then enemies killed by type and those that escaped with loot; the scarecrow's damage
## taken (HP) and patches; structures built, damaged (HP lost), destroyed, and repaired;
## upgrades bought; and materials gathered (into the pouch) and spent, per material.
const EVENTS: Array[String] = [
"crops_stolen", "crops_recovered", "animals_stolen", "animals_strayed", "animals_recovered",
"supplies_stolen", "supplies_recovered", "supplies_lost",
"killed_crow", "killed_thief", "killed_breaker", "escaped",
"scarecrow_damage", "patches",
"structures_built", "structures_damaged", "structures_destroyed", "repairs", "upgrades_bought",
"gathered_wood", "gathered_scrap", "gathered_straw", "spent_wood", "spent_scrap", "spent_straw",
]
## The keys of a night_log entry: the night, crops and animals lost, then every EVENTS key.
const LOG_KEYS: Array[String] = [
"night", "crops_lost", "animals_lost",
"crops_stolen", "crops_recovered", "animals_stolen", "animals_strayed", "animals_recovered",
"supplies_stolen", "supplies_recovered", "supplies_lost",
"killed_crow", "killed_thief", "killed_breaker", "escaped",
"scarecrow_damage", "patches",
"structures_built", "structures_damaged", "structures_destroyed", "repairs", "upgrades_bought",
"gathered_wood", "gathered_scrap", "gathered_straw", "spent_wood", "spent_scrap", "spent_straw",
]
const LOG_KEYS: Array[String] = ["night", "crops_lost", "animals_lost", "supplies_lost"]
## Current night (1-based). The morning, day, dusk, night, and dawn of a cycle all belong to it.
var night: int = 1
@ -21,17 +49,64 @@ var phase_time_left: float = 0.0
var scarecrow_max_hp: int = 10
var scarecrow_hp: int = 10
## Co-op (a second scarecrow, player 2, is on the farm) and that scarecrow's health. Upgrades to
## max health apply to both. In co-op a scarecrow at 0 HP is out until the morning, and only both
## down at once is a Game Over.
var coop := false
var partner_max_hp: int = 10
var partner_hp: int = 10
## Per category: the starting count (0 = not in play yet) and what remains on the farm.
## Per category: the starting count (0 = not in play) and what remains on the farm.
var crops_total: int = 0
var crops: int = 0
## Ids of the crop units that are gone for good (carried off the farm), sorted.
var lost_crops := PackedInt32Array()
var animals_total: int = 0
var animals: int = 0
## Ids of the animals that are gone for good (carried or wandered off the farm), sorted.
var lost_animals := PackedInt32Array()
## The shed's stock when the vacation started (0 = supplies not in play).
var supplies_total: int = 0
var supplies: int = 0
## The shed was last emptied by thieves (not by spending). Only then do empty supplies count
## toward a stripped farm (D2); storing anything clears it (settle_supplies).
var shed_raided := false
## Material units carried off by thieves or lying dropped, still on the farm. Not saved: the dawn
## grace ends with none (LootSystem keeps it).
var supplies_in_transit: int = 0
## One entry per completed night, closed when its dawn ends:
## {"night", "crops_lost", "animals_lost", "supplies_lost"}.
## Crop units still on the farm (home, targeted, carried, or dropped). Derived from lost_crops;
## change it through lose_crop().
var crops: int:
get:
return crops_total - lost_crops.size()
set(_value):
push_error("FarmState.crops is derived from lost_crops; use lose_crop()")
## Animals still on the farm (in the pen, loose, following, or carried). Derived from lost_animals.
var animals: int:
get:
return animals_total - lost_animals.size()
set(_value):
push_error("FarmState.animals is derived from lost_animals; use lose_animal()")
## Supplies still on the farm: the shed's stock plus what thieves carry or dropped.
var supplies: int:
get:
return resources.shed_total() + supplies_in_transit
set(_value):
push_error("FarmState.supplies is derived from the shed's stock")
## Wood, scrap, and straw in the supply shed and in the scarecrow's pouch.
var resources := ResourceStore.new()
## Charges of the gather points that are below full (GatherNode name -> charges left); a point
## missing here is full.
var gather_charges: Dictionary = {}
## Bought upgrades (id -> level).
var upgrades: Dictionary = {}
## Built structures: {"id", "type", "x", "z" (world position, on the 0.5 m build grid), "rot"
## (0..7, steps of 45 degrees), "hp" (for a slowing trap, the enemies it can still slow)}.
var structures: Array[Dictionary] = []
var next_structure_id: int = 1
## Event counts of the day and night in progress (EVENTS keys), since this morning.
var night_events: Dictionary = {}
## One entry per completed night, closed when its dawn ends (LOG_KEYS).
var night_log: Array[Dictionary] = []
@ -39,24 +114,117 @@ static func create(cfg: GameConfig) -> FarmState:
var s := FarmState.new()
s.scarecrow_max_hp = cfg.scarecrow_max_hp
s.scarecrow_hp = cfg.scarecrow_max_hp
s.partner_max_hp = cfg.scarecrow_max_hp
s.partner_hp = cfg.scarecrow_max_hp
s.crops_total = cfg.start_crops
s.crops = cfg.start_crops
s.animals_total = cfg.start_animals
s.animals = cfg.start_animals
s.supplies_total = cfg.start_supplies
s.supplies = cfg.start_supplies
s.resources.pouch_capacity = cfg.pouch_capacity
s.resources.shed = {"wood": cfg.start_wood, "scrap": cfg.start_scrap, "straw": cfg.start_straw}
s.supplies_total = s.resources.shed_total()
for e in cfg.start_structures:
var t := String(e["type"])
s.structures.append({"id": s.next_structure_id, "type": t, "x": float(e["x"]), "z": float(e["z"]),
"rot": int(e.get("rot", 0)), "hp": cfg.structure_hp(t)})
s.next_structure_id += 1
return s
## D2: every category in play is gone. Categories not in play (starting count 0) are ignored.
func is_crop_lost(unit_id: int) -> bool:
return lost_crops.has(unit_id)
## Marks a crop unit as gone for good. Returns false for unknown or already-lost units.
func lose_crop(unit_id: int) -> bool:
if unit_id < 1 or unit_id > crops_total or lost_crops.has(unit_id):
return false
lost_crops.append(unit_id)
lost_crops.sort()
return true
func lose_all_crops() -> void:
for id in range(1, crops_total + 1):
lose_crop(id)
func is_animal_lost(id: int) -> bool:
return lost_animals.has(id)
## Marks an animal as gone for good. Returns false for unknown or already-lost animals.
func lose_animal(id: int) -> bool:
if id < 1 or id > animals_total or lost_animals.has(id):
return false
lost_animals.append(id)
lost_animals.sort()
return true
func lose_all_animals() -> void:
for id in range(1, animals_total + 1):
lose_animal(id)
## Debug and tests: every asset gone, the shed emptied by thieves.
func strip() -> void:
lose_all_crops()
lose_all_animals()
for m in ResourceStore.MATERIALS:
resources.shed[m] = 0
supplies_in_transit = 0
shed_raided = true
func record_event(key: String, amount: int = 1) -> void:
night_events[key] = int(night_events.get(key, 0)) + amount
## Pays a cost from the pouch and shed (ResourceStore.pay) and counts what was spent. Every
## purchase (building, repairs, patching, upgrades) goes through here.
func pay(cost: Dictionary) -> bool:
if not resources.pay(cost):
return false
for m in cost:
if int(cost[m]) > 0:
record_event("spent_" + String(m), int(cost[m]))
return true
## Every night_log entry's EVENTS key added up (plus crops_lost and animals_lost).
func totals() -> Dictionary:
var out := {}
for key in LOG_KEYS:
if key != "night":
out[key] = 0
for entry in night_log:
for key in out:
out[key] += int(entry.get(key, 0))
return out
## Called every tick before the outcome check: once the shed holds anything again, it no longer
## counts as raided.
func settle_supplies() -> void:
if shed_raided and resources.shed_total() > 0:
shed_raided = false
## D2: every category in play is gone. Categories not in play are ignored. Supplies only count
## as gone when thieves emptied the shed: spending the last materials doesn't strip the farm.
func is_stripped() -> bool:
var in_play := false
for pair: Vector2i in [Vector2i(crops_total, crops), Vector2i(animals_total, animals),
Vector2i(supplies_total, supplies)]:
if pair.x > 0:
in_play = true
if pair.y > 0:
return false
if crops_total > 0:
in_play = true
if crops > 0:
return false
if animals_total > 0:
in_play = true
if animals > 0:
return false
if supplies_total > 0:
in_play = true
if supplies > 0 or not shed_raided:
return false
return in_play
@ -64,23 +232,34 @@ func asset_counts() -> PackedInt32Array:
return PackedInt32Array([crops, animals, supplies])
## Records the night that just ended, given the asset counts when it started.
## Records the night that just ended, given the asset counts when it started, and clears the
## night's event counts. Crops and animals lost are what's gone since then; supplies lost are the
## units carried off (the shed's stock also changes by storing and spending).
func log_night(start: PackedInt32Array) -> void:
var now := asset_counts()
if start.size() != now.size():
start = now
night_log.append({
var entry := {
"night": night,
"crops_lost": maxi(start[0] - now[0], 0),
"animals_lost": maxi(start[1] - now[1], 0),
"supplies_lost": maxi(start[2] - now[2], 0),
})
}
for key in EVENTS:
entry[key] = int(night_events.get(key, 0))
night_log.append(entry)
night_events.clear()
func to_dict() -> Dictionary:
var entries: Array = []
for entry in night_log:
entries.append(entry.duplicate())
var lost: Array = []
for id in lost_crops:
lost.append(id)
var lost_a: Array = []
for id in lost_animals:
lost_a.append(id)
return {
"version": VERSION,
"night": night,
@ -90,12 +269,21 @@ func to_dict() -> Dictionary:
"scarecrow_max_hp": scarecrow_max_hp,
"scarecrow_hp": scarecrow_hp,
"crops_total": crops_total,
"crops": crops,
"lost_crops": lost,
"animals_total": animals_total,
"animals": animals,
"lost_animals": lost_a,
"supplies_total": supplies_total,
"supplies": supplies,
"shed_raided": shed_raided,
"resources": resources.to_dict(),
"gather_charges": gather_charges.duplicate(),
"upgrades": upgrades.duplicate(),
"structures": _structures_copy(),
"next_structure_id": next_structure_id,
"night_events": night_events.duplicate(),
"night_log": entries,
"coop": coop,
"partner_max_hp": partner_max_hp,
"partner_hp": partner_hp,
}
@ -110,7 +298,11 @@ static func from_dict(d: Dictionary) -> FarmState:
var phase_value := int(d["phase"])
if not CampaignController.Phase.values().has(phase_value):
return null
if not d["night_log"] is Array:
if not (d["night_log"] is Array and d["lost_crops"] is Array and d["lost_animals"] is Array and d["night_events"] is Dictionary
and d["gather_charges"] is Dictionary and d["upgrades"] is Dictionary and d["structures"] is Array):
return null
var store := ResourceStore.from_dict(d["resources"])
if store == null:
return null
var s := FarmState.new()
s.night = int(d["night"])
@ -119,12 +311,52 @@ static func from_dict(d: Dictionary) -> FarmState:
s.phase_time_left = float(d["phase_time_left"])
s.scarecrow_max_hp = int(d["scarecrow_max_hp"])
s.scarecrow_hp = int(d["scarecrow_hp"])
s.coop = bool(d["coop"])
s.partner_max_hp = int(d["partner_max_hp"])
s.partner_hp = int(d["partner_hp"])
s.crops_total = int(d["crops_total"])
s.crops = int(d["crops"])
for id in d["lost_crops"]:
if not s.lose_crop(int(id)):
return null # unknown or duplicate unit id
s.animals_total = int(d["animals_total"])
s.animals = int(d["animals"])
for id in d["lost_animals"]:
if not s.lose_animal(int(id)):
return null
s.supplies_total = int(d["supplies_total"])
s.supplies = int(d["supplies"])
s.shed_raided = bool(d["shed_raided"])
s.resources = store
for key in d["gather_charges"]:
if int(d["gather_charges"][key]) < 0:
return null
s.gather_charges[String(key)] = int(d["gather_charges"][key])
for key in d["upgrades"]:
if int(d["upgrades"][key]) < 0:
return null
s.upgrades[String(key)] = int(d["upgrades"][key])
s.next_structure_id = int(d["next_structure_id"])
var ids := {}
for raw in d["structures"]:
if not raw is Dictionary:
return null
var e := {}
for key in STRUCTURE_KEYS:
if not (raw as Dictionary).has(key):
return null
e["id"] = int(raw["id"])
e["type"] = String(raw["type"])
e["x"] = float(raw["x"])
e["z"] = float(raw["z"])
e["rot"] = int(raw["rot"])
e["hp"] = int(raw["hp"])
if e["id"] < 1 or e["id"] >= s.next_structure_id or ids.has(e["id"]) or e["type"] == "" \
or e["rot"] < 0 or e["rot"] > 7 or e["hp"] < 0:
return null
ids[e["id"]] = true
s.structures.append(e)
for key in d["night_events"]:
if not EVENTS.has(String(key)):
return null
s.night_events[String(key)] = int(d["night_events"][key])
for raw in d["night_log"]:
if not raw is Dictionary:
return null
@ -137,10 +369,26 @@ static func from_dict(d: Dictionary) -> FarmState:
return s if s.is_valid() else null
## The structure record with this id, or an empty dictionary.
func structure(id: int) -> Dictionary:
for e in structures:
if int(e["id"]) == id:
return e
return {}
func _structures_copy() -> Array:
var out: Array = []
for e in structures:
out.append(e.duplicate())
return out
func is_valid() -> bool:
return night >= 1 and nights_survived >= 0 and nights_survived <= night \
and phase_time_left >= 0.0 \
and scarecrow_max_hp >= 1 and scarecrow_hp >= 0 and scarecrow_hp <= scarecrow_max_hp \
and crops >= 0 and crops <= crops_total \
and animals >= 0 and animals <= animals_total \
and supplies >= 0 and supplies <= supplies_total
and partner_max_hp >= 1 and partner_hp >= 0 and partner_hp <= partner_max_hp \
and crops_total >= 0 and lost_crops.size() <= crops_total \
and animals_total >= 0 and lost_animals.size() <= animals_total \
and supplies_total >= 0 and supplies_in_transit >= 0

View file

@ -4,6 +4,9 @@ extends Node3D
## One purposeful area of the farm: an axis-aligned rectangle on the ground, centered on this
## node (rotation is ignored). Zones live under Zones/ in farm.tscn, and FarmZones looks them
## up by position. In the editor each zone draws a translucent box so the layout is visible.
## Outside zones are gathering areas beyond the farm's edge (north and east of it through the
## fence's gaps, south of it across open ground): there can be several of a kind, and
## FarmZones.zone(kind) only returns the farm's own.
enum Kind { CROP_FIELD, ANIMAL_PEN, SUPPLY_SHED, WORK_AREA, WOOD, SCRAP, STRAW }
@ -19,6 +22,8 @@ enum Kind { CROP_FIELD, ANIMAL_PEN, SUPPLY_SHED, WORK_AREA, WOOD, SCRAP, STRAW }
set(value):
tint = value
_update_preview()
## Beyond the farm's fence (a gathering area outside).
@export var outside := false
var _preview: MeshInstance3D

View file

@ -1,28 +1,37 @@
class_name FarmZones
extends Node3D
## The Zones/ node of farm.tscn: every FarmZone (with the props that belong to it), the
## perimeter and its markers, and the crop units, plus lookups by position. The playable map is
## the rectangle inside the perimeter fence; the rest of the farm is out-of-bounds scenery.
## perimeter (what's left of its fence, on the north and east sides, and that fence's gaps), and
## the crop units, plus lookups by position. The playable map is the farm's rectangle (where
## building, navigation, and the night happen). Its edge is where enemies come from and go:
## edge(margin) is the rectangle that far outside it, and enemies arrive at random points along it
## (WaveDirector). Beyond the map the scarecrow can roam out to the old farm's outer fences
## (Perimeter/PlayerBounds), where outside zones hold more to gather.
@export var playable := Rect2(-13.0, -45.0, 60.0, 60.0)
## Where the scarecrow can go: out to the old farm's outer fences.
@export var roam := Rect2(-27.6, -59.6, 82.4, 106.6)
## The farm's own zones (inside the fence).
func zones() -> Array[FarmZone]:
var out: Array[FarmZone] = []
for child in get_children():
if child is FarmZone:
if child is FarmZone and not (child as FarmZone).outside:
out.append(child)
return out
## The zone containing a world position (zones don't overlap), or null between zones.
## The zone containing a world position, inside the fence or out (zones don't overlap), or null
## between zones.
func zone_at(point: Vector3) -> FarmZone:
for zone in zones():
for zone in zones() + outside_zones():
if zone.contains(point):
return zone
return null
## The farm's own zone of a kind (never an outside one).
func zone(kind: FarmZone.Kind) -> FarmZone:
for z in zones():
if z.kind == kind:
@ -30,14 +39,76 @@ func zone(kind: FarmZone.Kind) -> FarmZone:
return null
func markers(kind: FarmMarker.Kind) -> Array[FarmMarker]:
## The gathering areas beyond the fence.
func outside_zones() -> Array[FarmZone]:
var out: Array[FarmZone] = []
for child in get_children():
if child is FarmZone and (child as FarmZone).outside:
out.append(child)
return out
func is_inside_fence(point: Vector3) -> bool:
return playable.has_point(Vector2(point.x, point.z))
## The gaps in what's left of the perimeter fence.
func gaps() -> Array[FarmMarker]:
var out: Array[FarmMarker] = []
for node in find_children("*", "Marker3D", true, false):
if node is FarmMarker and (node as FarmMarker).kind == kind:
if node is FarmMarker:
out.append(node)
return out
## The rectangle margin meters outside the playable map's edge.
func edge(margin: float) -> Rect2:
return playable.grow(margin)
## The point a share t (0..1, wrapping) of the way around edge(margin), clockwise from its
## north-west corner.
func edge_point(t: float, margin: float) -> Vector2:
var r := edge(margin)
var d := fposmod(t, 1.0) * 2.0 * (r.size.x + r.size.y)
if d < r.size.x:
return r.position + Vector2(d, 0.0)
d -= r.size.x
if d < r.size.y:
return Vector2(r.end.x, r.position.y + d)
d -= r.size.y
if d < r.size.x:
return Vector2(r.end.x - d, r.end.y)
return Vector2(r.position.x, r.end.y - (d - r.size.x))
## The nearest point on a rectangle's outline to p (from inside: straight out the nearest side).
static func nearest_on_outline(r: Rect2, p: Vector2) -> Vector2:
var q := p.clamp(r.position, r.end)
var to_side := [q.x - r.position.x, r.end.x - q.x, q.y - r.position.y, r.end.y - q.y]
match to_side.find(to_side.min()):
0:
q.x = r.position.x
1:
q.x = r.end.x
2:
q.y = r.position.y
_:
q.y = r.end.y
return q
## Which side of the farm p is on, as the HUD says it: "north", "south-east", ... (the map split
## in thirds each way; "" in the middle).
func side_of(p: Vector2) -> String:
var c := playable.get_center()
var u := (p.x - c.x) / (playable.size.x * 0.5)
var v := (p.y - c.y) / (playable.size.y * 0.5)
var ns := "north" if v < -1.0 / 3.0 else ("south" if v > 1.0 / 3.0 else "")
var we := "west" if u < -1.0 / 3.0 else ("east" if u > 1.0 / 3.0 else "")
return ns + "-" + we if ns != "" and we != "" else ns + we
func crop_units() -> Array[CropUnit]:
var out: Array[CropUnit] = []
var field := zone(FarmZone.Kind.CROP_FIELD)

View file

@ -0,0 +1,350 @@
class_name FarmersReturn
extends Node3D
## The ending once the last night's dawn is over (FARMERS_RETURN): the farmers' station wagon
## (car_002, roof rack and all) comes up the road east of the farm, turns in at the driveway gap,
## and parks in the farmyard by the house with a honk; the two farmers (tinted mannequins) get
## out, walk to the house door, wave to the scarecrow waiting by the yard, and cheer. A cutscene
## camera follows the car, then frames the yard; the HUD hides behind letterbox bars. Fire,
## interact, or Space / Enter / A skips to the end. finished is emitted once it's
## over (or skipped), and EndPanel shows the final assessment over the scene.
## Built when it starts, after the game is over, so nothing is created during play.
signal finished
const CAR_SCENE := "res://assets/farm/ithappy/farm/prefabs/assets/transport/car_002.tscn"
const FARMER_SCENE := "res://assets/kaykit_characters/characters/Mannequin_Medium.glb"
const ANIMATIONS := "res://game/resources/player_animations.res"
## The road from the south along the east side, in at GapDriveway, through the farmyard to the
## parking spot east of the house (game/LAYOUT.md); the car faces the way it drives.
const ROUTE: Array[Vector3] = [
Vector3(52.0, 0.0, 6.0), Vector3(52.0, 0.0, -30.0), Vector3(51.0, 0.0, -38.0), Vector3(46.0, 0.0, -39.6),
Vector3(38.0, 0.0, -39.4), Vector3(34.5, 0.0, -36.5), Vector3(33.0, 0.0, -32.5), Vector3(32.8, 0.0, -29.5),
]
const DRIVE_SPEED := 11.0
## Where the farmers walk (from the car's left and right doors to the porch steps on the house's
## north side) and where the scarecrow waits, beside their way. The yard shot looks south at the
## porch.
const DOOR := Vector3(19.6, 0.0, -29.8)
const FARMER_SPOTS: Array[Vector3] = [Vector3(18.9, 0.0, -31.4), Vector3(20.5, 0.0, -31.5)]
const SCARECROW_SPOT := Vector3(24.6, 0.0, -34.0)
const YARD_CAMERA := Vector3(28.0, 10.0, -45.5)
const YARD_LOOK := Vector3(24.8, 0.8, -30.8)
const WALK_SPEED := 2.0
const TINTS: Array[Color] = [Color(0.35, 0.5, 0.85), Color(0.85, 0.45, 0.4)]
## Seconds: honk after parking, farmers out, then waving, cheering, and the end.
const OUT_AT := 0.9
const WAVE_TIME := 2.2
const CHEER_TIME := 2.6
var sim: FarmSim
var running := false
var done := false
## Seconds since the start, and the stage: "drive", "walk", "wave", "cheer", "end".
var elapsed: float = 0.0
var stage := ""
var _car: Node3D
var _engine: AudioStreamPlayer3D
var _curve := Curve3D.new()
var _driven: float = 0.0
var _parked_for: float = 0.0
var _farmers: Array[Node3D] = []
var _anims: Array[AnimationPlayer] = []
var _camera: Camera3D
var _previous_camera: Camera3D
var _stage_left: float = 0.0
var _overlay: CanvasLayer
var _caption: Label
func setup(p_sim: FarmSim) -> void:
sim = p_sim
sim.campaign.campaign_ended.connect(func(outcome: CampaignController.Outcome) -> void:
if outcome == CampaignController.Outcome.VACATION_COMPLETE:
start())
sim.campaign.phase_changed.connect(func(phase: CampaignController.Phase, _p: CampaignController.Phase) -> void:
if phase == CampaignController.Phase.MORNING:
clear())
func start() -> void:
if running:
return
clear()
running = true
done = false
elapsed = 0.0
stage = "drive"
_driven = 0.0
_parked_for = 0.0
for p in ROUTE:
_curve.add_point(p)
for i in range(1, ROUTE.size() - 1): # round the corners
var t := (ROUTE[i + 1] - ROUTE[i - 1]) * 0.25
_curve.set_point_in(i, -t)
_curve.set_point_out(i, t)
_car = (load(CAR_SCENE) as PackedScene).instantiate() as Node3D
add_child(_car)
for body in _car.find_children("*", "CollisionObject3D", true, false):
(body as CollisionObject3D).collision_layer = 0
_engine = AudioStreamPlayer3D.new()
_engine.bus = &"SFX"
_engine.unit_size = 10.0
_engine.volume_db = -6.0
if sim.audio != null:
_engine.stream = sim.audio.stream_of("truck_engine")
_car.add_child(_engine)
if _engine.stream != null:
_engine.play()
_place_car(0.0)
var library := load(ANIMATIONS) as AnimationLibrary
for i in 2:
var root := Node3D.new()
root.visible = false
add_child(root)
var model := (load(FARMER_SCENE) as PackedScene).instantiate() as Node3D
root.add_child(model)
for mi in model.find_children("*", "MeshInstance3D", true, false):
var m := mi as MeshInstance3D
var base := m.get_active_material(0)
if base is BaseMaterial3D:
var tinted := (base as BaseMaterial3D).duplicate() as BaseMaterial3D
tinted.albedo_color = TINTS[i]
m.material_override = tinted
var straw := StandardMaterial3D.new() # a straw sun hat for the trip
straw.albedo_color = Color(0.92, 0.8, 0.45)
for part in [[0.62, 0.05, 2.12], [0.34, 0.26, 2.26]]: # brim, crown: radius, height, y
var mesh := CylinderMesh.new()
mesh.top_radius = part[0]
mesh.bottom_radius = part[0]
mesh.height = part[1]
var hat := MeshInstance3D.new()
hat.mesh = mesh
hat.position = Vector3(0.0, part[2], 0.0)
hat.material_override = straw
model.add_child(hat)
var anim := AnimationPlayer.new()
root.add_child(anim)
anim.root_node = anim.get_path_to(model)
anim.add_animation_library(&"", library)
_farmers.append(root)
_anims.append(anim)
# The scarecrow waits by the yard (in co-op, both, side by side).
for a in sim.avatars:
var at := SCARECROW_SPOT + Vector3(1.6, 0.0, 0.6) * a.slot
var yaw := atan2(-(DOOR.x - at.x), -(DOOR.z - at.z))
a.body.global_position = at
a.body.velocity = Vector3.ZERO
a.body.model.rotation.y = yaw
a.body.net_position = at
a.body.net_yaw = yaw
a.body.start_channel(&"Idle_A")
_previous_camera = get_viewport().get_camera_3d()
_camera = Camera3D.new()
_camera.fov = 45.0
add_child(_camera)
_camera.make_current()
_follow_camera(1.0)
if sim.audio != null:
sim.audio.focus = _car
_build_overlay()
_set_hud(false)
## Jumps to the end: parked, the farmers at the door cheering.
func skip() -> void:
if not running or done:
return
_driven = _curve.get_baked_length()
_place_car(_driven)
_stop_engine()
for i in 2:
_farmers[i].visible = true
_farmers[i].global_position = FARMER_SPOTS[i]
_face(_farmers[i], SCARECROW_SPOT)
_anims[i].play(&"Cheering")
_frame_yard(1.0)
_finish()
## Removes everything (a new vacation or a retry after the ending).
func clear() -> void:
running = false
stage = ""
for n in get_children():
n.queue_free()
_farmers.clear()
_anims.clear()
_car = null
_engine = null
_camera = null
_overlay = null
_curve = Curve3D.new()
if sim != null:
_set_hud(true)
if sim.audio != null:
sim.audio.focus = sim.player
if _previous_camera != null and is_instance_valid(_previous_camera):
_previous_camera.make_current()
for a in sim.avatars:
a.body.stop_channel()
func _process(delta: float) -> void:
if running and not done:
step(delta)
func step(delta: float) -> void:
elapsed += delta
match stage:
"drive":
var length := _curve.get_baked_length()
var left := length - _driven
var speed := DRIVE_SPEED * clampf(left / 9.0, 0.18, 1.0) # ease into the spot
_driven = minf(_driven + speed * delta, length)
_place_car(_driven)
_follow_camera(delta)
if _driven >= length:
_parked_for += delta
if _parked_for >= 0.15 and _engine != null and _engine.playing:
_stop_engine()
if sim.audio != null:
sim.audio.play("horn", _car.global_position)
if _parked_for >= OUT_AT:
stage = "walk"
var right := _car.global_basis.x
for i in 2:
_farmers[i].visible = true
_farmers[i].global_position = _car.global_position + right * (1.4 if i == 0 else -1.4)
_anims[i].play(&"Walking_A", 0.1)
"walk":
_frame_yard(delta)
var arrived := 0
for i in 2:
var f := _farmers[i]
var to := FARMER_SPOTS[i] - f.global_position
to.y = 0.0
if to.length() <= 0.05:
arrived += 1
continue
f.global_position += to.limit_length(WALK_SPEED * delta)
_face(f, f.global_position + to)
if arrived == 2:
stage = "wave"
_stage_left = WAVE_TIME
for i in 2:
_face(_farmers[i], SCARECROW_SPOT)
_anims[i].play(&"Waving", 0.15)
if sim.audio != null:
sim.audio.play("victory")
if _caption != null:
_caption.text = "The farmers are home!"
"wave", "cheer":
_frame_yard(delta)
_stage_left -= delta
if _stage_left <= 0.0:
if stage == "wave":
stage = "cheer"
_stage_left = CHEER_TIME
for a in _anims:
a.play(&"Cheering", 0.2)
else:
_finish()
func _finish() -> void:
done = true
stage = "end"
if _overlay != null:
_overlay.visible = false
_set_hud(true) # the final assessment is on it
finished.emit()
func _set_hud(on: bool) -> void:
if sim.hud != null and sim.hud.get_parent() is CanvasLayer:
(sim.hud.get_parent() as CanvasLayer).visible = on
func _place_car(distance: float) -> void:
var length := _curve.get_baked_length()
var at := _curve.sample_baked(distance, true)
var ahead := _curve.sample_baked(minf(distance + 1.0, length), true)
var behind := _curve.sample_baked(maxf(distance - 1.0, 0.0), true)
var dir := ahead - behind
dir.y = 0.0
if dir.length_squared() > 1e-6:
_car.rotation = Vector3(0.0, atan2(dir.x, dir.z), 0.0)
_car.global_position = Vector3(at.x, 0.0, at.z)
## Behind and above the car, looking a little ahead of it.
func _follow_camera(delta: float) -> void:
var fwd := _car.global_basis.z
var want := _car.global_position - fwd * 11.0 + Vector3(0.0, 8.0, 0.0) + _car.global_basis.x * 3.0
var look := _car.global_position + fwd * 4.0 + Vector3(0.0, 1.0, 0.0)
_move_camera(want, look, delta, 2.5)
## A wide shot of the yard from the north-east: the car, the porch, and the scarecrow.
func _frame_yard(delta: float) -> void:
_move_camera(YARD_CAMERA, YARD_LOOK, delta, 1.2)
func _move_camera(want: Vector3, look: Vector3, delta: float, rate: float) -> void:
var k := 1.0 - exp(-rate * delta) if delta < 1.0 else 1.0
_camera.global_position = _camera.global_position.lerp(want, k) if _camera.global_position != Vector3.ZERO else want
var target := _camera.global_transform.looking_at(look, Vector3.UP)
_camera.global_basis = _camera.global_basis.slerp(target.basis, k).orthonormalized() if k < 1.0 else target.basis
func _face(node: Node3D, at: Vector3) -> void:
var d := at - node.global_position
if Vector2(d.x, d.z).length_squared() > 1e-6:
node.rotation.y = atan2(d.x, d.z)
func _stop_engine() -> void:
if _engine != null:
_engine.stop()
func _build_overlay() -> void:
_overlay = CanvasLayer.new()
_overlay.layer = 5
add_child(_overlay)
for top in [true, false]:
var bar := ColorRect.new()
bar.color = Color.BLACK
bar.mouse_filter = Control.MOUSE_FILTER_IGNORE
_overlay.add_child(bar)
bar.set_anchors_and_offsets_preset(Control.PRESET_TOP_WIDE if top else Control.PRESET_BOTTOM_WIDE)
if top:
bar.offset_bottom = 96.0
else:
bar.offset_top = -96.0
_caption = Label.new()
_caption.text = "The farmers are on their way home"
_caption.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
_caption.add_theme_font_size_override("font_size", 38)
_caption.add_theme_color_override("font_color", Color(0.95, 0.85, 0.55))
_overlay.add_child(_caption)
_caption.set_anchors_and_offsets_preset(Control.PRESET_TOP_WIDE)
_caption.offset_top = 22.0
var hint := Label.new()
hint.text = "[Space / Enter / A] skip"
hint.add_theme_font_size_override("font_size", 22)
hint.add_theme_color_override("font_color", Color(0.8, 0.8, 0.75))
_overlay.add_child(hint)
hint.set_anchors_and_offsets_preset(Control.PRESET_BOTTOM_RIGHT)
hint.offset_left = -360.0
hint.offset_top = -70.0
func _unhandled_input(event: InputEvent) -> void:
if not running or done:
return
if event.is_action_pressed("ui_accept") or event.is_action_pressed("interact") or event.is_action_pressed("fire"):
skip()
get_viewport().set_input_as_handled()

View file

@ -0,0 +1 @@
uid://00yqn4v1vtyl

View file

@ -6,7 +6,20 @@ extends Resource
@export_group("Campaign")
## Nights the scarecrow must survive before the farmers return.
@export_range(1, 20) var campaign_nights: int = 5
@export_range(1, 60) var campaign_nights: int = 5
@export_group("Waves")
## Every night plan's groups are scaled when played: this many times the enemies, arriving this
## many times the plan's spacing apart (NightPlan.scaled_count / scaled_every). 5 and 0.4: five
## times the enemies, two and a half times as often. A plan can set its own instead
## (NightPlan.count_scale / spacing_scale; night 1 plays unscaled).
@export_range(0.1, 20.0) var wave_count_scale: float = 7.0
@export_range(0.05, 4.0) var wave_spacing_scale: float = 0.3
## Every enemy arrives at its own random point along the farm's edge (FarmZones.edge), on foot this
## many meters outside the playable map (also where carriers escape to), flyers this far out.
## Ground arrivals stay inside the navigation grid (5 m beyond the map).
@export_range(0.5, 4.5) var spawn_margin: float = 3.0
@export var flyer_spawn_margin: float = 8.0
@export_group("Phases")
## Seconds of game time per phase. The morning review is untimed: it waits for the player.
@ -20,14 +33,32 @@ extends Resource
@export_group("Scarecrow")
## HP carries over between nights (D7); 0 HP is an immediate Game Over.
@export_range(1, 100) var scarecrow_max_hp: int = 10
@export_range(1, 100) var scarecrow_max_hp: int = 3
## After an accepted hit the scarecrow ignores further hits for this long.
@export var invulnerability_time: float = 1.0
## Fear: enemies within fear_radius flee for fear_duration; usable every fear_cooldown seconds.
@export var fear_radius: float = 6.0
@export var fear_cooldown: float = 12.0
@export var fear_duration: float = 2.0
## Patch up: hold for patch_time (rooted, no shooting) to restore patch_heal HP.
@export var patch_time: float = 2.0
@export_range(1, 100) var patch_heal: int = 3
## Sprint (the workbench's Sprint upgrade): hold sprint while moving to run sprint_speed_mult
## times as fast for up to sprint_time seconds; once it ends, sprint_cooldown seconds until the
## next one.
@export var sprint_speed_mult: float = 1.6
@export var sprint_time: float = 3.0
@export var sprint_cooldown: float = 10.0
@export_group("Farm assets")
## Starting count per target category. A category with a count of 0 is not in play and is
## ignored by the "farm stripped" check (D2). Animals and supplies arrive in Step 8.
## Crop units and animals on the farm when the vacation starts; they must match the farm scene
## (the crop field's CropUnits, the animals in the pen). Supplies are the shed's stock (the start
## materials below). A category with nothing in it at the start is not in play and is ignored by
## the "farm stripped" check (D2).
@export_range(0, 500) var start_crops: int = 30
@export_range(0, 100) var start_animals: int = 0
@export_range(0, 5000) var start_supplies: int = 0
@export_range(0, 100) var start_animals: int = 8
## Structures standing when the vacation starts ({"type", "x", "z", "rot"}): the animal pen's gate.
@export var start_structures: Array[Dictionary] = [{"type": "gate", "x": 4.0, "z": -6.0, "rot": 2}]
@export_group("Theft rules")
## D5: fear makes carriers drop their loot, not only killing them.
@ -35,7 +66,228 @@ extends Resource
## D6: dropped loot still on the ground when the dawn grace ends returns home automatically.
@export var loot_returns_at_dawn: bool = true
## D6: animals that can follow the scarecrow back to the pen at once.
@export_range(1, 10) var max_following_animals: int = 3
@export_range(1, 10) var max_following_animals: int = 5
## Seconds an enemy needs to take a crop unit, catch an animal, or fill a sack at the shed (times
## its type's steal_time); damage during that time resets it.
@export var crop_steal_time: float = 2.5
@export var animal_capture_time: float = 2.0
@export var supply_steal_time: float = 1.0
## A supply thief takes this many units of the material the shed holds most of (never more than
## there is).
@export_range(1, 100) var supply_bundle: int = 5
## Loose animals (dropped, or wandered out of an open pen) walk toward the farm's nearest edge at
## this speed, stopping to graze now and then; one that gets off the farm is lost.
@export var stray_speed: float = 1.1
## At night, while the pen is open (its gate broken or removed), one animal wanders out every
## this many seconds. An animal brought back stays calm (won't wander out) for animal_calm_time.
@export var animal_wander_interval: float = 10.0
@export var animal_calm_time: float = 30.0
## Animals following the scarecrow walk its trail at up to this speed.
@export var follow_speed: float = 6.0
## What a thief with no set target goes for ("any" in a night plan), and where a thief whose target
## is gone goes next: relative weights per category.
@export var target_weights: Dictionary = {"crops": 2.0, "animals": 1.0, "supplies": 1.0}
## The scarecrow recovers dropped loot by walking within this distance of it.
@export var pickup_radius: float = 1.3
@export_group("Resources")
## Wood, scrap, and straw in the supply shed when the vacation starts.
@export_range(0, 999) var start_wood: int = 4
@export_range(0, 999) var start_scrap: int = 2
@export_range(0, 999) var start_straw: int = 4
## The scarecrow's pouch holds this many units in total; it empties into the shed on entry.
@export_range(1, 200) var pouch_capacity: int = 16
## Seconds of holding interact per gather (each takes one charge of the gather point).
@export var gather_time: float = 1.5
## What things cost: name -> {material: amount}: patching up, the buildables, and the upgrades.
@export var costs: Dictionary = {
"patch": {"straw": 2},
"straw_stuffing": {"straw": 12, "wood": 4},
"sprint": {"wood": 8, "straw": 6},
"corn_shooter": {"scrap": 10, "wood": 4},
"pumpkin_bomb": {"straw": 12, "scrap": 6},
"rapid_fire": {"scrap": 12, "wood": 8},
"heavy_seeds": {"scrap": 14, "straw": 10},
"wide_fear": {"straw": 20, "wood": 4},
"quick_fear": {"straw": 16, "scrap": 6},
"reinforced_fences": {"wood": 20, "scrap": 6},
"long_range": {"scrap": 14, "wood": 10},
"sticky_tar": {"straw": 14, "scrap": 6},
"fence": {"wood": 2},
"gate": {"wood": 4, "scrap": 1},
"slowing_trap": {"scrap": 3, "wood": 1},
"automated_defense": {"scrap": 6, "wood": 2, "straw": 2},
}
@export_group("Upgrades")
## Bought once each by day at the work area's workbench, for costs[id] (Upgrades). Each changes
## one stat: "mult" multiplies it, "add" adds to it. Stats are GameConfig settings, plus
## scarecrow_max_hp (the scarecrow's, in FarmState) and barrier_hp (fences' and gates' health).
## One without a stat unlocks something instead (sprint: PlayerCharacter; the corn shooter and
## pumpkin bombs: ScarecrowCombat). "requires": another upgrade that must be bought first.
@export var upgrades: Dictionary = {
"corn_shooter": {"name": "Corn shooter", "text": "A gun that fires corn kernels, from afar", "track": "Weapon"},
"rapid_fire": {"name": "Rapid fire", "text": "The corn shooter fires a third faster", "track": "Weapon", "stat": "fire_rate", "mult": 1.333, "requires": "corn_shooter"},
"heavy_seeds": {"name": "Heavy seeds", "text": "Each kernel does 2 damage", "track": "Weapon", "stat": "shot_damage", "add": 1, "requires": "corn_shooter"},
"pumpkin_bomb": {"name": "Pumpkin bombs", "text": "Throw a pumpkin that bursts, hurting everything within 3 m (one every 4 s)", "track": "Weapon"},
"wide_fear": {"name": "Wide fear", "text": "Fear reaches 30% farther", "track": "Fear", "stat": "fear_radius", "mult": 1.3},
"quick_fear": {"name": "Quick fear", "text": "Fear recharges 20% faster", "track": "Fear", "stat": "fear_cooldown", "mult": 0.8},
"straw_stuffing": {"name": "Straw stuffing", "text": "+2 max health", "track": "Scarecrow", "stat": "scarecrow_max_hp", "add": 2},
"sprint": {"name": "Sprint", "text": "Sprint 60% faster for 3 s at a time, every 10 s", "track": "Scarecrow"},
"reinforced_fences": {"name": "Reinforced fences", "text": "Fences and gates +50% health", "track": "Defenses", "stat": "barrier_hp", "mult": 1.5},
"long_range": {"name": "Long-range defenses", "text": "Automated defenses reach 30% farther", "track": "Defenses", "stat": "turret_range", "mult": 1.3},
"sticky_tar": {"name": "Sticky tar", "text": "Slowing traps hold 50% longer", "track": "Defenses", "stat": "trap_slow_time", "mult": 1.5},
}
@export_group("Assessment")
## The final assessment's weight per category (Assessment): the score is the weighted share of
## each category kept, renormalized over the categories in play, as 0..100 points.
@export var assessment_weights: Dictionary = {"crops": 0.5, "animals": 0.3, "supplies": 0.2}
## Rating tiers, best first: the first one whose min the score reaches.
@export var rating_tiers: Array[Dictionary] = [
{"min": 95, "name": "Blue-ribbon harvest", "text": "The farmers can hardly tell they were gone."},
{"min": 80, "name": "Bumper crop", "text": "A few gaps in the rows, nothing a good week won't fix."},
{"min": 60, "name": "Fair season", "text": "The farm made it, a little thinner than they left it."},
{"min": 40, "name": "Lean season", "text": "The farmers will be counting what's missing for a while."},
{"min": 0, "name": "Hanging by a thread", "text": "There's a farm left, but only just."},
]
@export_group("Structures")
## Hit points of the built defenses; a slowing trap's "HP" is the enemies it can still slow.
@export_range(1, 500) var fence_hp: int = 20
@export_range(1, 500) var gate_hp: int = 30
@export_range(1, 500) var trap_triggers: int = 10
@export_range(1, 500) var turret_hp: int = 25
## A ground enemy crossing a slowing trap moves at this share of its speed for this long.
@export_range(0.05, 1.0) var trap_slow_factor: float = 0.5
@export var trap_slow_time: float = 2.0
## The automated defense shoots the nearest enemy in range with a clear line, every interval.
@export var turret_range: float = 7.0
@export var turret_fire_interval: float = 1.0
## The scarecrow builds within this distance of itself.
@export var build_range: float = 9.0
## Enemies treat each cell of a barrier as this many meters of extra path, so they walk around
## a short wall but break through a long one.
@export var barrier_detour: float = 18.0
## Holding interact for repair_time repairs a structure fully, for its build cost scaled by the
## share of HP (or triggers) it is missing, rounded up.
@export var repair_time: float = 1.5
## Dismantling gives back this share of the build cost (rounded down), into the shed.
@export_range(0.0, 1.0) var dismantle_refund: float = 0.5
## Cells finalized per tick while flow fields rebuild after a structure change.
@export_range(100, 100000) var flow_slice_cells: int = 2000
@export_group("Combat")
## Height of the gun muzzle, the bullets, and enemy hit proxies (shots fly horizontally). It
## clears the sunflowers (1.67 m) and the pen fence (1.69 m), so thieves in the field stay
## visible and shootable.
@export var combat_height: float = 1.8
## The pitchfork, every scarecrow's from the start (ScarecrowCombat): a stab every
## pitchfork_interval s hits the nearest pitchfork_targets enemies within pitchfork_reach m of the
## scarecrow's center (plus their hit radius) and pitchfork_arc degrees of the aim, with a clear
## line, for pitchfork_damage each.
@export var pitchfork_reach: float = 2.2
@export var pitchfork_arc: float = 100.0
@export_range(1, 20) var pitchfork_damage: int = 2
@export_range(1, 20) var pitchfork_targets: int = 3
@export var pitchfork_interval: float = 0.5
## Pumpkin bombs (the Pumpkin bombs upgrade): thrown at the aim point, bomb_min_range ..
## bomb_range m away, flying at bomb_speed m/s; on landing every enemy within bomb_radius m takes
## bomb_damage. One every bomb_cooldown s.
@export var bomb_range: float = 10.0
@export var bomb_min_range: float = 2.0
@export var bomb_speed: float = 12.0
@export var bomb_radius: float = 3.0
@export_range(1, 50) var bomb_damage: int = 3
@export var bomb_cooldown: float = 4.0
## The corn shooter (the Corn shooter upgrade) is the gun: kernels per second and their damage
## (rapid fire and heavy seeds raise them), and the projectiles below.
@export var fire_rate: float = 6.0
## Damage of one of the scarecrow's shots (automated defenses always do 1).
@export_range(1, 10) var shot_damage: int = 1
@export var projectile_speed: float = 24.0
@export var projectile_lifetime: float = 2.0
@export_range(1, 1024) var projectile_capacity: int = 64
## Horizontal distance from the scarecrow's center to the muzzle along the aim direction.
@export var muzzle_distance: float = 1.05
## Right-stick radial dead zone, and mouse travel (px) that switches aiming back to the mouse.
@export var aim_dead_zone: float = 0.3
@export var mouse_switch_threshold: float = 12.0
@export_group("Enemies")
@export_range(1, 1024) var enemy_capacity: int = 800
## The enemy roster (EnemySystem.TYPE_NAMES), one row per type:
## speed, acceleration m/s, m/s^2
## hp hits it takes
## flying ignores ground occupancy, structures, and traps; altitude is only
## visual (its hit proxy stays at combat height)
## targets what it goes for: loot categories ("crops", "animals", "supplies"), or
## "structures" (barriers guarding valuables)
## steal_time times the category's steal time
## carry_speed share of its speed while carrying loot
## structure_damage per hit on a barrier, every hit_interval
## damage, hit_interval per melee hit on the scarecrow, and the cooldown between hits
## aggression "none" (never fights), "contact" (hits the scarecrow when touching it
## while busy), "fight" (turns on a scarecrow within aggro_range, and
## hunts it when nothing is left to break)
## hit_radius projectile hit proxy
@export var enemy_types: Dictionary = {
"thief": {"speed": 3.0, "acceleration": 14.0, "hp": 3, "flying": false, "targets": ["animals", "supplies"],
"steal_time": 1.0, "carry_speed": 0.7, "structure_damage": 2, "damage": 1, "hit_interval": 1.2,
"aggression": "contact", "hit_radius": 0.4, "aggro_range": 0.0},
"crow": {"speed": 5.5, "acceleration": 18.0, "hp": 1, "flying": true, "targets": ["crops"],
"steal_time": 0.8, "carry_speed": 0.75, "structure_damage": 0, "damage": 0, "hit_interval": 1.0,
"aggression": "none", "hit_radius": 0.45, "aggro_range": 0.0},
"breaker": {"speed": 1.9, "acceleration": 8.0, "hp": 6, "flying": false, "targets": ["structures"],
"steal_time": 0.0, "carry_speed": 0.0, "structure_damage": 8, "damage": 2, "hit_interval": 1.5,
"aggression": "fight", "hit_radius": 0.55, "aggro_range": 4.0},
}
## Flyers cruise at this visual altitude and come down to land_altitude to take a crop.
@export var cruise_altitude: float = 3.2
@export var land_altitude: float = 1.55
## Barriers within this distance of the crop rows, the pen, or the shed guard them: fence
## breakers go for those first.
@export var guard_range: float = 6.0
## Body radius of ground enemies (navigation clearance is this plus nav_inflate_margin).
@export var enemy_radius: float = 0.3
@export var nav_cell_size: float = 0.5
@export var nav_inflate_margin: float = 0.05
@export var separation_radius: float = 0.8
@export var separation_weight: float = 1.4
## Bounded push per tick when enemies overlap each other or the scarecrow.
@export var max_correction_per_tick: float = 0.15
## Melee: an enemy touching the scarecrow (within this much of contact) and off cooldown hits
## it for its type's damage; the cooldown (hit_interval) starts on every attempt.
@export var enemy_attack_reach: float = 0.25
## Fleeing enemies (fear) run at this share of their normal speed.
@export var flee_speed_factor: float = 1.15
## Within this distance and with a clear line, enemies steer straight at their target.
@export var direct_seek_distance: float = 12.0
## Trickle mode, for tests and soaks: when above 0, the night's plan is ignored and this many
## enemies of trickle_type are kept on the farm, the next arriving thief_spawn_interval after one
## leaves (anywhere along the farm's edge). 0 plays the night's NightPlan (WaveDirector).
@export_range(0, 32) var night_thieves: int = 0
@export var thief_spawn_interval: float = 6.0
@export var trickle_type: String = "crow"
## What trickle enemies go for: "crops", "animals", "supplies", or "any" (of their type's targets).
@export var trickle_target: String = "any"
## A row of the enemy roster.
func enemy(type_name: String) -> Dictionary:
return enemy_types.get(type_name, {})
## Full hit points of a structure type (a slowing trap's are the enemies it can still slow).
func structure_hp(type: String) -> int:
match type:
"fence":
return fence_hp
"gate":
return gate_hp
"slowing_trap":
return trap_triggers
return turret_hp
## Length of a phase in seconds, or INF for the untimed morning review and terminal phases.

View file

@ -0,0 +1,102 @@
class_name GameSettings
extends RefCounted
## The player's settings, kept in user://settings.cfg (ConfigFile) apart from the save game, and
## applied at start and on every change (SettingsMenu):
## * Audio: the volume of each audio bus (game/resources/audio_buses.tres).
## * Controls: the dead zones of the move stick (the move_* actions) and the aim stick
## (GameConfig.aim_dead_zone). Mouse aim follows the cursor directly, so it has no
## sensitivity to set.
## * Display: fullscreen, VSync, and the 3D resolution scale (the HUD stays sharp).
## * Gameplay: whether the tips show on the first day and night (Tutorial).
## * Co-op: your player name, and whether your microphone is sent in voice chat.
## Values missing from the file or out of range fall back to the defaults, so an old or
## hand-edited file never breaks the game.
const PATH := "user://settings.cfg"
const BUSES: Array[String] = ["Master", "Music", "SFX", "Ambience", "Voice"]
const BUS_NAMES := {"Master": "Master volume", "Music": "Music and stingers", "SFX": "Sound effects", "Ambience": "Ambience",
"Voice": "Voice chat (your friend)"}
const DEFAULT_VOLUME := {"Master": 0.8, "Music": 0.7, "SFX": 0.8, "Ambience": 0.6, "Voice": 1.0}
var volume := DEFAULT_VOLUME.duplicate()
var move_dead_zone := 0.2
var aim_dead_zone := 0.3
var fullscreen := false
var vsync := true
var resolution_scale := 1.0
var show_tips := true
## Co-op: your name for the lobby and the name tag, and whether your microphone is sent.
var player_name := ""
var microphone := true
static func load_from(path: String = PATH) -> GameSettings:
var g := GameSettings.new()
var f := ConfigFile.new()
if f.load(path) != OK:
return g
for bus in BUSES:
g.volume[bus] = _number(f.get_value("audio", bus.to_lower(), g.volume[bus]), 0.0, 1.0, g.volume[bus])
g.move_dead_zone = _number(f.get_value("controls", "move_dead_zone", g.move_dead_zone), 0.05, 0.9, g.move_dead_zone)
g.aim_dead_zone = _number(f.get_value("controls", "aim_dead_zone", g.aim_dead_zone), 0.05, 0.9, g.aim_dead_zone)
g.fullscreen = _flag(f.get_value("display", "fullscreen", g.fullscreen), g.fullscreen)
g.vsync = _flag(f.get_value("display", "vsync", g.vsync), g.vsync)
g.resolution_scale = _number(f.get_value("display", "resolution_scale", g.resolution_scale), 0.5, 1.0, g.resolution_scale)
g.show_tips = _flag(f.get_value("gameplay", "show_tips", g.show_tips), g.show_tips)
var n: Variant = f.get_value("coop", "player_name", "")
g.player_name = String(n).strip_edges().left(20) if n is String else ""
g.microphone = _flag(f.get_value("coop", "microphone", g.microphone), g.microphone)
return g
func save_to(path: String = PATH) -> Error:
var f := ConfigFile.new()
for bus in BUSES:
f.set_value("audio", bus.to_lower(), volume.get(bus, DEFAULT_VOLUME[bus]))
f.set_value("controls", "move_dead_zone", move_dead_zone)
f.set_value("controls", "aim_dead_zone", aim_dead_zone)
f.set_value("display", "fullscreen", fullscreen)
f.set_value("display", "vsync", vsync)
f.set_value("display", "resolution_scale", resolution_scale)
f.set_value("gameplay", "show_tips", show_tips)
f.set_value("coop", "player_name", player_name)
f.set_value("coop", "microphone", microphone)
return f.save(path)
## Applies everything: bus volumes, dead zones (into config too, when given), and the display
## (skipped without a real display, e.g. headless).
func apply(viewport: Viewport, config: GameConfig = null) -> void:
for bus in BUSES:
var i := AudioServer.get_bus_index(bus)
if i < 0:
continue
var v: float = volume.get(bus, DEFAULT_VOLUME[bus])
AudioServer.set_bus_volume_db(i, linear_to_db(maxf(v, 0.0001)))
AudioServer.set_bus_mute(i, v <= 0.001)
for action in ["move_left", "move_right", "move_forward", "move_back"]:
if InputMap.has_action(action):
InputMap.action_set_deadzone(action, move_dead_zone)
if config != null:
config.aim_dead_zone = aim_dead_zone
if viewport != null:
viewport.scaling_3d_scale = resolution_scale
if DisplayServer.get_name() == "headless":
return
var mode := DisplayServer.window_get_mode()
var want_full := fullscreen
var is_full := mode == DisplayServer.WINDOW_MODE_FULLSCREEN or mode == DisplayServer.WINDOW_MODE_EXCLUSIVE_FULLSCREEN
if want_full != is_full:
DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_FULLSCREEN if want_full else DisplayServer.WINDOW_MODE_WINDOWED)
DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_ENABLED if vsync else DisplayServer.VSYNC_DISABLED)
static func _number(v: Variant, lo: float, hi: float, fallback: float) -> float:
if not (v is float or v is int):
return fallback
var x := float(v)
return clampf(x, lo, hi) if is_finite(x) else fallback
static func _flag(v: Variant, fallback: bool) -> bool:
return bool(v) if v is bool else fallback

View file

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

View file

@ -0,0 +1,66 @@
class_name GatherNode
extends Node3D
## A spot where the scarecrow gathers one material by day: holding interact for gather_time
## puts yield_amount into the pouch and uses one of max_charges. Its children are the props it
## is made of; they fade grey once it is used up. Used charges come back overnight
## (regen_per_night each, applied by Interactions). The farm state keeps only points below
## full, keyed by this node's name, so names must be unique among gather points.
const COLORS := {
"wood": Color(0.95, 0.68, 0.4),
"scrap": Color(0.72, 0.84, 0.95),
"straw": Color(1.0, 0.9, 0.42),
}
@export_enum("wood", "scrap", "straw") var material: String = "wood"
@export_range(1, 20) var max_charges: int = 2
@export_range(1, 20) var yield_amount: int = 2
@export_range(1, 20) var regen_per_night: int = 20
## How close the scarecrow's center has to be to this node's origin to gather.
@export var reach: float = 1.8
## Clip the scarecrow loops while gathering here.
@export var clip: StringName = &"PickUp"
var _faded := false
var _fade: StandardMaterial3D
var _label: Label3D
var _top: float = 1.5
func _ready() -> void:
_fade = StandardMaterial3D.new()
_fade.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
_fade.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
_fade.albedo_color = Color(0.45, 0.45, 0.45, 0.6)
for vi in find_children("*", "VisualInstance3D", true, false):
var box := (vi as VisualInstance3D).global_transform * (vi as VisualInstance3D).get_aabb()
_top = maxf(_top, box.end.y - global_position.y)
_label = Label3D.new()
_label.billboard = BaseMaterial3D.BILLBOARD_ENABLED
_label.no_depth_test = true
_label.shaded = false
_label.font_size = 40
_label.outline_size = 10
_label.pixel_size = 0.0075
_label.modulate = COLORS[material]
_label.position = Vector3(0.0, minf(_top, 4.0) + 0.5, 0.0)
_label.visible = false
add_child(_label)
## Top of the point's props (local), for popups.
func top() -> float:
return minf(_top, 4.0)
## Updates the faded look and the floating label (hidden when show is false).
func show_state(charges: int, show: bool, prompt: String) -> void:
var empty := charges <= 0
if empty != _faded:
_faded = empty
for mi in find_children("*", "MeshInstance3D", true, false):
(mi as MeshInstance3D).material_overlay = _fade if empty else null
_label.visible = show
if show:
var text := "%s %d/%d" % [material.capitalize(), charges, max_charges]
_label.text = text if prompt == "" else text + "\n" + prompt

View file

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

View file

@ -0,0 +1,24 @@
class_name GDSyncLink
extends CoopLink
## The co-op wire over GD-Sync (the GDSync autoload; LAN or online): every message is a remote
## call of CoopSession.net_receive on the other machine (the same node path on both, since both
## run main.tscn), reliable or unreliable. The session exposes that function to GD-Sync.
var gdsync: Node
var peer: int = -1
var session: Node
func _init(p_gdsync: Node, p_peer: int, p_session: Node) -> void:
gdsync = p_gdsync
peer = p_peer
session = p_session
func _deliver(kind: String, data: Variant, reliable: bool) -> void:
if closed or gdsync == null or peer < 0:
return
if reliable:
gdsync.call_func_on(peer, session.net_receive, kind, data)
else:
gdsync.call_func_on_unreliable(peer, session.net_receive, kind, data)

View file

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

View file

@ -0,0 +1,313 @@
class_name Interactions
extends Node3D
## The scarecrow's hands: gathering at GatherNodes, buying at the Workbench, repairing damaged
## structures, and dropping the pouch off at the supply shed. Nothing here works in build mode.
## * Focus: the nearest gather point or workbench within its reach, preferring points with
## charges left over used-up ones; nearby points show their charges, the focused one its
## prompt (or why it can't be used).
## * Gather: hold interact by day (D8) at a point with charges left and room in the pouch for
## the whole yield (so a charge is never half wasted).
## The scarecrow is rooted for gather_time looping the point's clip, then yield_amount goes
## into the pouch ("+2 wood" pops up) and one charge is used. Keep holding to gather again.
## Letting go, a hit, fear, nightfall, or a full pouch cancels it.
## * Workbench: press interact by day to open the upgrade menu (UpgradePanel); interact again,
## walking away, or nightfall closes it. Nothing else happens here while it's open.
## * Repair: a damaged structure within REPAIR_REACH comes first. Hold interact for
## repair_time (any phase) to repair it fully for StructureSystem.repair_cost (paid at the
## end); it is refused, once per press, without the materials.
## * Deposit: walking into the Supply Shed zone empties the pouch into the shed.
## * Overnight (the end of the dawn grace) every used point regains regen_per_night charges.
## In co-op each scarecrow has its own Interactions. The partner's, on the host, reads its
## RemoteControls (remote), asks the partner's game to open its own upgrade menu
## (workbench_requested), and leaves the gather labels to the local player's (show_labels).
signal gathered(material: String, amount: int, node: GatherNode)
signal deposited(moved: Dictionary)
signal message(text: String, color: Color)
## A remote kit pressed interact at the workbench by day (its game opens the upgrade menu).
signal workbench_requested
const LABEL_RANGE := 7.0
const REPAIR_REACH := 1.4
const POPUP_TIME := 1.1
const POPUPS := 6
var config: GameConfig
var campaign: CampaignController
var player: PlayerCharacter
var kit: Scarecrow
var zones: FarmZones
## Set by FarmSim.
var structures: StructureSystem
var build: BuildMode
var upgrade_panel: UpgradePanel
## The partner's input on the host (co-op), and whether this one draws the gather labels.
var remote: RemoteControls
var show_labels := true
var nodes: Array[GatherNode] = []
var workbench: Workbench
var focus: Node3D
var gathering: GatherNode
var gather_elapsed: float = 0.0
## Damaged structure in reach (-1 = none) and the one being repaired.
var repair_target: int = -1
var repairing: int = -1
var repair_elapsed: float = 0.0
var _shed: FarmZone
var _interact_requested := false
var _interact_was_held := false
var _denied := false
var _popups: Array[Label3D] = []
var _repair_label: Label3D
var _popup_left := PackedFloat32Array()
func setup(cfg: GameConfig, p_campaign: CampaignController, p_player: PlayerCharacter, p_kit: Scarecrow,
p_zones: FarmZones) -> void:
config = cfg
campaign = p_campaign
player = p_player
kit = p_kit
zones = p_zones
_shed = zones.zone(FarmZone.Kind.SUPPLY_SHED)
for n in zones.find_children("*", "Node3D", true, false):
if n is GatherNode:
nodes.append(n)
elif n is Workbench and workbench == null:
workbench = n
kit.damaged.connect(func(_hp: int) -> void: cancel())
kit.fear_used.connect(func(_p: Vector3, _n: int) -> void: cancel())
_repair_label = Label3D.new()
_repair_label.billboard = BaseMaterial3D.BILLBOARD_ENABLED
_repair_label.no_depth_test = true
_repair_label.shaded = false
_repair_label.font_size = 40
_repair_label.outline_size = 10
_repair_label.pixel_size = 0.0075
_repair_label.modulate = Color(1.0, 0.9, 0.7)
_repair_label.top_level = true
_repair_label.visible = false
add_child(_repair_label)
_popup_left.resize(POPUPS)
for i in POPUPS:
var l := Label3D.new()
l.billboard = BaseMaterial3D.BILLBOARD_ENABLED
l.no_depth_test = true
l.shaded = false
l.font_size = 56
l.outline_size = 12
l.pixel_size = 0.01
l.visible = false
l.top_level = true
l.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(l)
_popups.append(l)
func charges(n: GatherNode) -> int:
return int(campaign.state.gather_charges.get(String(n.name), n.max_charges))
func channeling() -> bool:
return gathering != null or repairing >= 0
func can_shoot() -> bool:
return not channeling() and not (upgrade_panel != null and upgrade_panel.is_open) and not (remote != null and remote.ui_open)
## One physics tick, after the scarecrow kit.
func step(dt: float) -> void:
var held := remote.held(&"interact") if remote != null else Input.is_action_pressed("interact")
var pressed := _interact_requested or (held and not _interact_was_held)
if remote != null:
pressed = remote.take(&"interact")
_interact_requested = false
_interact_was_held = held
if not held:
_denied = false
if not kit.alive or (build != null and build.active) or (remote != null and (remote.build_active or remote.ui_open)):
if upgrade_panel != null:
upgrade_panel.close()
cancel()
repair_target = -1
focus = null
return
var p := Vector2(player.global_position.x, player.global_position.z)
if upgrade_panel != null and upgrade_panel.is_open:
var bench := Vector2(workbench.global_position.x, workbench.global_position.z) if workbench != null else p
if pressed or not campaign.is_daytime() or bench.distance_to(p) > workbench.reach + 0.5 or (build != null and build.active):
upgrade_panel.close()
return
if _shed != null and _shed.contains(player.global_position) and campaign.state.resources.pouch_total() > 0:
var moved := campaign.state.resources.deposit()
deposited.emit(moved)
message.emit("Stored %s in the shed" % ResourceStore.describe(moved), Color(0.85, 0.95, 1.0))
if repairing >= 0:
if not held or structures.repair_cost(repairing).is_empty():
cancel()
return
repair_elapsed += dt
if repair_elapsed >= config.repair_time:
var id := repairing
var cost := structures.repair_cost(id)
cancel()
if structures.repair(id):
message.emit("Repaired (%s)" % ResourceStore.describe(cost), Color(0.6, 1.0, 0.55))
return
if gathering != null:
if not held or _blocker(gathering) != "":
cancel()
return
gather_elapsed += dt
var to := Vector2(gathering.global_position.x - p.x, gathering.global_position.z - p.y)
if to.length_squared() > 1e-4:
player.face_aim(to.normalized(), 0.3)
if gather_elapsed >= config.gather_time:
_finish_gather()
return
repair_target = structures.structure_near(p, REPAIR_REACH, true) if structures != null else -1
if repair_target >= 0:
focus = null
if held and not kit.patching:
var cost := structures.repair_cost(repair_target)
if campaign.state.resources.can_afford(cost):
repairing = repair_target
repair_elapsed = 0.0
player.start_channel(&"Hammering")
elif not _denied:
_denied = true
message.emit("Not enough to repair: need %s more" % ResourceStore.describe(campaign.state.resources.missing(cost)), Color(1.0, 0.8, 0.5))
return
focus = _nearest(p)
if focus is GatherNode and held and not kit.patching:
var why := _blocker(focus)
if why == "":
gathering = focus
gather_elapsed = 0.0
player.start_channel(gathering.clip)
elif not _denied:
_denied = true
message.emit(why, Color(1.0, 0.8, 0.5))
elif focus is Workbench and pressed:
if not campaign.is_daytime():
message.emit("The work area is for daytime", Color(1.0, 0.8, 0.5))
elif upgrade_panel != null:
upgrade_panel.open()
elif remote != null:
workbench_requested.emit()
## Why a point can't be gathered right now ("" if it can).
func _blocker(n: GatherNode) -> String:
if not campaign.is_daytime():
return "Gathering is for daytime"
if charges(n) <= 0:
return "Nothing left here; it grows back overnight"
if campaign.state.resources.pouch_room() < n.yield_amount:
return "Pouch full: drop it off at the supply shed"
return ""
func cancel() -> void:
if gathering != null or repairing >= 0:
gathering = null
gather_elapsed = 0.0
repairing = -1
repair_elapsed = 0.0
player.stop_channel()
## Overnight: every used gather point regains its regen_per_night charges.
func regen_overnight() -> void:
var used := campaign.state.gather_charges
for n in nodes:
var key := String(n.name)
if used.has(key):
var c := int(used[key]) + n.regen_per_night
if c >= n.max_charges:
used.erase(key)
else:
used[key] = c
func _finish_gather() -> void:
var n := gathering
var s := campaign.state
var added := s.resources.add_to_pouch(n.material, n.yield_amount)
var left := charges(n) - 1
s.gather_charges[String(n.name)] = left
cancel()
gathered.emit(n.material, added, n)
_popup("+%d %s" % [added, n.material], n.global_position + Vector3(0.0, n.top() + 1.4, 0.0), GatherNode.COLORS[n.material])
func _nearest(p: Vector2) -> Node3D:
var best: Node3D = null
var best_d := INF
for n in nodes:
var d := Vector2(n.global_position.x, n.global_position.z).distance_to(p)
var score := d + (100.0 if charges(n) <= 0 else 0.0) # used-up points only as a fallback
if d <= n.reach and score < best_d:
best = n
best_d = score
if workbench != null:
var d := Vector2(workbench.global_position.x, workbench.global_position.z).distance_to(p)
if d <= workbench.reach and d < best_d:
best = workbench
best_d = d
return best
func _popup(text: String, at: Vector3, color: Color) -> void:
var slot := 0
for i in POPUPS:
if _popup_left[i] < _popup_left[slot]:
slot = i
var l := _popups[slot]
l.text = text
l.modulate = color
l.global_position = at
l.visible = true
_popup_left[slot] = POPUP_TIME
func _process(delta: float) -> void:
if player == null:
return
var p := player.global_position
for n in nodes if show_labels else []:
var near := Vector2(n.global_position.x - p.x, n.global_position.z - p.z).length() < LABEL_RANGE
var prompt := ""
if n == gathering:
prompt = "Gathering..."
elif n == focus:
var why := _blocker(n)
prompt = "[E / X] Gather" if why == "" else why
n.show_state(charges(n), near and kit.alive, prompt)
if workbench != null and show_labels:
var near := Vector2(workbench.global_position.x - p.x, workbench.global_position.z - p.z).length() < LABEL_RANGE
workbench.show_state(campaign, near and kit.alive, focus == workbench)
var shown := (repairing if repairing >= 0 else repair_target) if show_labels else -1
_repair_label.visible = shown >= 0
if shown >= 0:
var e := campaign.state.structure(shown)
if not e.is_empty():
_repair_label.global_position = Vector3(e["x"], 2.7, e["z"])
var cost := structures.repair_cost(shown)
_repair_label.text = "%s %d/%d\n%s" % [StructureSystem.NAMES[e["type"]], int(e["hp"]), structures.max_hp(e["type"]),
"Repairing..." if repairing >= 0 else "[E / X] Repair (%s)" % ResourceStore.describe(cost)]
for i in POPUPS:
if _popup_left[i] <= 0.0:
continue
_popup_left[i] = maxf(_popup_left[i] - delta, 0.0)
var l := _popups[i]
l.visible = _popup_left[i] > 0.0
l.global_position.y += delta * 1.2
l.modulate.a = clampf(_popup_left[i] / 0.4, 0.0, 1.0)
func _unhandled_input(event: InputEvent) -> void:
if remote == null and event.is_action_pressed("interact", false):
_interact_requested = true

View file

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

717
game/scripts/loot_system.gd Normal file
View file

@ -0,0 +1,717 @@
class_name LootSystem
extends Node3D
## Runtime state and feedback of everything thieves can take, on top of the persistent record in
## FarmState. Three categories share one id space (1..item_count):
## CROP ids 1..unit_count: one crop unit each (CropUnit.unit_id), at home in its plot.
## ANIMAL the next animal_count ids: one animal each (AnimalSystem moves it), at home in the pen.
## SUPPLY the last SACKS ids: sacks for bundles of the shed's stock. A sack at home is "in the
## shed": it can be claimed while the shed has stock, and the thief takes it from the pile
## of the material the shed holds most of. Picking it up fills it with up to
## supply_bundle units of that material (never more than there is).
## Each item has a status:
## HOME in its plot, the pen, or the shed. One thief at a time may claim it: it is then
## targeted ("!" marker) and, while being taken, shows a filling progress ring.
## CARRIED on a thief, outlined in its category's color, with a badge over it.
## DROPPED its carrier was stopped. A crop or a sack lies on the ground, glowing; an animal is
## loose and makes for the farm's edge (AnimalSystem). The scarecrow walks up to it to
## recover it (a loose animal then follows it, at most max_following_animals at once),
## and another thief may claim it.
## FOLLOWING animals only: following the scarecrow; back inside the pen it is home.
## LOST carried (or, for an animal, wandered) off the farm. Crops and animals are recorded
## in FarmState and gone for the rest of the run; a sack's contents are gone and the
## sack is free for the next theft.
## Supplies in a carried or dropped sack still count as on the farm (FarmState.supplies_in_transit).
## Claims and carriers are enemy handles (id + generation), so a stale handle from a reused enemy
## slot can never move an item. Every change emits loot_event (toasts now, sounds later); steals,
## recoveries, strays, and supply losses count toward the night's record.
enum Category { CROP, ANIMAL, SUPPLY }
enum Status { HOME, CARRIED, DROPPED, LOST, FOLLOWING }
enum Threat { NONE, TARGETED, CARRIED, DROPPED }
## EnemySystem.want for a thief with no set target (it goes by GameConfig.target_weights).
const ANY := 255
## Every category (a bit per Category), for claim()'s allowed mask.
const ALL := 7
const SACKS := 6
const CATEGORY_KEYS: Array[String] = ["crops", "animals", "supplies"]
const CATEGORY_COLORS := {
Category.CROP: Color(1.0, 0.8, 0.15),
Category.ANIMAL: Color(1.0, 0.45, 0.75),
Category.SUPPLY: Color(0.35, 0.8, 1.0),
}
## Badge interiors (loot_icon.gdshader): fill and center per category.
const BADGE_FILL := {
Category.CROP: [Color(1.0, 0.82, 0.18), Color(0.32, 0.18, 0.07)],
Category.ANIMAL: [Color(1.0, 0.62, 0.78), Color(1.0, 0.92, 0.95)],
Category.SUPPLY: [Color(0.78, 0.62, 0.4), Color(0.35, 0.8, 1.0)],
}
const TOKEN_SCENE := "res://assets/farm/ithappy/farm/prefabs/assets/plant/plant_007.tscn"
const SACK_SCENE := "res://assets/farm/ithappy/farm/prefabs/assets/prop/bag_002.tscn"
const THREAT_COLORS := {
Threat.TARGETED: Color(1.0, 0.6, 0.1),
Threat.CARRIED: Color(1.0, 0.22, 0.15),
Threat.DROPPED: Color(1.0, 0.9, 0.25),
}
## kind: &"targeted", &"stolen", &"dropped", &"recovered", &"returned" (back home without the
## scarecrow's help: auto at dawn, or an animal dropped inside the pen), &"lost", &"following",
## &"follow_full" (the scarecrow already leads the most animals it can), &"strayed" (an animal
## wandered out of an open pen).
signal loot_event(kind: StringName, id: int, position: Vector3)
var campaign: CampaignController
var enemies: EnemySystem
var config: GameConfig
## Set by FarmSim: animal positions and the shed's piles (where supply thieves stand).
var animals: AnimalSystem
var shed_stock: ShedStock
## Crop units (ids 1..unit_count), then animals, then sacks.
var unit_count: int = 0
var animal_count: int = 0
var item_count: int = 0
# Per item, indexed by id (index 0 unused).
var category := PackedByteArray()
var status := PackedByteArray()
var holder := PackedInt32Array()
var progress := PackedFloat32Array()
## Crops: the plot position. Sacks: the pile spot it is taken from (set when claimed).
var home := PackedVector2Array()
var ground := PackedVector2Array()
## Sacks: the material and how much of it they hold.
var sack_material: Array[String] = []
var sack_amount := PackedInt32Array()
## What the HUD should point at this frame, and where (filled in _process).
var threat := PackedByteArray()
var focus := PackedVector3Array()
var _units: Array[CropUnit] = []
var _markers: Array[Label3D] = []
var _rings: Array[MeshInstance3D] = []
var _ring_mats: Array[ShaderMaterial] = []
var _tokens: Array[Node3D] = []
var _icons: Array[MeshInstance3D] = []
var _icon_mats: Array[ShaderMaterial] = []
var _warned := PackedByteArray()
var _outline := {} # Category -> StandardMaterial3D
var _rng := RandomNumberGenerator.new()
var _time: float = 0.0
func setup(p_campaign: CampaignController, units: Array[CropUnit], p_enemies: EnemySystem, p_animal_count: int = 0) -> void:
campaign = p_campaign
config = p_campaign.config
enemies = p_enemies
unit_count = units.size()
animal_count = p_animal_count
item_count = unit_count + animal_count + SACKS
var n := item_count + 1
for a: PackedByteArray in [category, status, threat, _warned]:
a.resize(n)
for a: PackedInt32Array in [holder, sack_amount]:
a.resize(n)
progress.resize(n)
home.resize(n)
ground.resize(n)
focus.resize(n)
sack_material.resize(n)
sack_material.fill("")
_units.resize(unit_count + 1)
_markers.resize(n)
_rings.resize(n)
_ring_mats.resize(n)
_tokens.resize(n)
_icons.resize(n)
_icon_mats.resize(n)
_rng.seed = 20261003
for c: Category in CATEGORY_COLORS:
_outline[c] = outline_material(CATEGORY_COLORS[c])
var ring_shader := load("res://game/resources/steal_ring.gdshader") as Shader
var icon_shader := load("res://game/resources/loot_icon.gdshader") as Shader
var token_scene := load(TOKEN_SCENE) as PackedScene
var sack_scene := load(SACK_SCENE) as PackedScene
for id in range(1, n):
category[id] = _category_of(id)
_markers[id] = _marker()
_ring_mats[id] = ShaderMaterial.new()
_ring_mats[id].shader = ring_shader
_rings[id] = _billboard(1.1, _ring_mats[id])
_icon_mats[id] = ShaderMaterial.new()
_icon_mats[id].shader = icon_shader
var fill: Array = BADGE_FILL[category[id]]
_icon_mats[id].set_shader_parameter("fill_color", fill[0])
_icon_mats[id].set_shader_parameter("center_color", fill[1])
_icons[id] = _billboard(0.9, _icon_mats[id])
var token: Node3D = null
match category[id]:
Category.CROP:
token = token_scene.instantiate() as Node3D
token.scale = Vector3.ONE * 0.6
Category.SUPPLY:
token = sack_scene.instantiate() as Node3D
token.scale = Vector3.ONE * 0.85
StructureSystem._strip_collision(token)
if token != null:
token.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
for mi in token.find_children("*", "MeshInstance3D", true, false):
(mi as MeshInstance3D).material_overlay = _outline[category[id]]
add_child(token)
_tokens[id] = token
for u in units:
_units[u.unit_id] = u
home[u.unit_id] = Vector2(u.global_position.x, u.global_position.z)
sync_from_state()
## Every item back home, or gone if the farm state records it as lost (new vacation, retry,
## load). Clears all claims and empties every sack.
func sync_from_state() -> void:
var s := campaign.state
for id in range(1, item_count + 1):
match category[id]:
Category.CROP:
status[id] = Status.LOST if s.is_crop_lost(id) else Status.HOME
_units[id].visible = status[id] == Status.HOME
Category.ANIMAL:
status[id] = Status.LOST if s.is_animal_lost(animal_index(id)) else Status.HOME
Category.SUPPLY:
status[id] = Status.HOME
sack_amount[id] = 0
holder[id] = -1
progress[id] = 0.0
_warned[id] = 0
s.supplies_in_transit = 0
update_visuals()
## Co-op host: every item's status, holder (enemy handle), steal progress, ground spot, and sack.
func replica_record() -> Dictionary:
var shown := PackedByteArray()
shown.resize(unit_count + 1)
for id in range(1, unit_count + 1):
shown[id] = 1 if _units[id].visible else 0
return {"status": status, "holder": holder, "progress": progress, "ground": ground, "amount": sack_amount,
"material": sack_material.duplicate(), "transit": campaign.state.supplies_in_transit, "units": shown}
## Co-op partner: shows the host's items (resolve: host enemy handle -> this machine's handle).
func apply_replica(rec: Dictionary, resolve: Callable) -> void:
var st: PackedByteArray = rec.get("status", PackedByteArray())
if st.size() != status.size():
return
status = st
var hosts: PackedInt32Array = rec["holder"]
for id in hosts.size():
holder[id] = int(resolve.call(hosts[id])) if hosts[id] >= 0 else -1
progress = rec["progress"]
ground = rec["ground"]
sack_amount = rec["amount"]
for i in mini(sack_material.size(), (rec["material"] as Array).size()):
sack_material[i] = String(rec["material"][i])
campaign.state.supplies_in_transit = int(rec.get("transit", 0))
var shown: PackedByteArray = rec.get("units", PackedByteArray())
for id in range(1, mini(unit_count + 1, shown.size())):
_units[id].visible = shown[id] == 1
func is_valid_unit(id: int) -> bool:
return id >= 1 and id <= item_count
func is_home(id: int) -> bool:
return is_valid_unit(id) and status[id] == Status.HOME
## Animal ids in FarmState (1..animal_count) <-> item ids.
func animal_index(id: int) -> int:
return id - unit_count
func animal_item(index: int) -> int:
return unit_count + index
func first_sack() -> int:
return unit_count + animal_count + 1
func is_claimed_by(id: int, handle: int) -> bool:
return is_valid_unit(id) and handle >= 0 and holder[id] == handle \
and (status[id] == Status.HOME or status[id] == Status.DROPPED)
## Where a thief has to go for this item: its plot, the animal itself, the shed pile, or where it
## was dropped.
func position_of(id: int) -> Vector2:
if category[id] == Category.ANIMAL and animals != null:
return animals.position(animal_index(id))
return ground[id] if status[id] == Status.DROPPED else home[id]
## Seconds a thief needs to take this item.
func steal_time(id: int) -> float:
match category[id]:
Category.ANIMAL:
return config.animal_capture_time
Category.SUPPLY:
return config.supply_steal_time
return config.crop_steal_time
## Claims an item for a thief, only from the allowed categories (a bit per Category: what its
## enemy type takes): the nearest unclaimed dropped item in view within range (in clear view
## unless need_line is off, for flyers), else one at home in the wanted category (a random crop or
## animal, a sack at the pile of the material the shed holds most of), else in another allowed
## category, picked by target_weights. Returns the id, or -1 if nothing is left.
func claim(handle: int, from: Vector2, nav: FarmNavigation, view_range: float, want: int = ANY,
allowed: int = ALL, need_line: bool = true) -> int:
var best := -1
var best_d := view_range
for id in range(1, item_count + 1):
if status[id] == Status.DROPPED and holder[id] == -1 and (allowed & (1 << category[id])) != 0:
var at := position_of(id)
var d := at.distance_to(from)
if d < best_d and (not need_line or nav.line_clear(from.x, from.y, at.x, at.y)):
best = id
best_d = d
if best < 0:
for c in _preference(want):
if (allowed & (1 << c)) == 0:
continue
best = _claim_home(c)
if best > 0:
break
if best < 0:
return -1
holder[best] = handle
progress[best] = 0.0
loot_event.emit(&"targeted", best, _world(position_of(best)))
return best
## Whether a thief could claim anything at home in this category right now.
func available(c: Category) -> bool:
match c:
Category.SUPPLY:
return campaign.state.resources.shed_total() > 0 and _free_sack() > 0
_:
for id in _ids(c):
if status[id] == Status.HOME and holder[id] == -1:
return true
return false
func release(id: int, handle: int) -> void:
if is_claimed_by(id, handle):
holder[id] = -1
progress[id] = 0.0
func set_progress(id: int, handle: int, value: float) -> void:
if is_claimed_by(id, handle):
progress[id] = clampf(value, 0.0, 1.0)
## The claiming thief takes the item. Returns false if it doesn't hold the claim, or (for a sack)
## the shed has nothing left; the claim is released then.
func pick_up(id: int, handle: int) -> bool:
if not is_claimed_by(id, handle):
return false
var s := campaign.state
var at := position_of(id)
match category[id]:
Category.CROP:
_units[id].visible = false
s.record_event("crops_stolen")
Category.ANIMAL:
s.record_event("animals_stolen")
Category.SUPPLY:
if status[id] == Status.HOME:
var r := s.resources
var m := sack_material[id]
if m == "" or int(r.shed[m]) <= 0:
m = r.most_stocked()
if m == "":
release(id, handle)
return false
var amount := mini(config.supply_bundle, int(r.shed[m]))
r.shed[m] = int(r.shed[m]) - amount
sack_material[id] = m
sack_amount[id] = amount
s.supplies_in_transit += amount
s.record_event("supplies_stolen", amount)
if r.shed_total() == 0:
s.shed_raided = true
status[id] = Status.CARRIED
progress[id] = 0.0
loot_event.emit(&"stolen", id, _world(at))
return true
## The carrier was stopped at (x, z).
func drop(id: int, handle: int, x: float, z: float) -> void:
if not is_valid_unit(id) or status[id] != Status.CARRIED or holder[id] != handle:
return
status[id] = Status.DROPPED
holder[id] = -1
ground[id] = Vector2(x, z)
if category[id] == Category.ANIMAL and animals != null:
animals.place(animal_index(id), ground[id])
loot_event.emit(&"dropped", id, _world(ground[id]))
## The carrier left the farm with the item: it is lost for good (a sack's contents are).
func escape(id: int, handle: int) -> void:
if not is_valid_unit(id) or status[id] != Status.CARRIED or holder[id] != handle:
return
_lose(id)
## The scarecrow got a dropped item back: a crop returns to its plot, a sack to the shed, and a
## loose animal starts following (if the scarecrow has room for another).
func recover(id: int) -> bool:
if not is_valid_unit(id) or status[id] != Status.DROPPED:
return false
var s := campaign.state
match category[id]:
Category.ANIMAL:
if followers() >= config.max_following_animals:
return false
status[id] = Status.FOLLOWING
holder[id] = -1
if animals != null:
animals.start_following(animal_index(id))
loot_event.emit(&"following", id, _world(position_of(id)))
return true
Category.CROP:
_return_home(id)
s.record_event("crops_recovered")
Category.SUPPLY:
s.record_event("supplies_recovered", sack_amount[id])
loot_event.emit(&"recovered", id, _world(ground[id]))
_empty_sack(id, true)
return true
loot_event.emit(&"recovered", id, _world(home[id]))
return true
## An animal (loose, or following the scarecrow) is back inside the pen.
func animal_home(id: int) -> void:
if not is_valid_unit(id) or category[id] != Category.ANIMAL:
return
if status[id] != Status.FOLLOWING and status[id] != Status.DROPPED:
return
var led := status[id] == Status.FOLLOWING
status[id] = Status.HOME
holder[id] = -1
progress[id] = 0.0
if led:
campaign.state.record_event("animals_recovered")
loot_event.emit(&"recovered" if led else &"returned", id, _world(position_of(id)))
## An animal at home walks out of the open pen: it is loose now.
func animal_strays(id: int) -> void:
if not is_valid_unit(id) or category[id] != Category.ANIMAL or status[id] != Status.HOME or holder[id] != -1:
return
status[id] = Status.DROPPED
ground[id] = position_of(id)
campaign.state.record_event("animals_strayed")
loot_event.emit(&"strayed", id, _world(ground[id]))
## A loose animal got off the farm on its own.
func animal_escaped(id: int) -> void:
if not is_valid_unit(id) or category[id] != Category.ANIMAL or status[id] != Status.DROPPED:
return
_lose(id)
## End of the dawn grace (D6): dropped items still on the ground go home (crops to their plots,
## sacks to the shed); loose and following animals are back in the pen.
func return_dropped() -> void:
for id in range(1, item_count + 1):
var st := status[id]
if st == Status.DROPPED or (st == Status.FOLLOWING and category[id] == Category.ANIMAL):
var at := _world(position_of(id))
if category[id] == Category.SUPPLY:
_empty_sack(id, true)
else:
_return_home(id)
loot_event.emit(&"returned", id, at)
## Settles what a removed enemy held: a killed carrier drops its loot, one that left at the end
## of the night takes it along, and any claim is released.
func on_enemy_removed(handle: int, reason: EnemySystem.Removal, x: float, z: float, carried: int, targeted: int) -> void:
if carried >= 0:
if reason == EnemySystem.Removal.KILLED:
drop(carried, handle, x, z)
elif reason == EnemySystem.Removal.LEFT:
escape(carried, handle)
if targeted >= 0:
release(targeted, handle)
## Physics tick: the scarecrow recovers dropped items it walks up to (a loose animal starts
## following it; with no room left it says so once per approach).
## Co-op: which scarecrow (0 = player 1, 1 = player 2) recovered last (a loose animal follows it).
var recoverer: int = 0
## Recovery by touch for one scarecrow (who: 0 = player 1, 1 = player 2; call once each).
func step(scarecrow: Vector2, who: int = 0) -> void:
recoverer = who
var r2 := config.pickup_radius * config.pickup_radius
for id in range(1, item_count + 1):
if status[id] != Status.DROPPED:
_warned[id] = 0
continue
var near := position_of(id).distance_squared_to(scarecrow) <= r2
if not near:
_warned[id] = 0
elif not recover(id) and _warned[id] == 0:
_warned[id] = 1
loot_event.emit(&"follow_full", id, _world(position_of(id)))
func followers() -> int:
return count(Status.FOLLOWING, Category.ANIMAL)
## Items with this status, in one category (or all, cat = -1).
func count(which: Status, cat: int = -1) -> int:
var n := 0
for id in range(1, item_count + 1):
if status[id] == which and (cat < 0 or category[id] == cat):
n += 1
return n
## "crop", "pig", "sack of wood": what an item is, for messages.
func noun(id: int) -> String:
match category[id]:
Category.ANIMAL:
return animals.kind(animal_index(id)) if animals != null else "animal"
Category.SUPPLY:
return "%d %s" % [sack_amount[id], sack_material[id]] if sack_amount[id] > 0 else "supplies"
return "crop"
func _process(delta: float) -> void:
_time += delta
update_visuals()
## Places markers, rings, tokens, and badges, and fills threat / focus for the HUD.
func update_visuals() -> void:
var bob := sin(_time * 5.0)
for id in range(1, item_count + 1):
var st := status[id]
var cat := category[id]
var h := position_of(id) if st == Status.HOME or st == Status.FOLLOWING else home[id]
var top := 2.0 if cat == Category.ANIMAL else 3.2
var targeted := st == Status.HOME and holder[id] >= 0
var marker := _markers[id]
var ring := _rings[id]
ring.visible = targeted and progress[id] > 0.0
marker.visible = targeted
if targeted:
marker.position = Vector3(h.x, (top + 0.55 if ring.visible else top) + bob * 0.12, h.y)
if ring.visible:
ring.position = Vector3(h.x, top - 0.75, h.y)
_ring_mats[id].set_shader_parameter("progress", progress[id])
var token := _tokens[id]
var icon := _icons[id]
threat[id] = Threat.TARGETED if targeted else Threat.NONE
focus[id] = Vector3(h.x, 2.0, h.y)
var shown := false
match st:
Status.CARRIED:
var d := enemies.resolve_handle(holder[id]) if enemies != null else -1
var p := enemies.visual_position(d) if d >= 0 else h
if token != null:
token.position = Vector3(p.x, config.combat_height + 0.25, p.y)
token.rotation.y = _time * 1.5
icon.position = Vector3(p.x, config.combat_height + 1.55, p.y)
_icon_mats[id].set_shader_parameter("edge_color", THREAT_COLORS[Threat.CARRIED])
_icon_mats[id].set_shader_parameter("pulse", 0.0)
threat[id] = Threat.CARRIED
focus[id] = Vector3(p.x, config.combat_height + 0.25, p.y)
shown = true
Status.DROPPED:
var g := position_of(id)
if token != null:
token.position = Vector3(g.x, 0.15 + (bob + 1.0) * 0.12, g.y)
token.rotation.y = _time * 0.8
icon.position = Vector3(g.x, 1.75 + bob * 0.12, g.y)
_icon_mats[id].set_shader_parameter("edge_color", THREAT_COLORS[Threat.DROPPED])
_icon_mats[id].set_shader_parameter("pulse", 0.5 + 0.5 * sin(_time * 7.0))
threat[id] = Threat.DROPPED
focus[id] = Vector3(g.x, 0.6, g.y)
shown = true
if token != null:
token.visible = shown
icon.visible = shown
## An unshaded, front-culled shell drawn over a mesh: a colored outline.
static func outline_material(color: Color) -> StandardMaterial3D:
var m := StandardMaterial3D.new()
m.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
m.cull_mode = BaseMaterial3D.CULL_FRONT
m.grow = true
m.grow_amount = 0.05
m.albedo_color = color
return m
func outline_for(c: Category) -> StandardMaterial3D:
return _outline[c]
func _category_of(id: int) -> Category:
if id <= unit_count:
return Category.CROP
if id <= unit_count + animal_count:
return Category.ANIMAL
return Category.SUPPLY
func _ids(c: Category) -> Array:
match c:
Category.CROP:
return range(1, unit_count + 1)
Category.ANIMAL:
return range(unit_count + 1, unit_count + animal_count + 1)
return range(first_sack(), item_count + 1)
## The categories to try, in order: the wanted one first (all of them by weight for ANY), then
## the others in a weighted random order.
func _preference(want: int) -> Array[int]:
var left: Array[int] = [Category.CROP, Category.ANIMAL, Category.SUPPLY]
var out: Array[int] = []
if want != ANY and left.has(want):
out.append(want)
left.erase(want)
while not left.is_empty():
var total := 0.0
for c in left:
total += _weight(c)
var pick := left[0]
if total > 0.0:
var roll := _rng.randf() * total
for c in left:
roll -= _weight(c)
if roll <= 0.0:
pick = c
break
out.append(pick)
left.erase(pick)
return out
func _weight(c: int) -> float:
return maxf(float(config.target_weights.get(CATEGORY_KEYS[c], 1.0)), 0.0)
func _claim_home(c: int) -> int:
if c == Category.SUPPLY:
var r := campaign.state.resources
var m := r.most_stocked()
var sack := _free_sack()
if m == "" or sack < 0:
return -1
sack_material[sack] = m
home[sack] = shed_stock.spot(m) if shed_stock != null else Vector2.ZERO
return sack
var free: Array[int] = []
for id in _ids(c):
if status[id] == Status.HOME and holder[id] == -1:
free.append(id)
if free.is_empty():
return -1
return free[_rng.randi() % free.size()]
func _free_sack() -> int:
for id in range(first_sack(), item_count + 1):
if status[id] == Status.HOME and holder[id] == -1:
return id
return -1
func _lose(id: int) -> void:
var s := campaign.state
var at := _world(position_of(id))
holder[id] = -1
match category[id]:
Category.CROP:
status[id] = Status.LOST
s.lose_crop(id)
_units[id].visible = false
Category.ANIMAL:
status[id] = Status.LOST
s.lose_animal(animal_index(id))
Category.SUPPLY:
s.record_event("supplies_lost", sack_amount[id])
loot_event.emit(&"lost", id, at)
_empty_sack(id, false)
return
loot_event.emit(&"lost", id, at)
## A sack is done with: its contents go back to the shed (or are gone), and it is free again.
func _empty_sack(id: int, to_shed: bool) -> void:
var s := campaign.state
if to_shed and sack_material[id] != "":
s.resources.shed[sack_material[id]] = int(s.resources.shed[sack_material[id]]) + sack_amount[id]
s.supplies_in_transit = maxi(s.supplies_in_transit - sack_amount[id], 0)
sack_amount[id] = 0
status[id] = Status.HOME
holder[id] = -1
progress[id] = 0.0
func _return_home(id: int) -> void:
status[id] = Status.HOME
holder[id] = -1
progress[id] = 0.0
if category[id] == Category.CROP:
_units[id].visible = true
func _world(p: Vector2) -> Vector3:
return Vector3(p.x, 0.0, p.y)
func _marker() -> Label3D:
var l := Label3D.new()
l.text = "!"
l.font_size = 128
l.outline_size = 28
l.pixel_size = 0.006
l.modulate = THREAT_COLORS[Threat.TARGETED]
l.outline_modulate = Color(0.1, 0.05, 0.0)
l.billboard = BaseMaterial3D.BILLBOARD_ENABLED
l.no_depth_test = true
l.shaded = false
l.visible = false
l.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(l)
return l
func _billboard(size: float, mat: ShaderMaterial) -> MeshInstance3D:
var quad := QuadMesh.new()
quad.size = Vector2(size, size)
var mi := MeshInstance3D.new()
mi.mesh = quad
mi.material_override = mat
mi.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
mi.visible = false
mi.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(mi)
return mi

View file

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

384
game/scripts/main.gd Normal file
View file

@ -0,0 +1,384 @@
class_name Main
extends Node
## The game's entry scene (game/scenes/main.tscn): the farm (farm.tscn) with the menus over it.
## * Starts at the main menu: the tree is paused (the farm stands still) and a camera slowly
## circles the farm behind the menu; the HUD is hidden.
## * New vacation (asks first when it would replace a save), Continue (the saved morning,
## SaveGame; refused with the reason when the save can't be used), Settings, Quit.
## * During play, Escape / Start pauses (PauseMenu): the tree pauses, so the simulation tick,
## timers, enemies, and game sounds all freeze. Resume, Restart the night (asks first),
## Settings, Save & quit to menu, Quit the game (asks first).
## * Every morning is autosaved (CampaignController.save_path). Back at the menu the farm is
## put back at that morning without saving again, so the menu never changes the save.
## * Settings (GameSettings) load at start and are applied and saved on every change.
## * Play with a friend (CoopMenu): host (continue or start a vacation, then the lobby opens,
## CoopLobby) or join (the games found). When both are in, the farm's CoopSession takes over
## over GD-Sync (GDSyncLink), with voice chat. In co-op the menus don't pause the farm; the
## host's leaving ends the partner's game (back to this menu, which says why), the partner's
## leaving leaves the host alone. [M] mutes the microphone.
## Main processes while paused; the farm doesn't. Tests set save_path and settings_path
## before adding it to the tree.
enum Screen { MENU, PLAYING, PAUSED }
const ORBIT_CENTER := Vector3(17.0, 0.0, -15.0)
const ORBIT_RADIUS := 44.0
const ORBIT_HEIGHT := 26.0
const ORBIT_SPEED := 0.035
var save_path := SaveGame.PATH
var settings_path := GameSettings.PATH
var screen: Screen = Screen.MENU
var settings: GameSettings
var quitting := false
## Why the last co-op game ended, for the main menu after the scene reloads.
static var notice := ""
var lobby: CoopLobby
var coop_hud: CoopHud
@onready var farm: Node3D = $Farm
@onready var sim: FarmSim = $Farm/FarmSim
@onready var main_menu: MainMenu = $Menus/MainMenu
@onready var pause_menu: PauseMenu = $Menus/PauseMenu
@onready var settings_menu: SettingsMenu = $Menus/SettingsMenu
@onready var confirm: ConfirmBox = $Menus/ConfirmBox
@onready var coop_menu: CoopMenu = $Menus/CoopMenu
var _menu_camera: Camera3D
var _orbit: float = 0.6
func _ready() -> void:
get_tree().auto_accept_quit = false # the window's close button goes through quit_game()
process_mode = Node.PROCESS_MODE_ALWAYS
farm.process_mode = Node.PROCESS_MODE_PAUSABLE
settings = GameSettings.load_from(settings_path)
settings.apply(get_viewport(), sim.config)
sim.campaign.save_path = save_path
if sim.end_panel != null:
sim.end_panel.has_menu = true
sim.end_panel.menu_requested.connect(to_menu)
if sim.tutorial != null:
sim.tutorial.enabled = settings.show_tips
main_menu.continue_requested.connect(continue_vacation)
main_menu.new_requested.connect(_ask_new_vacation)
main_menu.settings_requested.connect(_open_settings)
main_menu.quit_requested.connect(quit_game)
pause_menu.resume_requested.connect(resume)
pause_menu.restart_requested.connect(func() -> void:
confirm.ask("Restart night %d from this morning? Everything since the morning is lost." % sim.campaign.state.night,
"Restart the night", restart_night))
pause_menu.settings_requested.connect(_open_settings)
pause_menu.menu_requested.connect(to_menu)
pause_menu.quit_requested.connect(func() -> void:
confirm.ask("Quit the game? Continue picks up at the morning of day %d." % sim.campaign.state.night, "Quit", quit_game))
settings_menu.changed.connect(_on_settings_changed)
settings_menu.closed.connect(_on_settings_closed)
lobby = CoopLobby.new()
lobby.name = "Lobby"
add_child(lobby)
main_menu.coop_requested.connect(func() -> void:
main_menu.close()
coop_menu.open(SaveGame.read(save_path), sim.config.campaign_nights, settings.player_name))
coop_menu.back_requested.connect(func() -> void:
lobby.leave()
coop_menu.close()
show_main_menu())
coop_menu.host_requested.connect(_host_coop)
coop_menu.search_requested.connect(func(mode: CoopLobby.Mode, player: String) -> void:
_remember_name(player)
lobby.search(mode, player))
coop_menu.join_requested.connect(func(n: String) -> void: lobby.join(n))
coop_menu.join_address_requested.connect(func(a: String) -> void:
_remember_name(coop_menu.player_name())
lobby.join_address(a, coop_menu.player_name()))
lobby.status_changed.connect(func(text: String) -> void:
if coop_menu.is_open:
coop_menu.set_status(text))
lobby.failed.connect(func(text: String) -> void:
if coop_menu.is_open:
coop_menu.set_status(text)
elif sim.toasts != null:
sim.toasts.push(text, Color(1.0, 0.6, 0.4)))
lobby.lobbies_found.connect(func(list: Array) -> void: coop_menu.show_lobbies(list))
lobby.partner_arrived.connect(_on_partner_arrived)
lobby.joined.connect(_on_joined)
lobby.other_left.connect(_on_other_left)
var session := sim.coop
session.process_mode = Node.PROCESS_MODE_ALWAYS # a join arrives while the menus pause the farm
if lobby.gdsync != null:
lobby.gdsync.expose_func(session.net_receive) # before anyone can call it
session.welcomed.connect(_on_welcomed)
session.ended.connect(_on_session_ended)
coop_hud = CoopHud.new()
coop_hud.name = "CoopHud"
coop_hud.setup(sim, session, lobby)
var hud_layer := farm.get_node_or_null("Hud")
if hud_layer != null:
hud_layer.add_child(coop_hud)
if sim.audio != null:
sim.audio.wire_buttons($Menus)
_menu_camera = Camera3D.new()
_menu_camera.fov = 50.0
add_child(_menu_camera)
show_main_menu()
func _process(delta: float) -> void:
if screen == Screen.MENU:
_orbit += ORBIT_SPEED * delta
_place_menu_camera()
func show_main_menu() -> void:
screen = Screen.MENU
get_tree().paused = true
_set_hud(false)
pause_menu.close()
_place_menu_camera()
_menu_camera.make_current()
main_menu.open(SaveGame.read(save_path), sim.config.campaign_nights)
main_menu.notice.text = notice
notice = ""
## Continue: the saved morning, if it can be used.
func continue_vacation() -> bool:
var saved := SaveGame.read(save_path)
if saved.status != SaveGame.Status.OK:
main_menu.open(saved, sim.config.campaign_nights)
if sim.audio != null:
sim.audio.ui("error")
return false
_play()
sim.campaign.load_state(saved.state)
return true
## New vacation: a fresh farm, the morning of night 1 (saved at once, replacing any save).
func new_vacation() -> void:
_play()
sim.campaign.new_campaign()
func pause() -> void:
if screen != Screen.PLAYING:
return
screen = Screen.PAUSED
var coop := 0
if sim.coop.is_host():
coop = 1
elif sim.coop.is_client():
coop = 2
if coop == 0:
get_tree().paused = true
else:
sim.freeze_local(true) # co-op: the farm doesn't stop for one player's menu
pause_menu.open(sim.campaign, coop)
func resume() -> void:
if screen != Screen.PAUSED:
return
confirm.close()
settings_menu.close()
pause_menu.close()
screen = Screen.PLAYING
get_tree().paused = false
if sim.local_frozen:
sim.freeze_local(false)
func restart_night() -> void:
resume()
sim.campaign.retry_night()
## Back to the main menu, with the farm reset to the saved morning (nothing is saved). In co-op
## the host ends the game for both; a partner leaves (their game resets).
func to_menu() -> void:
confirm.close()
settings_menu.close()
if sim.coop.is_client():
_leave_as_partner("")
return
sim.coop.stop()
lobby.leave()
var c := sim.campaign
c.save_path = ""
if c.outcome == CampaignController.Outcome.VACATION_COMPLETE or not SaveGame.exists(save_path):
c.new_campaign()
else:
c.retry_night()
c.save_path = save_path
show_main_menu()
## Quits (the save is the morning's; nothing else to write): the farm goes first, and the audio
## server gets a moment to drop its stopped sounds.
func quit_game() -> void:
if quitting:
return
quitting = true
sim.coop.stop()
lobby.leave()
if is_instance_valid(farm):
farm.queue_free()
await get_tree().process_frame
await get_tree().create_timer(0.2, true, false, true).timeout
get_tree().quit()
func _notification(what: int) -> void:
if what == NOTIFICATION_WM_CLOSE_REQUEST:
quit_game()
func _play() -> void:
main_menu.close()
confirm.close()
settings_menu.close()
pause_menu.close()
_set_hud(true)
sim.camera.make_current()
screen = Screen.PLAYING
get_tree().paused = false
## Hosting: the vacation first (the save, or a new one), then the lobby opens; the friend can
## join any time.
func _host_coop(mode: CoopLobby.Mode, player: String, resume: bool) -> void:
_remember_name(player)
var go := func() -> void:
coop_menu.close()
if resume:
if not continue_vacation():
return
else:
new_vacation()
lobby.host(mode, player)
if not resume and SaveGame.read(save_path).status == SaveGame.Status.OK:
confirm.ask("Start a new vacation? It replaces your saved one.", "New vacation", go)
else:
go.call()
func _on_partner_arrived(client_id: int) -> void:
var gd := lobby.gdsync
gd.expose_func(sim.coop.net_receive)
var link := GDSyncLink.new(gd, client_id, sim.coop)
sim.coop.start_host(sim, link, lobby.my_name, String(gd.player_get_username(client_id, "Friend")))
sim.coop.start_voice(gd, [lobby.my_id(), client_id], settings.microphone)
func _on_joined(host_id: int) -> void:
var gd := lobby.gdsync
gd.expose_func(sim.coop.net_receive)
var link := GDSyncLink.new(gd, host_id, sim.coop)
sim.coop.start_client(sim, link, lobby.my_name)
sim.coop.start_voice(gd, [host_id, lobby.my_id()], settings.microphone)
coop_menu.set_status("Joined: waiting for the farm...")
func _on_welcomed() -> void:
coop_menu.close()
_play()
func _on_other_left(_client_id: int) -> void:
if sim.coop.is_host():
sim.coop.stop() # the host plays on alone; the lobby stays open
elif sim.coop.is_client():
sim.coop.stop("The host left the game")
func _on_session_ended(reason: String) -> void:
_leave_as_partner(reason)
## A partner's game is a replica of the host's: leaving resets it by reloading the scene.
func _leave_as_partner(reason: String) -> void:
notice = reason
sim.coop.stop()
lobby.leave()
get_tree().paused = false
get_tree().reload_current_scene.call_deferred()
func _remember_name(player: String) -> void:
if player != settings.player_name:
settings.player_name = player
settings.save_to(settings_path)
func _ask_new_vacation() -> void:
var saved := SaveGame.read(save_path)
if saved.status == SaveGame.Status.OK:
confirm.ask("Start a new vacation? It replaces your saved one (the morning of day %d of %d)." % [saved.state.night,
sim.config.campaign_nights], "New vacation", new_vacation)
else:
new_vacation()
func _open_settings() -> void:
pause_menu.visible = false # one menu at a time
settings_menu.open(settings)
func _on_settings_changed() -> void:
settings.apply(get_viewport(), sim.config)
sim.coop.set_microphone(settings.microphone)
if sim.tutorial != null:
sim.tutorial.enabled = settings.show_tips
var err := settings.save_to(settings_path)
if err != OK:
push_warning("Couldn't save settings to %s: %s" % [settings_path, error_string(err)])
func _on_settings_closed() -> void:
match screen:
Screen.MENU:
main_menu.settings_button.grab_focus.call_deferred()
Screen.PAUSED:
pause_menu.visible = true
pause_menu.settings_button.grab_focus.call_deferred()
func _set_hud(on: bool) -> void:
for layer_name in ["Hud", "ZoneBanner"]:
var layer := farm.get_node_or_null(layer_name) as CanvasLayer
if layer != null:
layer.visible = on
func _place_menu_camera() -> void:
var at := ORBIT_CENTER + Vector3(cos(_orbit) * ORBIT_RADIUS, ORBIT_HEIGHT, sin(_orbit) * ORBIT_RADIUS)
_menu_camera.global_position = at
_menu_camera.look_at(ORBIT_CENTER + Vector3(4.0, 0.0, 0.0), Vector3.UP)
func _unhandled_input(event: InputEvent) -> void:
if quitting:
return
if event.is_action_pressed("toggle_mic") and sim.coop.is_active() and not sim.coop.voices.is_empty():
settings.microphone = not settings.microphone
sim.coop.set_microphone(settings.microphone)
settings.save_to(settings_path)
if sim.toasts != null:
sim.toasts.push("Microphone %s" % ("on" if settings.microphone else "muted"), Color(0.85, 0.95, 1.0))
get_viewport().set_input_as_handled()
return
if not event.is_action_pressed("pause"):
return
match screen:
Screen.PLAYING:
pause()
get_viewport().set_input_as_handled()
Screen.PAUSED:
if confirm.is_open:
confirm.close()
elif settings_menu.is_open:
settings_menu.close()
else:
resume()
get_viewport().set_input_as_handled()

1
game/scripts/main.gd.uid Normal file
View file

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

Some files were not shown because too many files have changed in this diff Show more