diff --git a/.gitignore b/.gitignore
index 0af181c..d6d626a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,9 @@
# Godot 4+ specific ignores
.godot/
/android/
+
+# GD-Sync API keys. Never commit these.
+addons/GD-Sync/keys.cfg
+
+# Exported builds (export_presets.cfg)
+build/
diff --git a/GD-Sync_1.0.2.zip b/GD-Sync_1.0.2.zip
new file mode 100644
index 0000000..4b9d5d3
Binary files /dev/null and b/GD-Sync_1.0.2.zip differ
diff --git a/README.md b/README.md
index 841f47d..d49913a 100644
--- a/README.md
+++ b/README.md
@@ -12,12 +12,16 @@ Built with **Godot 4.7.2 (stable, official) and typed GDScript only**. Measured
Requirements: Godot **4.7.2** (`Godot_v4.7.2-stable_linux.x86_64` was used; no other engine
version or language). The project is configured for the **Mobile** renderer (Vulkan).
-The project's main scene is now the farm (`res://game/scenes/farm.tscn`, see
-[Farm scene](#farm-scene)); the prototype arena is launched by passing its scene explicitly:
+The project's main scene is the game (`res://game/scenes/main.tscn`: the title screen over the
+farm, see [Farm scene](#farm-scene)). The farm scene on its own (`res://game/scenes/farm.tscn`,
+F6 in the editor) starts straight at the first morning, without menus or saving. The prototype
+arena is launched by passing its scene explicitly:
```sh
-# Farm (main scene; F5 in the editor)
+# The game (main scene; F5 in the editor)
godot --path .
+# The farm on its own: no menus, no save
+godot --path . res://game/scenes/farm.tscn
# Prototype: normal demo, 50 birds
godot --path . res://prototype/scenes/main.tscn
# Prototype with 25 birds
@@ -38,9 +42,11 @@ pack (`assets/farm/ithappy/farm/prefabs/assets/`).
* **Player** — `PlayerCharacter` (`game/scripts/player_character.gd`): camera-relative movement
on the `move_*` actions with gravity; the model turns toward travel and crossfades
idle / walk (partial stick) / run. Clips come from `game/resources/player_animations.res`, an
- AnimationLibrary of KayKit Rig_Medium clips (idle, walk, run, interact, pick-up, use item, dig,
- chop, hammer, wave) built by `game/tools/build_player_animations.gd` — add clips to its
- `CLIPS` table and re-run it with the editor closed.
+ AnimationLibrary of KayKit Rig_Medium clips (idle, walk, run, sneak, interact, pick-up, use item,
+ dig, chop, hammer, lockpick, punch, hit, wave, death; the ground thieves share it), built with
+ `game/resources/breaker_animations.res` (Rig_Large, for the fence breaker) by
+ `game/tools/build_player_animations.gd`. Add clips to its `BUILDS` table and re-run it with the
+ editor closed.
* **Camera** — `FollowCamera` (`game/scripts/follow_camera.gd`): framing from pitch / yaw /
distance (inspector), smoothed follow, mouse-wheel zoom. It is a tool script, so the editor
viewport preview shows the in-game framing.
@@ -53,23 +59,211 @@ pack (`assets/farm/ithappy/farm/prefabs/assets/`).
a new prefab type, re-run it with the editor closed (prefabs that already have a
CollisionShape3D are skipped, so hand-tuned shapes survive; `-- --force` regenerates its own).
Animals (`animal/`) get none either; the open pen gate (`fence_018`) has a hand-made thin box.
-* **Zones** — the playable map is 60 × 60 m (x −13…47, z −45…15) inside a perimeter fence with 6
- gaps; the rest of the farm is scenery. `Zones/` holds one `FarmZone` per area (crop field,
+* **Zones** — the playable map is 60 × 60 m (x −13…47, z −45…15). What's left of the perimeter
+ fence runs along its north and east sides, with 3 gaps; the south and west are open. Enemies
+ arrive at random points all along the map's edge. The rest of the farm is scenery. `Zones/` holds one `FarmZone` per area (crop field,
animal pen, supply shed, work area, woodlot, scrap heap, haystacks) with its props as children,
- the 30 `CropUnit`s of the crop field, and the perimeter (fence, gap and crow `FarmMarker`s, and
+ the 30 `CropUnit`s of the crop field, and the perimeter (fence, gap `FarmMarker`s, and
scarecrow-only `PlayerBounds` on physics layer 3). `ZoneBanner` shows the zone's name when the
scarecrow walks in. `FarmNavigation` rasterizes the farm's collision into a 0.5 m grid for
ground enemies. Details, travel times, and how to edit: [`game/LAYOUT.md`](game/LAYOUT.md).
`game/tools/render_overview.gd` renders a top-down picture (`--zones` draws the zones).
+* **Enemies and theft** — `FarmSim` (`game/scripts/farm_sim.gd`) runs the farm's simulation in a
+ fixed order each physics tick and applies the phase rules.
+ - **`EnemySystem`** is forked from the prototype's horde: pooled slots, handles with
+ generations, one MultiMesh for the flyers. It runs three types from the type table
+ (`GameConfig.enemy_types`).
+ - **Crows** fly straight to a crop, over fences and traps, land, take it, and fly straight off
+ the farm.
+ - **Ground thieves** go for animals and supplies along flow fields: the inside of the pen, each
+ shed pile. They break barriers that block their way, and carry their loot to the farm's nearest edge.
+ - **Fence breakers** follow a field to the barriers guarding valuables and smash them. They turn
+ on the scarecrow when it comes close or shoots them, and hunt it, along a field toward the
+ scarecrow, once nothing is left to break.
+ - **`ThiefBehavior`** decides all of that. **`EnemyCharacters`** draws the ground enemies with
+ a fixed pool of KayKit characters: a dark Mannequin_Medium thief, a rust-red Mannequin_Large
+ breaker with a primitive club. Clips follow what each is doing, hits flash, and they glow at
+ night.
+ - **`LootSystem`** holds every stealable item in one id space (crop units, animals, sacks of
+ supplies). It tracks each item's state (home / carried / dropped / following / lost) and its
+ feedback:
+ - a "!" over a targeted item and a filling ring while it's taken;
+ - a token outlined in the category's color, and a badge, on the carrier or on the ground.
+ - **`AlertManager`** draws labeled edge-of-screen arrows: grouped, prioritized, escape alerts
+ escalating, at most 5 at once. **`ToastFeed`** shows event toasts.
+ - Shooting a carrier drops its loot, and walking up to it recovers it. A carrier that gets off
+ the farm loses it for good.
+ - The scarecrow's weapons (`ScarecrowCombat`): mouse or right-stick aim, hold fire. It starts
+ with the **pitchfork** (melee: a stab every 0.5 s at the nearest few enemies in reach and in
+ front). The **corn shooter** (the prototype's gun, through `FarmProjectiles`) and **pumpkin
+ bombs** (thrown, bursting over 3 m: `PumpkinBombs`) are workbench upgrades. Switch with Tab /
+ d-pad down or 1-3 outside build mode. The models are the user's (`assets/weapons/`, posed on
+ the scarecrow by `WeaponModels`); the HUD's weapon panel (bottom right) shows them. Shots, the
+ corn shooter, and enemy hit proxies sit at 1.8 m, above the sunflowers and the pen fence.
* **Campaign** — `CampaignController` (`game/scripts/campaign_controller.gd`) runs the five-night
vacation: Morning → Day → Dusk → Night → Dawn per night, then the farmers' return, with Game
Over from any phase. `FarmState` (`farm_state.gd`) is the single source of truth for what
persists; settings are in `game/resources/game_config.tres` (`GameConfig`). The rules are in
[`game/RULES.md`](game/RULES.md) and the development plan in
- [`first-game-plan.md`](first-game-plan.md). Until the real HUD arrives, `CampaignDebug` shows the
- phase and farm state top-left. Keys: Enter begins the day, F6 ends the current phase, F7 cycles
- 1× / 5× / 20× speed, F9 sets the scarecrow to 0 HP, F10 strips the farm, R retries after a Game
- Over, and N starts the night early (only when `allow_early_night` is on).
+ [`first-game-plan.md`](first-game-plan.md). `CampaignDebug` is a debug readout of the phase and
+ farm state, hidden until F1. Debug keys: F6 ends the current phase, F7 cycles 1× / 5× / 20×
+ speed, F9 sets the scarecrow to 0 HP, F10 strips the farm (every category), R retries after a
+ Game Over, and T / G / H send in a thief / a crow / a fence breaker. F2 cycles tonight's plan
+ through the debug scenarios (`game/resources/scenarios/`). They introduce the enemies one type at
+ a time (crows, thieves, fence breakers), then pairs, then all three. N starts the night early
+ (only when `allow_early_night` is on).
+ On the farm the scarecrow moves with WASD / left stick, aims with the mouse / right stick, and
+ fires with the left mouse button / right trigger.
+* **Scarecrow kit** — `Scarecrow` (`game/scripts/scarecrow.gd`): health in `FarmState` with 1 s
+ of invulnerability after a hit (the model blinks, the screen tints), fear (Q / LB: enemies
+ within 6 m flee for 2 s, carriers drop their loot, 12 s cooldown), patching up (hold F / Y:
+ rooted 2 s for +3 HP, cancelled by a hit or letting go), and the fall at 0 HP. Thieves hit it
+ when touching it, and fence breakers when fighting it (`EnemySystem.evaluate_attacks`). `ScarecrowHud` shows health pips, the fear
+ cooldown, and the patch hint. The scarecrow still looks like the farmer mannequin;
+ its look comes later. `game/tools/soak_night.gd` plays nights headless with a scripted
+ scarecrow (`--mode=idle | guard`, `--thieves=N`) and prints what was stolen, recovered, and
+ lost; `--mode=gather` plays a day of gathering everything and reports the time and yield;
+ `--mode=cycle --cycles=N` plays whole days and nights (gather, rebuild the pen's gate, build a
+ fixed defense plan, buy upgrades with what's left, guard all three targets and lead loose
+ animals home; `--build=0` / `--guard=0` / `--upgrades=0` turn parts off), reports each night's
+ losses per target, and checks what carries over. `--cycles=5` plays the whole vacation.
+
+* **Economy** — wood, scrap, and straw (`ResourceStore` in `FarmState`): shed stock plus the
+ scarecrow's 15-unit pouch, which empties into the shed when it walks into the Supply Shed zone.
+ `Interactions` (`game/scripts/interactions.gd`) handles the interact action: hold at a
+ `GatherNode` (4 per material, made of the zone's props) to gather by day; press at the
+ `Workbench` (work area table) to open the upgrade menu (`UpgradePanel`). Patching costs 2 straw.
+ Points grow back overnight; `ResourceHud` (top right) shows the shed and pouch. Costs live in
+ `GameConfig.costs`.
+
+* **Upgrades** — `Upgrades` (`upgrades.gd`) holds the eleven upgrades in `GameConfig.upgrades`:
+ the corn shooter, rapid fire, heavy seeds, pumpkin bombs, wide fear, quick fear, straw
+ stuffing, sprint, reinforced fences, long-range defenses, and sticky tar. Sprint and the two
+ weapons change no stat: they unlock sprinting (`PlayerCharacter`: hold Shift / L3 while moving,
+ 1.6 times as fast for 3 s, then 10 s to recharge, shown on the scarecrow HUD) and the weapons
+ (`ScarecrowCombat`). Rapid fire and heavy seeds need the corn shooter first (`"requires"`). Each is bought once and kept in `FarmState.upgrades`. Systems read the
+ upgraded value of their stat through `Upgrades.value()` rather than `GameConfig` directly. The
+ stats are the corn shooter's fire rate and damage, fear's reach and recharge, fence and gate health, the
+ automated defense's range, and trap slow time. `UpgradePanel` is the menu, grouped by track,
+ showing costs and what's missing; mouse, keyboard, and gamepad all work.
+
+* **Animals and supplies** — `AnimalSystem` (`animal_system.gd`) turns the pen's farm-pack animals
+ into moving entities. They wander the pen with a procedural hop or waddle. Loose animals head for
+ the farm's nearest edge, and animals the scarecrow touches follow its trail home (at most 3). At night an
+ open pen lets one wander out every few seconds; the pen's gate is a normal gate structure, standing
+ from the start (`GameConfig.start_structures`). `ShedStock` (`shed_stock.gd`) shows the shed's
+ stock as piles of logs, crates, and hay that grow and shrink with it, and gives supply thieves a
+ spot at each pile. `AssetHud` (top center) shows "Crops · Animals · Supplies", flashing on change.
+ Rules: `game/RULES.md`; the piles: `game/LAYOUT.md`.
+
+* **Construction** — `StructureSystem` (`game/scripts/structure_system.gd`) validates, places,
+ draws, damages, repairs, and dismantles the four buildables (fence, gate, slowing trap,
+ automated defense), recorded in `FarmState.structures`, and runs traps and automated
+ defenses. Barriers are expensive cells in `FarmNavigation`'s structure layer: thieves route
+ around short fences, break through long ones (`ThiefBehavior` BREAK), and the flow fields are
+ rebuilt in slices (`FieldJob`) after every change. `BuildMode` + `BuildHud` are the build mode
+ and hotbar; `Interactions` repairs. Rules and numbers: `game/RULES.md`.
+
+* **Day and night** — `WaveDirector` (`game/scripts/wave_director.gd`) plays each night's
+ `NightPlan` (`game/resources/nights/night_1..5.tres`).
+ - A plan has a title, a dusk hint, an optional night length and scales, and groups of enemies by type,
+ time, count, spacing, and target. Where isn't planned: each enemy arrives at its own random
+ point along the farm's edge (on foot `GameConfig.spawn_margin` out, wherever there's a route
+ in; crows `flyer_spawn_margin` out).
+ - The five nights each test something new: crows only; a second target; breakers; groups at
+ once; three waves. From night 2, every group is played at seven times its size, about three
+ times as often (`GameConfig.wave_count_scale` 7, `wave_spacing_scale` 0.3). Night 1 sets its
+ own scales to 1 (`NightPlan.count_scale` / `spacing_scale`), so it plays as designed: 11 crows.
+ - `NightPlan.problems()` checks a plan against the farm.
+ - At dusk the phase HUD lists what tonight brings, from every side (nothing is marked on the
+ farm itself). `DayNight` (`day_night.gd`) eases the sun, sky,
+ ambient light, and a whole-picture brightness / saturation between day, sunset, night (moonlight),
+ and sunrise; the scarecrow carries a lantern that lights up as it gets dark, and thieves glow
+ faintly at night. `PhaseHud` (top left) is the sun / moon dial with "Night N of 5", the phase and
+ its time left, a hint line (what tonight brings, enemies on the farm), and a banner at each phase
+ change ("Night 3: Breakers at the fences"), with the dusk hint under it from dusk into the
+ night. `ReviewPanel` is the morning review: last night's losses per category, what's left, what
+ needs repair, materials, and tonight's title; "Start the day" ends it. Playtest findings
+ and tuning notes: [`game/PLAYTEST.md`](game/PLAYTEST.md).
+
+* **Menus and saving** — `Main` (`game/scripts/main.gd`, `game/scenes/main.tscn`) hosts the farm
+ under the menus. `MainMenu` is the title screen (Continue, New vacation, Settings, Quit) over
+ the paused farm, with a camera circling it. `PauseMenu` (Escape / Start) pauses the whole tree
+ and offers Resume, Restart the night, Settings, Save & quit to menu, and Quit the game;
+ `ConfirmBox` asks before anything throws progress away. `SaveGame` (`save_game.gd`) writes
+ the morning's `FarmState` to `user://savegame.json` every morning (atomically, full float
+ precision) and reads it back defensively: missing, damaged, and newer saves are refused with
+ the reason, and older ones are upgraded (`SaveGame.migrate`). Continue resumes at that morning;
+ finishing the vacation deletes the save. `GameSettings` (`game_settings.gd`) keeps the
+ settings in `user://settings.cfg`: volumes per audio bus, stick dead zones, fullscreen, VSync,
+ 3D resolution scale, and tips; `SettingsMenu` edits them and shows every binding.
+ `UiTheme` (`ui_theme.gd`, written to `game/resources/ui_theme.tres` by
+ `game/tools/build_ui_theme.gd`) is the project's default theme, with a gold focus ring so
+ keyboard and gamepad players always see where they are.
+
+* **Results and endings** — the morning screen (`ReviewPanel`) opens with last night's results:
+ a taken / recovered / lost table per category, enemies defeated by type, damage, and materials
+ gathered and spent (all counted in `FarmState.night_events`, kept per night in `night_log`).
+ `EndPanel` is the failure screen (the cause, the night and its plan, what's left, the totals,
+ Retry the night and Main menu) and, after the farmers' return, the final assessment:
+ `Assessment` (`assessment.gd`) scores the share of each category kept (weights and rating
+ tiers in `GameConfig`), with a bar per category and the vacation's totals. `FarmersReturn`
+ (`farmers_return.gd`) is the ending: the farmers' station wagon drives in at the driveway gap
+ and parks by the house, and the two farmers (tinted mannequins in straw hats) walk to the
+ porch, wave to the scarecrow, and cheer, under a cutscene camera; any of fire, interact, or
+ Enter / A skips it.
+
+* **Co-op** — two players over [GD-Sync](https://www.gd-sync.com) (`addons/GD-Sync/`): on the same
+ network with no account, by the host's address (VPNs, strict firewalls), or online with the
+ project's GD-Sync API keys. Each player has a scarecrow (P1 gold, P2 blue, name tags), a partner
+ panel and an edge arrow show the other one, and voice chat runs over GD-Sync (M mutes). The host
+ simulates and saves; the partner's farm is a replica that moves only its own scarecrow
+ (`CoopSession`). How to play, the rules, the protocol, and the plugin patches:
+ [`game/COOP.md`](game/COOP.md).
+
+* **Outside the fence** — the scarecrow can walk off the farm (through the fence's gaps, or across
+ the open south and west), as far as the old farm's
+ outer fences. Four areas there have more to gather (3 per charge): the North Grove (wood), the
+ Old Hangar and the East Road (scrap), and the South Fields (straw). Building, navigation, and
+ the night stay inside the fence, and dusk warns anyone still outside. [`game/LAYOUT.md`](game/LAYOUT.md).
+
+* **Tips** — `Tutorial` (`tutorial.gd`) shows short contextual tips on the first day and night:
+ move, gather, store, build, the dusk warning, shoot, fear, recover, and patch, each when it's
+ useful and gone once done. Backspace / Back hides them; Settings turns them off.
+
+* **Audio** — `FarmAudio` (`farm_audio.gd`) plays every sound by cue name through the Master,
+ Music, SFX, and Ambience buses (`game/resources/audio_buses.tres`): footsteps, the gun, hits
+ and deaths by enemy type, crow caws and arrivals from where they come in, theft and breach
+ alarms, building, repairs, traps, the automated defenses, gathering, upgrades, the dusk bell
+ and phase stingers, the outcome jingles, and the day and night ambience. Positional sounds
+ are heard from the scarecrow facing the way the camera does. Sounds are Kenney's CC0 packs
+ (`assets/audio/kenney/`, licenses included) plus ambience, crows, the farmers' car, the
+ pitchfork's whoosh, and the pumpkin bomb's burst, made
+ by `game/tools/synth_audio.gd` (`assets/audio/synth/`). Music: "On the Farm" on the title
+ screen and by day, DavidKBD's "Purgatory" at night, none at dusk and dawn (`assets/audio/music/`).
+ See [`assets/audio/CREDITS.md`](assets/audio/CREDITS.md).
+
+### Farm controls
+
+| Action | Keyboard / mouse | Gamepad |
+|---|---|---|
+| Move | WASD or arrow keys | Left stick |
+| Aim | Mouse cursor (aim marker) | Right stick |
+| Fire (hold) | Left mouse button | Right trigger or right shoulder |
+| Fear | Q | Left shoulder |
+| Patch up (hold) | F | Y |
+| Interact: hold to gather, press at the workbench | E | X |
+| Build mode (toggle) | B | D-pad up |
+| In build mode: build / rotate / pick / dismantle or leave | LMB / Z, C / 1-4, Tab / RMB | RT / d-pad left, right / d-pad down / B |
+| Repair a damaged structure (hold) | E | X |
+| Start the day (morning review) | Click, Enter | A |
+| Pause / resume | Escape | Start |
+| Hide the tips | Backspace | Back |
+| Mute / unmute your microphone (co-op) | M | - |
+| Skip the farmers' return | Space, Enter, E, or click | A or X |
+| Menus and end screens | Click, arrows + Enter, Escape to go back | D-pad + A, B to go back |
+
+`game/tools/configure_input.gd` writes these actions into `project.godot` (editor closed).
### Controls
@@ -91,22 +285,43 @@ trigger selects the gamepad. After any restart, fire must be released and presse
```
game/
RULES.md rules of the vacation
- LAYOUT.md the playable farm: zones, gaps, travel times
- scenes/ farm.tscn (main scene), player.tscn
+ LAYOUT.md the playable farm: zones, the edge and the fence's gaps, travel times
+ PLAYTEST.md playtest results and what to tune
+ scenes/ main.tscn (main scene: the menus over the farm), farm.tscn, player.tscn
scripts/ player_character.gd, follow_camera.gd, campaign_controller.gd, farm_state.gd,
game_config.gd, campaign_debug.gd, farm_zones.gd, farm_zone.gd, farm_marker.gd,
- crop_unit.gd, farm_navigation.gd, zone_banner.gd
- resources/ player_animations.res (generated), game_config.tres
- tests/ headless test runner and suites (campaign rules, farm layout)
- tools/ build_player_animations.gd, build_prop_collision.gd, render_overview.gd
+ crop_unit.gd, farm_navigation.gd, zone_banner.gd, farm_sim.gd, enemy_system.gd,
+ thief_behavior.gd, loot_system.gd, farm_projectiles.gd, scarecrow_combat.gd,
+ weapon_models.gd, pumpkin_bombs.gd,
+ alert_manager.gd, toast_feed.gd, scarecrow.gd, scarecrow_hud.gd,
+ end_panel.gd, resource_store.gd, gather_node.gd, workbench.gd,
+ interactions.gd, resource_hud.gd, structure_system.gd, build_mode.gd,
+ build_hud.gd, action_edges.gd, night_plan.gd, wave_director.gd, day_night.gd,
+ phase_hud.gd, review_panel.gd, animal_system.gd, shed_stock.gd, asset_hud.gd,
+ enemy_characters.gd, upgrades.gd, upgrade_panel.gd, main.gd, main_menu.gd,
+ pause_menu.gd, settings_menu.gd, confirm_box.gd, save_game.gd, game_settings.gd,
+ ui_theme.gd, assessment.gd, farmers_return.gd, tutorial.gd, farm_audio.gd, avatar.gd,
+ remote_controls.gd, coop_session.gd, coop_link.gd, gdsync_link.gd, coop_lobby.gd,
+ coop_voice.gd, coop_hud.gd, coop_menu.gd
+ resources/ player_animations.res and breaker_animations.res (generated), game_config.tres,
+ audio_buses.tres, ui_theme.tres (generated),
+ nights/ (night plans), scenarios/ (debug plans), thief (crow) / enemy overlay /
+ steal ring / loot icon / fear burst / HP bar shaders
+ tests/ headless test runner and suites (campaign rules, farm layout, theft, scarecrow,
+ economy, structures, all three targets, the enemy roster, the five nights, full
+ cycle, saving and settings, the whole game through its menus, co-op)
+ tools/ build_player_animations.gd, build_prop_collision.gd, render_overview.gd,
+ configure_input.gd, soak_night.gd, synth_audio.gd, build_ui_theme.gd, coop_smoke.gd
prototype/
scenes/ main.tscn (round), player.tscn, hud.tscn
scripts/ gameplay systems (one class per file, see Architecture)
resources/ default_config.tres, floor / bird / hit-flash shaders
tests/ headless test runner and suites
tools/ configure_project.gd, inspect_assets.gd, probe_hand_pose.gd
+addons/ GD-Sync (the co-op plugin; four small patches, see game/COOP.md)
benchmarks/ run_benchmarks.sh, summarize.py, results/*.json, REPORT.md
-assets/ the original asset kits (unchanged; referenced in place)
+assets/ the original asset kits (unchanged; referenced in place); audio/ holds the game's
+ sounds (Kenney CC0 packs and synthesized ones, CREDITS.md)
```
## Configuration
@@ -274,14 +489,73 @@ godot --headless --path . --script res://game/tests/run_tests.gd
godot --headless --path . --fixed-fps 60 --script res://prototype/tests/run_tests.gd # prototype
```
-Game: 298 checks, about 1.3 s. Covers `FarmState` round trips (also through JSON) and rejection
-of invalid data, every outcome rule including the loss-before-completion tie on the final dawn,
+Game: 908 checks, about 80 s. Covers `FarmState` round trips (also through JSON) and rejection
+of invalid data, every outcome rule including the loss-before-completion tie on the final dawn
+and a stripped farm across all three categories (spent supplies don't count),
failure in every phase, the untimed morning, phase order and lengths, exactly five nights,
starting the night early (off by default), per-night loss records, and retrying a failed night
from its morning. The farm layout suite checks one non-overlapping zone per kind inside the
-60 × 60 m map, zone lookup, the 30 crop units, the gap and crow markers, a perimeter fence with no
-holes outside its gaps, ground-enemy routes from every gap to every zone, that the scarecrow can't
-walk out through a gap, zone-to-zone travel times (at most 12 s), and the zone banner.
+60 × 60 m map, zone lookup, the 30 crop units, the farm's edge and its side names, the remaining
+north and east fence with no holes outside its gaps (and the open south and west), ground-enemy
+routes from anywhere on the edge to every zone, that the scarecrow can walk out through a gap,
+zone-to-zone travel times (at most 12 s), and the zone banner. The theft
+suite runs crop theft on the real farm, by crows: claiming, flying in and landing, the steal
+timer, carrying, escaping over the fence (crop lost), one hit killing a crow and dropping its crop
+exactly once, touch recovery, stale handles after slot reuse, shots hitting thieves and cruising
+crows and stopping at the barn, stick aim and the fresh-press rule, the sunrise retreat, the end of
+the dawn grace, retry, night arrivals, and FarmState agreeing with the loot state. The scarecrow suite covers invulnerability, thief melee (cooldown, cover, not while
+fleeing), fear (range, drops, lost progress, cooldown, recovery), patching (heal, rooted, every
+cancel), sprint, defeat ahead of a stripped farm, the end panel's Retry, the morning revive, and
+the new input actions. The weapons suite covers starting with only the pitchfork, its stab (reach,
+arc, the nearest three, damage, cadence, held fire, not through walls), buying the corn shooter and
+pumpkin bombs (and rapid fire / heavy seeds needing the corn shooter), switching (cycling, 1-3,
+owned only, not in build mode, falling back, each weapon's own wait), a bomb's throw, flight,
+burst, range, and recharge, the models on the scarecrow, and the HUD's weapon panel. The economy suite covers the resource store's rules and validation, the gather
+points' layout and reachability, gathering (day only, charges, every cancel, a full pouch, the
+used-up/full focus rule), the shed drop-off, overnight regrowth, retry, the patch's straw cost,
+and buying Straw stuffing from the workbench's menu (opening, what's missing, closing). The structures suite covers every placement rule, build mode driven by
+gamepad input, the sliced rebuild, gates, a thief shut in the pen breaking its gate to get out,
+traps, the automated defense's range, damage and breaking, repair and dismantling, persistence
+and retry, and two A/B nights (two at a time, scarecrow away). Crows: open field 15 crops lost,
+fence ring 15 (nothing broken), ring + 6 automated defenses 2. Thieves after supplies: open shed 40
+units, fenced 35 (2 breaks), fenced + 3 automated defenses 0. The targets suite covers the animals (wandering kept in by the pen's gate,
+an animal thief breaking in, catching, carrying, a dropped animal running for the farm's edge,
+leading three back through a gate, the fourth waiting, a pen breach letting animals wander out at
+night but not by day, losses, the dawn return, retry), the supplies (bundles from the most
+stocked pile, never more than the shed holds, dropping, recovery, carrying off, a raided shed,
+the piles scaling with the stock), thieves falling back to another target, the asset HUD, and a
+farm stripped of all three. The roster suite covers the type table, crows flying over fences and
+traps but shot down by automated defenses and never fighting, thieves keeping to animals and
+supplies (and a hit restarting their theft), fence breakers smashing the barriers that guard
+valuables (heavy hits, the next one after, a gap a thief then walks through, hunting and hitting
+the scarecrow, turning on it when shot, six hits to stop), the character pool (one per ground
+enemy, spawns skipped past it, corpses taken over), the alert manager (grouping, escape priority
+and escalation, breaches before thefts, the cap), and the debug scenarios. The nights suite checks
+every night plan and debug scenario against the farm (and that broken plans are caught), what
+each of the five nights tests, every upgrade's effect on the real systems (fire rate, damage,
+fear, max health, fence health, defense range, trap time), that upgrades can't be bought twice or
+at night and persist (next morning, JSON, retry, not into a new vacation), and all five nights
+played back to back to the farmers' return. Each night brings its own plan's enemies under its
+own banner, each morning is its night's snapshot, and the last night is longer.
+The cycle suite plays one whole day and night on the real farm: the morning review, the phase
+HUD, a day's gathering and building, no thieves by day, the dusk warnings, the lighting of each
+phase, the night plan's arrival times and targets at random points all along the edge, the dawn retreat, everything carrying
+into the next morning (structures and their damage, materials less what was carried off, losses
+in every category, health), the morning screen's results table and lines, and an exact retry.
+The save suite covers saving and loading reproducing the farm state field for field, missing,
+damaged, rule-breaking, non-morning, newer, and too-old saves refused with a reason, a version 2
+save upgraded, the autosave every morning, retry restoring the saved morning, the save deleted
+when the vacation is finished, settings saved, loaded, clamped, and applied (bus volumes, dead
+zones), and the final assessment's score, tiers, and renormalized weights. The flow suite plays
+the game through `main.tscn`: the title screen over the paused farm, New vacation and Continue
+(and their questions), pausing freezing the simulation tick, settings applying and saving from
+the pause menu, Restart the night and Save & quit leaving the save untouched, a damaged save
+refused, the failure screens and Retry, the farmers' return to the final assessment (and
+skipping it), the first day's and night's tips, and the sounds hooked to the game. The co-op suite
+runs a host and a partner in one process (the partner's farm in its own world, over a loopback
+link): the join, the partner's requests, moves, gathering, and shots, enemies, loot, and shots
+arriving, the fall rule and Retry, a crowd with dropped packets and message sizes, and either side
+leaving. `game/tools/coop_smoke.gd` plays the same over real GD-Sync between two processes.
Prototype: 107 checks, ~1.5 s. Covers pool acquire/release/exhaustion and swap identities, slot reuse
hygiene and stale handles, U-shape routing, corner cutting, unreachable spawns, octile costs,
@@ -316,6 +590,9 @@ navigation stay fully enabled.
* **VSync and hidden windows.** On this desktop (labwc via XWayland), a VSync-enabled window that
is not visible is throttled to ~1 FPS by the compositor; VSync-on checks need a visible window.
* Measured on one machine only (see the report); minimum hardware is not defined.
+* **Sounds were chosen without listening.** Cues were picked from Kenney's file names and a
+ pitch analysis of the jingles; the synthesized ambience, crows, and car were checked as
+ waveforms only. Each cue is one line in `FarmAudio.CUES`, so a bad one is a one-line swap.
* Native Wayland (`--display-driver wayland`) was not tested; Godot ran under X11/XWayland.
* Animation: backward movement uses a walking clip (foot slide at run speed); no hit reaction clip.
* Birds' wings overlap visually in dense crowds (collision fits the torso by design).
diff --git a/addons/GD-Sync/GD-Sync.gd b/addons/GD-Sync/GD-Sync.gd
new file mode 100644
index 0000000..3c6babe
--- /dev/null
+++ b/addons/GD-Sync/GD-Sync.gd
@@ -0,0 +1,766 @@
+@tool
+extends EditorPlugin
+
+# Copyright (c) 2023-present GD-Sync.
+# All rights reserved.
+#
+# Redistribution and use in source form, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+# 1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+# 2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+#region GD-Sync
+
+const CSHARP_REPO_URL : String = "https://raw.githubusercontent.com/GD-Sync/GD-SyncCSharp/"
+const PLUGIN_PATH : String = "res://addons/GD-Sync"
+const CSHARP_PATH : String = "res://addons/GD-Sync/GDSync.cs"
+const CSHARP_UID_PATH : String = "res://addons/GD-Sync/GDSync.cs.uid"
+
+const KeyStore = preload("res://addons/GD-Sync/Scripts/KeyStore.gd")
+
+var version : String = "1.0.2"
+
+var debugger = GDSyncProfiler.new()
+var export_plugin : EditorExportPlugin = GDSyncExportPlugin.new()
+
+func _enable_plugin() -> void:
+ add_autoload_singleton("GDSync", "res://addons/GD-Sync/MultiplayerClient.gd")
+
+ print_rich("[color=#408EAB] - Please visit our website for more info (https://www.gd-sync.com)[/color]")
+ print_rich("[color=#408EAB] - The plugin configuration menu can be found under Project > Tools > GD-Sync.[/color]")
+
+ show_message("[b]GD-Sync version "+version+" enabled.[/b]
+
+Please visit our website for more info ([color=#408EAB][url=https://www.gd-sync.com]gd-sync.com[/url][/color])", 10.0)
+
+
+var config_menu : Control
+func _enter_tree() -> void:
+ var previous_version : String = ProjectSettings.get_setting("GD-Sync/version", version)
+ ProjectSettings.set_setting("GD-Sync/version", version)
+
+ print_rich("[color=#408EAB][b]GD-Sync version "+version+" enabled.[/b][/color]")
+
+ if FileAccess.file_exists(CSHARP_PATH):
+ print_rich("[color=#408EAB] - GD-Sync C# API detected and enabled.[/color]")
+
+ if Engine.has_singleton("Steam"):
+ print_rich("[color=#408EAB] - Steam integration detected and enabled.[/color]")
+
+ _relocate_api_keys()
+
+ config_menu = load("res://addons/GD-Sync/UI/ConfigMenu/ConfigMenu.tscn").instantiate()
+ config_menu.plugin = self
+ get_editor_interface().get_base_control().add_child(config_menu)
+ add_tool_menu_item("GD-Sync", config_selected)
+
+ _cleanup_stale_csharp_uid()
+ _check_for_updates_and_news()
+ _initialize_remote_call_validator()
+ add_debugger_plugin(debugger)
+ add_export_plugin(export_plugin)
+
+func _exit_tree() -> void:
+ _disable_remote_call_validator()
+ remove_tool_menu_item("GD-Sync")
+
+ if config_menu != null:
+ config_menu.free()
+ config_menu = null
+
+ remove_debugger_plugin(debugger)
+ remove_export_plugin(export_plugin)
+
+func _relocate_api_keys() -> void:
+ KeyStore.ensure_gitignore()
+ if !KeyStore.needs_migrate() or !KeyStore.migrate():
+ return
+ if Engine.is_editor_hint():
+ get_editor_interface().get_resource_filesystem().update_file(KeyStore.KEYS_PATH)
+ print_rich("[color=#61ff71] - API keys were moved out of project.godot into "+KeyStore.KEYS_PATH+".[/color]")
+ show_message("[b]GD-Sync moved your API keys out of project.godot.[/b]
+They are now in [code]"+KeyStore.KEYS_PATH+"[/code]. If those keys were ever committed, we recommend creating a new API key.", 15.0)
+
+func _cleanup_stale_csharp_uid() -> void:
+ if FileAccess.file_exists(CSHARP_PATH): return
+ if !FileAccess.file_exists(CSHARP_UID_PATH): return
+ DirAccess.remove_absolute(CSHARP_UID_PATH)
+
+func config_selected() -> void:
+ config_menu.open()
+
+func enable_csharp_api() -> void:
+ if FileAccess.file_exists(CSHARP_PATH): return
+
+ var body : PackedByteArray = await _download_csharp_api()
+
+ if body.is_empty():
+ show_message("[color=indianred][b]GD-Sync C# API failed to download. Please disable and enable C# support to try again.[/b][/color]")
+ return
+
+ var file : FileAccess = FileAccess.open(CSHARP_PATH, FileAccess.WRITE)
+ if file == null:
+ show_message("[color=indianred][b]GD-Sync C# API could not be saved to "+CSHARP_PATH+".[/b][/color]")
+ return
+
+ file.store_buffer(body)
+ file.close()
+
+ add_autoload_singleton("GDSyncSharp", CSHARP_PATH)
+ show_message("[b]GD-Sync C# API installed. Please restart and build your project.[/b]")
+
+func _download_csharp_api() -> PackedByteArray:
+ var request : HTTPRequest = HTTPRequest.new()
+ request.timeout = 20
+ add_child(request)
+
+ var result : Array = []
+ if request.request(CSHARP_REPO_URL+"main/GDSync.cs") == OK:
+ result = await request.request_completed
+
+ if is_instance_valid(request): request.queue_free()
+
+ if result.size() < 4: return PackedByteArray()
+ if result[1] != 200: return PackedByteArray()
+
+ var body : PackedByteArray = result[3]
+ if !body.get_string_from_utf8().contains("class GDSync"): return PackedByteArray()
+
+ return body
+
+func disable_csharp_api() -> void:
+ if !FileAccess.file_exists(CSHARP_PATH): return
+ show_message("[b]GD-Sync C# API removed.[/b]")
+
+ var dir : DirAccess = DirAccess.open(PLUGIN_PATH)
+ if dir != null:
+ dir.remove("GDSync.cs")
+ if dir.file_exists("GDSync.cs.uid"): dir.remove("GDSync.cs.uid")
+
+ remove_autoload_singleton("GDSyncSharp")
+
+func _check_for_updates_and_news() -> void:
+ var request : HTTPRequest = HTTPRequest.new()
+ request.timeout = 15
+ add_child(request)
+
+ var url : String = "https://www.gd-sync.com/version"
+ request.request(
+ url,
+ [],
+ HTTPClient.METHOD_GET
+ )
+
+ var result = await request.request_completed
+
+ if result[1] == 200:
+ var html : String = result[3].get_string_from_ascii()
+ var data : Dictionary = extract_data_from_html(html)
+
+ var new_version : String = data.get("version", version)
+ if is_version_newer(version, new_version):
+ config_menu.update_ready()
+ show_message("[color=#61ff71][b]A new version of GD-Sync is available.[/b][/color]
+[color=#61ff71]You can upgrade to version "+new_version+" in the configuration menu (Project -> Tools -> GD-Sync).[/color]
+
+[color=#61ff71][url=https://www.gd-sync.com/news]Click here for the patch notes.[/url][/color]", 10.0)
+ print("")
+ for news in data.get("news", []):
+ print_rich(news)
+
+func extract_data_from_html(html: String) -> Dictionary:
+ var re := RegEx.new()
+ re.compile("
]*class=['\\\"]paragraph['\\\"][^>]*>(.*?)
")
+ var m := re.search(html)
+ if m == null:
+ return {}
+ var txt := m.get_string(1).strip_edges().replace(""", "\"")
+ var v := JSON.parse_string(txt)
+ if typeof(v) == TYPE_DICTIONARY:
+ return v
+ if typeof(v) == TYPE_ARRAY and v.size() > 0 and typeof(v[0]) == TYPE_DICTIONARY:
+ return v[0]
+ return {}
+
+func is_version_newer(current_version: String, new_version: String) -> bool:
+ var current_nums: PackedStringArray = current_version.split(".")
+ var new_nums: PackedStringArray = new_version.split(".")
+ var len: int = maxi(current_nums.size(), new_nums.size())
+ for i in range(len):
+ var new_num: int = 0 if i >= new_nums.size() else int(new_nums[i])
+ var current_num: int = 0 if i >= current_nums.size() else int(current_nums[i])
+ if new_num > current_num:
+ return true
+ if new_num < current_num:
+ return false
+ return false
+
+func _disable_plugin() -> void:
+ remove_autoload_singleton("GDSync")
+ if FileAccess.file_exists(CSHARP_PATH):
+ remove_autoload_singleton("GDSyncSharp")
+
+#endregion
+
+
+#region CodeParser
+# ==============================================================================
+# Remote Call Validation
+# ==============================================================================
+
+var _script_editor: ScriptEditor
+var _file_system: EditorFileSystem
+
+func _initialize_remote_call_validator() -> void:
+ _script_editor = get_editor_interface().get_script_editor()
+ _file_system = get_editor_interface().get_resource_filesystem()
+
+ if _script_editor.has_signal("editor_script_changed"):
+ _script_editor.connect("editor_script_changed", _on_editor_script_changed)
+
+ if _script_editor.has_signal("editor_script_saved"):
+ _script_editor.connect("editor_script_saved", _on_script_saved)
+
+ _file_system.connect("filesystem_changed", _on_filesystem_changed)
+
+func _on_editor_script_changed(script: Script) -> void:
+ if script:
+ _analyze_script_for_remote_calls(script, true)
+ _start_text_change_monitoring(script)
+
+func _on_script_saved(script: Script) -> void:
+ _analyze_script_for_remote_calls(script, true)
+
+func _on_filesystem_changed() -> void:
+ var current_script = _script_editor.get_current_script()
+ if current_script:
+ _analyze_script_for_remote_calls(current_script, true)
+
+var _monitored_script: Script = null
+var _validation_timer: Timer = null
+var _last_validated_sources: Dictionary = {}
+
+func _start_text_change_monitoring(script: Script) -> void:
+ _monitored_script = script
+
+ if not _validation_timer:
+ _validation_timer = Timer.new()
+ _validation_timer.one_shot = true
+ _validation_timer.timeout.connect(_validate_monitored_script)
+ add_child(_validation_timer)
+
+ var editor = _script_editor.get_current_editor()
+ if editor:
+ var code_edit = editor.get_base_editor() as CodeEdit
+ if code_edit:
+ _last_validated_sources[script.resource_path] = code_edit.text
+
+ var callable : Callable = _on_code_edit_text_changed.bind(code_edit)
+ if not code_edit.text_changed.is_connected(callable):
+ code_edit.text_changed.connect(callable)
+
+func _on_code_edit_text_changed(code_edit: CodeEdit) -> void:
+ if not _monitored_script or _script_editor.get_current_script() != _monitored_script:
+ return
+
+ var current_source = code_edit.text
+ _last_validated_sources[_monitored_script.resource_path] = current_source
+
+ if _validation_timer:
+ _validation_timer.stop()
+ _validation_timer.start(1.0)
+
+func _validate_monitored_script() -> void:
+ if _monitored_script:
+ _analyze_script_for_remote_calls(_monitored_script, false)
+
+func _analyze_script_for_remote_calls(script: Script, console : bool) -> void:
+ var script_validation_enabled : bool = true
+ if ProjectSettings.has_setting("GD-Sync/scriptValidation"):
+ script_validation_enabled = ProjectSettings.get_setting("GD-Sync/scriptValidation")
+
+ if not script or not script is GDScript:
+ return
+
+ var script_path: String = script.resource_path
+ if not script_path.ends_with(".gd"):
+ return
+
+ var editor = _script_editor.get_current_editor()
+ if not editor:
+ return
+
+ var code_edit = editor.get_base_editor() as CodeEdit
+ if not code_edit:
+ return
+
+ var parser = RemoteCallParser.new()
+ var issues: PackedStringArray = parser.parse_script(code_edit.text)
+
+ if console and script_validation_enabled:
+ for issue in issues:
+ push_warning("[GD-Sync] %s: %s" % [script_path, issue])
+
+ if issues.size() > 0:
+ print_rich("[color=orange][b]GD-Sync found %d issue(s) in %s[/b][/color]" % [issues.size(), script_path.get_file()])
+ else:
+ _set_editor_issues(issues, script_validation_enabled)
+
+func _set_editor_issues(issues : PackedStringArray, script_validation_enabled : bool) -> void:
+ var current_editor = _script_editor.get_current_editor()
+ if current_editor == null:
+ return
+
+ var label : RichTextLabel
+
+ var vsplitcontainer : Node = _get_issue_label_container(current_editor)
+ if vsplitcontainer == null:
+ return
+
+ if vsplitcontainer.has_node("GDSyncWarning"):
+ label = vsplitcontainer.get_node("GDSyncWarning")
+ else:
+ label = RichTextLabel.new()
+ vsplitcontainer.add_child(label)
+ label.name = "GDSyncWarning"
+ label.bbcode_enabled = true
+ label.scroll_active = true
+ label.custom_minimum_size = Vector2(0, get_viewport().get_window().size.y*0.05)
+
+ if issues.size() > 0:
+ label.text = (
+ "[color=#408EAB][b]GD-Sync Warnings: [/b][/color][color=gold] \n - " +
+ "\n - ".join(issues)
+ )
+
+ label.visible = script_validation_enabled
+ else:
+ label.visible = false
+
+static func find_node_of_type(node: Node, type: String, index: int = 0) -> Node:
+ var found_nodes := []
+ _find_nodes_of_type_recursive(node, type, found_nodes)
+
+ if index < found_nodes.size():
+ return found_nodes[index]
+ return null
+
+static func _find_nodes_of_type_recursive(node: Node, type: String, found_nodes: Array) -> void:
+ if node.is_class(type):
+ found_nodes.append(node)
+
+ for child in node.get_children():
+ _find_nodes_of_type_recursive(child, type, found_nodes)
+
+class RemoteCallParser:
+ func parse_script(source_code: String) -> PackedStringArray:
+ var issues: PackedStringArray = []
+ var lines: PackedStringArray = source_code.split("\n")
+
+ if _has_expose_node(lines):
+ return issues
+
+ var exposed_functions: Array = _find_exposed_functions(lines)
+ var exposed_variables: Array = _find_exposed_variables(lines)
+ var exposed_signals : Array = _find_exposed_signals(lines)
+ var remote_calls: Dictionary = _find_remote_calls(lines)
+ var sync_var_calls: Dictionary = _find_sync_var_calls(lines)
+ var signal_emissions : Dictionary = _find_signal_emissions(lines)
+
+ for call_name in remote_calls.keys():
+ if call_name not in exposed_functions:
+ var line_num = remote_calls[call_name]
+ issues.append("Line %d: Remote function call to '%s' but function is not exposed with GDSync.expose_func(%s)" % [line_num, call_name, call_name])
+
+ for var_name in sync_var_calls.keys():
+ if var_name not in exposed_variables:
+ var line_num = sync_var_calls[var_name]
+ issues.append("Line %d: sync_var call for '%s' but variable is not exposed with GDSync.expose_var(self, \"%s\")" % [line_num, var_name, var_name])
+
+ for signal_name in signal_emissions.keys():
+ if signal_name not in exposed_signals:
+ var line_num = signal_emissions[signal_name]
+ issues.append("Line %d: Remote signal emission '%s' but signal is not exposed with GDSync.expose_signal(%s)" % [line_num, signal_name, signal_name])
+
+ return issues
+
+ func _has_expose_node(lines: PackedStringArray) -> bool:
+ var expose_node_pattern: RegEx = RegEx.new()
+ expose_node_pattern.compile("GDSync\\.expose_node\\((self)")
+
+ for line in lines:
+ var comment_pos = line.find("#")
+ var clean_line: String = line
+ if comment_pos != -1:
+ clean_line = line.substr(0, comment_pos)
+
+ var result = expose_node_pattern.search(clean_line)
+ if result:
+ return true
+
+ return false
+
+ func _find_exposed_functions(lines: PackedStringArray) -> Array:
+ var functions: Array = []
+ var expose_func_pattern: RegEx = RegEx.new()
+ expose_func_pattern.compile("GDSync\\.expose_func\\(\\s*([a-zA-Z_][a-zA-Z0-9_]*)(?:\\s*,\\s*[^)]+)?\\s*\\)")
+
+ for line in lines:
+ var comment_pos = line.find("#")
+ var clean_line: String = line
+ if comment_pos != -1:
+ clean_line = line.substr(0, comment_pos)
+
+ var result = expose_func_pattern.search(clean_line)
+ if result:
+ var func_name: String = result.get_string(1)
+ functions.append(func_name)
+
+ return functions
+
+ func _find_exposed_variables(lines: PackedStringArray) -> Array:
+ var variables: Array = []
+ var expose_var_pattern: RegEx = RegEx.new()
+ expose_var_pattern.compile("GDSync\\.expose_var\\(\\s*self\\s*,\\s*\"([^\"]+)\"(?:\\s*,\\s*[^)]+)?\\s*\\)")
+
+ for line in lines:
+ var comment_pos = line.find("#")
+ var clean_line: String = line
+ if comment_pos != -1:
+ clean_line = line.substr(0, comment_pos)
+
+ var result = expose_var_pattern.search(clean_line)
+ if result:
+ variables.append(result.get_string(1))
+
+ return variables
+
+ func _find_exposed_signals(lines: PackedStringArray) -> Array:
+ var functions: Array = []
+ var expose_func_pattern: RegEx = RegEx.new()
+ expose_func_pattern.compile("GDSync\\.expose_signal\\(\\s*([a-zA-Z_][a-zA-Z0-9_]*)(?:\\s*,\\s*[^)]+)?\\s*\\)")
+
+ for line in lines:
+ var comment_pos = line.find("#")
+ var clean_line: String = line
+ if comment_pos != -1:
+ clean_line = line.substr(0, comment_pos)
+
+ var result = expose_func_pattern.search(clean_line)
+ if result:
+ var func_name: String = result.get_string(1)
+ functions.append(func_name)
+
+ return functions
+
+ func _find_remote_calls(lines: PackedStringArray) -> Dictionary:
+ var calls: Dictionary = {}
+ var call_patterns: Array = [
+ RegEx.new(),
+ RegEx.new(),
+ RegEx.new(),
+ RegEx.new(),
+ RegEx.new(),
+ RegEx.new(),
+ RegEx.new(),
+ RegEx.new(),
+ RegEx.new(),
+ RegEx.new(),
+ RegEx.new(),
+ RegEx.new(),
+ ]
+
+
+ call_patterns[0].compile("GDSync\\.call_func_all\\(\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+ call_patterns[1].compile("GDSync\\.call_func\\(\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+ call_patterns[2].compile("GDSync\\.call_func_on\\(\\s*[^,]+\\s*,\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+ call_patterns[3].compile("GDSync\\.call_func_all_relevant\\(\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+ call_patterns[4].compile("GDSync\\.call_func_relevant\\(\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+ call_patterns[5].compile("GDSync\\.call_func_all_relevant_unreliable\\(\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+ call_patterns[6].compile("GDSync\\.call_func_relevant_unreliable\\(\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+ call_patterns[7].compile("GDSync\\.call_func_all_unreliable\\(\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+ call_patterns[8].compile("GDSync\\.call_func_unreliable\\(\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+ call_patterns[9].compile("GDSync\\.call_func_on_unreliable\\(\\s*[^,]+\\s*,\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+ call_patterns[10].compile("GDSync\\.call_func_on_relevant\\(\\s*[^,]+\\s*,\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+ call_patterns[11].compile("GDSync\\.call_func_on_relevant_unreliable\\(\\s*[^,]+\\s*,\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+
+ for line_num in range(lines.size()):
+ var line = lines[line_num]
+
+ var comment_pos = line.find("#")
+ var clean_line: String = line
+ if comment_pos != -1:
+ clean_line = line.substr(0, comment_pos)
+
+ for pattern in call_patterns:
+ var result = pattern.search(clean_line)
+ while result:
+ var function_name: String = result.get_string(1)
+ if function_name not in calls:
+ calls[function_name] = line_num + 1
+ result = pattern.search(clean_line, result.get_end())
+
+ return calls
+
+ func _find_sync_var_calls(lines: PackedStringArray) -> Dictionary:
+ var vars: Dictionary = {}
+ var sync_var_pattern: RegEx = RegEx.new()
+ sync_var_pattern.compile("GDSync\\.sync_var(?:_relevant)?\\(\\s*self\\s*,\\s*\"([^\"]+)\"\\s*[,\\)]|GDSync\\.sync_var_on_relevant\\(\\s*[^,]+\\s*,\\s*self\\s*,\\s*\"([^\"]+)\"\\s*[,\\)]")
+
+ for line_num in range(lines.size()):
+ var line = lines[line_num]
+ var comment_pos = line.find("#")
+ var clean_line: String = line
+ if comment_pos != -1:
+ clean_line = line.substr(0, comment_pos)
+
+ var result = sync_var_pattern.search(clean_line)
+ while result:
+ var var_name: String = result.get_string(1) if result.get_string(1) != "" else result.get_string(2)
+ if var_name not in vars:
+ vars[var_name] = line_num + 1
+ result = sync_var_pattern.search(clean_line, result.get_end())
+
+ return vars
+
+ func _find_signal_emissions(lines: PackedStringArray) -> Dictionary:
+ var calls: Dictionary = {}
+ var call_patterns: Array = [
+ RegEx.new(),
+ RegEx.new(),
+ RegEx.new(),
+ RegEx.new(),
+ RegEx.new(),
+ RegEx.new(),
+ ]
+
+
+ call_patterns[0].compile("GDSync\\.emit_signal_remote_all\\(\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+ call_patterns[1].compile("GDSync\\.emit_signal_remote\\(\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+ call_patterns[2].compile("GDSync\\.emit_signal_remote_on\\(\\s*[^,]+\\s*,\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+ call_patterns[3].compile("GDSync\\.emit_signal_remote_all_relevant\\(\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+ call_patterns[4].compile("GDSync\\.emit_signal_remote_relevant\\(\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+ call_patterns[5].compile("GDSync\\.emit_signal_remote_on_relevant\\(\\s*[^,]+\\s*,\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*[,\\)]")
+
+ for line_num in range(lines.size()):
+ var line = lines[line_num]
+
+ var comment_pos = line.find("#")
+ var clean_line: String = line
+ if comment_pos != -1:
+ clean_line = line.substr(0, comment_pos)
+
+ for pattern in call_patterns:
+ var result = pattern.search(clean_line)
+ while result:
+ var function_name: String = result.get_string(1)
+ if function_name not in calls:
+ calls[function_name] = line_num + 1
+ result = pattern.search(clean_line, result.get_end())
+
+ return calls
+
+func _disable_remote_call_validator() -> void:
+ _remove_editor_issue_labels()
+
+ if _script_editor:
+ if _script_editor.is_connected("editor_script_changed", _on_editor_script_changed):
+ _script_editor.disconnect("editor_script_changed", _on_editor_script_changed)
+
+ if _script_editor.is_connected("editor_script_saved", _on_script_saved):
+ _script_editor.disconnect("editor_script_saved", _on_script_saved)
+
+ if _file_system and _file_system.is_connected("filesystem_changed", _on_filesystem_changed):
+ _file_system.disconnect("filesystem_changed", _on_filesystem_changed)
+
+ if _validation_timer != null:
+ _validation_timer.queue_free()
+ _validation_timer = null
+
+ _monitored_script = null
+ _last_validated_sources.clear()
+ _script_editor = null
+ _file_system = null
+
+func _remove_editor_issue_labels() -> void:
+ if _script_editor == null: return
+
+ for script_editor in _script_editor.get_open_script_editors():
+ var container : Node = _get_issue_label_container(script_editor)
+ if container == null: continue
+
+ var label : Node = container.get_node_or_null("GDSyncWarning")
+ if label == null: continue
+
+ container.remove_child(label)
+ label.queue_free()
+
+func _get_issue_label_container(script_editor : Node) -> Node:
+ var split : Node = find_node_of_type(script_editor, "VSplitContainer")
+ if split == null: return null
+ return split.get_parent()
+
+#endregion
+
+
+#region GD-SyncProfiler
+class GDSyncProfiler extends EditorDebuggerPlugin:
+ var profilers : Dictionary = {}
+ var message_history : Dictionary = {}
+
+ func _has_capture(capture):
+ return capture == "gdsyncprofiler"
+
+ func _capture(message : String, data : Array, session_id : int) -> bool:
+ if !("gdsyncprofiler" in message): return false
+
+ var profiler = profilers[session_id]
+ if !is_instance_valid(profiler):
+ return false
+
+ if message == "gdsyncprofiler:registertransfer":
+ profiler.callv("register_transfer_usage", data)
+ return true
+
+ message_history[session_id].append([message, data.duplicate(true), session_id])
+
+ if message == "gdsyncprofiler:setdata":
+ profiler.callv("register_custom_data", data)
+ elif message == "gdsyncprofiler:pingmeasured":
+ data.push_front("ping_measured")
+ profiler.callv("emit_signal", data)
+ elif message == "gdsyncprofiler:clientjoined":
+ data.push_front("client_joined")
+ profiler.callv("emit_signal", data)
+ elif message == "gdsyncprofiler:clientleft":
+ data.push_front("client_left")
+ profiler.callv("emit_signal", data)
+ elif message == "gdsyncprofiler:gamestart":
+ profiler.game_started()
+ if profiler.artificial_latency_ms > 0:
+ get_session(session_id).send_message("gdsyncprofiler:set_artificial_latency", [profiler.artificial_latency_ms])
+ return true
+
+ func _setup_session(session_id : int):
+ var profiler_scene : PackedScene = load("res://addons/GD-Sync/UI/Profiler/GDSyncProfiler.tscn")
+ if profiler_scene == null: return
+ var profiler : Control = profiler_scene.instantiate()
+ profiler.name = "GD-Sync Profiler"
+ var session = get_session(session_id)
+
+ message_history[session_id] = []
+
+ session.started.connect(func ():
+ profiler.validate_session()
+ message_history[session_id].clear()
+ profiler.clear()
+ if profiler.artificial_latency_ms > 0:
+ get_session(session_id).send_message("gdsyncprofiler:set_artificial_latency", [profiler.artificial_latency_ms])
+ )
+ session.stopped.connect(func ():
+ profiler.stop()
+ profiler.invalidate_session())
+
+ profiler.profiler_cleared.connect(func ():
+ var history : Array = message_history[session_id].duplicate(true)
+ await profiler.get_tree().process_frame
+
+ for message in history:
+ _capture.callv(message)
+
+ message_history[session_id] = history
+ )
+ profiler.profiler_started.connect(func ():
+ get_session(session_id).send_message("gdsyncprofiler:start", [])
+ )
+ profiler.profiler_stopped.connect(func ():
+ get_session(session_id).send_message("gdsyncprofiler:stop", [])
+ )
+
+ profiler.start_monitoring_connections.connect(func ():
+ get_session(session_id).send_message("gdsyncprofiler:start_monitoring_connections", [])
+ )
+ profiler.stop_monitoring_connections.connect(func ():
+ get_session(session_id).send_message("gdsyncprofiler:stop_monitoring_connections", [])
+ )
+ profiler.artificial_latency_changed.connect(func (latency_ms : int):
+ get_session(session_id).send_message("gdsyncprofiler:set_artificial_latency", [latency_ms])
+ )
+
+ session.add_session_tab(profiler)
+ profilers[session_id] = profiler
+
+#endregion
+
+
+#region ExportPlugin
+class GDSyncExportPlugin extends EditorExportPlugin:
+ const KeyStore = preload("res://addons/GD-Sync/Scripts/KeyStore.gd")
+
+ func _get_name() -> String:
+ return "GD-Sync"
+
+ func _export_begin(_features : PackedStringArray, _is_debug : bool, _path : String, _flags : int) -> void:
+ var keys : Dictionary = KeyStore.load_keys()
+
+ if keys["PublicKey"].is_empty() or keys["PrivateKey"].is_empty():
+ push_warning("GD-Sync could not find any API keys. The exported project will be unable to connect. Keys can be entered under Project > Tools > GD-Sync.")
+ return
+
+ add_file(KeyStore.KEYS_PATH, KeyStore.encode_keys(keys["PublicKey"], keys["PrivateKey"]), false)
+
+#endregion
+
+
+#region ToastMessages
+var message_count : int = 0
+
+func show_message(message : String, duration : float = 5.0) -> void:
+ var message_packed : PackedScene = load("res://addons/GD-Sync/UI/Messages/ToastMessage.tscn")
+ if message_packed == null: return
+
+ var message_scene : Control = message_packed.instantiate()
+ message_scene.name = "GDSyncMessage"+str(message_count)
+ message_count += 1
+
+ get_editor_interface().get_base_control().add_child(message_scene)
+ message_scene.set_message(message, true, duration)
+ message_scene.tree_exiting.connect(_on_message_destroyed)
+
+ _update_all_message_positions()
+
+func _on_message_destroyed() -> void:
+ await get_tree().process_frame
+ _update_all_message_positions()
+
+func _update_all_message_positions() -> void:
+ var messages : Array = []
+ for child in get_editor_interface().get_base_control().get_children():
+ if "GDSyncMessage" in child.name and child.has_method("get_height"):
+ messages.append(child)
+
+ var cumulative_height : float = 0.0
+ for i in range(messages.size() - 1, -1, -1):
+ var message = messages[i]
+ if i == messages.size()-1:
+ cumulative_height += message.get_height()*0.5
+ else:
+ cumulative_height += message.get_height()
+ message.update_position(cumulative_height)
+#endregion
diff --git a/addons/GD-Sync/GD-Sync.gd.uid b/addons/GD-Sync/GD-Sync.gd.uid
new file mode 100644
index 0000000..a9c27d2
--- /dev/null
+++ b/addons/GD-Sync/GD-Sync.gd.uid
@@ -0,0 +1 @@
+uid://cwk2f7hf5pp3b
diff --git a/addons/GD-Sync/LICENSE b/addons/GD-Sync/LICENSE
new file mode 100644
index 0000000..0ba0bde
--- /dev/null
+++ b/addons/GD-Sync/LICENSE
@@ -0,0 +1,23 @@
+Copyright (c) 2023-present GD-Sync.
+All rights reserved.
+
+Redistribution and use in source form, with or without modification,
+are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+2. Neither the name of GD-Sync nor the names of its contributors may be used
+ to endorse or promote products derived from this software without specific
+ prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
diff --git a/addons/GD-Sync/MultiplayerClient.gd b/addons/GD-Sync/MultiplayerClient.gd
new file mode 100644
index 0000000..56f88cc
--- /dev/null
+++ b/addons/GD-Sync/MultiplayerClient.gd
@@ -0,0 +1,1923 @@
+extends Node
+class_name MultiplayerClient
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+
+
+
+
+
+
+
+
+
+# Signals ---------------------------------------------------------------------
+# *****************************************************************************
+# -----------------------------------------------------------------------------
+#region Signals
+
+## Emitted when the plugin successfully completes the connection and encryption handshake.
+## This signal is emitted after using [method start_multiplayer].
+## If this is emitted it means you can use all other multiplayer functions.
+signal connected()
+
+## Emitted if the connection handshake fails. This signal is emitted after using [method start_multiplayer].
+## [br]
+## [br][b]error -[/b] The reason behind the failed connection attempt. See [constant ENUMS.CONNECTION_FAILED] for possible errors.
+signal connection_failed(error : int)
+
+## Emitted when the client disconnects. Might be due to connectivity issues or when the server goes down.
+## [br]
+## [br][b]IMPORTANT: The plugin does not automatically try to reconnect when a disconnect occurs.[/b]
+signal disconnected()
+
+## Emitted when the Client ID changes. This happens when using [method start_multiplayer] and might happen
+## when using [method lobby_join]. This will NEVER happen while inside a lobby, so don't worry when
+## using methods such as [method set_gdsync_owner], [method call_func_on], etc.
+signal client_id_changed(own_id : int)
+
+## Emitted if [method lobby_create] was successful.
+## [br]
+## [br][b]lobby_name -[/b] The name of the lobby that was created.
+signal lobby_created(lobby_name : String)
+
+## Emitted if [method lobby_create] fails.
+## [br]
+## [br][b]lobby_name -[/b] The name of the lobby that failed to create.
+## [br][b]error -[/b] The reason why the creation failed.
+## Check [constant ENUMS.LOBBY_CREATION_ERROR] for possible errors.
+signal lobby_creation_failed(lobby_name : String, error : int)
+
+## Emitted if [method lobby_change_name] was successful.
+## [br]
+## [br][b]lobby_name -[/b] The new lobby name.
+signal lobby_name_changed(lobby_name : String)
+
+## Emitted if [method lobby_change_name] fails.
+## [br]
+## [br][b]lobby_name -[/b] The new lobby name that failed.
+## [br][b]error -[/b] The reason why the name change failed.
+## Check [constant ENUMS.LOBBY_NAME_CHANGE_ERROR] for possible errors.
+signal lobby_name_change_failed(lobby_name : String, error : int)
+
+## Emitted when [method lobby_join] was successful.
+## [br]
+## [br][b]lobby_name -[/b] The name of the lobby that the player joined.
+signal lobby_joined(lobby_name : String)
+
+## Emitted when [method lobby_join] failed.
+## [br]
+## [br][b]lobby_name -[/b] The name of the lobby that the player was unable to join.
+## [br][b]error -[/b] The reason why the joining failed.
+## Check [constant ENUMS.LOBBY_JOIN_ERROR] for possible errors.
+signal lobby_join_failed(lobby_name : String, error : int)
+
+## Emitted when any lobby data value is changed. Emitted after [method lobby_set_data].
+## [br]
+## [br][b]key -[/b] The key of the data that changed.
+## [br][b]value -[/b] The new value. This will be null is the data was erased.
+signal lobby_data_changed(key : String, value)
+
+## Emitted when any lobby tags value is changed. Emitted after [method set_lobby_tags] and [method erase_lobby_tags].
+## [br]
+## [br][b]key -[/b] The key of the tag that changed.
+## [br][b]value -[/b] The new value. This will be null is the tag was erased.
+signal lobby_tag_changed(key : String, value)
+
+## Emitted when a client joins the current lobby.
+## [br][b]IMPORTANT: This is emitted for all clients, [color=light_green]INCLUDING[/color] yourself when joining a lobby.[/b]
+## [br]
+## [br][b]client_id -[/b] The id of the client that joined.
+signal client_joined(client_id : int)
+
+## Emitted when a client leaves the current lobby.
+## [br][b]IMPORTANT: This is emitted for ALL clients, [color=crimson]EXCLUDING[/color] yourself when leaving a lobby.[/b]
+## [br]
+## [br][b]client_id -[/b] is the id of the client that left.
+signal client_left(client_id : int)
+
+## Emitted when a player uses [method player_set_data], [method player_erase_data] or [method player_set_username].
+## Player data is synchronized every second if it is altered.
+## [br]
+## [br][b]client_id -[/b] is the id of the client that left.
+signal player_data_changed(client_id : int, key : String, value)
+
+## Emitted if you get kicked from the current lobby.
+## [br]
+## [br][b]reason -[/b] The reason you were kicked, or an empty string if none was provided.
+signal kicked(reason : String)
+
+## Emitted as a result of [method get_public_lobbies].
+## [br]
+## [br][b]lobbies -[/b] An array of all public lobbies and their publicly available data.
+signal lobbies_received(lobbies : Array)
+
+## Emitted as a result of [method get_public_lobby].
+## [br]
+## [br][b]lobby -[/b] A dictionary containing public lobby data. If the lobby was not found the dictionary will be empty.
+signal lobby_received(lobby : Dictionary)
+
+## Emitted when the server accepts a matchmaking request.
+signal matchmaking_started()
+
+## Emitted whenever the current matchmaking phase changes.
+signal matchmaking_status_changed(status : int, details : Dictionary)
+
+## Emitted when matchmaking reserves a lobby. The normal [signal lobby_joined]
+## signal follows after the existing lobby join flow completes.
+signal matchmaking_match_found(lobby_name : String)
+
+## Emitted when matchmaking cannot find or create a match.
+signal matchmaking_failed(error : int)
+
+## Emitted after an active matchmaking request is cancelled.
+signal matchmaking_cancelled()
+
+## Emitted when a server switch rolls back or fails.
+signal lobby_switch_failed(error : int)
+
+## Emitted when the host of the current lobby changes. This might happen if the current host leaves or disconnects.
+## The server automatically decides which player is the host.
+## [br]
+## [br]Being the host does not do anything by itself, but is something that can help you when developing authoritative code.
+## [br]The [PropertySynchronizer] class will also make use of this if told to do so in the inspector.
+## [br]
+## [br][b]is_host -[/b] A boolean that indicates if you are the new host or not.
+## [br][b]new_host_id -[/b] The Client ID of the new host.
+signal host_changed(is_host : bool, new_host_id : int)
+
+## Emitted when a time synchronized event is triggered. See [method synced_event_create] for more information.
+## [br]
+## [br][b]event_name -[/b] The name of the event that has been triggered.
+## [br][b]parameters -[/b] Any parameters binded to the event.
+signal synced_event_triggered(event_name : String, parameters : Array)
+
+## Emitted when [method change_scene] is called.
+## [br]
+## [br][b]scene_path -[/b] The path of the scene.
+signal change_scene_called(scene_path : String)
+
+## Emitted right before the scene is switched when using [method change_scene]
+## [br]
+## [br][b]scene_path -[/b] The path of the scene.
+signal change_scene_success(scene_path : String)
+
+## Emitted when a scene change failed for any of the clients in the lobby.
+## This can be because of an invalid path, failing to load the resource, etc.
+## [br]
+## [br][b]scene_path -[/b] The path of the scene.
+signal change_scene_failed(scene_path : String)
+
+## Emitted when the player tries to join a friend on Steam.
+## [br]
+## [br][b]lobby_name -[/b] The name of lobby the player is trying to join.
+## [br][b]has_password -[/b] If the lobby has a password or not.
+signal steam_join_request(lobby_name : String, has_password : bool)
+
+## Emitted when the local player successfully logs into a GD-Sync account.
+## See [method account_login], [method account_login_from_session] and [method steam_login].
+## [br]
+## [br][b]username -[/b] The username of the logged in account.
+signal account_logged_in(username : String)
+
+## Emitted when the local player logs out of their GD-Sync account.
+## See [method account_logout].
+signal account_logged_out()
+
+
+
+
+#endregion
+# Initialization --------------------------------------------------------------
+# *****************************************************************************
+# -----------------------------------------------------------------------------
+#region Initialization
+
+var _request_processor
+var _connection_controller
+var _session_controller
+var _https_controller
+var _data_controller
+var _node_tracker
+var _interest_manager
+var _local_server
+var _steam
+var _logger
+var _matchmaking_controller
+var _server_switch_controller
+
+func _init():
+ process_mode = Node.PROCESS_MODE_ALWAYS
+
+ _request_processor = preload("res://addons/GD-Sync/Scripts/RequestProcessor.gd").new()
+ _request_processor.GDSync = self
+
+ _connection_controller = preload("res://addons/GD-Sync/Scripts/ConnectionController.gd").new()
+ _connection_controller.GDSync = self
+
+ _session_controller = preload("res://addons/GD-Sync/Scripts/SessionController.gd").new()
+ _session_controller.GDSync = self
+
+ _https_controller = preload("res://addons/GD-Sync/Scripts/HTTPSController.gd").new()
+ _https_controller.GDSync = self
+
+ _data_controller = preload("res://addons/GD-Sync/Scripts/DataController.gd").new()
+ _data_controller.GDSync = self
+
+ _node_tracker = preload("res://addons/GD-Sync/Scripts/NodeTracker.gd").new()
+ _node_tracker.GDSync = self
+
+ _interest_manager = preload("res://addons/GD-Sync/Scripts/InterestManager.gd").new()
+ _interest_manager.GDSync = self
+
+ _local_server = preload("res://addons/GD-Sync/Scripts/LocalServer.gd").new()
+ _local_server.GDSync = self
+
+ _steam = preload("res://addons/GD-Sync/Scripts/Steam.gd").new()
+ _steam.GDSync = self
+
+ _logger = preload("res://addons/GD-Sync/Scripts/Logger.gd").new()
+ _logger.GDSync = self
+
+ _matchmaking_controller = preload("res://addons/GD-Sync/Scripts/MatchmakingController.gd").new()
+ _matchmaking_controller.GDSync = self
+
+ _server_switch_controller = preload("res://addons/GD-Sync/Scripts/ServerSwitchController.gd").new()
+ _server_switch_controller.GDSync = self
+
+func _ready():
+ add_child(_request_processor)
+ add_child(_connection_controller)
+ add_child(_session_controller)
+ add_child(_https_controller)
+ add_child(_data_controller)
+ add_child(_node_tracker)
+ add_child(_interest_manager)
+ add_child(_local_server)
+ add_child(_steam)
+ add_child(_logger)
+ add_child(_matchmaking_controller)
+ add_child(_server_switch_controller)
+
+
+
+
+
+
+
+
+
+#endregion
+# General functions -----------------------------------------------------------
+# *****************************************************************************
+# -----------------------------------------------------------------------------
+#region General Functions
+
+## Starts the GD-Sync plugin by connecting to a server. If successful, [signal connected] will be emitted.
+## If not, [signal connection_failed] will be emitted.
+## [br][br][codeblock]
+## func _ready() -> void:
+## GDSync.connected.connect(_on_connected)
+## GDSync.connection_failed.connect(_on_connection_failed)
+## GDSync.disconnected.connect(_on_disconnected)
+## GDSync.start_multiplayer()
+##
+## func _on_connected() -> void:
+## print("Connected! Client ID: ", GDSync.get_client_id())
+##
+## func _on_connection_failed(error: int) -> void:
+## match error:
+## ENUMS.CONNECTION_FAILED.INVALID_PUBLIC_KEY:
+## push_error("Invalid public or private key.")
+## ENUMS.CONNECTION_FAILED.TIMEOUT:
+## push_error("Connection timed out.")
+##
+## func _on_disconnected() -> void:
+## print("Disconnected from GD-Sync.")
+## [/codeblock]
+func start_multiplayer() -> void:
+ _connection_controller.start_multiplayer()
+
+## An alternative for get_tree().quit(). Only use if you log into a GD-Sync account using [method account_login].
+## When quitting while logged in the plugin makes some callbacks to the server to update information like
+## your friend status.
+func quit() -> void:
+ _data_controller.quit()
+
+## Starts the GD-Sync plugin locally. This will allow for local peer-to-peer connections but will disable features
+## such as database access and automatic host switching. Local mode also disables some optimization features
+## related to networking.
+## Using local multiplayer does not require an account or API keys and does not use any data transfer.
+## [br][br]If successful, [signal connected] will be emitted.
+## If not, [signal connection_failed] will be emitted.
+func start_local_multiplayer() -> void:
+ _connection_controller.start_local_multiplayer()
+
+## Stops the GD-Sync plugin. This will break any existing connections and disable the multiplayer.
+func stop_multiplayer() -> void:
+ _connection_controller.stop_multiplayer()
+
+## Returns true if the plugin is connected to a server. Returns false if there is no active connection.
+func is_active() -> bool:
+ return _connection_controller.is_active()
+
+func _manual_connect(address : String) -> void:
+ _connection_controller.connect_to_server(address)
+
+## Returns your own Client ID. Returns -1 if you are not connected to a server.
+func get_client_id() -> int:
+ return _connection_controller.client_id
+
+## Measures and returns the ping between this client and another client. This only measures network travel time for the message. Useful for checking raw network latency between clients.
+## If the returned float is -1, the ping calculation failed.
+func get_client_ping(client_id : int) -> float:
+ return await _session_controller.get_ping(client_id, true)
+
+## Measures and returns the perceived ping between this client and another client. This includes network travel time plus additional delay caused by frame timing. Useful for estimating player-visible latency..
+## If the returned float is -1, the ping calculation failed.
+func get_client_perceived_ping(client_id : int) -> float:
+ return await _session_controller.get_ping(client_id, false)
+
+## Sets artificial network latency in milliseconds for debugging purposes.
+## The delay is applied locally on this client to both outgoing and incoming packets.
+## Set to [code]0[/code] to disable.
+## [br]
+## [br][b]latency_ms -[/b] The artificial latency in milliseconds.
+func set_artificial_latency(latency_ms : int) -> void:
+ _connection_controller.set_artificial_latency(latency_ms)
+
+## Returns the current artificial latency in milliseconds. Returns [code]0[/code] when disabled.
+func get_artificial_latency() -> int:
+ return _connection_controller.get_artificial_latency()
+
+## Returns the Client ID of the last client to perform a remote function call or variable sync on this client.
+## Useful for knowing where a remote function call came from.
+## Returns -1 if nobody performed a remote function call yet.
+func get_sender_id() -> int:
+ return _session_controller.get_sender_id()
+
+## Returns whether you are the host of the lobby you are in.
+## [br][br][codeblock]
+## func _ready() -> void:
+## GDSync.host_changed.connect(_on_host_changed)
+## if GDSync.is_host():
+## print("I am the host")
+##
+## func _on_host_changed(is_host: bool, new_host_id: int) -> void:
+## print("Host is now ", new_host_id, " (me=", is_host, ")")
+## [/codeblock]
+func is_host() -> bool:
+ return _connection_controller.host == get_client_id()
+
+## Returns the Client ID of the host of the current lobby you are in. Returns -1 if you are not in a lobby.
+func get_host() -> int:
+ return _connection_controller.host
+
+## Manually sets the host of the current lobby. Can only be used by the current host. This function does not work in local multiplayer.
+## [br]
+## [br][b]client_id -[/b] The Client ID of the new host.
+func set_host(client_id : int) -> void:
+ _request_processor.create_set_host_request(client_id)
+
+## Synchronizes a variable on a Object across all other clients in the current lobby.
+## Make sure that the variable is exposed using [method expose_var] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## Prefer [PropertySynchronizer] for values that change every frame.
+## [br]
+## [br][b]object -[/b] The Object you want to synchronize a variable on.
+## [br][b]variable_name -[/b] The name of the variable you want to synchronize.
+## [br][b]reliable -[/b] If reliable, if the request fails to deliver it will reattempt until successful.
+## This may introduce more latency. Use unreliable if the sync happens frequently (such as the position of a Node) for lower latency.
+## [br][br][codeblock]
+## var health := 100
+##
+## func _ready() -> void:
+## GDSync.expose_var(self, "health")
+##
+## func take_damage(amount: int) -> void:
+## health -= amount
+## GDSync.sync_var(self, "health")
+## [/codeblock]
+func sync_var(object : Object, variable_name : String, reliable : bool = true) -> void:
+ _request_processor.create_set_var_request(object, variable_name, -1, reliable)
+
+## Synchronizes a variable on a Object to a specific client in the current lobby.
+## Make sure that the variable is exposed using [method expose_var] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]client_id -[/b] The Client ID of the client you want to synchronize to.
+## [br][b]object -[/b] The Object you want to synchronize a variable on.
+## [br][b]variable_name -[/b] The name of the variable you want to synchronize.
+## [br][b]reliable -[/b] If reliable, if the request fails to deliver it will reattempt until successful.
+## This may introduce more latency. Use unreliable if the sync happens frequently (such as the position of a Node) for lower latency.
+func sync_var_on(client_id : int, object : Object, variable_name : String, reliable : bool = true) -> void:
+ _request_processor.create_set_var_request(object, variable_name, client_id, reliable)
+
+## Synchronizes a variable on an Object to a specific client, but only if that client is interested in the nearest [InterestObject].
+## If no enabled [InterestObject] is found, this behaves exactly like [method sync_var_on].
+## Make sure that the variable is exposed using [method expose_var] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]client_id -[/b] The Client ID of the client you want to synchronize to.
+## [br][b]object -[/b] The Object you want to synchronize a variable on.
+## [br][b]variable_name -[/b] The name of the variable you want to synchronize.
+## [br][b]reliable -[/b] If reliable, failed delivery will be retried until successful.
+## This may introduce more latency. Use unreliable for frequently synchronized state such as position.
+func sync_var_on_relevant(client_id : int, object : Object, variable_name : String, reliable : bool = true) -> void:
+ if _interest_manager.get_relevant_clients(object, true).has(client_id):
+ _request_processor.create_set_var_request(object, variable_name, client_id, reliable)
+
+## Synchronizes a variable on an Object to clients interested in the nearest [InterestObject].
+## If no enabled [InterestObject] is found, this behaves exactly like [method sync_var].
+## Make sure that the variable is exposed using [method expose_var] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]object -[/b] The Object you want to synchronize a variable on.
+## [br][b]variable_name -[/b] The name of the variable you want to synchronize.
+## [br][b]reliable -[/b] If reliable, failed delivery will be retried until successful.
+## This may introduce more latency. Use unreliable for frequently synchronized state such as position.
+func sync_var_relevant(object : Object, variable_name : String, reliable : bool = true) -> void:
+ _interest_manager.sync_variable(object, variable_name, reliable)
+
+## Calls a function on a Node or Resource on all other clients in the current lobby, excluding yourself. If the request fails to deliver it will reattempt until successful.
+## Make sure that the function is exposed using [method expose_func] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]callable -[/b] The function that you want to call.
+## [br][b]parameters -[/b] Optional arguments passed after the callable.
+## [br][br][codeblock]
+## # This Node must exist at the same path on every client.
+## func _ready() -> void:
+## GDSync.expose_func(open_door)
+## GDSync.call_func(open_door, "north")
+##
+## func open_door(door_id: String) -> void:
+## print("Door opened: ", door_id, " by ", GDSync.get_sender_id())
+## [/codeblock]
+func call_func(callable : Callable, ...parameters : Array) -> void:
+ _request_processor.create_function_call_request(callable, parameters, -1, true)
+
+## Calls a function on a Node or Resource on all other clients in the current lobby, excluding yourself. If the request fails to deliver it will not reattempt, may result in lower latency compared to the regular version.
+## Make sure that the function is exposed using [method expose_func] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]callable -[/b] The function that you want to call.
+## [br][b]parameters -[/b] The parameters of the function you are calling (if it has any).
+func call_func_unreliable(callable : Callable, ...parameters : Array) -> void:
+ _request_processor.create_function_call_request(callable, parameters, -1, false)
+
+## Calls a function on a Node or Resource on a specific client in the current lobby. If the request fails to deliver it will reattempt until successful.
+## Make sure that the function is exposed using [method expose_func] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]client_id -[/b] The Client ID of the client you want to call the function on.
+## [br][b]callable -[/b] The function that you want to call.
+## [br][b]parameters -[/b] The parameters of the function you are calling (if it has any).
+func call_func_on(client_id : int, callable : Callable, ...parameters : Array) -> void:
+ _request_processor.create_function_call_request(callable, parameters, client_id, true)
+
+## Calls a function on a Node or Resource on a specific client in the current lobby. If the request fails to deliver it will not reattempt, may result in lower latency compared to the regular version.
+## Make sure that the function is exposed using [method expose_func] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]client_id -[/b] The Client ID of the client you want to call the function on.
+## [br][b]callable -[/b] The function that you want to call.
+## [br][b]parameters -[/b] Optional parameters.
+func call_func_on_unreliable(client_id : int, callable : Callable, ...parameters : Array) -> void:
+ _request_processor.create_function_call_request(callable, parameters, client_id, false)
+
+## Calls a function on a specific client, but only if that client is interested in the nearest [InterestObject].
+## If no enabled [InterestObject] is found, this behaves exactly like [method call_func_on].
+## Make sure that the function is exposed using [method expose_func] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]client_id -[/b] The Client ID of the client you want to call the function on.
+## [br][b]callable -[/b] The function that you want to call.
+## [br][b]parameters -[/b] The parameters of the function you are calling (if it has any).
+func call_func_on_relevant(client_id : int, callable : Callable, ...parameters : Array) -> void:
+ if _interest_manager.get_relevant_clients(callable.get_object(), true).has(client_id):
+ _request_processor.create_function_call_request(callable, parameters, client_id, true)
+
+## Calls a function on a specific client, but only if that client is interested in the nearest [InterestObject]. If the request fails to deliver it will not reattempt, which may result in lower latency.
+## If no enabled [InterestObject] is found, this behaves exactly like [method call_func_on_unreliable].
+## Make sure that the function is exposed using [method expose_func] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]client_id -[/b] The Client ID of the client you want to call the function on.
+## [br][b]callable -[/b] The function that you want to call.
+## [br][b]parameters -[/b] Optional parameters.
+func call_func_on_relevant_unreliable(client_id : int, callable : Callable, ...parameters : Array) -> void:
+ if _interest_manager.get_relevant_clients(callable.get_object(), true).has(client_id):
+ _request_processor.create_function_call_request(callable, parameters, client_id, false)
+
+## Calls a function on clients interested in the nearest [InterestObject], excluding yourself. If the request fails to deliver it will reattempt until successful.
+## If no enabled [InterestObject] is found, this behaves exactly like [method call_func].
+## Make sure that the function is exposed using [method expose_func] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]callable -[/b] The function that you want to call.
+## [br][b]parameters -[/b] The parameters of the function you are calling (if it has any).
+func call_func_relevant(callable : Callable, ...parameters : Array) -> void:
+ _interest_manager.call_function(callable, parameters, true)
+
+## Calls a function on clients interested in the nearest [InterestObject], excluding yourself. If the request fails to deliver it will not reattempt, which may result in lower latency.
+## If no enabled [InterestObject] is found, this behaves exactly like [method call_func_unreliable].
+## Make sure that the function is exposed using [method expose_func] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]callable -[/b] The function that you want to call.
+## [br][b]parameters -[/b] The parameters of the function you are calling (if it has any).
+func call_func_relevant_unreliable(callable : Callable, ...parameters : Array) -> void:
+ _interest_manager.call_function(callable, parameters, false)
+
+## Calls a function on a Node or Resource on all clients in the current lobby, including yourself. If the request fails to deliver it will reattempt until successful.
+## Make sure that the function is exposed using [method expose_func] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]callable -[/b] The function that you want to call.
+## [br][b]parameters -[/b] The parameters of the function you are calling (if it has any).
+func call_func_all(callable : Callable, ...parameters : Array) -> void:
+ callable.callv(parameters)
+ _request_processor.create_function_call_request(callable, parameters, -1, true)
+
+## Calls a function on a Node or Resource on all clients in the current lobby, including yourself. If the request fails to deliver it will not reattempt, may result in lower latency compared to the regular version.
+## Make sure that the function is exposed using [method expose_func] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]callable -[/b] The function that you want to call.
+## [br][b]parameters -[/b] The parameters of the function you are calling (if it has any).
+func call_func_all_unreliable(callable : Callable, ...parameters : Array) -> void:
+ callable.callv(parameters)
+ _request_processor.create_function_call_request(callable, parameters, -1, false)
+
+## Calls a function locally and on clients interested in the nearest [InterestObject]. If the request fails to deliver it will reattempt until successful.
+## If no enabled [InterestObject] is found, this behaves exactly like [method call_func_all].
+## Make sure that the function is exposed using [method expose_func] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]callable -[/b] The function that you want to call.
+## [br][b]parameters -[/b] The parameters of the function you are calling (if it has any).
+func call_func_all_relevant(callable : Callable, ...parameters : Array) -> void:
+ callable.callv(parameters)
+ _interest_manager.call_function(callable, parameters, true)
+
+## Calls a function locally and on clients interested in the nearest [InterestObject]. If the request fails to deliver it will not reattempt, which may result in lower latency.
+## If no enabled [InterestObject] is found, this behaves exactly like [method call_func_all_unreliable].
+## Make sure that the function is exposed using [method expose_func] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]callable -[/b] The function that you want to call.
+## [br][b]parameters -[/b] The parameters of the function you are calling (if it has any).
+func call_func_all_relevant_unreliable(callable : Callable, ...parameters : Array) -> void:
+ callable.callv(parameters)
+ _interest_manager.call_function(callable, parameters, false)
+
+## Emits a signal on a Node or Resource on all other clients in the current lobby, excluding yourself.
+## Make sure that the signal is exposed using [method expose_signal] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]object -[/b] The object on which you want to emit the signal.
+## [br][b]signal_name -[/b] The name of the signal.
+## [br][b]parameters -[/b] Optional signal arguments.
+## [br][br][codeblock]
+## signal door_opened(door_id: String)
+##
+## func _ready() -> void:
+## GDSync.expose_signal(door_opened)
+## GDSync.emit_signal_remote(door_opened, "north")
+## [/codeblock]
+func emit_signal_remote(target_signal : Signal, ...parameters : Array) -> void:
+ var clients : Array = lobby_get_all_clients()
+ clients.erase(get_client_id())
+ _session_controller.emit_signal_on_clients(clients, target_signal, parameters)
+
+## Emits a signal on clients interested in the nearest [InterestObject], excluding yourself.
+## If no enabled [InterestObject] is found, this behaves exactly like [method emit_signal_remote].
+## Make sure that the signal is exposed using [method expose_signal] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]target_signal -[/b] The signal you want to emit.
+## [br][b]parameters -[/b] The parameters of the signal you are emitting (if it has any).
+func emit_signal_remote_relevant(target_signal : Signal, ...parameters : Array) -> void:
+ var clients : Array = _interest_manager.get_relevant_clients(target_signal.get_object())
+ _session_controller.emit_signal_on_clients(clients, target_signal, parameters)
+
+## Emits a signal on a Node or Resource on specific client in the current lobby.
+## Make sure that the signal is exposed using [method expose_signal] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]client_id -[/b] The Client ID of the client you want to emit the signal on.
+## [br][b]object -[/b] The object on which you want to emit the signal.
+## [br][b]signal_name -[/b] The name of the signal.
+## [br][b]parameters -[/b] The parameters of the signal you are emitting (if it has any).
+func emit_signal_remote_on(client_id : int, target_signal : Signal, ...parameters : Array) -> void:
+ _session_controller.emit_signal_on_clients([client_id], target_signal, parameters)
+
+## Emits a signal on a specific client, but only if that client is interested in the nearest [InterestObject].
+## If no enabled [InterestObject] is found, this behaves exactly like [method emit_signal_remote_on].
+## Make sure that the signal is exposed using [method expose_signal] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]client_id -[/b] The Client ID of the client you want to emit the signal on.
+## [br][b]target_signal -[/b] The signal you want to emit.
+## [br][b]parameters -[/b] The parameters of the signal you are emitting (if it has any).
+func emit_signal_remote_on_relevant(client_id : int, target_signal : Signal, ...parameters : Array) -> void:
+ if _interest_manager.get_relevant_clients(target_signal.get_object(), true).has(client_id):
+ _session_controller.emit_signal_on_clients([client_id], target_signal, parameters)
+
+## Emits a signal on a Node or Resource on all other clients in the current lobby, including yourself.
+## Make sure that the signal is exposed using [method expose_signal] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]object -[/b] The object on which you want to emit the signal.
+## [br][b]signal_name -[/b] The name of the signal.
+## [br][b]parameters -[/b] The parameters of the signal you are emitting (if it has any).
+func emit_signal_remote_all(target_signal : Signal, ...parameters : Array) -> void:
+ var clients : Array = lobby_get_all_clients()
+ _session_controller.emit_signal_on_clients(clients, target_signal, parameters)
+
+## Emits a signal locally and on clients interested in the nearest [InterestObject].
+## If no enabled [InterestObject] is found, this behaves exactly like [method emit_signal_remote_all].
+## Make sure that the signal is exposed using [method expose_signal] or [method expose_node]/[method expose_resource].
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]target_signal -[/b] The signal you want to emit.
+## [br][b]parameters -[/b] The parameters of the signal you are emitting (if it has any).
+func emit_signal_remote_all_relevant(target_signal : Signal, ...parameters : Array) -> void:
+ var clients : Array = _interest_manager.get_relevant_clients(target_signal.get_object(), true)
+ _session_controller.emit_signal_on_clients(clients, target_signal, parameters)
+
+## Instantiates a Node on all clients in the current lobby.
+## [br]
+## [br][b]IMPORTANT:[/b] Make sure the NodePath of the parent matches up on all clients.
+## [br]
+## [br][b]scene -[/b] The [PackedScene] you want to instantiate.
+## [br][b]parent -[/b] The parent/location of where you want to instantiate the Node.
+## [br][b]sync_starting_changes -[/b] If enabled, any changes made to the root Node of the instantiated scene
+## within the same frame will automatically be synchronized.
+## [br][b]excluded_properties -[/b] Names of properties you want to exclude from sync_starting_changes.
+## [br][b]replicate_on_join -[/b] If enabled, the instantiated Node will be replicated on clients that
+## join the lobby later on.
+## [br][br][codeblock]
+## var player := GDSync.multiplayer_instantiate(player_scene, $Players)
+## player.global_position = spawn_point.global_position
+## GDSync.set_gdsync_owner(player, GDSync.get_client_id())
+## [/codeblock]
+func multiplayer_instantiate(
+ scene : PackedScene,
+ parent : Node,
+ sync_starting_changes : bool = true,
+ excluded_properties : PackedStringArray = [],
+ replicate_on_join : bool = true) -> Node:
+ return _node_tracker.multiplayer_instantiate(scene, parent, sync_starting_changes, excluded_properties, replicate_on_join)
+
+## Queues a Node to be freed on all clients in the lobby.
+func multiplayer_queue_free(node : Node) -> void:
+ _node_tracker.multiplayer_queue_free(node)
+
+## Returns a float which contains the current multiplayer time. This time is synchronized across clients in
+## the same lobby. Can be used for time-based events. See [method synced_event_create] for creating
+## time-based triggers.
+## [br]
+## [br][b]IMPORTANT:[/b] It may take up to a second for the time to synchronize after just joining a lobby.
+func get_multiplayer_time() -> float:
+ return _session_controller.synced_time
+
+## Create a time-based event that triggers after a delay. GD-Sync will attempt to trigger this event
+## on all clients at the same time, regardless of the latency between clients. Useful for creating
+## time-critical events or mechanics. After the delay, [signal synced_event_triggered] is emitted.
+## [br]
+## [br][b]IMPORTANT:[/b] If the given delay is shorter than the latency between two clients, the
+## event trigger might be delayed. It is recommended to always use a delay >= 1 second.
+## [br]
+## [br][b]event_name -[/b] The name of the event. Queued events can share the same name.
+## [br][b]delay -[/b] The delay in seconds after which the event should be triggered.
+## [br][b]parameters -[/b] Any parameters which should be binded to the event.
+## [br][br][codeblock]
+## func _ready() -> void:
+## GDSync.synced_event_triggered.connect(_on_synced_event)
+##
+## func start_round() -> void:
+## GDSync.synced_event_create("RoundStart", 3.0, ["Desert"])
+##
+## func _on_synced_event(event_name: String, parameters: Array) -> void:
+## if event_name == "RoundStart":
+## print("Round starts on map ", parameters[0])
+## [/codeblock]
+func synced_event_create(event_name : String, delay : float = 1.0, parameters : Array = []) -> void:
+ _session_controller.register_event(event_name, get_multiplayer_time()+delay, parameters, true)
+
+## Changes the current scene for all clients. Waits with changing until the scene has fully loaded on all clients.
+## Emits [code]change_scene_called[/code] when a scene change is requested, [code]change_scene_success[/code] when it succeeds,
+## and [code]change_scene_failed[/code] if it fails on any client.
+## [br]
+## [br][b]scene_path -[/b] The resource path of the scene.
+## [br][br][codeblock]
+## func _ready() -> void:
+## GDSync.change_scene_called.connect(func (path): print("Loading ", path))
+## GDSync.change_scene_success.connect(func (path): print("Switched to ", path))
+## GDSync.change_scene_failed.connect(func (path): push_error("Failed to load ", path))
+##
+## func go_to_game() -> void:
+## GDSync.change_scene("res://Scenes/game.tscn")
+## [/codeblock]
+func change_scene(scene_path : String) -> void:
+ _session_controller.change_scene(scene_path)
+
+
+
+
+
+
+
+#endregion
+# Security & safety functions -------------------------------------------------
+# *****************************************************************************
+# -----------------------------------------------------------------------------
+#region Security & safety functions
+
+## If set to true, all remote function calls and variable synchronization requests will be blocked by default.
+## Only functions, variables and Nodes that are exposed using [method expose_func], [method expose_var] and [expose_node]
+## may be accessed remotely. This setting can also be found in the configuration menu.
+## [br]
+## [br]
+## We STRONGLY recommended keeping this enabled at all times. Disabling it may introduce security risks.
+## [br]
+## [br][b]protected -[/b] If protected mode should be enabled or disabled.
+func set_protection_mode(protected : bool) -> void:
+ _request_processor.set_protection_mode(protected)
+
+## Allows you to register a resource with a unique ID so that GD-Sync may access it remotely.
+## [br]
+## [br][b]resource -[/b] The resource you want to register.
+## [br][b]id -[/b] The ID you want to assign to it.
+func register_resource(resource : RefCounted, id : String) -> void:
+ _session_controller.create_resource_reference(resource, id)
+
+## Allows you to deregister a previously registered resource.
+## [br]
+## [br][b]resource -[/b] The resource you want to deregister.
+func deregister_resource(resource : RefCounted) -> void:
+ _session_controller.erase_resource_reference(resource)
+
+## Exposes a Node so that all [method call_func], [method call_func_on], [method sync_var] and [method sync_var_on] will succeed.
+## Only use if the Node and its script contain non-destructive functions.
+## [br]
+## [br][b]IMPORTANT:[/b] Make sure the NodePath of the Node matches up on all clients.
+## [br]
+## [br][b]node -[/b] The Node you want to expose.
+func expose_node(node : Node) -> void:
+ _session_controller.expose_object(node)
+
+## Hides a Node so that all [method call_func], [method call_func_on], [method sync_var] and [method sync_var_on] will fail.
+## This will not revert [method expose_func] and [method expose_var].
+## [br]
+## [br][b]IMPORTANT:[/b] Make sure the NodePath of the Node matches up on all clients.
+## [br]
+## [br][b]node -[/b] The Node you want to hide.
+func hide_node(node : Node) -> void:
+ _session_controller.hide_object(node)
+
+## Exposes a Resource so that all [method call_func], [method call_func_on], [method sync_var] and [method sync_var_on] will succeed.
+## Only use if the Resource and its script contain non-destructive functions.
+## [br]
+## [br][b]IMPORTANT:[/b] Make sure the Resource has been registered using [method register_resource].
+## [br]
+## [br][b]resource -[/b] The Resource you want to expose.
+func expose_resource(resource : RefCounted) -> void:
+ _session_controller.expose_object(resource)
+
+## Hides a Resource so that all [method call_func], [method call_func_on], [method sync_var] and [method sync_var_on] will fail.
+## This will not revert [method expose_func] and [method expose_var].
+## [br]
+## [br][b]IMPORTANT:[/b] Make sure the Resource has been registered using [method register_resource].
+## [br]
+## [br][b]resource -[/b] The Resource you want to hide.
+func hide_resource(resource : RefCounted) -> void:
+ _session_controller.hide_object(resource)
+
+## Exposes a function so that the [code]call_func*[/code] methods will succeed.
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]callable -[/b] The function you want to expose.
+## [br][b]permission -[/b] Which lobby members may invoke this remotely. See [constant ENUMS.EXPOSE_PERMISSION].
+func expose_func(callable : Callable, permission : int = ENUMS.EXPOSE_PERMISSION.ANYONE) -> void:
+ _session_controller.expose_func(callable, permission)
+
+## Hides a function so that the [code]call_func*[/code] methods will fail.
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]callable -[/b] The function you want to hide.
+func hide_func(callable : Callable) -> void:
+ _session_controller.hide_func(callable)
+
+## Exposes a signal so that the [code]emit_signal_remote*[/code] methods will succeed.
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]signal_name -[/b] The signal you want to expose.
+## [br][b]permission -[/b] Which lobby members may emit this remotely. See [constant ENUMS.EXPOSE_PERMISSION].
+func expose_signal(target_signal : Signal, permission : int = ENUMS.EXPOSE_PERMISSION.ANYONE) -> void:
+ _session_controller.expose_signal(target_signal, permission)
+
+## Hides a signal so that the [code]emit_signal_remote*[/code] methods will fail.
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]signal_name -[/b] The signal you want to hide.
+func hide_signal(target_signal : Signal) -> void:
+ _session_controller.hide_signal(target_signal)
+
+## Exposes a variable so that the [code]sync_var*[/code] methods will succeed.
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]object -[/b] The Object on which you want to expose the variable.
+## [br][b]variable_name -[/b] The name of the variable you want to expose.
+## [br][b]permission -[/b] Which lobby members may sync this remotely. See [constant ENUMS.EXPOSE_PERMISSION].
+func expose_var(object : Object, variable_name : String, permission : int = ENUMS.EXPOSE_PERMISSION.ANYONE) -> void:
+ _session_controller.expose_property(object, variable_name, permission)
+
+## Hides a variable so that the [code]sync_var*[/code] methods will fail.
+## [br]
+## [br][b]IMPORTANT:[/b] For Nodes, make sure the NodePath of the Node matches up on all clients. For Resources, register them using [method register_resource].
+## [br]
+## [br][b]object -[/b] The Object on which you want to hide the variable.
+## [br][b]variable_name -[/b] The name of the variable you want to hide.
+func hide_var(object : Object, variable_name : String) -> void:
+ _session_controller.hide_property(object, variable_name)
+
+
+
+
+
+
+
+
+
+#endregion
+# Node Ownership --------------------------------------------------------------
+# *****************************************************************************
+# -----------------------------------------------------------------------------
+#region Node Ownership
+
+## Sets the owner of a Node. Node ownership is recursive and will apply to all children.
+## Being the owner of a Node does not do anything by itself, but is useful when writing certain scripts.
+## For example, when you are re-using your player scene for all players, you can only execute the keyboard inputs on
+## the player of which you are the owner.
+## [br]The [PropertySynchronizer] class will also make use of this if told to do so in the inspector.
+## [br]
+## [br][b]IMPORTANT:[/b] Make sure the NodePath of the Node matches up on all clients.
+## [br]
+## [br][b]node -[/b] The Node on which you want to assign ownership to.
+## [br][b]owner -[/b] The client ID of the new owner.
+## [br][br][codeblock]
+## func _ready() -> void:
+## GDSync.connect_gdsync_owner_changed(self, _on_owner_changed)
+## GDSync.set_gdsync_owner(self, GDSync.get_client_id())
+##
+## func _process(_delta: float) -> void:
+## if not GDSync.is_gdsync_owner(self):
+## return
+## # Local input only on the owned player instance.
+##
+## func _on_owner_changed(new_owner: int) -> void:
+## print("Owner is now ", new_owner)
+## [/codeblock]
+func set_gdsync_owner(node : Node, owner : int) -> void:
+ if !_connection_controller.valid_connection(): return
+ _session_controller.set_gdsync_owner(node, owner)
+
+## Clears the owner of a Node. Node ownership is recursive and will be removed on all children.
+## [br]
+## [br][b]IMPORTANT:[/b] Make sure the NodePath of the Node matches up on all clients.
+## [br]
+## [br][b]node -[/b] The Node on which you want to clear ownership.
+func clear_gdsync_owner(node : Node) -> void:
+ if !_connection_controller.valid_connection(): return
+ _session_controller.set_gdsync_owner(node, -1)
+
+## Returns the Client ID of the client that has ownership of the Node. Returns -1 if there is no owner.
+## [br]
+## [br][b]node -[/b] The Node from which you want to retrieve the owner.
+func get_gdsync_owner(node : Node) -> int:
+ return _session_controller.get_gdsync_owner(node)
+
+## Returns true if you are the owner of the Node in question. Returns false if you are not the owner or when there is not owner.
+## [br]
+## [br][b]node -[/b] The Node on which you want to perform the ownership check.
+func is_gdsync_owner(node : Node) -> bool:
+ return _session_controller.is_gdsync_owner(node)
+
+## Connects up a signal so that a specific function gets called if the owner of the Node changes.
+## The function must have one parameter which is the Client ID of the new owner.
+## The Client ID will be -1 if the doesn't have an owner anymore
+## [br]
+## [br][b]node -[/b] The Node of which you want to monitor ownership.
+## [br][b]callable -[/b] The function that should get called if the owner changes.
+func connect_gdsync_owner_changed(node : Node, callable : Callable) -> void:
+ _session_controller.connect_gdsync_owner_changed(node, callable)
+
+
+## Disconnects a function from the ownership signal created in [method connect_gdsync_owner_changed].
+## [br]
+## [br][b]node -[/b] The Node of which you want to disconnect ownership monitoring.
+## [br][b]callable -[/b] The function that should get disconnected.
+func disconnect_gdsync_owner_changed(node : Node, callable : Callable) -> void:
+ _session_controller.disconnect_gdsync_owner_changed(node, callable)
+
+
+
+
+
+
+
+
+
+#endregion
+# Lobby Functions -------------------------------------------------------------
+# *****************************************************************************
+# -----------------------------------------------------------------------------
+#region Lobby Functions
+
+## Attempts to retrieve all publicly visible lobbies from the server.
+## Will emit the signal [signal lobbies_received] once the server has collected all lobbies
+## [br][br][codeblock]
+## func _ready() -> void:
+## GDSync.lobbies_received.connect(_on_lobbies_received)
+## GDSync.get_public_lobbies()
+##
+## func _on_lobbies_received(lobbies: Array) -> void:
+## for lobby in lobbies:
+## print(lobby["Name"], " ", lobby["PlayerCount"], "/", lobby["PlayerLimit"])
+## [/codeblock]
+func get_public_lobbies() -> void:
+ if !_connection_controller.valid_connection(): return
+ if _connection_controller.is_local():
+ _local_server.get_public_lobbies()
+ else:
+ _request_processor.get_public_lobbies()
+
+## Attempts to retrieve a publicly visible lobby from the server.
+## Will emit the signal [signal lobby_received] once the server has collected the lobby information
+## [br]
+## [br][b]lobby_name -[/b] The name of the lobby.
+func get_public_lobby(lobby_name : String) -> void:
+ if !_connection_controller.valid_connection(): return
+ if _connection_controller.is_local():
+ _local_server.get_public_lobby(lobby_name)
+ else:
+ _request_processor.get_public_lobby(lobby_name)
+
+## Attempts to create a lobby on the server. If successful [signal lobby_created] is emitted.
+## If it fails [signal lobby_creation_failed] is emitted. Creating a lobby has a cooldown of 3 seconds.
+## Creating a lobby does not automatically join it. Call [method lobby_join] after [signal lobby_created].
+## [br]
+## [br][b]name -[/b] The name of the lobby you want to create. Has a maximum of 32 characters.
+## [br][b]password -[/b] The password of the lobby. Leave empty if you want everyone to be able to join without a password.
+## Has a maximum of 16 characters.
+## [br][b]public -[/b] If true, the lobby will be visible when using [method get_public_lobbies]
+## [br][b]player_limit -[/b] The player limit of the lobby. If 0 it will automatically be set to the maximum your plan allows.
+## This is also the case if the limit entered exceeds your plan limit.
+## [br][b]tags -[/b] Any starting tags you would like to add to the lobby.
+## [br][b]data -[/b] Any starting data you would like to add to the lobby.
+## [br][br][codeblock]
+## func _ready() -> void:
+## GDSync.lobby_created.connect(_on_lobby_created)
+## GDSync.lobby_creation_failed.connect(_on_lobby_creation_failed)
+## GDSync.lobby_create(
+## "Cool Lobby",
+## "",
+## true,
+## 8,
+## {"Map": "Desert", "Mode": "FFA"},
+## )
+##
+## func _on_lobby_created(lobby_name: String) -> void:
+## GDSync.lobby_join(lobby_name)
+##
+## func _on_lobby_creation_failed(lobby_name: String, error: int) -> void:
+## push_error("Failed to create ", lobby_name, ": ", error)
+## [/codeblock]
+func lobby_create(name : String, password : String = "", public : bool = true, player_limit : int = 0, tags : Dictionary = {}, data : Dictionary = {}) -> void:
+ if !_connection_controller.valid_connection(): return
+ if _connection_controller.is_local():
+ _local_server.create_local_lobby(name, password, public, player_limit, tags, data)
+ else:
+ _request_processor.create_new_lobby_request(name, password, public, player_limit, tags, data)
+
+## Attempts to join an existing lobby. If successful [signal lobby_joined] is emitted.
+## If it fails [signal lobby_join_failed] is emitted.
+## Using this function might cause your Client ID to change when joining a lobby that is not on your current server.
+## [br]
+## [br][b]name -[/b] The name of the lobby you are trying to join.
+## [br][b]password -[/b] The password of the lobby you are trying to join.
+## If the lobby has no password this can have any value.
+## [br][br][codeblock]
+## func _ready() -> void:
+## GDSync.lobby_joined.connect(func (n): print("Joined ", n))
+## GDSync.lobby_join_failed.connect(func (n, e): push_error("Join failed ", n, " ", e))
+## GDSync.client_joined.connect(func (id): print("Client joined ", id))
+## GDSync.client_left.connect(func (id): print("Client left ", id))
+## GDSync.lobby_join("Cool Lobby")
+## [/codeblock]
+func lobby_join(name : String, password : String = "") -> void:
+ if !_connection_controller.valid_connection(): return
+ _session_controller.set_lobby_data(name, password)
+ if _connection_controller.is_local():
+ _local_server.join_lobby(name, password)
+ else:
+ _request_processor.create_join_lobby_request(name, password)
+
+## Closes the lobby you are currently in, blocking any new players from joining. The lobby will still be visible when using [method get_public_lobbies].
+func lobby_close() -> void:
+ if !_connection_controller.valid_connection(): return
+ _request_processor.create_close_lobby_request()
+
+## Opens the lobby you are currently in, allowing new players to join.
+func lobby_open() -> void:
+ if !_connection_controller.valid_connection(): return
+ _request_processor.create_open_lobby_request()
+
+## Sets the visibility of the lobby you are currently in. Decides whether the lobby shows up when using [method get_public_lobbies]
+## [br]
+## [br][b]public -[/b] If the lobby should be visible or not.
+func lobby_set_visibility(public : bool) -> void:
+ if !_connection_controller.valid_connection(): return
+ _request_processor.create_lobby_visiblity_request(public)
+
+## Changes the name of the current lobby. Only works for the host of the lobby. If successful [signal lobby_name_changed] is emitted.
+## If it fails [signal lobby_name_change_failed] is emitted. Changing the lobby name shares a 3 second cooldown with [method lobby_create].
+## [br]
+## [br][b]name -[/b] The new lobby name. Has a maximum of 32 characters.
+func lobby_change_name(name : String) -> void:
+ _request_processor.create_lobby_name_change_request(name)
+
+## Changes the password of the lobby. Only works for the host of the lobby.
+## [br]
+## [br][b]password -[/b] The new password of the lobby.
+func lobby_change_password(password : String) -> void:
+ if !_connection_controller.valid_connection(): return
+ _request_processor.create_change_lobby_password_request(password)
+
+## Leaves the lobby you are currently in. This does not emit any signals.
+func lobby_leave() -> void:
+ if !_connection_controller.valid_connection(): return
+ if _connection_controller.is_local():
+ _local_server.leave_local_lobby()
+ _connection_controller.leave_local_lobby_client()
+ else:
+ _request_processor.create_leave_lobby_request()
+ _data_controller.set_friend_status()
+ _session_controller.lobby_left()
+ _node_tracker.lobby_left()
+ _interest_manager.clear()
+ _steam.leave_steam_lobby()
+
+## Kicks a client from the current lobby. Only works for the host of the lobby.
+## [br]
+## [br][b]client_id -[/b] The ID of the client you want to kick.
+## [br][b]reason -[/b] An optional message explaining why the client was kicked.
+func lobby_kick_client(client_id : int, reason : String = "") -> void:
+ if !_connection_controller.valid_connection(): return
+ _request_processor.kick_player(client_id, reason)
+
+## Returns the client IDs of all clients in the current lobby.
+func lobby_get_all_clients() -> Array:
+ return _session_controller.get_all_clients()
+
+## Returns the amount of players in the current lobby.
+func lobby_get_player_count() -> int:
+ return _session_controller.get_all_clients().size()
+
+## Get the current lobby name
+func lobby_get_name() -> String:
+ return _session_controller.lobby_name
+
+## Get the current lobby visibility. Returns true if the lobby is publicly visible.
+func lobby_get_visibility() -> bool:
+ return _session_controller.get_lobby_visibility()
+
+## Returns the player limit of the current lobby.
+func lobby_get_player_limit() -> int:
+ return _session_controller.get_lobby_player_limit()
+
+## Returns true if the current lobby has a password.
+func lobby_has_password() -> bool:
+ return _session_controller.lobby_has_password()
+
+## Adds a new or updates the value of a tag. Tags are publicly visible data that is returned with [method get_public_lobbies].
+## Especially useful when display information like the gamemode or map.
+## [br]
+## [br]
+## This does not instantly update, so it won't have an affect on [method lobby_has_tag] and [method lobby_get_tag] until
+## a response from the server is returned. If the operation was successful [signal lobby_tag_changed] is emitted.
+## [br]
+## [br][b]key -[/b] The key of the tag.
+## [br][b]value -[/b] The value of the tag that should be stored.
+func lobby_set_tag(key : String, value) -> void:
+ if !_connection_controller.valid_connection(): return
+ _request_processor.create_set_lobby_tag_request(key, value)
+
+## Deletes an existing tag.
+## [br]
+## [br]
+## This does not instantly update, so it won't have an affect on [method lobby_has_tag] and [method lobby_get_tag] until
+## a response from the server is returned. If the operation was successful [signal lobby_tag_changed] is emitted.
+## [br]
+## [br][b]key -[/b] The key of the tag.
+func lobby_erase_tag(key : String) -> void:
+ if !_connection_controller.valid_connection(): return
+ _request_processor.create_erase_lobby_tag_request(key)
+
+## Returns true if a tag with the given key exists.
+## [br]
+## [br][b]key -[/b] The key of the tag.
+func lobby_has_tag(key : String) -> bool:
+ return _session_controller.has_lobby_tag(key)
+
+## Gets the value of a lobby tag.
+## [br]
+## [br][b]key -[/b] The key of the tag.
+## [br][b]default -[/b] The default value that is returned if the given key does not exist.
+func lobby_get_tag(key : String, default = null):
+ return _session_controller.get_lobby_tag(key, default)
+
+## Returns a dictionary with all lobby tags and their values.
+func lobby_get_all_tags() -> Dictionary:
+ return _session_controller.get_all_lobby_tags()
+
+## Adds new or updates existing lobby data. Data is private data that can only be viewed from inside the lobby.
+## [br]
+## [br]
+## This does not instantly update, so it won't have an affect on [method lobby_has_data] and [method lobby_get_data] until
+## a response from the server is returned. If operation was successful [signal lobby_data_changed] is emitted.
+## [br]
+## [br][b]key -[/b] The key of the data.
+## [br][b]value -[/b] The value of the data that should be stored.
+func lobby_set_data(key : String, value) -> void:
+ if !_connection_controller.valid_connection(): return
+ _request_processor.create_set_lobby_data_request(key, value)
+
+## Deletes existing data.
+## [br]
+## [br]
+## This does not instantly update, so it won't have an affect on [method lobby_has_data] and [method lobby_get_data] until
+## a response from the server is returned. If operation was successful [signal lobby_data_changed] is emitted.
+## [br]
+## [br][b]key -[/b] The key of the tag.
+func lobby_erase_data(key : String) -> void:
+ if !_connection_controller.valid_connection(): return
+ _request_processor.create_erase_lobby_data_request(key)
+
+## Returns true if data with the given key exists.
+## [br]
+## [br][b]key -[/b] The key of the data.
+func lobby_has_data(key : String) -> bool:
+ return _session_controller.has_lobby_data(key)
+
+## Gets the value of lobby data.
+## [br]
+## [br][b]key -[/b] The key of the data.
+## [br][b]default -[/b] The default value that is returned if the given key does not exist.
+func lobby_get_data(key : String, default = null):
+ return _session_controller.get_lobby_data(key, default)
+
+## Returns a dictionary with all lobby data and their values.
+func lobby_get_all_data() -> Dictionary:
+ return _session_controller.get_all_lobby_data()
+
+
+
+
+
+
+
+#endregion
+# Matchmaking Functions -------------------------------------------------------
+# *****************************************************************************
+# -----------------------------------------------------------------------------
+#region Matchmaking Functions
+
+## Starts matchmaking. Starting a new request automatically cancels the
+## previous request. Matchmaking is not available in local multiplayer.
+## Use [method MatchmakingRequest.set_min_players] to create a lobby before it is full;
+## later queued players can still join while that lobby stays open.
+## [br][br]See [MatchmakingRequest] for full configuration options.
+## [br][br][codeblock]
+## func _ready() -> void:
+## GDSync.matchmaking_started.connect(func (): print("Searching…"))
+## GDSync.matchmaking_match_found.connect(func (name): print("Found ", name))
+## GDSync.matchmaking_failed.connect(func (error): push_error(error))
+## GDSync.lobby_joined.connect(func (name): print("In lobby ", name))
+##
+## var request := MatchmakingRequest.new(4)
+## request.set_min_players(2)
+## request.set_required_tags({"Mode": "Co-op"})
+## request.set_timeout(60.0)
+## GDSync.matchmaking_start(request)
+## [/codeblock]
+func matchmaking_start(request: MatchmakingRequest) -> void:
+ _matchmaking_controller.start(request)
+
+## Cancels the active matchmaking request.
+func matchmaking_cancel() -> void:
+ _matchmaking_controller.cancel()
+
+## Returns whether a matchmaking request is currently active.
+func matchmaking_is_active() -> bool:
+ return _matchmaking_controller.is_active()
+
+## Returns the status of the active matchmaking request.
+## See [enum ENUMS.MATCHMAKING_STATUS] for all possible values.
+func matchmaking_get_status() -> int:
+ return _matchmaking_controller.get_status()
+
+## Returns additional information about the status of the active matchmaking request,
+## such as the amount of queued players. Empty if no request is active.
+func matchmaking_get_status_details() -> Dictionary:
+ return _matchmaking_controller.get_status_details()
+
+#endregion
+# Player Functions ------------------------------------------------------------
+# *****************************************************************************
+# -----------------------------------------------------------------------------
+#region Player Functions
+
+## Sets data for your client. Player data has a maximum size of 2048 bytes, if this limit is exceeded
+## a critical error is printed.
+## Emits [signal player_data_changed]. It may take up to 1 second for this signal to be emitted, as player
+## data is synchronized every second if altered.
+## [br]
+## [br][b]key -[/b] The key of the player data.
+## [br][b]value -[/b] The value of the player data.
+## [br][br][codeblock]
+## var player_id: int
+##
+## func _ready() -> void:
+## player_id = GDSync.get_client_id()
+## GDSync.player_data_changed.connect(_on_player_data_changed)
+## GDSync.player_set_data("Color", Color.RED)
+##
+## func _on_player_data_changed(client_id: int, key: String, value) -> void:
+## if client_id != player_id:
+## return
+## if key == "Color" and value is Color:
+## modulate = value
+## [/codeblock]
+func player_set_data(key : String, value) -> void:
+ if !_connection_controller.valid_connection(): return
+ _session_controller.set_player_data(key, value)
+ _request_processor.create_set_player_data_request(key, value)
+
+## Erases data for your client.
+## Emits [signal player_data_changed] with null as the value.
+## [br]
+## [br][b]key -[/b] The key of the player data.
+func player_erase_data(key : String) -> void:
+ if !_connection_controller.valid_connection(): return
+ _session_controller.erase_player_data(key)
+ _request_processor.create_erase_player_data_request(key)
+
+## Gets data from a specific client. If you want to retrieve your own data you can input your own id.
+## You can get your own id using [method get_client_id].
+## [br]
+## [br][b]client_id -[/b] The Client ID of which client you would like to get the data from.
+## [br][b]key -[/b] The key of the player data.
+## [br][b]default -[/b] The default value that is returned if the given key does not exist.
+func player_get_data(client_id : int, key : String, default = null):
+ if !_connection_controller.valid_connection(): return default
+ return _session_controller.get_player_data(client_id, key, default)
+
+## Returns whether a specific client has player data stored under the given key.
+## If you want to check your own data you can input your own id.
+## You can get your own id using [method get_client_id].
+## [br]
+## [br][b]client_id -[/b] The Client ID of which client you would like to check the data from.
+## [br][b]key -[/b] The key of the player data.
+func player_has_data(client_id : int, key : String) -> bool:
+ if !_connection_controller.valid_connection(): return false
+ return _session_controller.has_player_data(client_id, key)
+
+## Gets all data from a specific client. If you want to retrieve your own data you can input your own id.
+## You can get your own id using [method get_client_id].
+## [br]
+## [br][b]client_id -[/b] The Client ID of which client you would like to get the data from.
+func player_get_all_data(client_id : int) -> Dictionary:
+ if !_connection_controller.valid_connection(): return {}
+ return _session_controller.get_all_player_data(client_id)
+
+## Sets the username of the player. If enabled in the configuration menu, usernames can be set to unique.
+## When this setting is enabled there can be no duplicate usernames inside a lobby.
+## Emits [signal player_data_changed] with the key "Username".
+## [br]
+## [br][b]name -[/b] The username of this client.
+func player_set_username(name : String) -> void:
+ _request_processor.create_set_username_request(name)
+ _session_controller.set_player_data("Username", name)
+
+## Gets the username of the player with the given client ID. By default uses the ID of the local player.
+## [br]
+## [br][b]client_id -[/b] The ID of this client.
+## [br][b]default -[/b] The default value to return if the username was not found.
+func player_get_username(client_id : int = get_client_id(), default := "") -> String:
+ if !_connection_controller.valid_connection(): return default
+ return _session_controller.get_player_data(client_id, "Username", default)
+
+
+
+
+#endregion
+# Accounts & Persistent Data Storage ------------------------------------------
+# *****************************************************************************
+# -----------------------------------------------------------------------------
+#region Accounts & Persistent Data Storage
+
+## Creates an account in the database linked to the API key.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_CREATION_RESPONSE_CODE].
+## [br]
+## [br][b]email -[/b] The email of the account. The email has to be unique.
+## [br][b]username -[/b] The username of the account. The username has to be unique.
+## The username has to be between 3 and 20 characters long.
+## [br][b]password -[/b] The password of the account.
+## The password has to be between 3 and 20 characters long.
+func account_create(email : String, username : String, password : String) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.create_account(email, username, password)
+
+## Deletes an existing account in the database linked to the API key.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_DELETION_RESPONSE_CODE].
+## [br]
+## [br][b]email -[/b] The email of the account.
+## [br][b]password -[/b] The password of the account.
+func account_delete(email : String, password : String) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.delete_account(email, password)
+
+## Can be used to verify the email of an account. Requires email verification to be enabled in the User Accounts
+## settings. An email can be verified by inputting the verification code sent to the email address.
+## Verifying the email will automatically log in the user.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_VERIFICATION_RESPONSE_CODE].
+## [br]
+## [br][b]email -[/b] The email of the account.
+## [br][b]code -[/b] The verification code that was sent to the email address.
+## [br][b]valid_time -[/b] The time in seconds how long the login session is valid.
+func account_verify(email : String, code : String, valid_time : float = 86400) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.verify_account(email, code, valid_time)
+
+## Sends a new verification code to the email address. A new code can only be sent once the most recent
+## code has expired. Requires email verification to be enabled in the User Account settings.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_RESEND_VERIFICATION_RESPONSE_CODE].
+## [br]
+## [br][b]email -[/b] The email of the account.
+## [br][b]password -[/b] The password of the account.
+func account_resend_verification_code(email : String, password : String) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.resend_verification_code(email, password)
+
+## Returns if the specified account has a verified email.
+## [br][br]Returns a [Dictionary] with the format seen below
+## and the [constant ENUMS.ACCOUNT_IS_VERIFIED_RESPONSE_CODE] response code.
+## [br]
+## [br][b]username -[/b] The username of the account.
+## [codeblock]
+## {
+## "Code" : 0,
+## "Result" : true
+## }[/codeblock]
+func account_is_verified(username : String = "") -> Dictionary:
+ if _connection_controller.is_local_check(): return {"Code" : 1}
+ return await _data_controller.is_verified(username)
+
+## Returns whether the local player is currently logged into a GD-Sync account.
+## This does not reflect lobby usernames set using [method player_set_username].
+func account_is_logged_in() -> bool:
+ return _data_controller.logged_in
+
+## Attempt to login into an existing account.
+## [br][br]Returns a [Dictionary] with the format seen below
+## and the [constant ENUMS.ACCOUNT_LOGIN_RESPONSE_CODE] response code.
+## [br]
+## [br]
+## If the user is banned, it will include the "Banned" key, which contains the unix timestamp when the ban will
+## expire. If the ban is permanent, the value will be -1.
+## [br]
+## [br][b]email -[/b] The email of the account.
+## [br][b]password -[/b] The password of the account.
+## [br][b]valid_time -[/b] The time in seconds how long the login session is valid.
+## [codeblock]
+## {
+## "Code" : 0,
+## "BanTime" : 1719973379
+## }[/codeblock]
+func account_login(email : String, password : String, valid_time : float = 86400) -> Dictionary:
+ if _connection_controller.is_local_check(): return {"Code" : 1}
+ return await _data_controller.login(email, password, valid_time)
+
+## Attempt to login with a previous session. If that session has not yet expired it will login using
+## and refresh the session time.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_LOGIN_RESPONSE_CODE].
+## [br]
+## [br][b]valid_time -[/b] The time in seconds how long the login session is valid.
+func account_login_from_session(valid_time : float = 86400) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.login_from_session(valid_time)
+
+## Invalidates the current login session.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_LOGOUT_RESPONSE_CODE].
+func account_logout() -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.logout()
+
+## Bans the current logged-in account.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_BAN_RESPONSE_CODE].
+## [br]
+## [br][b]ban_duration -[/b] The ban duration in days. Any amount above 1000 days results in a permanent ban.
+func account_ban(ban_duration : float) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.ban_account(ban_duration)
+
+## Changes the username of the currently logged in account.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_CHANGE_USERNAME_RESPONSE_CODE].
+## [br]
+## [br][b]new_username -[/b] The new username. The username has to be unique and between 3 and 20 characters long.
+func account_change_username(new_username : String) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.change_username(new_username)
+
+## Changes the password of an existing account.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_CHANGE_PASSWORD_RESPONSE_CODE].
+## [br]
+## [br][b]email -[/b] The email of the account.
+## [br][b]password -[/b] The current password of the account.
+## [br][b]new_password -[/b] The new password of the account.
+func account_change_password(email : String, password : String, new_password : String) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.change_password(email, password, new_password)
+
+## Requests a password reset code for the specified account. The reset code will be sent to the email address.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_REQUEST_PASSWORD_RESET_RESPONSE_CODE].
+## [br]
+## [br][b]email -[/b] The email of the account.
+func account_request_password_reset(email : String) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.request_password_reset(email)
+
+## Attempt to use a password reset code. If the code is valid the password of the account will be changed.
+## See [method account_request_password_reset] for sending the password reset code.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_RESET_PASSWORD_RESPONSE_CODE].
+## [br]
+## [br][b]email -[/b] The email of the account.
+func account_reset_password(email : String, reset_code : String, new_password : String) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.reset_password(email, reset_code, new_password)
+
+## Files a report against the specified account.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_CREATE_REPORT_RESPONSE_CODE].
+## [br]
+## [br][b]username_to_report -[/b] The username of the account you want to report.
+## [br][b]report -[/b] The report message. Has a maximum limit of 3000 characters.
+func account_create_report(username_to_report : String, report : String) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.report_user(username_to_report, report)
+
+## Sends a friend request to another account.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_SEND_FRIEND_REQUEST_RESPONSE_CODE].
+## [br]
+## [br][b]friend -[/b] The username of the account you want to send the friend request to.
+func account_send_friend_request(friend : String) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.send_friend_request(friend)
+
+## Accepts a friend request from another account
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_ACCEPT_FRIEND_REQUEST_RESPONSE_CODE].
+## [br]
+## [br][b]friend -[/b] The username of the account you want to accept the friend request from.
+func account_accept_friend_request(friend : String) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.accept_friend_request(friend)
+
+## Removes a friend. Also used to deny incoming friend requests.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_REMOVE_FRIEND_RESPONSE_CODE].
+## [br]
+## [br][b]friend -[/b] The username of the friend you want to remove.
+func account_remove_friend(friend : String) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.remove_friend(friend)
+
+## Gets the friend status between you and another account. Information besides the FriendStatus is only
+## available if the friend request is accepted.
+## If the lobby name is not empty, the player is in a lobby.
+## [br][br]Returns a [Dictionary] with the format seen below
+## and the [constant ENUMS.ACCOUNT_GET_FRIEND_STATUS_RESPONSE_CODE] response code.
+## [br]
+## [br][b]friend -[/b] The username of the account you want the friend status of.
+## [codeblock]
+## {
+## "Code" : 0,
+## "Result" : {
+## "FriendStatus" : 2,
+## "Lobby" : {
+## "Name" : "Epic Lobby",
+## "HasPassword" : false
+## }
+## }
+## }[/codeblock]
+func account_get_friend_status(friend : String) -> Dictionary:
+ if _connection_controller.is_local_check(): return {"Code" : 1}
+ return await _data_controller.get_friend_status(friend)
+
+## Returns an array of all friends with their status. Information besides the FriendStatus is only
+## available if the friend request is accepted.
+## If the lobby name is not empty, the player is in a lobby.
+## [br][br]Returns a [Dictionary] with the format seen below
+## and the [constant ENUMS.ACCOUNT_GET_FRIENDS_RESPONSE_CODE] response code.
+## [codeblock]
+## {
+## "Code" : 0,
+## "Result" : {
+## [
+## {
+## "Username" : "Epic Username",
+## "FriendStatus" : 2,
+## "Lobby" : {
+## "Name" : "Epic Lobby",
+## "HasPassword" : true
+## }
+## },
+## {
+## "Username" : "Cool Username",
+## "FriendStatus" : 2,
+## "Lobby" : {
+## "Name" : "",
+## "HasPassword" : false
+## }
+## },
+## {
+## "Username" : "Awesome Username",
+## "FriendStatus" : 1
+## }
+## ]
+## }
+## }[/codeblock]
+func account_get_friends() -> Dictionary:
+ if _connection_controller.is_local_check(): return {"Code" : 1}
+ return await _data_controller.get_friends()
+
+## Sends a lobby invitation to the specified friend. You must be in a lobby for this to succeed.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_INVITE_FRIEND_TO_LOBBY_RESPONSE_CODE].
+## [br]
+## [br][b]friend -[/b] The username of the friend you want to invite.
+func account_invite_friend_to_lobby(friend : String) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.invite_friend_to_lobby(friend)
+
+## Returns all pending lobby invitations for the currently logged-in account.
+## [br][br]Returns a [Dictionary] with the format seen below
+## and the [constant ENUMS.ACCOUNT_GET_LOBBY_INVITATIONS_RESPONSE_CODE] response code.
+## [codeblock]
+## {
+## "Code" : 0,
+## "Result" : [
+## {
+## "Username" : "Epic Username",
+## "LobbyName" : "Arena_12345",
+## "Password" : "dragon"
+## },
+## {
+## "Username" : "Cool Username",
+## "LobbyName" : "CustomLobby_987",
+## "Password" : ""
+## }
+## ]
+## }[/codeblock]
+func account_get_lobby_invitations() -> Dictionary:
+ if _connection_controller.is_local_check(): return {"Code" : 1}
+ return await _data_controller.get_lobby_invitations()
+
+## Store a dictionary/document of data on the currently logged-in account using GD-Sync cloud storage. The document
+## will be stored on the specified location. If the collections specified in the path don't already
+## exist, they are automatically created. Documents may also be nested in other documents.
+## [br][br]Documents can be private or public. If externally visible, other players may retrieve and read
+## the document contents. Setting [param externally_visible] to true will automatically make all parent
+## collections/documents visible as well. Setting [param externally_visible] to false will automatically
+## hide all nested collections and documents.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_DOCUMENT_SET_RESPONSE_CODE].
+## [br]
+## [br][b]path -[/b] The path where the document should be stored. An example path could be "saves/save1".
+## [br][b]document -[/b] The data that you want to store in the cloud.
+## [br][b]externally_visible -[/b] Decides if the document is public or private.
+func account_document_set(path : String, document : Dictionary, externally_visible : bool = false) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.set_player_document(path, document, externally_visible)
+
+## Documents can be private or public. If externally visible, other players may retrieve and read
+## the document contents. Setting [param externally_visible] to true will automatically make all parent
+## collections/documents visible as well. Setting [param externally_visible] to false will automatically
+## hide all nested collections and documents.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_DOCUMENT_SET_EXTERNAL_VISIBLE_RESPONSE_CODE].
+## [br]
+## [br][b]path -[/b] The path of the document or collection.
+## [br][b]externally_visible -[/b] Decides if the document is public or private.
+func account_document_set_external_visible(path : String, externally_visible : bool = false) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.set_external_visible(path, externally_visible)
+
+## Retrieve a dictionary/document of data from the currently logged-in account using GD-Sync cloud storage.
+## [br][br]Returns a [Dictionary] with the format seen below
+## and the [constant ENUMS.ACCOUNT_GET_DOCUMENT_RESPONSE_CODE] response code.
+## [br]
+## [br][b]path -[/b] The path of the document or collection.
+## [codeblock]
+## {
+## "Code" : 0,
+## "Result" : {}
+## }[/codeblock]
+func account_get_document(path : String) -> Dictionary:
+ if _connection_controller.is_local_check(): return {"Code" : 1}
+ return await _data_controller.get_player_document(path, "")
+
+## Check if a dictionary/document or collection exists on the currently logged-in account using GD-Sync cloud storage.
+## [br][br]Returns a [Dictionary] with the format seen below
+## and the [constant ENUMS.ACCOUNT_HAS_DOCUMENT_RESPONSE_CODE] response code.
+## [br]
+## [br][b]path -[/b] The path of the document or collection.
+## [codeblock]
+## {
+## "Code" : 0,
+## "Result" : true
+## }[/codeblock]
+func account_has_document(path : String) -> Dictionary:
+ if _connection_controller.is_local_check(): return {"Code" : 1}
+ return await _data_controller.has_player_document(path, "")
+
+## Browse through a collection from the currently logged-in account using GD-Sync cloud storage.
+## [br][br]Returns a [Dictionary] with the format seen below
+## and the [constant ENUMS.ACCOUNT_BROWSE_COLLECTION_RESPONSE_CODE] response code.
+## [br]
+## [br][b]path -[/b] The path of the document or collection.
+## [codeblock]
+## {
+## "Code" : 0,
+## "Result" :
+## [
+## {"ExternallyVisible" : true, "Name" : "profile", "Path" : "saves/profile", "Type" : "Document"},
+## {"ExternallyVisible" : false, "Name" : "save1", "Path" : "saves/save1", "Type" : "Document"},
+## {"ExternallyVisible" : false, "Name" : "save2", "Path" : "saves/save2", "Type" : "Document"},
+## {"ExternallyVisible" : false, "Name" : "configs", "Path" : "saves/configs", "Type" : "Collection"}
+## ]
+## }[/codeblock]
+func account_browse_collection(path : String) -> Dictionary:
+ if _connection_controller.is_local_check(): return {"Code" : 1}
+ return await _data_controller.browse_player_collection(path, "")
+
+## Delete a dictionary/document or collection from the currently logged-in account using GD-Sync cloud storage.
+## [br][br]Returns the result of the request as [constant ENUMS.ACCOUNT_DELETE_DOCUMENT_RESPONSE_CODE].
+## [br]
+## [br][b]path -[/b] The path of the document or collection.
+func account_delete_document(path : String) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.delete_player_document(path)
+
+## Retrieve a dictionary/document of data from another account using GD-Sync cloud storage.
+## [br][br]Returns a [Dictionary] with the format seen below
+## and the [constant ENUMS.ACCOUNT_GET_DOCUMENT_RESPONSE_CODE] response code.
+## [br]
+## [br][b]external_username -[/b] The username of the account you want to perform the action on.
+## [br][b]path -[/b] The path of the document or collection.
+## [codeblock]
+## {
+## "Code" : 0,
+## "Result" : {}
+## }[/codeblock]
+func account_get_external_document(external_username : String, path : String) -> Dictionary:
+ if _connection_controller.is_local_check(): return {"Code" : 1}
+ return await _data_controller.get_player_document(path, external_username)
+
+## Check if a dictionary/document or collection exists on another account using GD-Sync cloud storage.
+## [br][br]Returns a [Dictionary] with the format seen below
+## and the [constant ENUMS.ACCOUNT_HAS_DOCUMENT_RESPONSE_CODE] response code.
+## [br]
+## [br][b]external_username -[/b] The username of the account you want to perform the action on.
+## [br][b]path -[/b] The path of the document or collection.
+## [codeblock]
+## {
+## "Code" : 0,
+## "Result" : true
+## }[/codeblock]
+func account_has_external_document(external_username : String, path : String) -> Dictionary:
+ if _connection_controller.is_local_check(): return {"Code" : 1}
+ return await _data_controller.has_player_document(path, external_username)
+
+## Browse through a collection from another account using GD-Sync cloud storage.
+## [br][br]Returns a [Dictionary] with the format seen below
+## and the [constant ENUMS.ACCOUNT_BROWSE_COLLECTION_RESPONSE_CODE] response code.
+## [br]
+## [br][b]external_username -[/b] The username of the account you want to perform the action on.
+## [br][b]path -[/b] The path of the document or collection.
+## [codeblock]
+## {
+## "Code" : 0,
+## "Result" :
+## [
+## {"ExternallyVisible" : true, "Name" : "profile", "Path" : "saves/profile", "Type" : "Document"},
+## {"ExternallyVisible" : false, "Name" : "save1", "Path" : "saves/save1", "Type" : "Document"},
+## {"ExternallyVisible" : false, "Name" : "save2", "Path" : "saves/save2", "Type" : "Document"},
+## {"ExternallyVisible" : false, "Name" : "configs", "Path" : "saves/configs", "Type" : "Collection"}
+## ]
+## }[/codeblock]
+func account_browse_external_collection(external_username : String, path : String) -> Dictionary:
+ if _connection_controller.is_local_check(): return {"Code" : 1}
+ return await _data_controller.browse_player_collection(path, external_username)
+
+## Check if a leaderboard exists using GD-Sync cloud storage.
+## [br][br]Returns a [Dictionary] with the format seen below
+## and the [constant ENUMS.LEADERBOARD_EXISTS_RESPONSE_CODE] response code.
+## [br]
+## [br][b]leaderboard -[/b] The name of the leaderboard.
+## [codeblock]
+## {
+## "Code" : 0,
+## "Result" : true
+## }[/codeblock]
+func leaderboard_exists(leaderboard : String) -> Dictionary:
+ if _connection_controller.is_local_check(): return {"Code" : 1}
+ return await _data_controller.has_leaderboard(leaderboard)
+
+## Retrieve a list of all leaderboards using GD-Sync cloud storage.
+## [br][br]Returns a [Dictionary] with the format seen below
+## and the [constant ENUMS.LEADERBOARD_GET_ALL_RESPONSE_CODE] response code.
+## [br]
+## [br][b]leaderboard -[/b] The name of the leaderboard.
+## [codeblock]
+## {
+## "Code" : 0,
+## "Result" :
+## [
+## "Leaderboard1",
+## "Leaderboard2"
+## ]
+## }[/codeblock]
+func leaderboard_get_all() -> Dictionary:
+ if _connection_controller.is_local_check(): return {"Code" : 1}
+ return await _data_controller.get_leaderboards()
+
+
+## Browse a leaderboard and all submitted scores using GD-Sync cloud storage.
+## [br][br]Returns a [Dictionary] with the format seen below
+## and the [constant ENUMS.LEADERBOARD_BROWSE_SCORES_RESPONSE_CODE] response code.
+## [br]
+## [br][b]leaderboard -[/b] The name of the leaderboard.
+## [br][b]page_size -[/b] The amount of scores returned. The maximum page size is 100.
+## [br][b]page -[/b] The page you want to retrieve. The first page is page 1.
+## [codeblock]
+## {
+## "Code" : 0,
+## "FinalPage" : 7,
+## "Result" :
+## [
+## {"Rank" : 1, "Score" : 828, "Username" : "User1", "Data" : {"CustomValue" : 1},
+## {"Rank" : 2, "Score" : 700, "Username" : "User2"}, "Data" : {},
+## {"Rank" : 3, "Score" : 10, "Username" : "User3", "Data" : {}}
+## ]
+## }[/codeblock]
+func leaderboard_browse_scores(leaderboard : String, page_size : int, page : int) -> Dictionary:
+ if _connection_controller.is_local_check(): return {"Code" : 1}
+ return await _data_controller.browse_leaderboard(leaderboard, page_size, page)
+
+## Get the score and rank of an account for a specific leaderboard using GD-Sync cloud storage.
+## If the user has no score submission on the leaderboard, Score will be 0 and Rank -1.
+## [br][br]Returns a [Dictionary] with the format seen below
+## and the [constant ENUMS.LEADERBOARD_GET_SCORE_RESPONSE_CODE] response code.
+## [br]
+## [br][b]leaderboard -[/b] The name of the leaderboard.
+## [br][b]page_size -[/b] The amount of scores returned. The maximum page size is 100.
+## [codeblock]
+## {
+## "Code" : 0,
+## "Result" :
+## {
+## "Score" : 100,
+## "Rank" : 1,
+## "Data" : {"CustomValue" : 1}
+## }
+## }[/codeblock]
+func leaderboard_get_score(leaderboard : String, username : String) -> Dictionary:
+ if _connection_controller.is_local_check(): return {"Code" : 1}
+ return await _data_controller.get_leaderboard_score(leaderboard, username)
+
+## Submits a score to a leaderboard for the currently logged-in account using GD-Sync cloud storage.
+## If the user already has a score submission, it will be overwritten.
+## [br][br]Returns the result of the request as [constant ENUMS.LEADERBOARD_SUBMIT_SCORE_RESPONSE_CODE].
+## [br]
+## [br][b]leaderboard -[/b] The name of the leaderboard.
+## [br][b]score -[/b] The score you want to submit.
+## [br][b]data -[/b] Any extra information you would like to attach to the score. This dictionary can be a maximum of 2048 bytes in size.
+func leaderboard_submit_score(leaderboard : String, score : int, data : Dictionary = {}) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.submit_score(leaderboard, score, data)
+
+## Deletes a score from a leaderboard for the currently logged-in account using GD-Sync cloud storage.
+## [br][br]Returns the result of the request as [constant ENUMS.LEADERBOARD_DELETE_SCORE_RESPONSE_CODE].
+## [br]
+## [br][b]leaderboard -[/b] The name of the leaderboard.
+func leaderboard_delete_score(leaderboard : String) -> int:
+ if _connection_controller.is_local_check(): return 1
+ return await _data_controller.delete_score(leaderboard)
+
+
+
+
+
+
+
+
+
+#endregion
+# Steam Integration -----------------------------------------------------------
+# *****************************************************************************
+# -----------------------------------------------------------------------------
+#region Steam Integration
+
+## Returns true if the GodotSteam plugin is installed.
+func steam_integration_enabled() -> bool:
+ return _steam.steam_integration_enabled
+
+## Links your GD-Sync account with your Steam account. This will allow you to log into your GD-Sync account
+## using your active Steam session.
+## [br][br]Returns the result of the request as [constant ENUMS.LINK_STEAM_ACCOUNT_RESPONSE_CODE].
+func steam_link_account() -> int:
+ return await _steam.link_steam_account()
+
+## Unlinks your GD-Sync account from Steam.
+## [br][br]Returns the result of the request as [constant ENUMS.UNLINK_STEAM_ACCOUNT_RESPONSE_CODE].
+func steam_unlink_account() -> int:
+ return await _steam.unlink_steam_account()
+
+## Logs into your GD-Sync account using the active Steam session.
+## Only works if a Steam account has been linked.
+## [br][br]Returns a [Dictionary] with the format seen below
+## and the [constant ENUMS.STEAM_LOGIN_RESPONSE_CODE] response code.
+## [br]
+## [br]
+## If the user is banned, it will include the "Banned" key, which contains the unix timestamp when the ban will
+## expire. If the ban is permanent, the value will be -1.
+## [br]
+## [br][b]valid_time -[/b] The time in seconds how long the login session is valid.
+## [codeblock]
+## {
+## "Code" : 0,
+## "BanTime" : 1719973379
+## }[/codeblock]
+func steam_login(valid_time : float = 86400) -> Dictionary:
+ return await _steam.steam_login(valid_time)
+
+#endregion
diff --git a/addons/GD-Sync/MultiplayerClient.gd.uid b/addons/GD-Sync/MultiplayerClient.gd.uid
new file mode 100644
index 0000000..f6ad519
--- /dev/null
+++ b/addons/GD-Sync/MultiplayerClient.gd.uid
@@ -0,0 +1 @@
+uid://cgo4kiocg4a4a
diff --git a/addons/GD-Sync/Scripts/ConnectionController.gd b/addons/GD-Sync/Scripts/ConnectionController.gd
new file mode 100644
index 0000000..751ad7a
--- /dev/null
+++ b/addons/GD-Sync/Scripts/ConnectionController.gd
@@ -0,0 +1,868 @@
+extends Node
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+var GDSync
+var request_processor
+var https_controller
+var local_server
+var logger
+
+const API_VERSION : int = 6
+const PLUGIN_VERSION : String = "1.0.2"
+
+const KeyStore = preload("res://addons/GD-Sync/Scripts/KeyStore.gd")
+
+var _PUBLIC_KEY : String = ""
+var _PRIVATE_KEY : String = ""
+var UNIQUE_USERNAMES : bool = false
+var PROTECTED : bool = true
+
+var client : PacketPeer = ENetMultiplayerPeer.new()
+var client_id : int = -1
+var status : int = ENUMS.CONNECTION_STATUS.DISABLED
+var host : int = -1
+var connecting : bool = false
+var connection_i : int = 0
+var _connect_generation : int = 0
+var last_poll : float = 0.0
+var in_local_lobby : bool = false
+var attempt_tcp : bool = false
+var is_web_export : bool = false
+var web_hub_host : String = ""
+
+var server_ip : String = ""
+var reliable_encryptor : AESContext = AESContext.new()
+var reliable_decryptor : AESContext = AESContext.new()
+var unreliable_encryptor : AESContext = AESContext.new()
+var unreliable_decryptor : AESContext = AESContext.new()
+
+var _session_aes_key : PackedByteArray = PackedByteArray()
+var _session_crypto_ready : bool = false
+
+var artificial_latency_ms : int = 0
+var _unreliable_throttle_ready : bool = false
+
+const _LB_TIMEOUT_MS : int = 10000
+const _LB_MAX_ATTEMPTS : int = 3
+const _UDP_PING_EARLY_MS : int = 400
+const _UDP_PING_CAP_MS : int = 600
+const _CONNECT_TIMEOUT_S : float = 4.0
+const _SWITCH_CONNECT_TIMEOUT_S : float = 8.0
+
+var load_balancers : PackedStringArray = [
+ "lb1.gd-sync.com",
+ "lb2.gd-sync.com",
+]
+
+var web_servers : PackedStringArray = [
+ "ws1.gd-sync.com",
+ "ws2.gd-sync.com",
+]
+
+func _ready() -> void:
+ name = "ConnectionController"
+ process_priority = -1000
+
+ GDSync = get_node("/root/GDSync")
+ request_processor = GDSync._request_processor
+ https_controller = GDSync._https_controller
+ local_server = GDSync._local_server
+ logger = GDSync._logger
+ is_web_export = OS.has_feature("web")
+
+ var keys : Dictionary = KeyStore.load_keys()
+ _PUBLIC_KEY = keys["PublicKey"]
+ _PRIVATE_KEY = keys["PrivateKey"]
+
+ if ProjectSettings.has_setting("GD-Sync/protectedMode"):
+ PROTECTED = ProjectSettings.get_setting("GD-Sync/protectedMode")
+ if ProjectSettings.has_setting("GD-Sync/uniqueUsername"):
+ UNIQUE_USERNAMES = ProjectSettings.get_setting("GD-Sync/uniqueUsername")
+
+ logger.register_redacted_value(_PUBLIC_KEY)
+ logger.register_redacted_value(_PRIVATE_KEY)
+
+ if _PUBLIC_KEY == "" || _PRIVATE_KEY == "":
+ logger.write_error("No Public or Private key was entered in the GD-Sync settings. Please add one under Project->Tools->GD-Sync. If you are using local multiplayer only, you can ignore this error.")
+
+func is_active() -> bool:
+ return status >= ENUMS.CONNECTION_STATUS.CONNECTING
+
+func is_local() -> bool:
+ return status == ENUMS.CONNECTION_STATUS.LOCAL_CONNECTION
+
+func is_local_check() -> bool:
+ if status == ENUMS.CONNECTION_STATUS.LOCAL_CONNECTION:
+ logger.write_error("Some features are not available when using GD-Sync in local mode.")
+ return true
+ return false
+
+func valid_connection() -> bool:
+ var own_id : int = GDSync.get_client_id()
+ if own_id < 0:
+ logger.write_error("No valid connection. Please connect using GDSync.start_multiplayer() first")
+ return false
+ return true
+
+func reset_multiplayer(force_disconnect_signal : bool = false) -> void:
+ var emit_disconnect : bool = force_disconnect_signal or (status > ENUMS.CONNECTION_STATUS.CONNECTED and status != ENUMS.CONNECTION_STATUS.LOCAL_CONNECTION)
+ _connect_generation += 1
+
+ client.close()
+ local_server.reset_multiplayer()
+ _reset_session_crypto()
+ _unreliable_throttle_ready = false
+
+ status = ENUMS.CONNECTION_STATUS.DISABLED
+ client_id = -1
+ host = -1
+ in_local_lobby = false
+ attempt_tcp = false
+
+ if emit_disconnect: GDSync.disconnected.emit()
+
+func reset_session_keep_socket() -> void:
+ connection_i += 1
+ _reset_session_crypto()
+ client_id = -1
+ host = -1
+ in_local_lobby = false
+ status = ENUMS.CONNECTION_STATUS.CONNECTING
+ logger.write_log("Reset session crypto for web tunnel handshake.")
+
+func _reset_session_crypto() -> void:
+ reliable_encryptor.finish()
+ reliable_decryptor.finish()
+ unreliable_encryptor.finish()
+ unreliable_decryptor.finish()
+ _session_crypto_ready = false
+
+func start_multiplayer() -> void:
+ logger.write_log("Starting multiplayer.")
+ if status != ENUMS.CONNECTION_STATUS.DISABLED:
+ logger.write_error("Multiplayer has already been started.")
+ return
+
+ reset_multiplayer()
+ var gen : int = _connect_generation
+ last_poll = Time.get_unix_time_from_system()
+
+ if is_web_export:
+ await _start_web_connect(gen)
+ else:
+ await _start_native_connect(gen)
+
+func _connect_is_current(gen : int) -> bool:
+ return gen == _connect_generation
+
+func _fail_connect(gen : int, error : int, message : String) -> void:
+ if !_connect_is_current(gen):
+ return
+ logger.write_error(message)
+ reset_multiplayer()
+ GDSync.connection_failed.emit(error)
+
+func _start_native_connect(gen : int) -> void:
+ status = ENUMS.CONNECTION_STATUS.FINDING_LB
+ var lb_result : Dictionary = await _fetch_game_servers(gen)
+ if !_connect_is_current(gen):
+ return
+ var servers : Array = lb_result.get("servers", [])
+ if servers.is_empty():
+ if lb_result.get("invalid_key", false):
+ _fail_connect(gen, ENUMS.CONNECTION_FAILED.INVALID_PUBLIC_KEY,
+ "Load balancer request failed, incorrect public key.")
+ else:
+ _fail_connect(gen, ENUMS.CONNECTION_FAILED.TIMEOUT, "No response from load balancers.")
+ return
+
+ status = ENUMS.CONNECTION_STATUS.PINGING_SERVERS
+ var ranked : Array = await _rank_game_servers(servers, gen)
+ if !_connect_is_current(gen):
+ return
+ if ranked.is_empty():
+ _fail_connect(gen, ENUMS.CONNECTION_FAILED.TIMEOUT, "No pings received from any server.")
+ return
+
+ status = ENUMS.CONNECTION_STATUS.CONNECTING
+ var best : String = ranked[0]
+ for server in ranked:
+ if !_connect_is_current(gen):
+ return
+ client.close()
+ client = ENetMultiplayerPeer.new()
+ if await _try_connect(server, gen, _CONNECT_TIMEOUT_S):
+ return
+
+ if !_connect_is_current(gen):
+ return
+ logger.write_log("Attempting TCP connection.")
+ attempt_tcp = true
+ client.close()
+ client = WebSocketMultiplayerPeer.new()
+ if await _try_connect(best, gen, _CONNECT_TIMEOUT_S):
+ return
+ _fail_connect(gen, ENUMS.CONNECTION_FAILED.TIMEOUT, "Connection timeout, server did not respond.")
+
+func _start_web_connect(gen : int) -> void:
+ client = WebSocketPeer.new()
+ status = ENUMS.CONNECTION_STATUS.PINGING_SERVERS
+ var lb_state : Dictionary = { "done": false, "invalid_key": false }
+ _resolve_lb_for_web(gen, lb_state)
+ var ranked : Array = await _rank_web_servers(gen)
+ if !_connect_is_current(gen):
+ return
+ if ranked.is_empty():
+ _fail_connect(gen, ENUMS.CONNECTION_FAILED.TIMEOUT, "No reachable web servers.")
+ return
+
+ var lb_wait_budget_ms : int = _LB_TIMEOUT_MS * _LB_MAX_ATTEMPTS
+ var waited_ms : int = 0
+ while !lb_state.done and waited_ms < lb_wait_budget_ms:
+ if !_connect_is_current(gen):
+ return
+ await get_tree().create_timer(0.05).timeout
+ waited_ms += 50
+ if !_connect_is_current(gen):
+ return
+ if lb_state.invalid_key:
+ _fail_connect(gen, ENUMS.CONNECTION_FAILED.INVALID_PUBLIC_KEY,
+ "Load balancer request failed, incorrect public key.")
+ return
+
+ status = ENUMS.CONNECTION_STATUS.CONNECTING
+ for host in ranked:
+ if !_connect_is_current(gen):
+ return
+ client.close()
+ client = WebSocketPeer.new()
+ web_hub_host = host
+ if await _try_connect("wss://"+host, gen, _CONNECT_TIMEOUT_S):
+ return
+ _fail_connect(gen, ENUMS.CONNECTION_FAILED.TIMEOUT, "Connection timeout, server did not respond.")
+
+func _resolve_lb_for_web(gen : int, lb_state : Dictionary) -> void:
+ var lb_result : Dictionary = await _fetch_game_servers(gen)
+ if !_connect_is_current(gen):
+ lb_state.done = true
+ return
+ lb_state.invalid_key = lb_result.get("invalid_key", false)
+ lb_state.done = true
+ if https_controller.active_lb.is_empty() and !lb_state.invalid_key:
+ logger.write_error("No load balancer resolved for web HTTPS API.")
+
+func start_local_multiplayer() -> void:
+ logger.write_log("Starting local multiplayer.")
+ if status != ENUMS.CONNECTION_STATUS.DISABLED: return
+ reset_multiplayer()
+ status = ENUMS.CONNECTION_STATUS.LOCAL_CONNECTION
+
+ var rng : RandomNumberGenerator = RandomNumberGenerator.new()
+ rng.randomize()
+ # Harvest Season patch: targeted calls carry the client id in 30 bits (RequestProcessor
+ # encode_target_client), so a random 32-bit local id was cut off and the call reached nobody.
+ client_id = rng.randi_range(1, 0x3FFFFFFE)
+ logger.write_log("Local client id generated. <"+str(client_id)+">")
+
+ if local_server.start_local_peer():
+ logger.write_log("Local multiplayer started.")
+ GDSync.client_id_changed.emit.call_deferred(client_id)
+ GDSync.connected.emit.call_deferred()
+ else:
+ logger.write_error("Local multiplayer failed to start, port is in use.")
+ reset_multiplayer()
+ GDSync.connection_failed.emit.call_deferred(ENUMS.CONNECTION_FAILED.LOCAL_PORT_ERROR)
+
+func stop_multiplayer() -> void:
+ logger.write_log("Stopping multiplayer.")
+ reset_multiplayer(true)
+
+func leave_local_lobby_client() -> void:
+ in_local_lobby = false
+ host = -1
+ if client is MultiplayerPeer:
+ client.close()
+ client = ENetMultiplayerPeer.new()
+
+func _fetch_game_servers(gen : int) -> Dictionary:
+ var empty : Dictionary = { "servers": [], "invalid_key": false }
+ if load_balancers.is_empty():
+ return empty
+
+ for attempt in _LB_MAX_ATTEMPTS:
+ if !_connect_is_current(gen):
+ return empty
+ if attempt > 0:
+ logger.write_log("Retrying load balancer request. ")
+ await get_tree().create_timer(0.5).timeout
+ if !_connect_is_current(gen):
+ return empty
+
+ var result : Dictionary = await _fetch_game_servers_once(gen)
+ if !_connect_is_current(gen):
+ return result
+ if result.get("invalid_key", false) or !result.get("servers", []).is_empty():
+ return result
+
+ return empty
+
+func _fetch_game_servers_once(gen : int) -> Dictionary:
+ var result : Dictionary = { "servers": [], "invalid_key": false }
+ var lbs : Array = load_balancers.duplicate()
+ lbs.shuffle()
+ if lbs.is_empty():
+ return result
+
+ logger.write_log("Requesting servers from load balancers.")
+ var winner : Dictionary = { "taken": false }
+ var finished : int = 0
+ var inflight : Array = []
+
+ for address in lbs:
+ _query_load_balancer(str(address), gen, result, winner, inflight, func(): finished += 1)
+
+ var waited_ms : int = 0
+ while waited_ms < _LB_TIMEOUT_MS:
+ if !_connect_is_current(gen):
+ break
+ if result.invalid_key or winner.taken:
+ break
+ if finished >= lbs.size():
+ break
+ await get_tree().create_timer(0.05).timeout
+ waited_ms += 50
+
+ _cancel_http_requests(inflight)
+ return result
+
+func _query_load_balancer(
+ address : String,
+ gen : int,
+ result : Dictionary,
+ winner : Dictionary,
+ inflight : Array,
+ on_done : Callable
+) -> void:
+ logger.write_log("Requesting servers from "+address)
+ var request : HTTPRequest = HTTPRequest.new()
+ request.timeout = _LB_TIMEOUT_MS / 1000.0
+ add_child(request)
+ inflight.append(request)
+
+ var err : Error = request.request(
+ "https://"+address+"/connect",
+ ["Content-Type: text/plain"],
+ HTTPClient.METHOD_POST,
+ _PUBLIC_KEY)
+ if err != OK:
+ logger.write_error("Load balancer request failed to start. <"+address+"><"+str(err)+">")
+ inflight.erase(request)
+ request.queue_free()
+ on_done.call()
+ return
+
+ var completed : Array = await request.request_completed
+ inflight.erase(request)
+ if is_instance_valid(request):
+ request.queue_free()
+ if !_connect_is_current(gen):
+ on_done.call()
+ return
+
+ var response_code : int = completed[1]
+ logger.write_log("Load balancer completed. <"+address+"><"+str(response_code)+">")
+ if response_code == 401:
+ if !winner.taken:
+ result.invalid_key = true
+ on_done.call()
+ return
+ if response_code != 200:
+ logger.write_error("Load balancer request failed. <"+str(response_code)+">")
+ on_done.call()
+ return
+
+ var parsed : Variant = str_to_var(completed[3].get_string_from_ascii())
+ if typeof(parsed) != TYPE_ARRAY or parsed.is_empty():
+ logger.write_error("Load balancer request did not return any servers. <"+address+">")
+ on_done.call()
+ return
+ if winner.taken:
+ on_done.call()
+ return
+
+ winner.taken = true
+ result.servers = parsed
+ https_controller.active_lb = "https://"+address
+ logger.write_log("Received servers decoded. <"+str(parsed)+">")
+ on_done.call()
+
+func _cancel_http_requests(inflight : Array) -> void:
+ for request in inflight:
+ if request is HTTPRequest and is_instance_valid(request):
+ request.cancel_request()
+
+func _rank_game_servers(servers : Array, gen : int) -> Array:
+ logger.write_log("Pinging game servers. <"+str(servers)+">")
+ var replies : Dictionary = {}
+ for server in servers:
+ _ping_game_server(str(server), replies, gen)
+
+ var waited_ms : int = 0
+ while waited_ms < _UDP_PING_CAP_MS:
+ if !_connect_is_current(gen):
+ return []
+ if _all_servers_replied(servers, replies):
+ break
+ if waited_ms >= _UDP_PING_EARLY_MS and replies.size() > 0:
+ break
+ await get_tree().create_timer(0.02).timeout
+ waited_ms += 20
+
+ logger.write_log("Finding best server <"+str(replies)+">")
+ if replies.is_empty():
+ return []
+
+ var ranked : Array = []
+ for server in replies:
+ ranked.append({ "server": server, "ping": float(replies[server].total) / replies[server].count })
+ ranked.sort_custom(func(a, b): return a.ping < b.ping)
+
+ var hosts : Array = []
+ for entry in ranked:
+ hosts.append(entry.server)
+ logger.write_log("Game server ping. <"+str(entry.server)+"><"+str(entry.ping)+"ms>")
+ return hosts
+
+func _all_servers_replied(servers : Array, replies : Dictionary) -> bool:
+ if servers.is_empty():
+ return false
+ for server in servers:
+ if !replies.has(str(server)):
+ return false
+ return true
+
+func _ping_game_server(server : String, replies : Dictionary, gen : int) -> void:
+ logger.write_log("Pinging game server. <"+server+">")
+ var peer : PacketPeerUDP = PacketPeerUDP.new()
+ peer.connect_to_host(server, 8081)
+
+ var total : int = 0
+ var count : int = 0
+ var sends : int = 0
+ var elapsed_ms : int = 0
+ while _connect_is_current(gen) and status == ENUMS.CONNECTION_STATUS.PINGING_SERVERS and elapsed_ms < _UDP_PING_CAP_MS:
+ if sends < 3 and elapsed_ms >= sends * 50:
+ peer.put_var(Time.get_ticks_msec())
+ sends += 1
+ while peer.get_available_packet_count() > 0:
+ var sent_at : Variant = peer.get_var()
+ if typeof(sent_at) == TYPE_INT:
+ total += Time.get_ticks_msec() - int(sent_at)
+ count += 1
+ logger.write_log("Ping received. <"+server+">")
+ await get_tree().create_timer(0.02).timeout
+ elapsed_ms += 20
+ peer.close()
+ if count > 0 and _connect_is_current(gen):
+ replies[server] = { "total": total, "count": count }
+
+func connect_to_server(server : String) -> void:
+ logger.write_log("Connecting to server. <"+server+">")
+ _begin_client_connect(server)
+ last_poll = Time.get_unix_time_from_system()
+ connection_i += 1
+ var current_i : int = connection_i
+ var gen : int = _connect_generation
+ if status != ENUMS.CONNECTION_STATUS.LOBBY_SWITCH:
+ status = ENUMS.CONNECTION_STATUS.CONNECTING
+ server_ip = server
+
+ var elapsed : float = 0.0
+ while elapsed < _SWITCH_CONNECT_TIMEOUT_S:
+ if current_i != connection_i or !_connect_is_current(gen):
+ return
+ if status == ENUMS.CONNECTION_STATUS.CONNECTION_SECURED:
+ return
+ if elapsed >= 0.3 and _client_connect_lost():
+ break
+ await get_tree().create_timer(0.05).timeout
+ elapsed += 0.05
+
+ if current_i != connection_i or !_connect_is_current(gen):
+ return
+ if status == ENUMS.CONNECTION_STATUS.CONNECTION_SECURED:
+ return
+
+ logger.write_error("Connection timeout, server did not respond.")
+ if GDSync._server_switch_controller.transport_failed():
+ return
+ GDSync.connection_failed.emit(ENUMS.CONNECTION_FAILED.TIMEOUT)
+ reset_multiplayer()
+
+func _try_connect(address : String, gen : int, timeout_s : float) -> bool:
+ if !_connect_is_current(gen):
+ return false
+ logger.write_log("Connecting to server. <"+address+">")
+ _begin_client_connect(address)
+ last_poll = Time.get_unix_time_from_system()
+ server_ip = address
+ if status != ENUMS.CONNECTION_STATUS.LOBBY_SWITCH:
+ status = ENUMS.CONNECTION_STATUS.CONNECTING
+ connection_i += 1
+ var current_i : int = connection_i
+
+ var elapsed : float = 0.0
+ while elapsed < timeout_s:
+ if !_connect_is_current(gen) or current_i != connection_i:
+ return false
+ if status == ENUMS.CONNECTION_STATUS.CONNECTION_SECURED:
+ return true
+ if elapsed >= 0.3 and _client_connect_lost():
+ return false
+ await get_tree().create_timer(0.05).timeout
+ elapsed += 0.05
+ return _connect_is_current(gen) and current_i == connection_i and status == ENUMS.CONNECTION_STATUS.CONNECTION_SECURED
+
+func _client_connect_lost() -> bool:
+ if client is MultiplayerPeer:
+ return client.get_connection_status() == MultiplayerPeer.CONNECTION_DISCONNECTED
+ if client is WebSocketPeer:
+ return client.get_ready_state() == WebSocketPeer.STATE_CLOSED
+ return false
+
+func _begin_client_connect(server : String) -> void:
+ if client is WebSocketPeer:
+ logger.write_log("Connecting using TCP.")
+ client.connect_to_url(server)
+ elif client is WebSocketMultiplayerPeer:
+ logger.write_log("Connecting using TCP multiplayer.")
+ client.create_client(server)
+ else:
+ logger.write_log("Connecting using UDP.")
+ client.create_client(server, 8080)
+
+func connect_to_local_server(server : String, port : int) -> int:
+ logger.write_log("Connecting to local server. <"+server+":"+str(port)+">")
+
+ client.close()
+ client = ENetMultiplayerPeer.new()
+ return client.create_client(server, port)
+
+func _rank_web_servers(gen : int) -> Array:
+ logger.write_log("HTTPS pinging web servers. <"+str(web_servers)+">")
+ var server_pings : Dictionary = {}
+ var tasks_done : int = 0
+ var total : int = web_servers.size()
+
+ for host in web_servers:
+ _ping_web_server(host, server_pings, gen, func(): tasks_done += 1)
+
+ var waited_ms : int = 0
+ while tasks_done < total and waited_ms < 4500:
+ if !_connect_is_current(gen):
+ return []
+ await get_tree().create_timer(0.05).timeout
+ waited_ms += 50
+
+ if !_connect_is_current(gen) or server_pings.is_empty():
+ logger.write_error("No HTTPS pings received from web servers.")
+ return []
+
+ var pings : Array = server_pings.keys()
+ pings.sort()
+ var ranked : Array = []
+ for ping in pings:
+ ranked.append(server_pings[ping])
+ logger.write_log("Web server ping. <"+str(server_pings[ping])+"><"+str(ping)+"ms>")
+ logger.write_log("Best web server selected. <"+str(ranked[0])+"><"+str(pings[0])+"ms>")
+ return ranked
+
+func _ping_web_server(host : String, server_pings : Dictionary, gen : int, on_done : Callable) -> void:
+ var latency_ms : float = await https_controller.ping_https("https://"+host+"/ping", 3.0)
+ if !_connect_is_current(gen):
+ on_done.call()
+ return
+ if latency_ms >= 0.0:
+ var key : float = latency_ms
+ while server_pings.has(key):
+ key += 0.001
+ server_pings[key] = host
+ logger.write_log("Web server ping. <"+host+"><"+str(latency_ms)+"ms>")
+ on_done.call()
+
+func switch_server(server: String, use_websocket: bool = false) -> void:
+ logger.write_log("Switching server. <"+server+">")
+ status = ENUMS.CONNECTION_STATUS.LOBBY_SWITCH
+ reset_multiplayer()
+ attempt_tcp = false
+ if is_web_export:
+ client = WebSocketPeer.new()
+ var hub := web_hub_host
+ if hub.is_empty():
+ logger.write_error("Web hub host missing during server switch.")
+ connect_to_server("wss://"+server)
+ return
+ logger.write_log("Reconnecting to web hub. <"+hub+">")
+ connect_to_server("wss://"+hub)
+ return
+ client = WebSocketMultiplayerPeer.new() if use_websocket else ENetMultiplayerPeer.new()
+ var destination := server
+ if use_websocket and !destination.begins_with("ws://") and !destination.begins_with("wss://"):
+ destination = "wss://"+destination
+ connect_to_server(destination)
+
+func set_artificial_latency(latency_ms : int) -> void:
+ artificial_latency_ms = maxi(latency_ms, 0)
+
+func get_artificial_latency() -> int:
+ return artificial_latency_ms
+
+func _await_artificial_latency() -> void:
+ if artificial_latency_ms <= 0:
+ return
+ await get_tree().create_timer(artificial_latency_ms / 1000.0).timeout
+
+func _receive_packet(bytes : PackedByteArray, packet_channel : int) -> void:
+ await _await_artificial_latency()
+ if status < ENUMS.CONNECTION_STATUS.CONNECTING:
+ return
+ request_processor.unpack_packet(bytes, packet_channel)
+
+func _configure_unreliable_throttle() -> void:
+ if _unreliable_throttle_ready or !(client is ENetMultiplayerPeer):
+ return
+ if client.get_connection_status() != MultiplayerPeer.CONNECTION_CONNECTED:
+ return
+ var enet_peer : ENetPacketPeer = client.get_peer(1)
+ if enet_peer == null:
+ return
+ enet_peer.throttle_configure(5000, 2, 0)
+ _unreliable_throttle_ready = true
+
+func _send_multiplayer_packet(bytes : PackedByteArray, transfer_mode : int, transfer_channel : int) -> void:
+ await _await_artificial_latency()
+ if !(client is MultiplayerPeer) or client.get_connection_status() != MultiplayerPeer.CONNECTION_CONNECTED:
+ return
+ client.transfer_mode = transfer_mode
+ client.transfer_channel = transfer_channel
+ client.put_packet(bytes)
+
+func _send_websocket_packet(bytes : PackedByteArray) -> void:
+ await _await_artificial_latency()
+ if !(client is WebSocketPeer) or client.get_ready_state() != WebSocketPeer.STATE_OPEN:
+ return
+ client.send(bytes)
+
+func _process(delta) -> void:
+ if status >= ENUMS.CONNECTION_STATUS.CONNECTED and !is_local() and !is_web_export:
+ var current_time : float = Time.get_unix_time_from_system()
+ if current_time - last_poll >= 10:
+ logger.write_error("Client did not poll for over 10 seconds, disconnect.")
+ reset_multiplayer()
+ last_poll = current_time
+
+ if client is MultiplayerPeer:
+ match(client.get_connection_status()):
+ MultiplayerPeer.CONNECTION_DISCONNECTED:
+ if is_local():
+ if in_local_lobby:
+ logger.write_log("Local lobby connection lost, leaving lobby.")
+ in_local_lobby = false
+ GDSync.kicked.emit("")
+ GDSync.lobby_leave.call_deferred()
+ elif status >= ENUMS.CONNECTION_STATUS.CONNECTED:
+ logger.write_error("MultiplayerPeer lost its connection.")
+ if GDSync._server_switch_controller.transport_failed():
+ return
+ reset_multiplayer()
+ MultiplayerPeer.CONNECTION_CONNECTING:
+ client.poll()
+ MultiplayerPeer.CONNECTION_CONNECTED:
+ _configure_unreliable_throttle()
+ client.poll()
+
+ while client.get_available_packet_count() > 0:
+ var packet_channel : int = client.get_packet_channel()
+ var bytes : PackedByteArray = client.get_packet()
+ _receive_packet(bytes, packet_channel)
+
+ if request_processor.has_packets(ENUMS.PACKET_CHANNEL.SETUP):
+ _send_multiplayer_packet(
+ request_processor.package_requests(ENUMS.PACKET_CHANNEL.SETUP),
+ MultiplayerPeer.TRANSFER_MODE_RELIABLE,
+ 0
+ )
+ if request_processor.has_packets(ENUMS.PACKET_CHANNEL.SERVER):
+ _send_multiplayer_packet(
+ request_processor.package_requests(ENUMS.PACKET_CHANNEL.SERVER),
+ MultiplayerPeer.TRANSFER_MODE_RELIABLE,
+ 0
+ )
+ if request_processor.has_packets(ENUMS.PACKET_CHANNEL.RELIABLE):
+ _send_multiplayer_packet(
+ request_processor.package_requests(ENUMS.PACKET_CHANNEL.RELIABLE),
+ MultiplayerPeer.TRANSFER_MODE_RELIABLE,
+ 0
+ )
+ var unreliable_packets : int = 8
+ while unreliable_packets > 0 and request_processor.has_packets(ENUMS.PACKET_CHANNEL.UNRELIABLE):
+ unreliable_packets -= 1
+ _send_multiplayer_packet(
+ request_processor.package_requests(ENUMS.PACKET_CHANNEL.UNRELIABLE),
+ MultiplayerPeer.TRANSFER_MODE_UNRELIABLE_ORDERED,
+ 1
+ )
+
+ elif client is WebSocketPeer:
+ match(client.get_ready_state()):
+ WebSocketPeer.STATE_CLOSED:
+ if !is_local() or in_local_lobby:
+ if GDSync._server_switch_controller.is_active():
+ logger.write_error("WebSocketPeer lost its connection during server switch.")
+ GDSync._server_switch_controller.transport_failed()
+ elif status >= ENUMS.CONNECTION_STATUS.CONNECTED:
+ logger.write_error("WebSocketPeer lost its connection.")
+ reset_multiplayer()
+ WebSocketPeer.STATE_CLOSING:
+ client.poll()
+ WebSocketPeer.STATE_CONNECTING:
+ client.poll()
+ WebSocketPeer.STATE_OPEN:
+ client.poll()
+
+ while client.get_available_packet_count() > 0:
+ var bytes : PackedByteArray = client.get_packet()
+ _receive_packet(bytes, 0)
+
+ if request_processor.has_packets(ENUMS.PACKET_CHANNEL.SETUP):
+ _send_websocket_packet(request_processor.package_requests(ENUMS.PACKET_CHANNEL.SETUP))
+ if request_processor.has_packets(ENUMS.PACKET_CHANNEL.SERVER):
+ _send_websocket_packet(request_processor.package_requests(ENUMS.PACKET_CHANNEL.SERVER))
+ if request_processor.has_packets(ENUMS.PACKET_CHANNEL.RELIABLE):
+ _send_websocket_packet(request_processor.package_requests(ENUMS.PACKET_CHANNEL.RELIABLE))
+ if request_processor.has_packets(ENUMS.PACKET_CHANNEL.UNRELIABLE):
+ _send_websocket_packet(request_processor.package_requests(ENUMS.PACKET_CHANNEL.UNRELIABLE))
+
+func set_client_id(client_id : int) -> void:
+ logger.write_log("Client id received from server. <"+str(client_id)+">")
+ logger.register_profiler_data("client_id", client_id)
+ self.client_id = client_id
+ GDSync.client_id_changed.emit(client_id)
+ status = ENUMS.CONNECTION_STATUS.CONNECTED
+ request_processor.validate_public_key()
+
+func set_client_key(client_key: String) -> void:
+ logger.write_log("Client key received from server. <" + client_key + ">")
+ if client_key.is_empty():
+ logger.write_error("Client key was empty or public key invalid.")
+ reset_multiplayer()
+ GDSync.emit_signal("connection_failed", ENUMS.CONNECTION_FAILED.INVALID_PUBLIC_KEY)
+ return
+
+ request_processor.apply_settings()
+ request_processor.secure_connection()
+
+ var key_utf8 : PackedByteArray = _PRIVATE_KEY.to_utf8_buffer()
+ var client_utf8 : PackedByteArray = client_key.to_utf8_buffer()
+ _session_crypto_ready = false
+ unreliable_encryptor.finish()
+ unreliable_decryptor.finish()
+
+ _session_aes_key = _derive_session_aes_key(key_utf8, client_utf8)
+ var iv16 : PackedByteArray = _derive_session_iv(client_utf8)
+ reliable_encryptor.finish()
+ reliable_decryptor.finish()
+ reliable_encryptor.start(AESContext.MODE_CBC_ENCRYPT, _session_aes_key, iv16)
+ reliable_decryptor.start(AESContext.MODE_CBC_DECRYPT, _session_aes_key, iv16)
+ unreliable_encryptor.start(AESContext.MODE_ECB_ENCRYPT, _session_aes_key)
+ unreliable_decryptor.start(AESContext.MODE_ECB_DECRYPT, _session_aes_key)
+ _session_crypto_ready = true
+
+func is_session_crypto_ready() -> bool:
+ return _session_crypto_ready
+
+func _derive_session_aes_key(key_utf8 : PackedByteArray, client_key_utf8 : PackedByteArray) -> PackedByteArray:
+ var ctx : HashingContext = HashingContext.new()
+ ctx.start(HashingContext.HASH_SHA256)
+ ctx.update(key_utf8)
+ ctx.update(client_key_utf8)
+ return ctx.finish()
+
+func _derive_session_iv(client_key_utf8 : PackedByteArray) -> PackedByteArray:
+ var label : PackedByteArray = "gdsync:v3:aes-cbc:iv".to_utf8_buffer()
+ var ctx : HashingContext = HashingContext.new()
+ ctx.start(HashingContext.HASH_SHA256)
+ ctx.update(label)
+ ctx.update(client_key_utf8)
+ var h : PackedByteArray = ctx.finish()
+ return h.slice(0, 16)
+
+func _pkcs7_pad(blocks : PackedByteArray) -> PackedByteArray:
+ var n : int = 16 - (blocks.size() % 16)
+ if n == 0:
+ n = 16
+ var outb : PackedByteArray = blocks.duplicate()
+ for i in range(n):
+ outb.append(n)
+ return outb
+
+func _pkcs7_unpad(blocks : PackedByteArray) -> PackedByteArray:
+ if blocks.is_empty() or (blocks.size() % 16) != 0:
+ return PackedByteArray()
+ var n : int = blocks[blocks.size() - 1]
+ if n < 1 or n > 16 or n > blocks.size():
+ return PackedByteArray()
+ for i in range(n):
+ if blocks[blocks.size() - 1 - i] != n:
+ return PackedByteArray()
+ return blocks.slice(0, blocks.size() - n)
+
+func encrypt_secured_payload(plain : PackedByteArray, reliable_channel : bool) -> PackedByteArray:
+ if !_session_crypto_ready:
+ logger.write_error("encrypt_secured_payload called before session crypto is ready.")
+ return plain
+ var padded : PackedByteArray = _pkcs7_pad(plain)
+ if reliable_channel:
+ return reliable_encryptor.update(padded)
+ return unreliable_encryptor.update(padded)
+
+func decrypt_secured_payload(cipher : PackedByteArray, reliable_channel : bool) -> PackedByteArray:
+ if !_session_crypto_ready:
+ logger.write_error("decrypt_secured_payload called before session crypto is ready.")
+ return PackedByteArray()
+ if reliable_channel:
+ var dec : PackedByteArray = reliable_decryptor.update(cipher)
+ return _pkcs7_unpad(dec)
+ var dec2 : PackedByteArray = unreliable_decryptor.update(cipher)
+ return _pkcs7_unpad(dec2)
+
+func set_host(host : int) -> void:
+ logger.write_log("Host changed. <"+str(host)+">")
+ self.host = host
+ var is_host : bool = host == GDSync.get_client_id()
+ logger.register_profiler_data("is_host", is_host)
+ logger.register_profiler_data("host", host)
+ get_parent().emit_signal("host_changed", is_host, host)
diff --git a/addons/GD-Sync/Scripts/ConnectionController.gd.uid b/addons/GD-Sync/Scripts/ConnectionController.gd.uid
new file mode 100644
index 0000000..cd282ea
--- /dev/null
+++ b/addons/GD-Sync/Scripts/ConnectionController.gd.uid
@@ -0,0 +1 @@
+uid://b1kfyqmb115wg
diff --git a/addons/GD-Sync/Scripts/DataController.gd b/addons/GD-Sync/Scripts/DataController.gd
new file mode 100644
index 0000000..df559da
--- /dev/null
+++ b/addons/GD-Sync/Scripts/DataController.gd
@@ -0,0 +1,640 @@
+extends Node
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+var https_controller
+var connection_controller
+var session_controller
+var GDSync
+
+var login_email : String
+var login_token : String
+var previous_token : String
+var logged_in : bool = false
+var safe_quit : bool = false
+
+var status_ping_timer : float = 0.0
+
+func _ready() -> void:
+ name = "DataController"
+ GDSync = get_node("/root/GDSync")
+ https_controller = GDSync._https_controller
+ connection_controller = GDSync._connection_controller
+ session_controller = GDSync._session_controller
+
+ if !DirAccess.dir_exists_absolute("user://GD-Sync"):
+ DirAccess.make_dir_absolute("user://GD-Sync")
+
+ load_config()
+
+func _process(delta: float) -> void:
+ if logged_in:
+ status_ping_timer -= delta
+
+ if status_ping_timer <= 0.0:
+ status_ping_timer = 300
+ set_friend_status()
+
+func _notification(what : int) -> void:
+ if what == NOTIFICATION_WM_CLOSE_REQUEST:
+ quit()
+
+func quit() -> void:
+ if logged_in:
+ GDSync.lobby_leave()
+ await set_friend_status()
+
+ safe_quit = true
+ save_config()
+ get_tree().quit()
+
+func log_in(username : String = "") -> void:
+ logged_in = true
+ safe_quit = false
+ get_tree().set_auto_accept_quit(false)
+ GDSync.account_logged_in.emit.call_deferred(username)
+
+func load_config() -> void:
+ var dir = DirAccess.open("user://")
+ if !dir.file_exists("user://GD-Sync/DataController.conf"): return
+
+ var file = FileAccess.open_encrypted_with_pass("user://GD-Sync/DataController.conf", FileAccess.READ, connection_controller._PRIVATE_KEY)
+ if file == null: return
+ var data : Dictionary = bytes_to_var(file.get_buffer(file.get_length()))
+ file.close()
+
+ if data.has("LoginEmail"): login_email = data["LoginEmail"]
+ if data.has("LoginToken"): previous_token = data["LoginToken"]
+
+ safe_quit = true
+ if data.has("SafeQuit"):
+ if !data["SafeQuit"]:
+ push_error("GD-Sync did not close correctly. Please use GD-Sync.quit() instead of get_tree().quit().")
+
+ save_config()
+
+func save_config() -> void:
+ var file = FileAccess.open_encrypted_with_pass("user://GD-Sync/DataController.conf", FileAccess.WRITE, connection_controller._PRIVATE_KEY)
+ file.store_buffer(var_to_bytes({
+ "LoginEmail" : login_email,
+ "LoginToken" : login_token,
+ "SafeQuit" : safe_quit
+ }))
+ file.close()
+
+func set_friend_status() -> int:
+ if !logged_in: return 0
+
+ var result : Dictionary = await https_controller.perform_https_request(
+ "setfriendstatus",
+ {
+ "Token" : login_token,
+ "Data" :
+ {
+ "LobbyName" : session_controller.lobby_name,
+ "HasPassword" : session_controller.lobby_password != ""
+ }
+ }
+ )
+
+ return result["Code"]
+
+func create_account(email : String, username : String, password : String) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "createaccount",
+ {
+ "Email" : email,
+ "Username" : username,
+ "Password" : password
+ }
+ )
+
+ return result["Code"]
+
+func delete_account(email : String, password : String) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "deleteaccount",
+ {
+ "Email" : email,
+ "Password" : password
+ }
+ )
+
+ return result["Code"]
+
+func verify_account(email : String, code : String, valid_time : float) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "verifyaccount",
+ {
+ "Email" : email,
+ "Code" : code,
+ "ValidTime" : valid_time
+ }
+ )
+
+ login_email = email
+
+ if result["Code"] == ENUMS.ACCOUNT_VERIFICATION_RESPONSE_CODE.SUCCESS:
+ login_token = result["Result"]
+ save_config()
+
+ return result["Code"]
+
+func login(email : String, password : String, valid_time : float) -> Dictionary:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "login",
+ {
+ "Email" : email,
+ "Password" : password,
+ "ValidTime" : valid_time
+ }
+ )
+
+ login_email = email
+
+ var data : Dictionary = {
+ "Code" : result["Code"]
+ }
+
+ if result["Code"] == ENUMS.ACCOUNT_LOGIN_RESPONSE_CODE.SUCCESS:
+ login_token = result["Result"]
+ log_in(result["Username"])
+ save_config()
+ GDSync.player_set_username(result["Username"])
+ elif result["Code"] == ENUMS.ACCOUNT_LOGIN_RESPONSE_CODE.BANNED:
+ var ban_time : float = result["BanTime"]
+ if ban_time-Time.get_unix_time_from_system() >= 86400000:
+ ban_time = -1
+ data["BanTime"] = ban_time
+
+ return data
+
+func login_from_session(valid_time : int) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "loginfromsession",
+ {
+ "Email" : login_email,
+ "Token" : previous_token,
+ "ValidTime" : valid_time
+ }
+ )
+
+ if result["Code"] == ENUMS.ACCOUNT_LOGIN_RESPONSE_CODE.SUCCESS:
+ login_token = result["Result"]
+ log_in(result["Username"])
+ GDSync.player_set_username(result["Username"])
+ else:
+ login_token = ""
+ save_config()
+
+ return result["Code"]
+
+func resend_verification_code(email : String, password : String) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "resendverificationcode",
+ {
+ "Email" : email,
+ "Password" : password
+ }
+ )
+
+ return result["Code"]
+
+func is_verified(username : String) -> Dictionary:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "isverified",
+ {
+ "Token" : login_token,
+ "Username" : username
+ }
+ )
+
+ var data : Dictionary = {
+ "Code" : result["Code"],
+ "Result" : result["Result"] if result.size() > 1 else false
+ }
+ return data
+
+func logout() -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "logout",
+ {
+ "Email" : login_email,
+ "Token" : login_token
+ }
+ )
+
+ var was_logged_in : bool = logged_in
+ login_token = ""
+ login_email = ""
+ logged_in = false
+ save_config()
+
+ if was_logged_in:
+ GDSync.account_logged_out.emit.call_deferred()
+
+ return result["Code"]
+
+func change_username(new_username : String) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "changeusername",
+ {
+ "Token" : login_token,
+ "Username" : new_username
+ }
+ )
+
+ return result["Code"]
+
+func change_password(email : String, password : String, new_password : String) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "changepassword",
+ {
+ "Email" : email,
+ "Password" : password,
+ "NewPassword" : new_password
+ }
+ )
+
+ return result["Code"]
+
+func request_password_reset(email : String) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "requestpasswordreset",
+ {
+ "Email" : email
+ }
+ )
+
+ return result["Code"]
+
+func reset_password(email : String, reset_code : String, new_password : String) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "resetpassword",
+ {
+ "Email" : email,
+ "ResetCode" : reset_code,
+ "NewPassword" : new_password
+ }
+ )
+
+ return result["Code"]
+
+func set_player_document(path : String, data : Dictionary, externally_visible : bool) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "setplayerdocument",
+ {
+ "Token" : login_token,
+ "Path" : path,
+ "Data" : data,
+ "ExternallyVisible" : externally_visible
+ }
+ )
+
+ return result["Code"]
+
+func set_external_visible(path : String, externally_visible : bool) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "setexternalvisible",
+ {
+ "Token" : login_token,
+ "Path" : path,
+ "ExternallyVisible" : externally_visible
+ }
+ )
+
+ return result["Code"]
+
+func get_player_document(path : String, external_username : String) -> Dictionary:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "getplayerdocument",
+ {
+ "Token" : login_token,
+ "Path" : path,
+ "ExternalUsername" : external_username
+ }
+ )
+
+ var data : Dictionary = {
+ "Code" : result["Code"],
+ "Result" : result["Result"] if result.size() > 1 else {}
+ }
+ return data
+
+func browse_player_collection(path : String, external_username : String) -> Dictionary:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "browseplayercollection",
+ {
+ "Token" : login_token,
+ "Path" : path,
+ "ExternalUsername" : external_username
+ }
+ )
+
+ var data : Dictionary = {
+ "Code" : result["Code"],
+ "Result" : result["Result"] if result.size() > 1 and result["Result"] != null else []
+ }
+ return data
+
+func has_player_document(path : String, external_username : String) -> Dictionary:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "hasplayerdocument",
+ {
+ "Token" : login_token,
+ "Path" : path,
+ "ExternalUsername" : external_username
+ }
+ )
+
+ var data : Dictionary = {
+ "Code" : result["Code"],
+ "Result" : result["Result"] if result.size() > 1 else false
+ }
+ return data
+
+func delete_player_document(path : String) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "deleteplayerdocument",
+ {
+ "Token" : login_token,
+ "Path" : path
+ }
+ )
+
+ return result["Code"]
+
+func report_user(user : String, report : String) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "createreport",
+ {
+ "Token" : login_token,
+ "Against" : user,
+ "Report" : report
+ }
+ )
+
+ return result["Code"]
+
+func has_leaderboard(leaderboard : String) -> Dictionary:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "hasleaderboard",
+ {
+ "Token" : login_token,
+ "Leaderboard" : leaderboard
+ }
+ )
+
+ var data : Dictionary = {
+ "Code" : result["Code"],
+ "Result" : result["Result"] if result.size() > 1 else false
+ }
+ return data
+
+func get_leaderboards() -> Dictionary:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "getleaderboardstoken",
+ {
+ "Token" : login_token
+ }
+ )
+
+ var data : Dictionary = {
+ "Code" : result["Code"],
+ "Result" : result["Result"] if result.size() > 1 else []
+ }
+ return data
+
+func browse_leaderboard(leaderboard : String, page_size : int, page : int) -> Dictionary:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "browseleaderboardtoken",
+ {
+ "Token" : login_token,
+ "Leaderboard" : leaderboard,
+ "Page" : page,
+ "PageSize" : page_size
+ }
+ )
+
+ var data : Dictionary = {
+ "Code" : result["Code"],
+ "FinalPage" : result["FinalPage"] if result.has("FinalPage") else 0,
+ "Result" : result["Result"] if result.has("Result") else []
+ }
+ return data
+
+func get_leaderboard_score(leaderboard : String, username : String) -> Dictionary:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "getleaderboardscore",
+ {
+ "Token" : login_token,
+ "Leaderboard" : leaderboard,
+ "Username" : username
+ }
+ )
+
+ var data : Dictionary = {
+ "Code" : result["Code"],
+ "Result" : result["Result"] if result.size() > 1 else {"Rank" : -1, "Score" : 0, "Data" : {}}
+ }
+ return data
+
+func submit_score(leaderboard : String, score : int, data : Dictionary) -> int:
+ if var_to_bytes(data).size() > 2048:
+ return ENUMS.LEADERBOARD_SUBMIT_SCORE_RESPONSE_CODE.DATA_TOO_LAGE
+
+ var result : Dictionary = await https_controller.perform_https_request(
+ "submitscore",
+ {
+ "Token" : login_token,
+ "Leaderboard" : leaderboard,
+ "Score" : score,
+ "Data" : data
+ }
+ )
+
+ return result["Code"]
+
+func delete_score(leaderboard : String) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "deletescore",
+ {
+ "Token" : login_token,
+ "Leaderboard" : leaderboard
+ }
+ )
+
+ return result["Code"]
+
+func send_friend_request(friend : String) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "sendfriendrequest",
+ {
+ "Token" : login_token,
+ "Friend" : friend
+ }
+ )
+
+ return result["Code"]
+
+func get_friend_status(friend : String) -> Dictionary:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "getfriendstatus",
+ {
+ "Token" : login_token,
+ "Friend" : friend
+ }
+ )
+
+ var data : Dictionary = {
+ "Code" : result["Code"],
+ "Result" : result["Result"] if result.size() > 1 else {}
+ }
+ return data
+
+func get_friends() -> Dictionary:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "getfriends",
+ {
+ "Token" : login_token
+ }
+ )
+
+ var data : Dictionary = {
+ "Code" : result["Code"],
+ "Result" : result["Result"] if result.size() > 1 else 0
+ }
+ return data
+
+func accept_friend_request(friend : String) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "acceptfriendrequest",
+ {
+ "Token" : login_token,
+ "Friend" : friend
+ }
+ )
+
+ return result["Code"]
+
+func remove_friend(friend : String) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "removefriend",
+ {
+ "Token" : login_token,
+ "Friend" : friend
+ }
+ )
+
+ return result["Code"]
+
+func invite_friend_to_lobby(friend : String) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "invitefriendtolobby",
+ {
+ "Token" : login_token,
+ "Friend" : friend,
+ "Data" : {
+ "LobbyName" : session_controller.lobby_name,
+ "Password" : session_controller.lobby_password
+ }
+ }
+ )
+
+ return result["Code"]
+
+func get_lobby_invitations() -> Dictionary:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "getlobbyinvitations",
+ {
+ "Token" : login_token
+ }
+ )
+
+ var data : Dictionary = {
+ "Code" : result["Code"],
+ "Result" : result["Result"] if result.size() > 1 else []
+ }
+ return data
+
+func link_steam_account(auth_ticket : PackedByteArray, app_id : int) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "linksteamaccount",
+ {
+ "Token" : login_token,
+ "AuthTicket" : auth_ticket,
+ "AppID" : app_id
+ }
+ )
+
+ return result["Code"]
+
+func unlink_steam_account() -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "unlinksteamaccount",
+ {
+ "Token" : login_token
+ }
+ )
+
+ return result["Code"]
+
+func steam_login(auth_ticket : PackedByteArray, app_id : int, valid_time : float) -> Dictionary:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "steamlogin",
+ {
+ "AuthTicket" : auth_ticket,
+ "AppID" : app_id,
+ "ValidTime" : valid_time
+ }
+ )
+
+ var data : Dictionary = {
+ "Code" : result["Code"]
+ }
+
+ if result["Code"] == ENUMS.ACCOUNT_LOGIN_RESPONSE_CODE.SUCCESS:
+ login_token = result["Result"]
+ log_in(result["Username"])
+ save_config()
+ GDSync.player_set_username(result["Username"])
+ elif result["Code"] == ENUMS.ACCOUNT_LOGIN_RESPONSE_CODE.BANNED:
+ var ban_time : float = result["BanTime"]
+ if ban_time-Time.get_unix_time_from_system() >= 86400000:
+ ban_time = -1
+ data["BanTime"] = ban_time
+
+ return data
+
+func ban_account(ban_time : float) -> int:
+ var result : Dictionary = await https_controller.perform_https_request(
+ "banaccount",
+ {
+ "Token" : login_token,
+ "BanTime" : ban_time
+ }
+ )
+
+ return result["Code"]
diff --git a/addons/GD-Sync/Scripts/DataController.gd.uid b/addons/GD-Sync/Scripts/DataController.gd.uid
new file mode 100644
index 0000000..d0196cb
--- /dev/null
+++ b/addons/GD-Sync/Scripts/DataController.gd.uid
@@ -0,0 +1 @@
+uid://bikhttkxiialg
diff --git a/addons/GD-Sync/Scripts/Enums/Enums.gd b/addons/GD-Sync/Scripts/Enums/Enums.gd
new file mode 100644
index 0000000..4f25622
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Enums/Enums.gd
@@ -0,0 +1,720 @@
+class_name ENUMS
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+enum CONNECTION_STATUS
+{
+ LOBBY_SWITCH = -1,
+ DISABLED,
+ FINDING_LB,
+ PINGING_SERVERS,
+ CONNECTING,
+ CONNECTED,
+ CONNECTION_SECURED,
+ LOCAL_CONNECTION
+}
+
+enum PACKET_CHANNEL
+{
+ SETUP,
+ SERVER,
+ RELIABLE,
+ UNRELIABLE,
+ INTERNAL,
+}
+
+enum PACKET_VALUE
+{
+ PADDING,
+ CLIENT_REQUESTS,
+ SERVER_REQUESTS,
+ INTERNAL_REQUESTS,
+}
+
+enum REQUEST_TYPE
+{
+ VALIDATE_KEY,
+ SECURE_CONNECTION,
+ MESSAGE,
+ SET_VARIABLE,
+ CALL_FUNCTION,
+ SET_VARIABLE_CACHED,
+ CALL_FUNCTION_CACHED,
+ CACHE_NODE_PATH,
+ ERASE_NODE_PATH_CACHE,
+ CACHE_NAME,
+ ERASE_NAME_CACHE,
+ SET_GDSYNC_OWNER,
+ CREATE_LOBBY,
+ JOIN_LOBBY,
+ LEAVE_LOBBY,
+ OPEN_LOBBY,
+ CLOSE_LOBBY,
+ SET_LOBBY_TAG,
+ ERASE_LOBBY_TAG,
+ SET_LOBBY_DATA,
+ ERASE_LOBBY_DATA,
+ SET_LOBBY_VISIBILITY,
+ SET_LOBBY_PLAYER_LIMIT,
+ SET_LOBBY_PASSWORD,
+ GET_PUBLIC_LOBBIES,
+ SET_PLAYER_USERNAME,
+ SET_PLAYER_DATA,
+ ERASE_PLAYER_DATA,
+ SET_CONNECT_TIME,
+ SET_SETTING,
+ SET_CLIENT_ID,
+ KICK_PLAYER,
+ CHANGE_PASSWORD,
+ GET_PUBLIC_LOBBY,
+ CHANGE_LOBBY_NAME,
+ SET_HOST,
+ START_MATCHMAKING,
+ CANCEL_MATCHMAKING,
+ JOIN_LOBBY_WITH_TICKET,
+ COMMIT_SERVER_SWITCH,
+ TUNNEL_TO,
+}
+
+enum MESSAGE_TYPE
+{
+ CRITICAL_ERROR,
+ CLIENT_ID_RECEIVED,
+ CLIENT_KEY_RECEIVED,
+ INVALID_PUBLIC_KEY,
+ SET_NODE_PATH_CACHE,
+ ERASE_NODE_PATH_CACHE,
+ SET_NAME_CACHE,
+ ERASE_NAME_CACHE,
+ SET_GDSYNC_OWNER,
+ HOST_CHANGED,
+ LOBBY_CREATED,
+ LOBBY_CREATION_FAILED,
+ LOBBY_JOINED,
+ SWITCH_SERVER,
+ LOBBY_JOIN_FAILED,
+ LOBBIES_RECEIVED,
+ LOBBY_DATA_RECEIVED,
+ LOBBY_DATA_CHANGED,
+ LOBBY_TAGS_CHANGED,
+ PLAYER_DATA_RECEIVED,
+ PLAYER_DATA_CHANGED,
+ CLIENT_JOINED,
+ CLIENT_LEFT,
+ SET_CONNECT_TIME,
+ SET_SENDER_ID,
+ SET_DATA_USAGE,
+ KICKED,
+ LOBBY_RECEIVED,
+ LOBBY_NAME_CHANGED,
+ LOBBY_NAME_CHANGE_FAILED,
+ MATCHMAKING_STARTED,
+ MATCHMAKING_STATUS_CHANGED,
+ MATCHMAKING_MATCH_FOUND,
+ MATCHMAKING_FAILED,
+ MATCHMAKING_CANCELLED,
+ SWITCH_SERVER_PREPARED,
+ MATCHMAKING_SWITCH_PREPARED,
+ TUNNEL_READY,
+ TUNNEL_FAILED,
+ TUNNEL_LOCAL,
+}
+
+enum SETTING
+{
+ API_VERSION,
+ USE_SENDER_ID,
+}
+
+enum EXPOSE_PERMISSION
+{
+ ANYONE = 0,
+ HOST = 1,
+ CLIENT = 2,
+}
+
+enum DATA
+{
+ REQUEST_TYPE,
+ NAME,
+ VALUE,
+ TARGET_CLIENT = 3,
+}
+
+enum LOBBY_DATA
+{
+ NAME = 1,
+ PASSWORD = 2,
+ PARAMETERS = 1,
+ VISIBILITY = 1,
+ VALUE = 2,
+}
+
+enum FUNCTION_DATA
+{
+ NODE_PATH = 1,
+ NAME = 2,
+ PARAMETERS = 4
+}
+
+enum VAR_DATA
+{
+ NODE_PATH = 1,
+ NAME = 2,
+ VALUE = 4
+}
+
+enum MESSAGE_DATA
+{
+ TYPE = 1,
+ VALUE = 2,
+ ERROR = 3,
+ VALUE2 = 3,
+}
+
+enum CRITICAL_ERROR
+{
+ LOBBY_DATA_FULL,
+ LOBBY_TAGS_FULL,
+ PLAYER_DATA_FULL,
+ REQUEST_TOO_LARGE,
+ OBJECT_IN_REQUEST,
+}
+
+enum INTERNAL_MESSAGE
+{
+ LOBBY_UPDATED,
+ LOBBY_DELETED,
+ REQUEST_LOBBIES,
+ INCREASE_DATA_USAGE,
+}
+
+enum CONNECTION_FAILED
+{
+ INVALID_PUBLIC_KEY,
+ TIMEOUT,
+ LOCAL_PORT_ERROR,
+}
+
+enum LOBBY_CREATION_ERROR
+{
+ LOBBY_ALREADY_EXISTS,
+ NAME_TOO_SHORT,
+ NAME_TOO_LONG,
+ PASSWORD_TOO_LONG,
+ TAGS_TOO_LARGE,
+ DATA_TOO_LARGE,
+ ON_COOLDOWN,
+ LOCAL_PORT_ERROR,
+}
+
+enum LOBBY_JOIN_ERROR
+{
+ LOBBY_DOES_NOT_EXIST,
+ LOBBY_IS_CLOSED,
+ LOBBY_IS_FULL,
+ INCORRECT_PASSWORD,
+ DUPLICATE_USERNAME,
+}
+
+enum LOBBY_NAME_CHANGE_ERROR {
+ NAME_ALREADY_EXISTS,
+ NAME_TOO_SHORT,
+ NAME_TOO_LONG,
+ ON_COOLDOWN,
+}
+
+enum MATCHMAKING_SEARCH_MODE {
+ PUBLIC_ONLY,
+ PUBLIC_THEN_MATCHMAKE,
+ MATCHMAKE_ONLY,
+}
+
+enum MATCHMAKING_STATUS {
+ INACTIVE,
+ SEARCHING_PUBLIC,
+ WAITING_FOR_PLAYERS,
+ MATCH_FOUND,
+ JOINING,
+}
+
+enum MATCHMAKING_ERROR {
+ INVALID_REQUEST,
+ ALREADY_IN_LOBBY,
+ NO_MATCH,
+ TIMEOUT,
+ UNSUPPORTED_LOCAL,
+ JOIN_FAILED,
+}
+
+enum LOBBY_SWITCH_ERROR {
+ INVALID_RESERVATION,
+ RESERVATION_EXPIRED,
+ DESTINATION_UNREACHABLE,
+ JOIN_FAILED,
+ ROLLBACK_FAILED,
+}
+
+enum NODE_REPLICATION_SETTINGS
+{
+ INSTANTIATOR,
+ SYNC_STARTING_CHANGES,
+ EXCLUDED_PROPERTIES,
+ SCENE,
+ TARGET,
+ ORIGINAL_PROPERTIES,
+}
+
+enum NODE_REPLICATION_DATA
+{
+ ID,
+ CHANGED_PROPERTIES,
+}
+
+enum ACCOUNT_CREATION_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ STORAGE_FULL,
+ INVALID_EMAIL,
+ INVALID_USERNAME,
+ EMAIL_ALREADY_EXISTS,
+ USERNAME_ALREADY_EXISTS,
+ USERNAME_TOO_SHORT,
+ USERNAME_TOO_LONG,
+ PASSWORD_TOO_SHORT,
+ PASSWORD_TOO_LONG,
+}
+
+enum ACCOUNT_DELETION_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ EMAIL_OR_PASSWORD_INCORRECT,
+}
+
+enum ACCOUNT_RESEND_VERIFICATION_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ VERIFICATION_DISABLED,
+ ON_COOLDOWN,
+ ALREADY_VERIFIED,
+ EMAIL_OR_PASSWORD_INCORRECT,
+ BANNED,
+}
+
+enum ACCOUNT_VERIFICATION_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ INCORRECT_CODE,
+ CODE_EXPIRED,
+ ALREADY_VERIFIED,
+ BANNED,
+}
+
+enum ACCOUNT_IS_VERIFIED_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ USER_DOESNT_EXIST,
+}
+
+enum ACCOUNT_LOGIN_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ EMAIL_OR_PASSWORD_INCORRECT,
+ NOT_VERIFIED,
+ EXPIRED_SESSION,
+ BANNED,
+}
+
+enum ACCOUNT_LOGOUT_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+}
+
+enum ACCOUNT_CHANGE_PASSWORD_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ ON_COOLDOWN,
+ EMAIL_OR_PASSWORD_INCORRECT,
+ NOT_VERIFIED,
+ BANNED,
+}
+
+enum ACCOUNT_CHANGE_USERNAME_RESPONSE_CODE
+{
+
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ ON_COOLDOWN,
+ USERNAME_ALREADY_EXISTS,
+ USERNAME_TOO_SHORT,
+ USERNAME_TOO_LONG,
+ INVALID_USERNAME
+}
+
+enum ACCOUNT_RESET_PASSWORD_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ EMAIL_OR_CODE_INCORRECT,
+ CODE_EXPIRED,
+}
+
+enum ACCOUNT_REQUEST_PASSWORD_RESET_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ ON_COOLDOWN,
+ EMAIL_DOESNT_EXIST,
+ BANNED,
+}
+
+enum ACCOUNT_DOCUMENT_SET_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ STORAGE_FULL,
+}
+
+enum ACCOUNT_GET_DOCUMENT_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ DOESNT_EXIST,
+}
+
+enum ACCOUNT_BROWSE_COLLECTION_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ DOESNT_EXIST,
+}
+
+enum ACCOUNT_DOCUMENT_SET_EXTERNAL_VISIBLE_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ DOESNT_EXIST,
+}
+
+
+enum ACCOUNT_HAS_DOCUMENT_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+}
+
+enum ACCOUNT_DELETE_DOCUMENT_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ DOESNT_EXIST,
+}
+
+enum ACCOUNT_CREATE_REPORT_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ STORAGE_FULL,
+ REPORT_TOO_LONG,
+ TOO_MANY_REPORTS,
+ USER_DOESNT_EXIST,
+}
+
+enum LEADERBOARD_SUBMIT_SCORE_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ STORAGE_FULL,
+ LEADERBOARD_DOESNT_EXIST,
+ DATA_TOO_LAGE
+}
+
+enum LEADERBOARD_DELETE_SCORE_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ LEADERBOARD_DOESNT_EXIST
+}
+
+enum LEADERBOARD_GET_ALL_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+}
+
+enum LEADERBOARD_EXISTS_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN
+}
+
+enum LEADERBOARD_BROWSE_SCORES_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ LEADERBOARD_DOESNT_EXIST
+}
+
+enum LEADERBOARD_GET_SCORE_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ LEADERBOARD_DOESNT_EXIST,
+ USER_DOESNT_EXIST
+}
+
+enum ACCOUNT_SEND_FRIEND_REQUEST_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ STORAGE_FULL,
+ USER_DOESNT_EXIST,
+ FRIEND_ALREADY_ADDED,
+ FRIENDS_LIST_FULL,
+}
+
+enum ACCOUNT_ACCEPT_FRIEND_REQUEST_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ STORAGE_FULL,
+ FRIEND_NOT_FOUND,
+}
+
+enum ACCOUNT_REMOVE_FRIEND_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ STORAGE_FULL,
+ FRIEND_DOESNT_EXIST,
+}
+
+enum ACCOUNT_GET_FRIENDS_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+}
+
+enum ACCOUNT_GET_FRIEND_STATUS_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ USER_DOESNT_EXIST,
+}
+
+enum ACCOUNT_INVITE_FRIEND_TO_LOBBY_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ STORAGE_FULL,
+ USER_DOESNT_EXIST,
+ NOT_FRIEND,
+ NOT_IN_LOBBY,
+}
+
+enum ACCOUNT_GET_LOBBY_INVITATIONS_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+}
+
+enum FRIEND_STATUS
+{
+ NONE,
+ INCOMING_REQUEST,
+ FRIEND,
+ WAITING_FOR_REPLY,
+}
+
+enum LINK_STEAM_ACCOUNT_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ ALREADY_LINKED,
+ STEAM_ERROR,
+}
+
+enum UNLINK_STEAM_ACCOUNT_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ STEAM_ERROR,
+}
+
+enum STEAM_LOGIN_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ STEAM_ERROR,
+ NOT_LINKED,
+ NOT_VERIFIED,
+ BANNED,
+}
+
+enum ACCOUNT_BAN_RESPONSE_CODE
+{
+ SUCCESS,
+ NO_RESPONSE_FROM_SERVER,
+ DATA_CAP_REACHED,
+ RATE_LIMIT_EXCEEDED,
+ NO_DATABASE,
+ NOT_LOGGED_IN,
+ STORAGE_FULL,
+}
diff --git a/addons/GD-Sync/Scripts/Enums/Enums.gd.uid b/addons/GD-Sync/Scripts/Enums/Enums.gd.uid
new file mode 100644
index 0000000..a63a0e1
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Enums/Enums.gd.uid
@@ -0,0 +1 @@
+uid://cvm8hol2ndcgr
diff --git a/addons/GD-Sync/Scripts/HTTPSController.gd b/addons/GD-Sync/Scripts/HTTPSController.gd
new file mode 100644
index 0000000..f264ddf
--- /dev/null
+++ b/addons/GD-Sync/Scripts/HTTPSController.gd
@@ -0,0 +1,102 @@
+extends Node
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+var GDSync
+var connection_controller
+var data_controller
+var logger
+
+var active_lb : String = ""
+
+func _ready():
+ GDSync = get_node("/root/GDSync")
+ name = "HTTPSController"
+ connection_controller = GDSync._connection_controller
+ data_controller = GDSync._data_controller
+ logger = GDSync._logger
+
+func perform_https_request(endpoint : String, message : Dictionary) -> Dictionary:
+ logger.write_log("Making HTTP request. <"+endpoint+"><"+str(message)+">", "[HTTP]")
+
+ if !GDSync.is_active():
+ logger.write_error("Failed HTTP request as the plugin is not active. <"+endpoint+">", "[HTTP]")
+ push_error("You must first start the plugin using GDSync.start_multiplayer() before using any cloudstorage functions.")
+ return {"Code" : 1}
+
+ if active_lb.is_empty():
+ logger.write_error("Failed HTTP request, no load balancer resolved. <"+endpoint+">", "[HTTP]")
+ return {"Code" : 1}
+
+ var request : HTTPRequest = HTTPRequest.new()
+ request.timeout = 20
+ add_child(request)
+
+ message["PublicKey"] = connection_controller._PUBLIC_KEY
+
+ request.request(
+ active_lb+"/"+endpoint,
+ ["Content-Type: text/plain"],
+ HTTPClient.METHOD_POST,
+ var_to_str(message)
+ )
+
+ var result = await request.request_completed
+
+ logger.write_log("Completed HTTP request. <"+endpoint+"><"+str(result[1])+">", "[HTTP]")
+
+ if result[1] == 200:
+ var text : String = result[3].get_string_from_ascii()
+ var received_message : Dictionary = str_to_var(text)
+ logger.write_log("Successful HTTP request. <"+endpoint+"><"+text+">", "[HTTP]")
+ return received_message
+ else:
+ logger.write_error("Failed HTTP request. <"+endpoint+"><"+str(result[1])+">", "[HTTP]")
+ return {"Code" : 1 if result[1] != 503 else 3}
+
+func ping_https(url : String, timeout_seconds : float = 3.0) -> float:
+ logger.write_log("HTTPS ping. <"+url+">", "[HTTP]")
+ var request : HTTPRequest = HTTPRequest.new()
+ request.timeout = timeout_seconds
+ add_child(request)
+
+ var started_ms : int = Time.get_ticks_msec()
+ var error : Error = request.request(url, [], HTTPClient.METHOD_GET)
+ if error != OK:
+ request.queue_free()
+ logger.write_error("HTTPS ping failed to start. <"+url+"><"+str(error)+">", "[HTTP]")
+ return -1.0
+
+ var result = await request.request_completed
+ var elapsed_ms : float = float(Time.get_ticks_msec() - started_ms)
+ request.queue_free()
+
+ var response_code : int = result[1]
+ if response_code <= 0:
+ logger.write_error("HTTPS ping failed. <"+url+"><"+str(response_code)+">", "[HTTP]")
+ return -1.0
+
+ logger.write_log("HTTPS ping complete. <"+url+"><"+str(elapsed_ms)+"ms><"+str(response_code)+">", "[HTTP]")
+ return elapsed_ms
diff --git a/addons/GD-Sync/Scripts/HTTPSController.gd.uid b/addons/GD-Sync/Scripts/HTTPSController.gd.uid
new file mode 100644
index 0000000..5966844
--- /dev/null
+++ b/addons/GD-Sync/Scripts/HTTPSController.gd.uid
@@ -0,0 +1 @@
+uid://d16jsc5k0bs3j
diff --git a/addons/GD-Sync/Scripts/InterestManager.gd b/addons/GD-Sync/Scripts/InterestManager.gd
new file mode 100644
index 0000000..9234625
--- /dev/null
+++ b/addons/GD-Sync/Scripts/InterestManager.gd
@@ -0,0 +1,472 @@
+extends Node
+
+# Copyright (c) 2023-present GD-Sync.
+# All rights reserved.
+#
+# Redistribution and use in source form, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+# 1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+# 2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+const DEFAULT_CELL_SIZE : float = 128.0
+
+var GDSync
+
+var _viewers : Dictionary = {}
+var _objects : Dictionary = {}
+var _object_grid : Dictionary = {}
+var _viewer_memberships : Dictionary = {}
+var _recipient_cache : Dictionary = {}
+var _ambiguous_object_branches : Dictionary = {}
+
+func _ready() -> void:
+ name = "InterestManager"
+ GDSync.expose_func(_receive_viewer_update)
+ GDSync.expose_func(_remove_viewer)
+ GDSync.expose_func(_receive_object_update)
+ GDSync.expose_func(_remove_object)
+ GDSync.expose_func(_set_object_recipients_remote)
+ GDSync.expose_func(_apply_object_recipient_delta_remote)
+ GDSync.client_joined.connect(_client_joined)
+ GDSync.client_left.connect(_client_left)
+ GDSync.host_changed.connect(_host_changed)
+
+func clear() -> void:
+ _viewers.clear()
+ _objects.clear()
+ _object_grid.clear()
+ _viewer_memberships.clear()
+ _recipient_cache.clear()
+ _ambiguous_object_branches.clear()
+
+func call_function(callable : Callable, parameters : Array, reliable : bool) -> void:
+ var object : Object = callable.get_object()
+ var interest_object : Node = _find_interest_object(object) if object is Node else null
+ if interest_object == null:
+ GDSync._request_processor.create_function_call_request(callable, parameters, -1, reliable)
+ return
+
+ for client_id in interest_object._get_gdsync_interest_object_recipients():
+ if client_id == GDSync.get_client_id():
+ continue
+ GDSync._request_processor.create_function_call_request(callable, parameters, client_id, reliable)
+
+func sync_variable(object : Object, variable_name : String, reliable : bool) -> void:
+ var interest_object : Node = _find_interest_object(object) if object is Node else null
+ if interest_object == null:
+ GDSync._request_processor.create_set_var_request(object, variable_name, -1, reliable)
+ return
+
+ for client_id in interest_object._get_gdsync_interest_object_recipients():
+ if client_id == GDSync.get_client_id():
+ continue
+ GDSync._request_processor.create_set_var_request(object, variable_name, client_id, reliable)
+
+func get_relevant_clients(object : Object, include_self : bool = false) -> Array:
+ var clients : Array
+ var interest_object : Node = _find_interest_object(object) if object is Node else null
+ if interest_object == null:
+ clients = GDSync.lobby_get_all_clients().duplicate()
+ else:
+ clients = interest_object._get_gdsync_interest_object_recipients().duplicate()
+ if !include_self:
+ clients.erase(GDSync.get_client_id())
+ return clients
+
+func has_interest_object(context : Node) -> bool:
+ return _find_interest_object(context) != null
+
+func get_interest_object(context : Node) -> Node:
+ return _find_interest_object(context)
+
+func apply_cached_recipients(interest_object : Node) -> void:
+ var object_path := str(interest_object.get_path())
+ if _recipient_cache.has(object_path):
+ interest_object._set_gdsync_interest_object_recipients(_recipient_cache[object_path])
+
+func report_viewer(
+ viewer_path : String,
+ client_id : int,
+ position : Vector3,
+ dimension : int,
+ layers : int
+ ) -> void:
+ if GDSync.is_host():
+ _receive_viewer_update(viewer_path, client_id, position, dimension, layers)
+ else:
+ GDSync.call_func_on_unreliable(
+ GDSync.get_host(),
+ _receive_viewer_update,
+ viewer_path,
+ client_id,
+ position,
+ dimension,
+ layers
+ )
+
+func unregister_viewer(viewer_path : String, client_id : int) -> void:
+ if !GDSync.is_active():
+ return
+ if GDSync.is_host():
+ _remove_viewer(viewer_path, client_id)
+ else:
+ GDSync.call_func_on(GDSync.get_host(), _remove_viewer, viewer_path, client_id)
+
+func report_object(
+ object_path : String,
+ authority_id : int,
+ position : Vector3,
+ dimension : int,
+ visibility_radius : float,
+ exit_margin : float,
+ layers : int,
+ host_receives_state : bool
+ ) -> void:
+ if GDSync.is_host():
+ _receive_object_update(
+ object_path,
+ authority_id,
+ position,
+ dimension,
+ visibility_radius,
+ exit_margin,
+ layers,
+ host_receives_state
+ )
+ else:
+ GDSync.call_func_on(
+ GDSync.get_host(),
+ _receive_object_update,
+ object_path,
+ authority_id,
+ position,
+ dimension,
+ visibility_radius,
+ exit_margin,
+ layers,
+ host_receives_state
+ )
+
+func unregister_object(object_path : String, authority_id : int) -> void:
+ if !GDSync.is_active():
+ return
+ if GDSync.is_host():
+ _remove_object(object_path, authority_id)
+ else:
+ GDSync.call_func_on(GDSync.get_host(), _remove_object, object_path, authority_id)
+
+func _receive_viewer_update(
+ viewer_path : String,
+ client_id : int,
+ position : Vector3,
+ dimension : int,
+ layers : int
+ ) -> void:
+ if !GDSync.is_host():
+ return
+
+ var viewer_key := _viewer_key(viewer_path, client_id)
+ _viewers[viewer_key] = {
+ "client_id": client_id,
+ "position": position,
+ "dimension": dimension,
+ "layers": layers,
+ }
+ _update_viewer_memberships(viewer_key)
+
+func _remove_viewer(viewer_path : String, client_id : int) -> void:
+ if !GDSync.is_host():
+ return
+
+ var viewer_key := _viewer_key(viewer_path, client_id)
+ var memberships : Dictionary = _viewer_memberships.get(viewer_key, {})
+ _viewers.erase(viewer_key)
+ _viewer_memberships.erase(viewer_key)
+ for object_path in memberships:
+ _refresh_object_recipients(object_path)
+
+func _receive_object_update(
+ object_path : String,
+ authority_id : int,
+ position : Vector3,
+ dimension : int,
+ visibility_radius : float,
+ exit_margin : float,
+ layers : int,
+ host_receives_state : bool
+ ) -> void:
+ if !GDSync.is_host():
+ return
+
+ if _objects.has(object_path):
+ _remove_object_from_grid(object_path)
+
+ var previous_recipients : Array = _objects.get(object_path, {}).get("recipients", [])
+ _objects[object_path] = {
+ "authority_id": authority_id,
+ "position": position,
+ "dimension": dimension,
+ "visibility_radius": maxf(visibility_radius, 0.0),
+ "exit_margin": maxf(exit_margin, 0.0),
+ "layers": layers,
+ "host_receives_state": host_receives_state,
+ "recipients": previous_recipients,
+ "cells": [],
+ }
+ _add_object_to_grid(object_path)
+
+ for viewer_key in _viewers:
+ _update_membership(viewer_key, object_path, false)
+ _refresh_object_recipients(object_path)
+
+func _remove_object(object_path : String, authority_id : int) -> void:
+ if !GDSync.is_host() or !_objects.has(object_path):
+ return
+ if _objects[object_path]["authority_id"] != authority_id:
+ return
+
+ var previous : Array = _objects[object_path]["recipients"]
+ if !previous.is_empty():
+ _apply_object_recipient_delta_remote(object_path, [], previous)
+ for client_id in GDSync.lobby_get_all_clients():
+ if client_id != GDSync.get_client_id():
+ GDSync.call_func_on(
+ client_id,
+ _apply_object_recipient_delta_remote,
+ object_path,
+ [],
+ previous
+ )
+ _remove_object_from_grid(object_path)
+ _objects.erase(object_path)
+ for memberships in _viewer_memberships.values():
+ memberships.erase(object_path)
+
+func _update_viewer_memberships(viewer_key : String) -> void:
+ var viewer : Dictionary = _viewers[viewer_key]
+ var candidates : Dictionary = _viewer_memberships.get(viewer_key, {}).duplicate()
+ var cell_key := _cell_key(viewer["position"], viewer["dimension"])
+ for object_path in _object_grid.get(cell_key, {}):
+ candidates[object_path] = true
+
+ for object_path in candidates:
+ _update_membership(viewer_key, object_path)
+
+func _update_membership(viewer_key : String, object_path : String, publish : bool = true) -> void:
+ if !_viewers.has(viewer_key):
+ return
+
+ var memberships : Dictionary = _viewer_memberships.get_or_add(viewer_key, {})
+ var was_relevant : bool = memberships.has(object_path)
+ if !_objects.has(object_path):
+ memberships.erase(object_path)
+ return
+
+ var viewer : Dictionary = _viewers[viewer_key]
+ var interest_object : Dictionary = _objects[object_path]
+ var relevant := false
+ if (
+ viewer["dimension"] == interest_object["dimension"]
+ and (viewer["layers"] & interest_object["layers"]) != 0
+ ):
+ var distance_squared := _distance_squared(
+ viewer["position"],
+ interest_object["position"],
+ interest_object["dimension"]
+ )
+ var threshold : float = interest_object["visibility_radius"]
+ if was_relevant:
+ threshold += interest_object["exit_margin"]
+ relevant = distance_squared <= threshold * threshold
+
+ if relevant == was_relevant:
+ return
+ if relevant:
+ memberships[object_path] = true
+ else:
+ memberships.erase(object_path)
+ if publish:
+ _refresh_object_recipients(object_path)
+
+func _refresh_object_recipients(object_path : String) -> void:
+ if !_objects.has(object_path):
+ return
+
+ var recipients : Dictionary = {}
+ for viewer_key in _viewer_memberships:
+ if _viewer_memberships[viewer_key].has(object_path) and _viewers.has(viewer_key):
+ recipients[_viewers[viewer_key]["client_id"]] = true
+
+ var interest_object : Dictionary = _objects[object_path]
+ if interest_object["host_receives_state"] and GDSync.get_host() >= 0:
+ recipients[GDSync.get_host()] = true
+
+ var recipient_list : Array[int] = []
+ for client_id in recipients:
+ recipient_list.append(client_id)
+ recipient_list.sort()
+
+ if interest_object["recipients"] == recipient_list:
+ return
+ var previous : Array = interest_object["recipients"]
+ var entered : Array = []
+ var exited : Array = []
+ for client_id in recipient_list:
+ if !previous.has(client_id):
+ entered.append(client_id)
+ for client_id in previous:
+ if !recipient_list.has(client_id):
+ exited.append(client_id)
+ interest_object["recipients"] = recipient_list
+
+ _apply_object_recipient_delta_remote(object_path, entered, exited)
+ for client_id in GDSync.lobby_get_all_clients():
+ if client_id != GDSync.get_client_id():
+ GDSync.call_func_on(
+ client_id,
+ _apply_object_recipient_delta_remote,
+ object_path,
+ entered,
+ exited
+ )
+
+func _set_object_recipients_remote(object_path : String, recipients : Array) -> void:
+ var updated : Array[int] = []
+ for client_id in recipients:
+ updated.append(int(client_id))
+ _recipient_cache[object_path] = updated
+ var interest_object := get_node_or_null(object_path)
+ if (
+ interest_object != null
+ and interest_object.has_method("_set_gdsync_interest_object_recipients")
+ ):
+ interest_object._set_gdsync_interest_object_recipients(updated)
+
+func _apply_object_recipient_delta_remote(object_path : String, entered : Array, exited : Array) -> void:
+ var updated : Array = _recipient_cache.get(object_path, []).duplicate()
+ for client_id in exited:
+ updated.erase(int(client_id))
+ for client_id in entered:
+ if !updated.has(int(client_id)):
+ updated.append(int(client_id))
+ _recipient_cache[object_path] = updated
+ var interest_object := get_node_or_null(object_path)
+ if (
+ interest_object != null
+ and interest_object.has_method("_set_gdsync_interest_object_recipients")
+ ):
+ interest_object._set_gdsync_interest_object_recipients(updated)
+
+func _add_object_to_grid(object_path : String) -> void:
+ var interest_object : Dictionary = _objects[object_path]
+ var radius : float = interest_object["visibility_radius"] + interest_object["exit_margin"]
+ var min_cell := _cell_coordinates(interest_object["position"] - Vector3.ONE * radius)
+ var max_cell := _cell_coordinates(interest_object["position"] + Vector3.ONE * radius)
+ if interest_object["dimension"] == 2:
+ min_cell.z = 0
+ max_cell.z = 0
+
+ var cells : Array = []
+ for x in range(min_cell.x, max_cell.x + 1):
+ for y in range(min_cell.y, max_cell.y + 1):
+ for z in range(min_cell.z, max_cell.z + 1):
+ var key := "%s:%s:%s:%s" % [interest_object["dimension"], x, y, z]
+ var bucket : Dictionary = _object_grid.get_or_add(key, {})
+ bucket[object_path] = true
+ cells.append(key)
+ interest_object["cells"] = cells
+
+func _remove_object_from_grid(object_path : String) -> void:
+ for key in _objects[object_path].get("cells", []):
+ if !_object_grid.has(key):
+ continue
+ _object_grid[key].erase(object_path)
+ if _object_grid[key].is_empty():
+ _object_grid.erase(key)
+
+func _find_interest_object(context : Node) -> Node:
+ var current := context
+ while current != null:
+ if current.has_method("_get_gdsync_interest_object_recipients"):
+ return current if current._is_gdsync_interest_object_enabled() else null
+ var sibling_objects : Array[Node] = []
+ for child in current.get_children():
+ if child.has_method("_get_gdsync_interest_object_recipients"):
+ sibling_objects.append(child)
+ if !sibling_objects.is_empty():
+ if sibling_objects.size() > 1:
+ var branch_id := current.get_instance_id()
+ if !_ambiguous_object_branches.has(branch_id):
+ _ambiguous_object_branches[branch_id] = true
+ push_error(
+ (
+ "GD-Sync found multiple sibling InterestObjects under %s. "
+ + "The first sibling is used; an entity should have exactly one."
+ ) % current.get_path()
+ )
+ var interest_object := sibling_objects[0]
+ return interest_object if interest_object._is_gdsync_interest_object_enabled() else null
+ current = current.get_parent()
+ return null
+
+func _viewer_key(viewer_path : String, client_id : int) -> String:
+ return "%s:%s" % [client_id, viewer_path]
+
+func _cell_coordinates(position : Vector3) -> Vector3i:
+ return Vector3i(
+ floori(position.x / DEFAULT_CELL_SIZE),
+ floori(position.y / DEFAULT_CELL_SIZE),
+ floori(position.z / DEFAULT_CELL_SIZE)
+ )
+
+func _cell_key(position : Vector3, dimension : int) -> String:
+ var cell := _cell_coordinates(position)
+ if dimension == 2:
+ cell.z = 0
+ return "%s:%s:%s:%s" % [dimension, cell.x, cell.y, cell.z]
+
+func _distance_squared(a : Vector3, b : Vector3, dimension : int) -> float:
+ if dimension == 2:
+ return Vector2(a.x, a.y).distance_squared_to(Vector2(b.x, b.y))
+ return a.distance_squared_to(b)
+
+func _client_left(client_id : int) -> void:
+ if !GDSync.is_host():
+ return
+ for viewer_key in _viewers.keys():
+ if _viewers[viewer_key]["client_id"] == client_id:
+ var viewer_path : String = viewer_key.trim_prefix("%s:" % client_id)
+ _remove_viewer(viewer_path, client_id)
+
+func _client_joined(client_id : int) -> void:
+ if !GDSync.is_host() or client_id == GDSync.get_client_id():
+ return
+ await get_tree().create_timer(0.5).timeout
+ for object_path in _objects:
+ GDSync.call_func_on(
+ client_id,
+ _set_object_recipients_remote,
+ object_path,
+ _objects[object_path]["recipients"]
+ )
+
+func _host_changed(is_host : bool, _new_host_id : int) -> void:
+ clear()
+ if is_host:
+ get_tree().call_group("_gdsync_interest", "_force_interest_report")
diff --git a/addons/GD-Sync/Scripts/InterestManager.gd.uid b/addons/GD-Sync/Scripts/InterestManager.gd.uid
new file mode 100644
index 0000000..f51c775
--- /dev/null
+++ b/addons/GD-Sync/Scripts/InterestManager.gd.uid
@@ -0,0 +1 @@
+uid://2jbx0lbddcpo
diff --git a/addons/GD-Sync/Scripts/KeyStore.gd b/addons/GD-Sync/Scripts/KeyStore.gd
new file mode 100644
index 0000000..e06873d
--- /dev/null
+++ b/addons/GD-Sync/Scripts/KeyStore.gd
@@ -0,0 +1,170 @@
+@tool
+extends RefCounted
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+const KEYS_PATH : String = "res://addons/GD-Sync/keys.cfg"
+const KEYS_SECTION : String = "keys"
+const PUBLIC_ENTRY : String = "publicKey"
+const PRIVATE_ENTRY : String = "privateKey"
+
+const GITIGNORE_PATH : String = "res://.gitignore"
+const GITIGNORE_ENTRY : String = "addons/GD-Sync/keys.cfg"
+const GITIGNORE_COMMENT : String = "# GD-Sync API keys. Never commit these."
+
+const PUBLIC_KEY_ENV : String = "GDSYNC_PUBLIC_KEY"
+const PRIVATE_KEY_ENV : String = "GDSYNC_PRIVATE_KEY"
+const PROJECT_FILE : String = "res://project.godot"
+const PROJECT_PUBLIC : String = "GD-Sync/publicKey"
+const PROJECT_PRIVATE : String = "GD-Sync/privateKey"
+
+static func load_keys() -> Dictionary:
+ var keys : Dictionary = {"PublicKey" : "", "PrivateKey" : ""}
+ var config : ConfigFile = ConfigFile.new()
+ if config.load(KEYS_PATH) == OK or config.load(_os(KEYS_PATH)) == OK:
+ keys["PublicKey"] = str(config.get_value(KEYS_SECTION, PUBLIC_ENTRY, ""))
+ keys["PrivateKey"] = str(config.get_value(KEYS_SECTION, PRIVATE_ENTRY, ""))
+ if keys["PublicKey"].is_empty():
+ keys["PublicKey"] = OS.get_environment(PUBLIC_KEY_ENV)
+ if keys["PrivateKey"].is_empty():
+ keys["PrivateKey"] = OS.get_environment(PRIVATE_KEY_ENV)
+ return keys
+
+static func save_keys(public_key : String, private_key : String) -> void:
+ var config : ConfigFile = ConfigFile.new()
+ config.load(KEYS_PATH)
+ config.set_value(KEYS_SECTION, PUBLIC_ENTRY, public_key)
+ config.set_value(KEYS_SECTION, PRIVATE_ENTRY, private_key)
+ if config.save(KEYS_PATH) != OK and config.save(_os(KEYS_PATH)) != OK:
+ push_error("GD-Sync was unable to save the API keys to "+KEYS_PATH+".")
+
+static func has_keys() -> bool:
+ var keys : Dictionary = load_keys()
+ return !keys["PublicKey"].is_empty() and !keys["PrivateKey"].is_empty()
+
+static func encode_keys(public_key : String, private_key : String) -> PackedByteArray:
+ var config : ConfigFile = ConfigFile.new()
+ config.set_value(KEYS_SECTION, PUBLIC_ENTRY, public_key)
+ config.set_value(KEYS_SECTION, PRIVATE_ENTRY, private_key)
+ return config.encode_to_text().to_utf8_buffer()
+
+static func needs_migrate() -> bool:
+ if ProjectSettings.has_setting(PROJECT_PUBLIC) or ProjectSettings.has_setting(PROJECT_PRIVATE):
+ return true
+ var project : ConfigFile = ConfigFile.new()
+ if project.load(PROJECT_FILE) != OK:
+ project.load(_os(PROJECT_FILE))
+ return project.has_section_key("GD-Sync", PUBLIC_ENTRY) or project.has_section_key("GD-Sync", PRIVATE_ENTRY)
+
+static func migrate() -> bool:
+ if !needs_migrate():
+ return false
+
+ var existing : Dictionary = load_keys()
+ var public_key : String = str(ProjectSettings.get_setting(PROJECT_PUBLIC, existing["PublicKey"]))
+ var private_key : String = str(ProjectSettings.get_setting(PROJECT_PRIVATE, existing["PrivateKey"]))
+
+ var project : ConfigFile = ConfigFile.new()
+ if project.load(PROJECT_FILE) == OK or project.load(_os(PROJECT_FILE)) == OK:
+ if public_key.is_empty():
+ public_key = str(project.get_value("GD-Sync", PUBLIC_ENTRY, ""))
+ if private_key.is_empty():
+ private_key = str(project.get_value("GD-Sync", PRIVATE_ENTRY, ""))
+
+ save_keys(public_key, private_key)
+
+ if ProjectSettings.has_setting(PROJECT_PUBLIC):
+ ProjectSettings.clear(PROJECT_PUBLIC)
+ if ProjectSettings.has_setting(PROJECT_PRIVATE):
+ ProjectSettings.clear(PROJECT_PRIVATE)
+ _strip_keys_from_project_file()
+ ProjectSettings.save()
+ return true
+
+static func ensure_gitignore() -> void:
+ var path : String = _os(GITIGNORE_PATH)
+ var content : String = _read_text(path)
+ if content.is_empty():
+ content = _read_text(GITIGNORE_PATH)
+ if _gitignore_has_entry(content):
+ return
+ if !content.is_empty() and !content.ends_with("\n"):
+ content += "\n"
+ if !content.is_empty():
+ content += "\n"
+ content += GITIGNORE_COMMENT+"\n"+GITIGNORE_ENTRY+"\n"
+ if !_write_text(path, content):
+ _write_text(GITIGNORE_PATH, content)
+
+static func _os(res_path : String) -> String:
+ return ProjectSettings.globalize_path(res_path)
+
+static func _read_text(path : String) -> String:
+ if !FileAccess.file_exists(path):
+ return ""
+ return FileAccess.get_file_as_string(path)
+
+static func _write_text(path : String, content : String) -> bool:
+ var file : FileAccess = FileAccess.open(path, FileAccess.WRITE)
+ if file == null:
+ return false
+ file.store_string(content)
+ file.close()
+ return true
+
+static func _gitignore_has_entry(content : String) -> bool:
+ for line in content.split("\n"):
+ var trimmed : String = line.strip_edges()
+ if trimmed.begins_with("#") or trimmed.is_empty():
+ continue
+ if trimmed == GITIGNORE_ENTRY or trimmed == "/"+GITIGNORE_ENTRY:
+ return true
+ return false
+
+static func _strip_keys_from_project_file() -> void:
+ var path : String = _os(PROJECT_FILE)
+ var text : String = _read_text(path)
+ if text.is_empty():
+ text = _read_text(PROJECT_FILE)
+ path = PROJECT_FILE
+ if text.is_empty():
+ return
+
+ var section : String = ""
+ var kept : PackedStringArray = PackedStringArray()
+ var removed : bool = false
+ for line in text.split("\n"):
+ var trimmed : String = line.strip_edges()
+ if trimmed.begins_with("[") and trimmed.ends_with("]"):
+ section = trimmed.substr(1, trimmed.length() - 2)
+ kept.append(line)
+ continue
+ if section == "GD-Sync" and (trimmed.begins_with("publicKey=") or trimmed.begins_with("privateKey=")):
+ removed = true
+ continue
+ kept.append(line)
+
+ if removed:
+ _write_text(path, "\n".join(kept))
diff --git a/addons/GD-Sync/Scripts/KeyStore.gd.uid b/addons/GD-Sync/Scripts/KeyStore.gd.uid
new file mode 100644
index 0000000..a81b6cb
--- /dev/null
+++ b/addons/GD-Sync/Scripts/KeyStore.gd.uid
@@ -0,0 +1 @@
+uid://cj8mturlqjcfd
diff --git a/addons/GD-Sync/Scripts/LocalServer.gd b/addons/GD-Sync/Scripts/LocalServer.gd
new file mode 100644
index 0000000..5969169
--- /dev/null
+++ b/addons/GD-Sync/Scripts/LocalServer.gd
@@ -0,0 +1,729 @@
+extends Node
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+var min_port_range : int = 42354
+var max_port_range : int = min_port_range + 20
+var min_game_port : int = 42400
+var max_game_port : int = min_game_port + 20
+
+var GDSync
+var connection_controller
+var request_processor
+var session_controller
+var logger
+
+var local_lobby_name : String = ""
+var local_lobby_password : String = ""
+var local_lobby_public : bool = false
+var local_lobby_open : bool = true
+var local_lobby_player_limit : int = 0
+var local_lobby_port : int = -1
+
+var local_lobby_data : Dictionary = {}
+var local_lobby_tags : Dictionary = {}
+var local_owner_cache : Dictionary = {}
+
+const _UNRELIABLE_WIRE_LIMIT : int = 1200
+
+var local_server : ENetMultiplayerPeer = ENetMultiplayerPeer.new()
+var local_peer : PacketPeerUDP = PacketPeerUDP.new()
+var local_lobby_timer : Timer = Timer.new()
+
+var found_lobbies : Dictionary = {}
+
+var peer_client_table : Dictionary = {}
+var lobby_client_table : Dictionary = {}
+var _lobby_host_id : int = -1
+var _creating_local_lobby : bool = false
+
+class Client extends RefCounted:
+ var valid : bool = false
+ var client_id : int = -1
+ var peer_id : int = -1
+ var peer : ENetPacketPeer
+ var username : String
+ var player_data : Dictionary = {}
+
+ var requests_RUDP : Array = []
+ var requests_UDP : Array = []
+ var lobby_targets : Array = []
+
+ func construct_lobby_targets(clients : Dictionary) -> void:
+ lobby_targets = clients.values()
+ lobby_targets.erase(self)
+
+ func collect_player_data() -> Dictionary:
+ var data : Dictionary = player_data.duplicate()
+ data["ID"] = client_id
+ data["Username"] = username
+ return data
+
+func _ready() -> void:
+ GDSync = get_node("/root/GDSync")
+ name = "LocalServer"
+ connection_controller = GDSync._connection_controller
+ request_processor = GDSync._request_processor
+ session_controller = GDSync._session_controller
+ logger = GDSync._logger
+
+ _bind_local_server_signals()
+
+ local_lobby_timer.wait_time = 0.5
+ local_lobby_timer.timeout.connect(perform_local_scan)
+ add_child(local_lobby_timer)
+
+ set_process(false)
+
+func reset_multiplayer() -> void:
+ logger.write_log("Closing local multiplayer.", "[LocalServer]")
+ local_peer.close()
+ local_lobby_timer.stop()
+ set_process(false)
+
+ found_lobbies.clear()
+
+ clear_lobby_data()
+
+func clear_lobby_data() -> void:
+ logger.write_log("Clear lobby data.", "[LocalServer]")
+ _clear_lobby_state()
+ local_server.close()
+
+func _clear_lobby_state() -> void:
+ local_lobby_name = ""
+ local_lobby_password = ""
+ local_lobby_public = false
+ local_lobby_open = true
+ local_lobby_player_limit = 0
+ local_lobby_port = -1
+ local_lobby_data.clear()
+ local_lobby_tags.clear()
+ local_owner_cache.clear()
+ peer_client_table.clear()
+ lobby_client_table.clear()
+ _lobby_host_id = -1
+
+func _bind_local_server_signals() -> void:
+ if !local_server.peer_connected.is_connected(peer_connected):
+ local_server.peer_connected.connect(peer_connected)
+ if !local_server.peer_disconnected.is_connected(peer_disconnected):
+ local_server.peer_disconnected.connect(peer_disconnected)
+
+func _close_lobby_server() -> void:
+ logger.write_log("Closing local lobby server.", "[LocalServer]")
+ set_process(false)
+ if local_lobby_name != "":
+ found_lobbies.erase(local_lobby_name)
+ _clear_lobby_state()
+ local_server.close()
+ local_server = ENetMultiplayerPeer.new()
+ _bind_local_server_signals()
+
+func leave_local_lobby() -> void:
+ if local_lobby_name == "":
+ return
+ logger.write_log("Leaving hosted local lobby.", "[LocalServer]")
+ for client_id in lobby_client_table:
+ var other_client : Client = lobby_client_table[client_id]
+ if other_client.client_id != GDSync.get_client_id():
+ send_message(ENUMS.MESSAGE_TYPE.KICKED, other_client)
+ _flush_outgoing_requests()
+ _close_lobby_server()
+
+func start_local_peer() -> bool:
+ logger.write_log("Starting local peer.", "[LocalServer]")
+ for port in range(min_port_range, max_port_range):
+ var bind_error : int = local_peer.bind(port)
+ if bind_error == OK:
+ logger.write_log("Local peer binded to port. <"+str(port)+">", "[LocalServer]")
+ local_lobby_timer.start()
+ return true
+
+ logger.write_error("Local peer war unable to bind to a port.", "[LocalServer]")
+ return false
+
+func _bind_game_server() -> int:
+ for port in range(min_game_port, max_game_port):
+ local_server.close()
+ local_server = ENetMultiplayerPeer.new()
+ if local_server.create_server(port) == OK:
+ _bind_local_server_signals()
+ logger.write_log("Local lobby server binded to port. <"+str(port)+">", "[LocalServer]")
+ return port
+ _bind_local_server_signals()
+ return -1
+
+func create_local_lobby(name : String, password : String = "", public : bool = true, player_limit : int = 0, tags : Dictionary = {}, data : Dictionary = {}) -> void:
+ logger.write_log("Creating local lobby.", "[LocalServer]")
+ var result : int = -1
+
+ if name.length() < 3: result = ENUMS.LOBBY_CREATION_ERROR.NAME_TOO_SHORT
+ elif name.length() > 32: result = ENUMS.LOBBY_CREATION_ERROR.NAME_TOO_LONG
+ elif password.length() > 16: result = ENUMS.LOBBY_CREATION_ERROR.PASSWORD_TOO_LONG
+ elif var_to_bytes(tags).size() > 2048: result = ENUMS.LOBBY_CREATION_ERROR.TAGS_TOO_LARGE
+ elif var_to_bytes(data).size() > 2048: result = ENUMS.LOBBY_CREATION_ERROR.DATA_TOO_LARGE
+
+ if result != -1:
+ GDSync.lobby_creation_failed.emit.call_deferred(name, result)
+ return
+ if _creating_local_lobby or local_lobby_name != "":
+ GDSync.lobby_creation_failed.emit.call_deferred(name, ENUMS.LOBBY_CREATION_ERROR.LOBBY_ALREADY_EXISTS)
+ return
+
+ _creating_local_lobby = true
+ _ingest_local_broadcasts()
+ if !_network_name_taken(name):
+ await get_tree().create_timer(0.6).timeout
+ _ingest_local_broadcasts()
+ _creating_local_lobby = false
+ if _network_name_taken(name) or local_lobby_name != "":
+ GDSync.lobby_creation_failed.emit.call_deferred(name, ENUMS.LOBBY_CREATION_ERROR.LOBBY_ALREADY_EXISTS)
+ return
+
+ local_peer.set_broadcast_enabled(true)
+
+ var bound_port : int = _bind_game_server()
+ if bound_port < 0:
+ GDSync.lobby_creation_failed.emit.call_deferred(name, ENUMS.LOBBY_CREATION_ERROR.LOCAL_PORT_ERROR)
+ return
+
+ local_lobby_name = name
+ local_lobby_password = password
+ local_lobby_public = public
+ local_lobby_player_limit = player_limit
+ local_lobby_port = bound_port
+ local_lobby_tags = tags
+ local_lobby_data = data
+
+ var lobby_dict : Dictionary = get_lobby_dictionary()
+ lobby_dict["IP"] = "127.0.0.1"
+ lobby_dict["DetectionTime"] = Time.get_unix_time_from_system()
+ found_lobbies[local_lobby_name] = lobby_dict
+
+ _lobby_host_id = GDSync.get_client_id()
+ connection_controller.set_host(_lobby_host_id)
+ session_controller.lobby_created()
+
+ set_process(true)
+ GDSync.lobby_created.emit.call_deferred(name)
+
+func join_lobby(name : String, password : String) -> void:
+ logger.write_log("Joining local lobby. <"+name+">", "[LocalServer]")
+
+ var tries : int = 0
+ while !found_lobbies.has(name) and tries < 5:
+ logger.write_error("Local lobby not found. <"+name+">", "[LocalServer]")
+ tries += 1
+ await get_tree().create_timer(1.0).timeout
+
+ if found_lobbies.has(name):
+ var lobby_data : Dictionary = found_lobbies[name]
+ var lobby_port : int = lobby_data.get("Port", min_game_port)
+ var connect_err : int = connection_controller.connect_to_local_server(lobby_data["IP"], lobby_port)
+
+ if connect_err == OK:
+ logger.write_log("Connected to local lobby host.", "[LocalServer]")
+ request_processor.send_client_id()
+ session_controller.broadcast_player_data()
+ request_processor.create_join_lobby_request(name, password)
+ return
+ else:
+ logger.write_error("Unable to connect to discovered lobby. <"+str(lobby_data["IP"])+">", "[LocalServer]")
+
+ GDSync.lobby_join_failed.emit.call_deferred(name, ENUMS.LOBBY_JOIN_ERROR.LOBBY_DOES_NOT_EXIST)
+
+func get_public_lobbies() -> void:
+ var lobbies : Array = []
+ for lobby_data in found_lobbies.values():
+ if lobby_data["Public"]:
+ lobbies.append(lobby_data)
+
+ GDSync.lobbies_received.emit.call_deferred(lobbies)
+
+func get_public_lobby(lobby_name : String) -> void:
+ for lobby_data in found_lobbies.values():
+ if lobby_data["Public"] and lobby_data["Name"] == lobby_name:
+ GDSync.lobby_received.emit.call_deferred(lobby_data)
+ return
+
+ GDSync.lobby_received.emit.call_deferred({})
+
+func _network_name_taken(lobby_name : String) -> bool:
+ if lobby_name == local_lobby_name or !found_lobbies.has(lobby_name):
+ return false
+ var lobby_data : Dictionary = found_lobbies[lobby_name]
+ if !lobby_data.has("DetectionTime"):
+ return true
+ return Time.get_unix_time_from_system() - float(lobby_data["DetectionTime"]) <= 2.0
+
+func _is_local_address(ip : String) -> bool:
+ if ip == "127.0.0.1" or ip == "::1":
+ return true
+ return IP.get_local_addresses().has(ip)
+
+func _ingest_local_broadcasts() -> void:
+ while local_peer.get_available_packet_count() > 0:
+ var server_ip : String = local_peer.get_packet_ip()
+ var port : int = local_peer.get_packet_port()
+ var bytes : PackedByteArray = local_peer.get_packet()
+
+ if server_ip == '' or port <= 0:
+ continue
+ var parsed = bytes_to_var(bytes)
+ if typeof(parsed) != TYPE_DICTIONARY or !parsed.has("Name"):
+ continue
+ var lobby_data : Dictionary = parsed
+ var heard_name : String = str(lobby_data["Name"])
+ if local_lobby_name != "" and heard_name == local_lobby_name:
+ if _is_local_address(server_ip) and int(lobby_data.get("Port", -1)) == local_lobby_port:
+ if found_lobbies.has(heard_name):
+ found_lobbies[heard_name]["DetectionTime"] = Time.get_unix_time_from_system()
+ continue
+ if !found_lobbies.has(heard_name):
+ logger.write_log("Discovered local lobby. <"+server_ip+"><"+heard_name+">", "[LocalServer]")
+ lobby_data["IP"] = server_ip
+ lobby_data["DetectionTime"] = Time.get_unix_time_from_system()
+ found_lobbies[heard_name] = lobby_data
+
+func perform_local_scan() -> void:
+ local_lobby_timer.start()
+ _ingest_local_broadcasts()
+
+ var expired : Array = []
+ for lobby_name in found_lobbies:
+ var lobby_data : Dictionary = found_lobbies[lobby_name]
+ if !lobby_data.has("DetectionTime"): continue
+ if Time.get_unix_time_from_system() - lobby_data["DetectionTime"] > 2.0:
+ expired.append(lobby_name)
+ for lobby_name in expired:
+ found_lobbies.erase(lobby_name)
+ logger.write_log("Local lobby lost. <"+lobby_name+">", "[LocalServer]")
+
+ if local_lobby_name != "":
+ if found_lobbies.has(local_lobby_name):
+ var lobby_dict : Dictionary = get_lobby_dictionary()
+ lobby_dict["IP"] = found_lobbies[local_lobby_name].get("IP", "127.0.0.1")
+ lobby_dict["DetectionTime"] = Time.get_unix_time_from_system()
+ found_lobbies[local_lobby_name] = lobby_dict
+ for port in range(min_port_range, max_port_range):
+ var bind_error : int = local_peer.set_dest_address("255.255.255.255", port)
+ if bind_error == OK:
+ local_peer.put_packet(var_to_bytes(get_lobby_dictionary()))
+
+func is_local_server() -> bool:
+ return local_lobby_name != ""
+
+func peer_connected(id : int) -> void:
+ logger.write_log("Peer connected.", "[LocalServer]")
+ var client : Client = Client.new()
+ client.peer = local_server.get_peer(id)
+ client.peer_id = id
+ if client.peer != null:
+ client.peer.throttle_configure(5000, 2, 0)
+ peer_client_table[id] = client
+
+func peer_disconnected(id : int) -> void:
+ logger.write_log("Peer disconnected.", "[LocalServer]")
+ if peer_client_table.has(id):
+ var client : Client = peer_client_table[id]
+ leave_lobby_request(client)
+
+func _take_unreliable_batch(requests : Array) -> Array:
+ var fit : int = 1
+ var lo : int = 1
+ var hi : int = requests.size()
+ while lo <= hi:
+ var mid : int = (lo + hi) >> 1
+ if var_to_bytes(requests.slice(0, mid)).size() <= _UNRELIABLE_WIRE_LIMIT:
+ fit = mid
+ lo = mid + 1
+ else:
+ hi = mid - 1
+ var batch : Array = []
+ for i in fit:
+ batch.append(requests[i])
+ for i in fit:
+ requests.pop_front()
+ return batch
+
+func _flush_outgoing_requests() -> void:
+ if local_server.get_connection_status() != MultiplayerPeer.CONNECTION_CONNECTED:
+ return
+ for peer in peer_client_table:
+ var client : Client = peer_client_table[peer]
+ if client.requests_RUDP.size() > 0:
+ local_server.transfer_mode = MultiplayerPeer.TRANSFER_MODE_RELIABLE
+ local_server.set_target_peer(client.peer_id)
+ local_server.put_packet(var_to_bytes(client.requests_RUDP))
+ client.requests_RUDP.clear()
+ if client.requests_UDP.size() > 0:
+ local_server.transfer_mode = MultiplayerPeer.TRANSFER_MODE_UNRELIABLE_ORDERED
+ local_server.set_target_peer(client.peer_id)
+ var unreliable_packets : int = 8
+ while unreliable_packets > 0 and client.requests_UDP.size() > 0:
+ unreliable_packets -= 1
+ local_server.put_packet(var_to_bytes(_take_unreliable_batch(client.requests_UDP)))
+ local_server.poll()
+
+func _process(delta: float) -> void:
+ match(local_server.get_connection_status()):
+ MultiplayerPeer.CONNECTION_DISCONNECTED:
+ return
+ MultiplayerPeer.CONNECTION_CONNECTING:
+ local_server.poll()
+ MultiplayerPeer.CONNECTION_CONNECTED:
+ local_server.poll()
+ _flush_outgoing_requests()
+
+ while local_server.get_available_packet_count() > 0:
+ var channel : int = local_server.get_packet_channel()
+ var peer_id : int = local_server.get_packet_peer()
+ var bytes : PackedByteArray = local_server.get_packet()
+
+ if !peer_client_table.has(peer_id):
+ continue
+
+ var from : Client = peer_client_table[peer_id]
+ var message : Dictionary = bytes_to_var(bytes)
+
+ if message.has(ENUMS.PACKET_VALUE.SERVER_REQUESTS):
+ for request in message[ENUMS.PACKET_VALUE.SERVER_REQUESTS]:
+ var request_type : int = request[ENUMS.DATA.REQUEST_TYPE]
+ logger.write_log("Received server request. <"+str(from.client_id)+"><"+str(ENUMS.REQUEST_TYPE.keys()[request_type])+"><"+str(request)+">", "[LocalServer]")
+ match(request_type):
+ ENUMS.REQUEST_TYPE.SET_CLIENT_ID:
+ from.client_id = request[ENUMS.DATA.NAME]
+ ENUMS.REQUEST_TYPE.JOIN_LOBBY:
+ join_lobby_request(from, request)
+ ENUMS.REQUEST_TYPE.LEAVE_LOBBY:
+ leave_lobby_request(from)
+ ENUMS.REQUEST_TYPE.OPEN_LOBBY:
+ open_lobby_request(from, request)
+ ENUMS.REQUEST_TYPE.CLOSE_LOBBY:
+ close_lobby_request(from, request)
+ ENUMS.REQUEST_TYPE.SET_GDSYNC_OWNER:
+ set_owner_request(from, request)
+ ENUMS.REQUEST_TYPE.SET_LOBBY_TAG:
+ set_lobby_tag_request(from, request)
+ ENUMS.REQUEST_TYPE.ERASE_LOBBY_TAG:
+ erase_lobby_tag_request(from, request)
+ ENUMS.REQUEST_TYPE.SET_LOBBY_DATA:
+ set_lobby_data_request(from, request)
+ ENUMS.REQUEST_TYPE.ERASE_LOBBY_DATA:
+ erase_lobby_data_request(from, request)
+ ENUMS.REQUEST_TYPE.SET_LOBBY_VISIBILITY:
+ set_lobby_visibility_request(from, request)
+ ENUMS.REQUEST_TYPE.SET_PLAYER_USERNAME:
+ set_player_username_request(from, request)
+ ENUMS.REQUEST_TYPE.SET_PLAYER_DATA:
+ set_player_data_request(from, request)
+ ENUMS.REQUEST_TYPE.ERASE_PLAYER_DATA:
+ erase_player_data_request(from, request)
+ ENUMS.REQUEST_TYPE.KICK_PLAYER:
+ kick_player(from, request)
+ ENUMS.REQUEST_TYPE.CHANGE_PASSWORD:
+ change_password(from, request)
+ ENUMS.REQUEST_TYPE.CHANGE_LOBBY_NAME:
+ change_lobby_name(from, request)
+
+ if message.has(ENUMS.PACKET_VALUE.CLIENT_REQUESTS):
+ for request in message[ENUMS.PACKET_VALUE.CLIENT_REQUESTS]:
+ broadcast_request(request, from, channel == 0)
+
+const _TARGET_CLIENT_ID_MASK : int = 0x3FFFFFFF
+const _TARGET_PERMISSION_SHIFT : int = 30
+
+func _decode_target_client(encoded : int) -> int:
+ var id_part : int = encoded & _TARGET_CLIENT_ID_MASK
+ return -1 if id_part == _TARGET_CLIENT_ID_MASK else id_part
+
+func broadcast_request(request : Array, from : Client, reliable : bool) -> void:
+ if !from.valid: return
+
+ request = request_processor.stamp_caller_id(request, from.client_id)
+ var peers : Array = get_target_peers(request, from)
+ for client in peers:
+ put_request(request, client, reliable)
+
+func get_target_peers(request : Array, from : Client) -> Array:
+ var targets : Array = []
+ if from.valid:
+ var encoded_target : int = int(request[int(ENUMS.DATA.TARGET_CLIENT)])
+ var target_client : int = _decode_target_client(encoded_target)
+ if target_client >= 0:
+ if lobby_client_table.has(target_client):
+ targets.append(lobby_client_table[target_client])
+ else:
+ return from.lobby_targets
+ return targets
+
+func send_message(message : int, client : Client, value = null, value2 = null, value3 = null) -> void:
+ if client == null:
+ return
+ if value3 != null:
+ put_request([
+ int(ENUMS.REQUEST_TYPE.MESSAGE),
+ message,
+ value,
+ value2,
+ value3
+ ], client, true)
+ elif value2 != null:
+ put_request([
+ int(ENUMS.REQUEST_TYPE.MESSAGE),
+ message,
+ value,
+ value2
+ ], client, true)
+ elif value != null:
+ put_request([
+ int(ENUMS.REQUEST_TYPE.MESSAGE),
+ message,
+ value
+ ], client, true)
+ else:
+ put_request([
+ int(ENUMS.REQUEST_TYPE.MESSAGE),
+ message
+ ], client, true)
+
+func put_request(request : Array, client : Client, reliable : bool) -> void:
+ if reliable:
+ client.requests_RUDP.append(request)
+ else:
+ client.requests_UDP.append(request)
+
+func join_lobby_request(from : Client, request : Array) -> void:
+ if local_lobby_name == "": return
+
+ if !local_lobby_open:
+ send_message(ENUMS.MESSAGE_TYPE.LOBBY_JOIN_FAILED, from, local_lobby_name, ENUMS.LOBBY_JOIN_ERROR.LOBBY_IS_CLOSED)
+ return
+ if local_lobby_player_limit > 0 and lobby_client_table.size() >= local_lobby_player_limit:
+ send_message(ENUMS.MESSAGE_TYPE.LOBBY_JOIN_FAILED, from, local_lobby_name, ENUMS.LOBBY_JOIN_ERROR.LOBBY_IS_FULL)
+ return
+
+ var password : String = request[ENUMS.LOBBY_DATA.PASSWORD]
+ if local_lobby_password != "" and password != local_lobby_password:
+ send_message(ENUMS.MESSAGE_TYPE.LOBBY_JOIN_FAILED, from, local_lobby_name, ENUMS.LOBBY_JOIN_ERROR.INCORRECT_PASSWORD)
+ return
+
+ if connection_controller.UNIQUE_USERNAMES:
+ for client in lobby_client_table.values():
+ if client.username == from.username:
+ send_message(ENUMS.MESSAGE_TYPE.LOBBY_JOIN_FAILED, from, local_lobby_name, ENUMS.LOBBY_JOIN_ERROR.DUPLICATE_USERNAME)
+ return
+
+ from.valid = true
+ lobby_client_table[from.client_id] = from
+
+ send_message(ENUMS.MESSAGE_TYPE.LOBBY_JOINED, from, local_lobby_name)
+ send_message(ENUMS.MESSAGE_TYPE.HOST_CHANGED, from, GDSync.get_client_id())
+ send_message(ENUMS.MESSAGE_TYPE.LOBBY_DATA_RECEIVED, from, get_lobby_dictionary(true))
+
+ for client_id in lobby_client_table:
+ var client : Client = lobby_client_table[client_id]
+ client.construct_lobby_targets(lobby_client_table)
+
+ if client != from:
+ send_message(ENUMS.MESSAGE_TYPE.PLAYER_DATA_RECEIVED, client, from.collect_player_data())
+ send_message(ENUMS.MESSAGE_TYPE.PLAYER_DATA_RECEIVED, from, client.collect_player_data())
+ send_message(ENUMS.MESSAGE_TYPE.CLIENT_JOINED, client, from.client_id)
+
+ send_message(ENUMS.MESSAGE_TYPE.CLIENT_JOINED, from, client.client_id)
+
+ for node_path in local_owner_cache:
+ send_message(ENUMS.MESSAGE_TYPE.SET_GDSYNC_OWNER, from, node_path, local_owner_cache[node_path])
+
+func leave_lobby_request(from : Client) -> void:
+ logger.write_log(" <"+str(from.client_id)+">", "[LocalServer]")
+ if lobby_client_table.has(from.client_id):
+ lobby_client_table.erase(from.client_id)
+
+ if from.client_id != GDSync.get_client_id():
+ for client_id in lobby_client_table:
+ var other_client : Client = lobby_client_table[client_id]
+ other_client.construct_lobby_targets(lobby_client_table)
+
+ if other_client != from:
+ send_message(ENUMS.MESSAGE_TYPE.CLIENT_LEFT, other_client, from.client_id)
+ else:
+ for client_id in lobby_client_table:
+ var other_client : Client = lobby_client_table[client_id]
+ if other_client != from:
+ send_message(ENUMS.MESSAGE_TYPE.KICKED, other_client)
+ _flush_outgoing_requests()
+ _close_lobby_server()
+ return
+
+ if peer_client_table.has(from.peer_id):
+ peer_client_table.erase(from.peer_id)
+
+ if local_server.get_peer(from.peer_id) != null:
+ local_server.disconnect_peer(from.peer_id)
+
+func open_lobby_request(from : Client, request : Array) -> void:
+ if !from.valid: return
+ local_lobby_open = true
+
+func close_lobby_request(from : Client, request : Array) -> void:
+ if !from.valid: return
+ local_lobby_open = false
+
+func set_owner_request(from : Client, request : Array) -> void:
+ if !from.valid: return
+
+ var node_path = request[ENUMS.DATA.NAME]
+ var owner = request[ENUMS.DATA.VALUE]
+ if owner == null or owner == -1:
+ if local_owner_cache.has(node_path):
+ local_owner_cache.erase(node_path)
+ else:
+ local_owner_cache[node_path] = owner
+
+ for client_id in lobby_client_table:
+ send_message(ENUMS.MESSAGE_TYPE.SET_GDSYNC_OWNER, lobby_client_table[client_id], node_path, owner)
+
+func set_lobby_tag_request(from : Client, request : Array) -> void:
+ var key = request[ENUMS.LOBBY_DATA.NAME]
+ var value = request[ENUMS.LOBBY_DATA.VALUE]
+
+ local_lobby_tags[key] = value
+
+ for client in lobby_client_table.values():
+ send_message(ENUMS.MESSAGE_TYPE.LOBBY_DATA_RECEIVED, client, get_lobby_dictionary(true))
+ send_message(ENUMS.MESSAGE_TYPE.LOBBY_TAGS_CHANGED, client, key)
+
+func erase_lobby_tag_request(from : Client, request : Array) -> void:
+ var key = request[ENUMS.LOBBY_DATA.NAME]
+
+ if local_lobby_tags.has(key):
+ local_lobby_tags.erase(key)
+ for client in lobby_client_table.values():
+ send_message(ENUMS.MESSAGE_TYPE.LOBBY_DATA_RECEIVED, client, get_lobby_dictionary(true))
+ send_message(ENUMS.MESSAGE_TYPE.LOBBY_TAGS_CHANGED, client, key)
+
+func set_lobby_data_request(from : Client, request : Array) -> void:
+ var key = request[ENUMS.LOBBY_DATA.NAME]
+ var value = request[ENUMS.LOBBY_DATA.VALUE]
+
+ local_lobby_data[key] = value
+
+ for client in lobby_client_table.values():
+ send_message(ENUMS.MESSAGE_TYPE.LOBBY_DATA_RECEIVED, client, get_lobby_dictionary(true))
+ send_message(ENUMS.MESSAGE_TYPE.LOBBY_DATA_CHANGED, client, key)
+
+func erase_lobby_data_request(from : Client, request : Array) -> void:
+ var key = request[ENUMS.LOBBY_DATA.NAME]
+
+ if local_lobby_data.has(key):
+ local_lobby_data.erase(key)
+ for client in lobby_client_table.values():
+ send_message(ENUMS.MESSAGE_TYPE.LOBBY_DATA_RECEIVED, client, get_lobby_dictionary(true))
+ send_message(ENUMS.MESSAGE_TYPE.LOBBY_DATA_CHANGED, client, key)
+
+func set_lobby_visibility_request(from : Client, request : Array) -> void:
+ local_lobby_public = request[ENUMS.LOBBY_DATA.VISIBILITY]
+
+func set_player_username_request(from : Client, request : Array) -> void:
+ from.username = request[ENUMS.DATA.NAME]
+
+ for client in from.lobby_targets:
+ send_message(ENUMS.MESSAGE_TYPE.PLAYER_DATA_RECEIVED, client, from.collect_player_data())
+ send_message(ENUMS.MESSAGE_TYPE.PLAYER_DATA_CHANGED, client, from.client_id, "Username")
+
+func set_player_data_request(from : Client, request : Array) -> void:
+ var key = request[ENUMS.DATA.NAME]
+ from.player_data[key] = request[ENUMS.DATA.VALUE]
+
+ for client in from.lobby_targets:
+ send_message(ENUMS.MESSAGE_TYPE.PLAYER_DATA_RECEIVED, client, from.collect_player_data())
+ send_message(ENUMS.MESSAGE_TYPE.PLAYER_DATA_CHANGED, client, from.client_id, key)
+
+func erase_player_data_request(from : Client, request : Array) -> void:
+ var key = request[ENUMS.DATA.NAME]
+
+ if from.player_data.has(key):
+ from.player_data.erase(key)
+
+ for client in from.lobby_targets:
+ send_message(ENUMS.MESSAGE_TYPE.PLAYER_DATA_RECEIVED, client, from.collect_player_data())
+ send_message(ENUMS.MESSAGE_TYPE.PLAYER_DATA_CHANGED, client, from.client_id, key)
+
+func kick_player(from : Client, request : Array) -> void:
+ var client_id : int = request[ENUMS.DATA.NAME]
+ var reason : String = ""
+ if request.size() >= 3:
+ reason = str(request[ENUMS.DATA.VALUE])
+
+ if(from.client_id != GDSync.get_client_id()): return
+
+ var kicked_client : Client = lobby_client_table.get(client_id, null)
+ if kicked_client == null: return
+
+ lobby_client_table.erase(client_id)
+ if reason.is_empty():
+ send_message(ENUMS.MESSAGE_TYPE.KICKED, kicked_client)
+ else:
+ send_message(ENUMS.MESSAGE_TYPE.KICKED, kicked_client, reason)
+ await get_tree().process_frame
+ await get_tree().process_frame
+ kicked_client.peer.peer_disconnect()
+
+func change_password(from : Client, request : Array) -> void:
+ if(from.client_id != GDSync.get_client_id()): return
+ var password : String = request[ENUMS.DATA.NAME]
+ local_lobby_password = password
+
+func change_lobby_name(from : Client, request : Array) -> void:
+ if(from.client_id != GDSync.get_client_id()): return
+ var name : String = request[ENUMS.DATA.NAME]
+ local_lobby_name = name
+
+func _get_lobby_player_count() -> int:
+ var count : int = lobby_client_table.size()
+ var host_id : int = GDSync.get_client_id()
+ if host_id >= 0 and !lobby_client_table.has(host_id):
+ count += 1
+ return count
+
+func get_lobby_dictionary(with_data : bool = false) -> Dictionary:
+ var dict : Dictionary = {
+ "Name" : local_lobby_name,
+ "PlayerCount" : _get_lobby_player_count(),
+ "PlayerLimit" : local_lobby_player_limit,
+ "Public" : local_lobby_public,
+ "Open" : local_lobby_open,
+ "Tags" : local_lobby_tags,
+ "HasPassword" : local_lobby_password != "",
+ "Host" : GDSync.player_get_data(GDSync.get_client_id(), "Username", ""),
+ "Port" : local_lobby_port
+ }
+
+ if with_data:
+ dict["Data"] = local_lobby_data
+
+ return dict
diff --git a/addons/GD-Sync/Scripts/LocalServer.gd.uid b/addons/GD-Sync/Scripts/LocalServer.gd.uid
new file mode 100644
index 0000000..8e8f18d
--- /dev/null
+++ b/addons/GD-Sync/Scripts/LocalServer.gd.uid
@@ -0,0 +1 @@
+uid://ceovwtxh0ol4y
diff --git a/addons/GD-Sync/Scripts/Logger.gd b/addons/GD-Sync/Scripts/Logger.gd
new file mode 100644
index 0000000..13f6e88
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Logger.gd
@@ -0,0 +1,208 @@
+extends Node
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+const LOG_PATH : String = "user://GD-Sync/Logs"
+var GDSync
+
+var logging_enabled : bool = true
+var session_id : String
+
+var redacted_values : PackedStringArray = PackedStringArray()
+
+var logs : PackedStringArray
+
+var original_log_times : Dictionary = {}
+var recent_log_times : Dictionary = {}
+var recent_log_counts : Dictionary = {}
+
+var log_timer : float = 0.0
+var new_logs : bool = false
+
+var use_profiler : bool = false
+var monitor_connections : bool = false
+var connection_timer : float = 0.0
+var profiler_data : Dictionary = {}
+var profiler_message_queue : Array = []
+var debugger_singleton
+
+func _ready() -> void:
+ name = "Logger"
+ GDSync = get_node("/root/GDSync")
+
+ logging_enabled = OS.is_debug_build()
+ set_process(logging_enabled)
+
+ if OS.has_feature("editor") and EngineDebugger.is_active(): # Harvest Season patch: only with a debugger attached
+ debugger_singleton = Engine.get_singleton("EngineDebugger")
+ debugger_singleton.register_message_capture("gdsyncprofiler", _capture)
+ debugger_singleton.send_message("gdsyncprofiler:gamestart", [])
+
+ GDSync.client_joined.connect(func(client_id : int):
+ register_profiler_message("clientjoined", [client_id]))
+ GDSync.client_left.connect(func(client_id : int):
+ register_profiler_message("clientleft", [client_id]))
+
+ if !logging_enabled: return
+ var time : float = Time.get_unix_time_from_system()
+ session_id = str(ceili(time)/86400)+str(ceili(time*1000.0)%86400000)
+
+ if !DirAccess.dir_exists_absolute(LOG_PATH):
+ DirAccess.make_dir_absolute(LOG_PATH)
+
+ var files : PackedStringArray = DirAccess.get_files_at(LOG_PATH)
+ if files.size() > 4:
+ var file_times : Dictionary = {}
+ for file in files:
+ file_times[FileAccess.get_modified_time(LOG_PATH+"/"+file)] = file
+
+ var keys : Array = file_times.keys()
+ keys.sort()
+ for i in range(files.size()-4):
+ var log_time : int = keys[i]
+ DirAccess.remove_absolute(LOG_PATH+"/"+file_times[log_time])
+
+func _process(delta: float) -> void:
+ log_timer -= delta
+ _process_logs()
+ _write_logs()
+ _monitor_connections(delta)
+
+func _monitor_connections(delta : float) -> void:
+ if !monitor_connections:
+ return
+
+ connection_timer -= delta
+ if connection_timer <= 0.0:
+ connection_timer += 1.0
+
+ for client_id in GDSync.lobby_get_all_clients():
+ _monitor_connection(client_id)
+
+func _monitor_connection(client_id : int) -> void:
+ if GDSync.get_client_id() == client_id: return
+
+ var ping : float = await GDSync.get_client_ping(client_id)
+ var perceived_ping : float = await GDSync.get_client_perceived_ping(client_id)
+ register_profiler_message("pingmeasured", [client_id, ping, perceived_ping])
+
+func _process_logs() -> void:
+ var current_time : float = Time.get_unix_time_from_system()
+ for log in recent_log_times:
+ var time : float = recent_log_times[log]
+ var count : int = recent_log_counts[log]
+ if current_time - time > 1.0 or count >= 100:
+
+ var original_time : float = original_log_times[log]
+ original_log_times.erase(log)
+ recent_log_times.erase(log)
+ recent_log_counts.erase(log)
+
+ var print_time : String = str(snappedf(fmod(original_time, 1000.0), 0.01)).pad_decimals(2)
+
+ new_logs = true
+ if count == 1:
+ logs.append("["+print_time+"]"+log+"\n")
+ else:
+ logs.append("["+print_time+"][x"+str(count)+"]"+log+"\n")
+
+func _write_logs() -> void:
+ if log_timer > 0.0: return
+ log_timer = 1.0
+ if !new_logs: return
+ new_logs = false
+
+ var log_path : String = LOG_PATH+"/GDLog"+session_id+".txt"
+ var file := FileAccess.open(log_path, FileAccess.READ_WRITE)
+ if file == null:
+ file = FileAccess.open(log_path, FileAccess.WRITE)
+ if file == null:
+ return
+
+ file.seek_end()
+ for log in logs:
+ file.store_string(log)
+ logs.clear()
+ file.close()
+
+func register_redacted_value(value : String) -> void:
+ if redacted_values.has(value): return
+ redacted_values.append(value)
+
+func redact(log : String) -> String:
+ for value in redacted_values:
+ log = log.replace(value, "[REDACTED]")
+ return log
+
+func write_log(log : String, prefix : String = "") -> void:
+ if !logging_enabled: return
+
+ log = redact(prefix+" "+log)
+
+ if !original_log_times.has(log): original_log_times[log] = Time.get_unix_time_from_system()
+ recent_log_times[log] = Time.get_unix_time_from_system()
+ recent_log_counts[log] = recent_log_counts.get(log, 0)+1
+
+func write_error(error : String, prefix : String = "") -> void:
+ write_log(error, prefix+"[ERROR]")
+
+func _capture(message : String, data : Array) -> bool:
+ if message == "start":
+ use_profiler = true
+ debugger_singleton.send_message("gdsyncprofiler:setdata", [profiler_data])
+
+ for message_data in profiler_message_queue:
+ debugger_singleton.send_message("gdsyncprofiler:"+message_data[0], message_data[1])
+ profiler_message_queue.clear()
+ return true
+ if message == "stop":
+ use_profiler = false
+ return true
+ if message == "start_monitoring_connections":
+ monitor_connections = true
+ return true
+ if message == "stop_monitoring_connections":
+ monitor_connections = false
+ return true
+ if message == "set_artificial_latency":
+ if data.size() > 0:
+ GDSync.set_artificial_latency(int(data[0]))
+ return true
+ return false
+
+func register_profiler_data(key : String, value) -> void:
+ profiler_data[key] = value
+ if !use_profiler: return
+ debugger_singleton.send_message("gdsyncprofiler:setdata", [profiler_data])
+
+func register_profiler_message(message : String, values : Array) -> void:
+ if !use_profiler:
+ profiler_message_queue.append([message, values])
+ return
+ debugger_singleton.send_message("gdsyncprofiler:"+message, values)
+
+func register_transfer_usage(origin : Dictionary, byte_count : int, upload : bool, details : String) -> void:
+ if !use_profiler: return
+ debugger_singleton.send_message("gdsyncprofiler:registertransfer", [GDSync.get_client_id(), origin, byte_count, upload, details])
diff --git a/addons/GD-Sync/Scripts/Logger.gd.uid b/addons/GD-Sync/Scripts/Logger.gd.uid
new file mode 100644
index 0000000..651116c
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Logger.gd.uid
@@ -0,0 +1 @@
+uid://dlxrcaucmagh6
diff --git a/addons/GD-Sync/Scripts/MatchmakingController.gd b/addons/GD-Sync/Scripts/MatchmakingController.gd
new file mode 100644
index 0000000..920641f
--- /dev/null
+++ b/addons/GD-Sync/Scripts/MatchmakingController.gd
@@ -0,0 +1,156 @@
+extends Node
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+var GDSync
+
+var request_processor
+var connection_controller
+
+var active: bool = false
+var status: int = ENUMS.MATCHMAKING_STATUS.INACTIVE
+var details: Dictionary = {}
+var request_id: int = 0
+var cancellation_pending: bool = false
+
+
+func _ready() -> void:
+ name = "MatchmakingController"
+ request_processor = GDSync._request_processor
+ connection_controller = GDSync._connection_controller
+ GDSync.disconnected.connect(disconnected)
+
+
+func start(request: MatchmakingRequest) -> void:
+ if !connection_controller.valid_connection():
+ return
+ if connection_controller.is_local_check():
+ GDSync.matchmaking_failed.emit(ENUMS.MATCHMAKING_ERROR.UNSUPPORTED_LOCAL)
+ return
+ if GDSync.lobby_get_name() != "":
+ GDSync.matchmaking_failed.emit(ENUMS.MATCHMAKING_ERROR.ALREADY_IN_LOBBY)
+ return
+ if request == null or !request._is_valid():
+ GDSync.matchmaking_failed.emit(ENUMS.MATCHMAKING_ERROR.INVALID_REQUEST)
+ return
+ if active:
+ request_processor.create_cancel_matchmaking_request(request_id)
+ request_id += 1
+ cancellation_pending = false
+ active = true
+ status = ENUMS.MATCHMAKING_STATUS.INACTIVE
+ var parameters := request._to_dictionary()
+ parameters["RequestId"] = request_id
+ request_processor.create_start_matchmaking_request(parameters)
+
+
+func cancel() -> void:
+ if !connection_controller.valid_connection() or !active:
+ return
+ request_processor.create_cancel_matchmaking_request(request_id)
+ cancellation_pending = true
+ active = false
+ status = ENUMS.MATCHMAKING_STATUS.INACTIVE
+ details.clear()
+
+
+func is_active() -> bool:
+ return active
+
+
+func get_status() -> int:
+ return status
+
+
+func get_status_details() -> Dictionary:
+ return details.duplicate(true)
+
+
+func started(received_request_id: int) -> void:
+ if received_request_id != request_id or cancellation_pending:
+ return
+ active = true
+ GDSync.matchmaking_started.emit()
+
+
+func status_changed(received_request_id: int, new_status: int, new_details: Dictionary) -> void:
+ if received_request_id != request_id or cancellation_pending:
+ return
+ status = new_status
+ details = new_details.duplicate(true)
+ GDSync.matchmaking_status_changed.emit(status, details)
+
+
+func match_found(received_request_id: int, lobby_name: String) -> void:
+ if received_request_id != request_id or cancellation_pending or !active:
+ return
+ status = ENUMS.MATCHMAKING_STATUS.JOINING
+ GDSync.matchmaking_match_found.emit(lobby_name)
+ if received_request_id == request_id and active:
+ GDSync.lobby_join(lobby_name)
+
+
+func remote_match_found(received_request_id: int, lobby_name: String) -> void:
+ if received_request_id != request_id or cancellation_pending or !active:
+ return
+ status = ENUMS.MATCHMAKING_STATUS.JOINING
+ GDSync.matchmaking_match_found.emit(lobby_name)
+
+
+func failed(received_request_id: int, error: int) -> void:
+ if received_request_id != request_id:
+ return
+ cancellation_pending = false
+ reset()
+ GDSync.matchmaking_failed.emit(error)
+
+
+func cancelled(received_request_id: int) -> void:
+ if received_request_id != request_id:
+ return
+ cancellation_pending = false
+ reset()
+ GDSync.matchmaking_cancelled.emit()
+
+
+func lobby_joined() -> void:
+ cancellation_pending = false
+ reset()
+
+
+func lobby_join_failed() -> void:
+ if status == ENUMS.MATCHMAKING_STATUS.JOINING:
+ failed(request_id, ENUMS.MATCHMAKING_ERROR.JOIN_FAILED)
+
+
+func disconnected() -> void:
+ cancellation_pending = false
+ reset()
+
+
+func reset() -> void:
+ active = false
+ status = ENUMS.MATCHMAKING_STATUS.INACTIVE
+ details.clear()
diff --git a/addons/GD-Sync/Scripts/MatchmakingController.gd.uid b/addons/GD-Sync/Scripts/MatchmakingController.gd.uid
new file mode 100644
index 0000000..a107bb6
--- /dev/null
+++ b/addons/GD-Sync/Scripts/MatchmakingController.gd.uid
@@ -0,0 +1 @@
+uid://bdpl3n36a1bui
diff --git a/addons/GD-Sync/Scripts/NodeTracker.gd b/addons/GD-Sync/Scripts/NodeTracker.gd
new file mode 100644
index 0000000..af96ec4
--- /dev/null
+++ b/addons/GD-Sync/Scripts/NodeTracker.gd
@@ -0,0 +1,305 @@
+extends Node
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+var INSTANTIATOR_SCENE : GDScript = load("res://addons/GD-Sync/Scripts/Types/NodeInstantiator.gd")
+
+var GDSync
+var request_processor
+var logger
+
+var replication_cache : Dictionary = {}
+var replication_settings : Dictionary = {}
+var root_instantiator
+var instantiator_regex : RegEx
+
+var instantiator_lib : Dictionary = {}
+
+var lobby_i : int = 0
+
+func _ready() -> void:
+ name = "NodeTracker"
+ GDSync = get_node("/root/GDSync")
+ request_processor = GDSync._request_processor
+ logger = GDSync._logger
+
+ root_instantiator = INSTANTIATOR_SCENE.new()
+ root_instantiator.spawn_type = 1
+ root_instantiator.name = "RootInstantiator"
+ add_child(root_instantiator)
+
+ instantiator_regex = RegEx.new()
+ instantiator_regex.compile("[^a-z0-9]")
+
+ GDSync.expose_func(replicate_remote)
+ GDSync.expose_func(create_instantiator_remote)
+ GDSync.expose_func(multiplayer_queue_free_remote)
+ GDSync.client_joined.connect(client_joined)
+
+func lobby_left() -> void:
+ lobby_i += 1
+
+ for instantiator in instantiator_lib.values():
+ if is_instance_valid(instantiator):
+ instantiator.queue_free()
+
+ instantiator_lib.clear()
+ replication_cache.clear()
+ replication_settings.clear()
+
+func client_joined(client_id : int) -> void:
+ if client_id == GDSync.get_client_id(): return
+ if !GDSync.is_host(): return
+ create_instantiators(client_id)
+ broadcast_replication(client_id)
+
+func create_instantiators(client_id : int) -> void:
+ for settings_key in instantiator_lib:
+ var instantiator = instantiator_lib[settings_key]
+ GDSync.call_func_on(client_id, create_instantiator_remote,
+ instantiator.scene.resource_path,
+ str(instantiator.target.get_path()),
+ instantiator.sync_starting_changes,
+ instantiator.excluded_properties,
+ instantiator.replicate_on_join
+ )
+
+func broadcast_replication(client_id : int) -> void:
+ for instantiator_path in replication_cache:
+ var nodes_to_replicate : Array = replication_cache[instantiator_path].duplicate()
+
+ while nodes_to_replicate.size() > 0:
+ create_replication_requests(client_id, instantiator_path, nodes_to_replicate)
+
+func create_replication_requests(client_id : int, instantiator_path : String, nodes_to_replicate : Array) -> void:
+ var settings : Array = replication_settings[instantiator_path]
+
+ logger.write_log("Creating remote replication requests. <"+str(client_id)+"><"+str(instantiator_path)+"><"+str(settings)+">", "[NodeTracker]")
+
+ var sync_starting_changes : bool = settings[ENUMS.NODE_REPLICATION_SETTINGS.SYNC_STARTING_CHANGES]
+ var original_properties : Dictionary = settings[ENUMS.NODE_REPLICATION_SETTINGS.ORIGINAL_PROPERTIES]
+ var excluded_properties : PackedStringArray = settings[ENUMS.NODE_REPLICATION_SETTINGS.EXCLUDED_PROPERTIES]
+
+ var replication_data : Array = []
+
+ var replication_counter : int = 0
+ while nodes_to_replicate.size() > 0 and replication_counter < 32:
+ var node : Node = nodes_to_replicate.pop_front()
+ replication_counter += 1
+ if !is_instance_valid(node):
+ logger.write_error("Failed to create remote replication request, Node was invalid. <"+str(client_id)+"><"+str(instantiator_path)+">", "[NodeTracker]")
+ continue
+ if !node.is_inside_tree():
+ logger.write_error("Failed to create remote replication request, Node is not inside the tree. <"+str(client_id)+"><"+str(instantiator_path)+">", "[NodeTracker]")
+ continue
+
+ var id : int = node.get_meta("GDID")
+ var changed_properties : Dictionary = {}
+
+ if sync_starting_changes:
+ var starting_properties : Dictionary = original_properties
+ var new_properties : Dictionary = root_instantiator._get_properties_as_bytes(node)
+
+ for property_name in starting_properties:
+ if new_properties[property_name] != starting_properties[property_name]:
+ var new_value = bytes_to_var(new_properties[property_name])
+ var type : int = typeof(new_value)
+ match(type):
+ TYPE_OBJECT: continue
+ TYPE_CALLABLE: continue
+ TYPE_SIGNAL: continue
+ TYPE_RID: continue
+ if root_instantiator._PERMANENT_EXCLUDED_PROPERTIES.has(property_name): continue
+ if excluded_properties.has(property_name): continue
+ if root_instantiator._contains_object(new_value): continue
+ changed_properties[property_name] = new_value
+
+ replication_data.append([id, changed_properties])
+
+ GDSync.call_func_on(client_id, replicate_remote,
+ settings,
+ replication_data
+ )
+
+func replicate_remote(settings : Array, replication_data : Array) -> void:
+ var instantiator : Node = get_node_or_null(settings[ENUMS.NODE_REPLICATION_SETTINGS.INSTANTIATOR])
+ var target : Node = get_node_or_null(settings[ENUMS.NODE_REPLICATION_SETTINGS.TARGET])
+
+ var tries : int = 0
+ var current_lobby_i : int = lobby_i
+ while target == null:
+ tries += 1
+ await get_tree().create_timer(0.6).timeout
+ logger.write_error("Remote replication failed, target Node was not found. Trying again. <"+str(settings)+">", "[NodeTracker]")
+ target = get_node_or_null(settings[ENUMS.NODE_REPLICATION_SETTINGS.TARGET])
+
+ if tries >= 100:
+ logger.write_error("Remote replication failed, target Node was not found. <"+str(settings)+">", "[NodeTracker]")
+ return
+
+ if current_lobby_i != lobby_i:
+ return
+
+ if instantiator == null:
+ logger.write_log("Remote replication did not find the target Instantiator, falling back to the root Instantiator. <"+str(settings)+">", "[NodeTracker]")
+ var scene : PackedScene = load(settings[ENUMS.NODE_REPLICATION_SETTINGS.SCENE])
+ root_instantiator.scene = scene
+ root_instantiator.target = target
+ root_instantiator.replicate_settings = settings
+ instantiator = root_instantiator
+
+ logger.write_log("Replicating Nodes. <"+str(settings)+"><"+str(replication_data)+">", "[NodeTracker]")
+ for node_replication_data in replication_data:
+ instantiator._instantiate_remote(
+ node_replication_data[ENUMS.NODE_REPLICATION_DATA.ID],
+ node_replication_data[ENUMS.NODE_REPLICATION_DATA.CHANGED_PROPERTIES]
+ )
+
+func register_replication(node : Node, instantiator_path : String, settings : Array) -> void:
+ if !replication_cache.has(instantiator_path):
+ replication_cache[instantiator_path] = []
+ replication_settings[instantiator_path] = settings
+
+ replication_cache[instantiator_path].append(node)
+
+func deregister_replication(node : Node) -> void:
+ var instantiator_path : String = node.get_meta("Instantiator")
+ if replication_cache.has(instantiator_path):
+ replication_cache[instantiator_path].erase(node)
+
+func multiplayer_instantiate(
+ scene : PackedScene,
+ parent : Node,
+ sync_starting_changes : bool,
+ excluded_properties : PackedStringArray,
+ replicate_on_join : bool) -> Node:
+
+ if parent == null:
+ parent = get_tree().current_scene
+
+ var settings_key : StringName = StringName(
+ str(scene.resource_path, sync_starting_changes, excluded_properties, replicate_on_join
+ ))
+
+ logger.write_log("Multiplayer Instantiate. <"+settings_key+">", "[NodeTracker]")
+
+ var instantiator : Node
+ if !instantiator_lib.has(settings_key):
+ logger.write_log("Creating Instantiator.", "[NodeTracker]")
+ instantiator = INSTANTIATOR_SCENE.new()
+ instantiator.name = instantiator_regex.sub(scene.resource_path.to_lower(), "", true)
+ instantiator.spawn_type = 1
+ instantiator.scene = scene
+ instantiator.sync_starting_changes = sync_starting_changes
+ instantiator.excluded_properties = excluded_properties
+ instantiator.replicate_on_join = replicate_on_join
+ add_child(instantiator)
+
+ instantiator_lib[settings_key] = instantiator
+
+ GDSync.call_func(create_instantiator_remote,
+ scene.resource_path,
+ str(parent.get_path()),
+ sync_starting_changes,
+ excluded_properties,
+ replicate_on_join
+ )
+ else:
+ instantiator = instantiator_lib[settings_key]
+ logger.write_log("Using existing Instantiator.", "[NodeTracker]")
+
+ instantiator.target = parent
+ instantiator.target_path = str(parent.get_path())
+
+ GDSync.call_func(instantiator._set_target_remote, instantiator.target_path)
+
+ return instantiator.instantiate_node()
+
+func create_instantiator_remote(
+ scene_path : String,
+ parent_path : NodePath,
+ sync_starting_changes : bool,
+ excluded_properties : PackedStringArray,
+ replicate_on_join : bool
+ ) -> void:
+
+ var scene : PackedScene = load(scene_path)
+ var parent : Node = get_node_or_null(parent_path)
+
+ if scene == null:
+ logger.write_error("Failed to create remote Instaniator, invalid scene path. <"+scene_path+">", "[NodeTracker]")
+ push_error("Remote instantiate failed, invalid scene path.")
+ return
+
+ var tries : int = 0
+ var current_lobby_i : int = lobby_i
+ while parent == null:
+ tries += 1
+ await get_tree().create_timer(0.6).timeout
+ logger.write_error("Failed to create remote Instantiator, parent Node not found. Trying again. <"+str(parent_path)+">", "[NodeTracker]")
+
+ if tries >= 100:
+ logger.write_error("Failed to create remote Instantiator, parent Node not found. <"+str(parent_path)+">", "[NodeTracker]")
+ return
+
+ if current_lobby_i != lobby_i:
+ return
+
+ var settings_key : StringName = StringName(
+ str(scene_path, sync_starting_changes, excluded_properties, replicate_on_join
+ ))
+
+ logger.write_log("Created remote Instaniator. <"+settings_key+">", "[NodeTracker]")
+
+ if !instantiator_lib.has(settings_key):
+ var instantiator : Node = INSTANTIATOR_SCENE.new()
+ instantiator.name = instantiator_regex.sub(scene_path.to_lower(), "", true)
+ instantiator.spawn_type = 1
+ instantiator.scene = scene
+ instantiator.sync_starting_changes = sync_starting_changes
+ instantiator.excluded_properties = excluded_properties
+ instantiator.replicate_on_join = replicate_on_join
+ add_child(instantiator)
+
+ instantiator.target = parent
+ instantiator.target_path = str(parent.get_path())
+
+ instantiator_lib[settings_key] = instantiator
+
+func multiplayer_queue_free(node : Node) -> void:
+ if !is_instance_valid(node) || !node.is_inside_tree(): return
+ node.queue_free()
+
+ logger.write_log("Creating remote free request. <"+str(node.get_path())+">", "[NodeTracker]")
+ GDSync.call_func(multiplayer_queue_free_remote, node.get_path())
+
+func multiplayer_queue_free_remote(node_path : NodePath) -> void:
+ var node : Node = get_node_or_null(node_path)
+ if node == null:
+ logger.write_error("Failed to remotely free, Node not found. <"+str(node_path)+">", "[NodeTracker]")
+ return
+
+ logger.write_log("Remotely freed Node. <"+str(node_path)+">", "[NodeTracker]")
+ node.queue_free()
diff --git a/addons/GD-Sync/Scripts/NodeTracker.gd.uid b/addons/GD-Sync/Scripts/NodeTracker.gd.uid
new file mode 100644
index 0000000..9752787
--- /dev/null
+++ b/addons/GD-Sync/Scripts/NodeTracker.gd.uid
@@ -0,0 +1 @@
+uid://caeuxki7ks0bq
diff --git a/addons/GD-Sync/Scripts/RequestProcessor.gd b/addons/GD-Sync/Scripts/RequestProcessor.gd
new file mode 100644
index 0000000..d350997
--- /dev/null
+++ b/addons/GD-Sync/Scripts/RequestProcessor.gd
@@ -0,0 +1,1332 @@
+extends Node
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+signal packets_processed
+
+var requestsSETUP : Array = []
+var requestsSERV : Array = []
+var requestsRUDP : Array = []
+var requestsUDP : Array = []
+
+var name_cache_temp : Dictionary = {}
+var node_path_cache_temp : Dictionary = {}
+
+var GDSync
+var connection_controller
+var session_controller
+var data_controller
+var matchmaking_controller
+var server_switch_controller
+var logger
+
+var settings_applied : bool = false
+
+func _ready() -> void:
+ name = "RequestProcessor"
+ GDSync = get_node("/root/GDSync")
+ connection_controller = GDSync._connection_controller
+ session_controller = GDSync._session_controller
+ data_controller = GDSync._data_controller
+ matchmaking_controller = GDSync._matchmaking_controller
+ server_switch_controller = GDSync._server_switch_controller
+ logger = GDSync._logger
+
+func has_packets(type : int) -> bool:
+ match(type):
+ ENUMS.PACKET_CHANNEL.SETUP:
+ return requestsSETUP.size() > 0
+ ENUMS.PACKET_CHANNEL.SERVER:
+ if !connection_controller.is_local() and connection_controller.status != ENUMS.CONNECTION_STATUS.CONNECTION_SECURED: return false
+ return requestsSERV.size() > 0
+ ENUMS.PACKET_CHANNEL.RELIABLE:
+ if !connection_controller.is_local() and connection_controller.status != ENUMS.CONNECTION_STATUS.CONNECTION_SECURED: return false
+ return requestsRUDP.size() > 0
+ ENUMS.PACKET_CHANNEL.UNRELIABLE:
+ if !connection_controller.is_local() and connection_controller.status != ENUMS.CONNECTION_STATUS.CONNECTION_SECURED: return false
+ return requestsUDP.size() > 0
+ return false
+
+func clear_for_server_switch() -> void:
+ requestsSETUP.clear()
+ requestsSERV.clear()
+ requestsRUDP.clear()
+ requestsUDP.clear()
+ _seen_unreliable_nonces.clear()
+ _senders_on_multiplayer_clock.clear()
+ _scene_swap_holding = false
+ _join_holding = false
+ _held_requests.clear()
+ settings_applied = false
+
+const _WIRE_COMPRESSION : int = FileAccess.COMPRESSION_ZSTD
+const _MAX_PLAIN_REQUEST_BATCH_BYTES : int = 20480
+const _MAX_DECOMPRESSED_PACKET_BYTES : int = 2097152
+const _UNRELIABLE_WIRE_LIMIT : int = 1200
+const _UNRELIABLE_COMPRESS_HEADROOM : int = 64
+const _UNRELIABLE_AUTH_NONCE_PLACEHOLDER : int = 9223372036854775807
+const _TARGET_CLIENT_ID_MASK : int = 0x3FFFFFFF
+const _TARGET_PERMISSION_SHIFT : int = 30
+
+const _UNRELIABLE_AUTH_KEY : String = "_gdsn"
+const _UNRELIABLE_NONCE_WINDOW_MS : int = 300000
+const _UNRELIABLE_UNSYNCED_SENDER_MS : int = 300000
+var _unreliable_nonce_counter : int = 0
+var _seen_unreliable_nonces : Dictionary = {}
+var _senders_on_multiplayer_clock : Dictionary = {}
+
+func encode_target_client(client_id : int, permission : int) -> int:
+ var id_part : int = client_id if client_id >= 0 else _TARGET_CLIENT_ID_MASK
+ return (permission << _TARGET_PERMISSION_SHIFT) | (id_part & _TARGET_CLIENT_ID_MASK)
+
+const _CALLER_CLIENT_INDEX : int = 4
+
+func _embed_caller_in_sync_request(parts : Array, trailing = null) -> Array:
+ parts.append(GDSync.get_client_id())
+ if trailing != null:
+ parts.append(trailing)
+ return parts
+
+func _request_has_embedded_caller(request : Array, request_type : int) -> bool:
+ if request.size() <= _CALLER_CLIENT_INDEX:
+ return false
+ match request_type:
+ ENUMS.REQUEST_TYPE.SET_VARIABLE, ENUMS.REQUEST_TYPE.SET_VARIABLE_CACHED:
+ return request.size() >= 6 and request[_CALLER_CLIENT_INDEX] is int
+ ENUMS.REQUEST_TYPE.CALL_FUNCTION, ENUMS.REQUEST_TYPE.CALL_FUNCTION_CACHED:
+ var slot = request[_CALLER_CLIENT_INDEX]
+ return slot is int and not (slot is Array)
+ return false
+
+func _request_caller_id(request : Array, request_type : int) -> int:
+ if !_request_has_embedded_caller(request, request_type):
+ return -1
+ return request[_CALLER_CLIENT_INDEX]
+
+func _request_var_value(request : Array, request_type : int):
+ if _request_has_embedded_caller(request, request_type):
+ return request[5]
+ return request[ENUMS.VAR_DATA.VALUE]
+
+func _request_func_parameters(request : Array, request_type : int):
+ if _request_has_embedded_caller(request, request_type):
+ if request.size() > 5:
+ var parameters = request[5]
+ if parameters is Dictionary and parameters.has(_UNRELIABLE_AUTH_KEY):
+ return null
+ return parameters
+ return null
+ if request.size() - 1 >= ENUMS.FUNCTION_DATA.PARAMETERS:
+ var parameters = request[ENUMS.FUNCTION_DATA.PARAMETERS]
+ if parameters is Dictionary and parameters.has(_UNRELIABLE_AUTH_KEY):
+ return null
+ return parameters
+ return null
+
+func stamp_caller_id(request : Array, caller_id : int) -> Array:
+ var req : Array = request.duplicate()
+ var request_type : int = req[ENUMS.DATA.REQUEST_TYPE]
+ if request_type not in [
+ ENUMS.REQUEST_TYPE.SET_VARIABLE,
+ ENUMS.REQUEST_TYPE.SET_VARIABLE_CACHED,
+ ENUMS.REQUEST_TYPE.CALL_FUNCTION,
+ ENUMS.REQUEST_TYPE.CALL_FUNCTION_CACHED,
+ ]:
+ return req
+ if _request_has_embedded_caller(req, request_type):
+ req[_CALLER_CLIENT_INDEX] = caller_id
+ return req
+ match request_type:
+ ENUMS.REQUEST_TYPE.SET_VARIABLE, ENUMS.REQUEST_TYPE.SET_VARIABLE_CACHED:
+ if req.size() >= 5:
+ req.insert(_CALLER_CLIENT_INDEX, caller_id)
+ ENUMS.REQUEST_TYPE.CALL_FUNCTION, ENUMS.REQUEST_TYPE.CALL_FUNCTION_CACHED:
+ if req.size() == 4:
+ req.append(caller_id)
+ elif req.size() >= 5:
+ req.insert(_CALLER_CLIENT_INDEX, caller_id)
+ return req
+
+func _send_channel_is_reliable(channel_type : int) -> bool:
+ return channel_type != ENUMS.PACKET_CHANNEL.UNRELIABLE
+
+func _recv_transport_is_reliable(transport_channel : int) -> bool:
+ return transport_channel == 0
+
+func _encrypt_outgoing_if_secured(plain : PackedByteArray, channel_type : int) -> PackedByteArray:
+ if connection_controller.status != ENUMS.CONNECTION_STATUS.CONNECTION_SECURED:
+ return plain
+ var reliable : bool = _send_channel_is_reliable(channel_type)
+ return connection_controller.encrypt_secured_payload(plain, reliable)
+
+func _wrap_remote_packet(inner : PackedByteArray) -> PackedByteArray:
+ var envelope : Array = [inner.size(), 0, inner.compress(_WIRE_COMPRESSION)]
+ return var_to_bytes(envelope)
+
+func package_requests(type : int) -> PackedByteArray:
+ var requests : Array
+ var packet_type : int
+ match type:
+ ENUMS.PACKET_CHANNEL.SETUP:
+ requests = requestsSETUP
+ packet_type = ENUMS.PACKET_VALUE.SERVER_REQUESTS
+ ENUMS.PACKET_CHANNEL.SERVER:
+ requests = requestsSERV
+ packet_type = ENUMS.PACKET_VALUE.SERVER_REQUESTS
+ ENUMS.PACKET_CHANNEL.RELIABLE:
+ requests = requestsRUDP
+ packet_type = ENUMS.PACKET_VALUE.CLIENT_REQUESTS
+ ENUMS.PACKET_CHANNEL.UNRELIABLE:
+ requests = requestsUDP
+ packet_type = ENUMS.PACKET_VALUE.CLIENT_REQUESTS
+
+ var batch : Array = []
+ if type == ENUMS.PACKET_CHANNEL.UNRELIABLE:
+ batch = _detach_unreliable_batch(requests, packet_type)
+ else:
+ batch = requests.duplicate()
+ var sized : Dictionary = {packet_type: batch}
+ var sized_plain : PackedByteArray = var_to_bytes(sized)
+ while sized_plain.size() > _MAX_PLAIN_REQUEST_BATCH_BYTES and batch.size() > 1:
+ batch = batch.slice(0, ceili(batch.size() / 2.0))
+ sized = {packet_type: batch}
+ sized_plain = var_to_bytes(sized)
+ for request in batch:
+ requests.erase(request)
+ var message : Dictionary = {packet_type: batch}
+ var plain : PackedByteArray = var_to_bytes(message)
+
+ var payload : PackedByteArray = _encrypt_outgoing_if_secured(plain, type)
+ packets_processed.emit()
+
+ var return_bytes : PackedByteArray = payload if connection_controller.is_local() else _wrap_remote_packet(payload)
+
+ if logger.use_profiler and batch.size() > 0:
+ var compressed_packet_size : float = return_bytes.size()
+ var total_uncompressed_size : float = 0.0
+ var uncompressed_size_table : Dictionary = {}
+ for r in batch:
+ var uncompressed_size : float = var_to_bytes(r).size()
+ total_uncompressed_size += uncompressed_size
+ uncompressed_size_table[r] = uncompressed_size
+
+ if total_uncompressed_size > 0.0:
+ for r in batch:
+ var compressed_size_estimate : int = (uncompressed_size_table[r] / total_uncompressed_size) * compressed_packet_size
+ var origin_data : Dictionary = get_request_origin_data(r)
+ if origin_data.size() > 0:
+ logger.register_transfer_usage(origin_data, compressed_size_estimate, true, var_to_str(r))
+
+ return return_bytes
+
+func _detach_unreliable_batch(requests : Array, packet_type : int) -> Array:
+ if requests.is_empty():
+ return []
+ var fit : int = 1
+ var lo : int = 1
+ var hi : int = requests.size()
+ while lo <= hi:
+ var mid : int = (lo + hi) >> 1
+ if _unreliable_prefix_fits(requests, mid, packet_type):
+ fit = mid
+ lo = mid + 1
+ else:
+ hi = mid - 1
+ var batch : Array = []
+ for i in fit:
+ var request = requests[i]
+ if request is Array:
+ _stamp_unreliable_auth(request)
+ batch.append(request)
+ for i in fit:
+ requests.pop_front()
+ return batch
+
+func _unreliable_prefix_fits(requests : Array, count : int, packet_type : int) -> bool:
+ var batch : Array = []
+ for i in count:
+ var request = requests[i]
+ if request is Array:
+ var copy : Array = request.duplicate(true)
+ var mac := PackedByteArray()
+ mac.resize(32)
+ copy.append({_UNRELIABLE_AUTH_KEY: [1, _UNRELIABLE_AUTH_NONCE_PLACEHOLDER, mac]})
+ batch.append(copy)
+ else:
+ batch.append(request)
+ var plain : PackedByteArray = var_to_bytes({packet_type: batch})
+ return _estimate_unreliable_wire_bytes(plain) <= _UNRELIABLE_WIRE_LIMIT
+
+func _estimate_unreliable_wire_bytes(plain : PackedByteArray) -> int:
+ var pad : int = 16 - (plain.size() % 16)
+ if pad == 0:
+ pad = 16
+ var cipher_len : int = plain.size() + pad
+ if connection_controller.is_local():
+ return cipher_len
+ var blob := PackedByteArray()
+ blob.resize(cipher_len + _UNRELIABLE_COMPRESS_HEADROOM)
+ return var_to_bytes([cipher_len, 0, blob]).size()
+
+func _requests_from_payload_bytes(data : PackedByteArray) -> Array:
+ if data.is_empty():
+ return []
+ return _requests_from_parsed_variant(bytes_to_var(data))
+
+func _requests_from_parsed_variant(parsed : Variant) -> Array:
+ if parsed is Dictionary:
+ return _requests_from_message_dict(parsed as Dictionary)
+ if parsed is Array:
+ return parsed as Array
+ return []
+
+func _requests_from_message_dict(d : Dictionary) -> Array:
+ for key in [ENUMS.PACKET_VALUE.CLIENT_REQUESTS, ENUMS.PACKET_VALUE.SERVER_REQUESTS, ENUMS.PACKET_VALUE.INTERNAL_REQUESTS]:
+ if d.has(key):
+ var v : Variant = d[key]
+ return v if v is Array else []
+ return []
+
+func _decompress_remote_envelope(outer : Array) -> PackedByteArray:
+ if outer.size() < 3 or !(outer[2] is PackedByteArray):
+ return PackedByteArray()
+ var uncompressed_size : int = int(outer[0])
+ var zstd_blob : PackedByteArray = outer[2] as PackedByteArray
+ if uncompressed_size <= 0 or uncompressed_size > _MAX_DECOMPRESSED_PACKET_BYTES:
+ logger.write_error("Dropped a packet whose claimed size was not valid. <"+str(uncompressed_size)+">")
+ return PackedByteArray()
+ if zstd_blob.is_empty() or zstd_blob.size() > _MAX_DECOMPRESSED_PACKET_BYTES:
+ return PackedByteArray()
+ var body : PackedByteArray = zstd_blob.decompress(uncompressed_size, _WIRE_COMPRESSION)
+ if body.size() != uncompressed_size:
+ return PackedByteArray()
+ return body
+
+func _multiplayer_time_ms() -> int:
+ return maxi(int(GDSync.get_multiplayer_time() * 1000.0), 0)
+
+func _next_unreliable_nonce() -> int:
+ _unreliable_nonce_counter = (_unreliable_nonce_counter + 1) & 0xFFFF
+ return (_multiplayer_time_ms() << 16) | _unreliable_nonce_counter
+
+func _unreliable_mac(request : Array, nonce : int) -> PackedByteArray:
+ var ctx : HMACContext = HMACContext.new()
+ # Harvest Season patch: local mode has no API keys, and an empty HMAC key errors on every packet.
+ var mac_key : String = connection_controller._PRIVATE_KEY if connection_controller._PRIVATE_KEY != "" else "gdsync-local-mode"
+ if ctx.start(HashingContext.HASH_SHA256, mac_key.to_utf8_buffer()) != OK:
+ return PackedByteArray()
+ ctx.update(var_to_bytes(request))
+ ctx.update(var_to_bytes(nonce))
+ return ctx.finish()
+
+func _stamp_unreliable_auth(request : Array) -> void:
+ var nonce : int = _next_unreliable_nonce()
+ request.append({_UNRELIABLE_AUTH_KEY: [1, nonce, _unreliable_mac(request, nonce)]})
+
+func clear_unreliable_nonces() -> void:
+ _seen_unreliable_nonces.clear()
+ _senders_on_multiplayer_clock.clear()
+ _unreliable_nonce_counter = 0
+
+func _remember_unreliable_nonce(nonce : int, sender_id : int) -> bool:
+ if _seen_unreliable_nonces.has(nonce):
+ return false
+ var now_ms : int = _multiplayer_time_ms()
+ var nonce_ms : int = nonce >> 16
+ var aligned : bool = absi(nonce_ms - now_ms) <= _UNRELIABLE_NONCE_WINDOW_MS
+ if aligned:
+ if sender_id >= 0 and session_controller.multiplayer_clock_synced:
+ _senders_on_multiplayer_clock[sender_id] = true
+ else:
+ var local_clock_ready : bool = session_controller.multiplayer_clock_synced
+ var sender_still_joining : bool = nonce_ms >= 0 and nonce_ms <= _UNRELIABLE_UNSYNCED_SENDER_MS
+ var sender_already_synced : bool = sender_id >= 0 and _senders_on_multiplayer_clock.has(sender_id)
+ if (local_clock_ready and !sender_still_joining) or sender_already_synced:
+ logger.write_error("Dropped an unreliable packet outside the multiplayer time window. <"+str(nonce_ms)+"><"+str(now_ms)+">")
+ return false
+
+ _seen_unreliable_nonces[nonce] = now_ms
+ if _seen_unreliable_nonces.size() > 4096:
+ var expired : Array = []
+ for seen in _seen_unreliable_nonces:
+ if int(_seen_unreliable_nonces[seen]) + _UNRELIABLE_NONCE_WINDOW_MS < now_ms:
+ expired.append(seen)
+ for seen in expired:
+ _seen_unreliable_nonces.erase(seen)
+ return true
+
+func _macs_equal(left : PackedByteArray, right : PackedByteArray) -> bool:
+ if left.size() != right.size():
+ return false
+ var mismatch : int = 0
+ for i in range(left.size()):
+ mismatch |= left[i] ^ right[i]
+ return mismatch == 0
+
+func _accept_incoming_request(request : Array) -> bool:
+ if request.is_empty():
+ return false
+ var last = request[request.size() - 1]
+ if !(last is Dictionary) or !last.has(_UNRELIABLE_AUTH_KEY):
+ return true
+
+ var auth = last[_UNRELIABLE_AUTH_KEY]
+ if !(auth is Array) or auth.size() < 3 or !(auth[2] is PackedByteArray):
+ return false
+
+ request.resize(request.size() - 1)
+ var nonce : int = int(auth[1])
+ if !_macs_equal(_unreliable_mac(request, nonce), auth[2]):
+ logger.write_error("Dropped a packet whose authentication check failed.")
+ return false
+ var sender_id : int = -1
+ if request.size() > 0 and request[0] is int:
+ sender_id = _request_caller_id(request, request[0])
+ if !_remember_unreliable_nonce(nonce, sender_id):
+ return false
+ return true
+
+func _request_min_size(request_type : int) -> int:
+ match request_type:
+ ENUMS.REQUEST_TYPE.SET_VARIABLE, ENUMS.REQUEST_TYPE.SET_VARIABLE_CACHED:
+ return 5
+ ENUMS.REQUEST_TYPE.CALL_FUNCTION, ENUMS.REQUEST_TYPE.CALL_FUNCTION_CACHED:
+ return 4
+ ENUMS.REQUEST_TYPE.MESSAGE:
+ return 2
+ return 1
+
+func _decrypt_body_if_needed(body : PackedByteArray, transport_channel : int) -> PackedByteArray:
+ if connection_controller.status != ENUMS.CONNECTION_STATUS.CONNECTION_SECURED:
+ return body
+ var reliable : bool = _recv_transport_is_reliable(transport_channel)
+ return connection_controller.decrypt_secured_payload(body, reliable)
+
+func _requests_from_packet_bytes(packet_bytes : PackedByteArray, transport_channel : int) -> Array:
+ var outer : Variant = bytes_to_var(packet_bytes)
+ if connection_controller.is_local():
+ if connection_controller.status != ENUMS.CONNECTION_STATUS.CONNECTION_SECURED:
+ return _requests_from_parsed_variant(outer)
+ if !(outer is PackedByteArray):
+ return []
+ var cipher_local : PackedByteArray = outer as PackedByteArray
+ var decrypted_body : PackedByteArray = _decrypt_body_if_needed(cipher_local, transport_channel)
+ if decrypted_body.is_empty():
+ return []
+ return _requests_from_payload_bytes(decrypted_body)
+ if !(outer is Array):
+ return []
+ var body : PackedByteArray = _decompress_remote_envelope(outer as Array)
+ if body.is_empty():
+ return []
+ var decrypted_body : PackedByteArray = _decrypt_body_if_needed(body, transport_channel)
+ if decrypted_body.is_empty():
+ return []
+ return _requests_from_payload_bytes(decrypted_body)
+
+func unpack_packet(bytes : PackedByteArray, transport_channel : int = 0) -> void:
+ var requests : Array = _requests_from_packet_bytes(bytes, transport_channel)
+ var compressed_packet_size : float = bytes.size()
+
+ for r in requests:
+ if !(r is Array):
+ continue
+ var request : Array = r
+ if !_accept_incoming_request(request):
+ continue
+ if request.size() < 1 or !(request[ENUMS.DATA.REQUEST_TYPE] is int):
+ continue
+ if request.size() < _request_min_size(request[ENUMS.DATA.REQUEST_TYPE]):
+ continue
+
+ if _should_hold_request(request):
+ continue
+ _dispatch_request(request)
+
+ if logger.use_profiler and requests.size() > 0:
+ var total_uncompressed_size : float = 0.0
+ var uncompressed_size_table : Dictionary = {}
+ for r in requests:
+ if !(r is Array):
+ continue
+ var uncompressed_size : float = var_to_bytes(r).size()
+ total_uncompressed_size += uncompressed_size
+ uncompressed_size_table[r] = uncompressed_size
+ if total_uncompressed_size > 0.0:
+ for r in requests:
+ if !(r is Array):
+ continue
+ var compressed_size_estimate : int = (uncompressed_size_table[r] / total_uncompressed_size) * compressed_packet_size
+ var origin_data : Dictionary = get_request_origin_data(r)
+ if origin_data.size() > 0:
+ logger.register_transfer_usage(origin_data, compressed_size_estimate, false, var_to_str(r))
+
+func get_request_origin_data(r : Array) -> Dictionary:
+ if r.size() < 1 or !(r[ENUMS.DATA.REQUEST_TYPE] is int):
+ return {}
+ if r.size() < _request_min_size(r[ENUMS.DATA.REQUEST_TYPE]):
+ return {}
+ match r[ENUMS.DATA.REQUEST_TYPE]:
+ ENUMS.REQUEST_TYPE.SET_VARIABLE:
+ var id : String = r[ENUMS.VAR_DATA.NODE_PATH]
+ var property_name : String = r[ENUMS.VAR_DATA.NAME]
+ return {"type" : "sync_var", "object" : id, "target" : property_name}
+ ENUMS.REQUEST_TYPE.SET_VARIABLE_CACHED:
+ if r[ENUMS.VAR_DATA.NODE_PATH] is int and !session_controller.has_nodepath_from_index(r[ENUMS.VAR_DATA.NODE_PATH]):
+ return {}
+ if r[ENUMS.VAR_DATA.NAME] is int and !session_controller.has_name_from_index(r[ENUMS.VAR_DATA.NAME]):
+ return {}
+ var id : String = session_controller.get_nodepath_from_index(r[ENUMS.VAR_DATA.NODE_PATH]) if r[ENUMS.VAR_DATA.NODE_PATH] is int else r[ENUMS.VAR_DATA.NODE_PATH]
+ var property_name : String = session_controller.get_name_from_index(r[ENUMS.VAR_DATA.NAME]) if r[ENUMS.VAR_DATA.NAME] is int else r[ENUMS.VAR_DATA.NAME]
+ return {"type" : "sync_var optimized", "object" : id, "target" : property_name}
+ ENUMS.REQUEST_TYPE.CALL_FUNCTION:
+ var id : String = r[ENUMS.FUNCTION_DATA.NODE_PATH]
+ var function_name : String = r[ENUMS.FUNCTION_DATA.NAME]
+ return {"type" : "call_func", "object" : id, "target" : function_name}
+ ENUMS.REQUEST_TYPE.CALL_FUNCTION_CACHED:
+ if r[ENUMS.FUNCTION_DATA.NODE_PATH] is int and !session_controller.has_nodepath_from_index(r[ENUMS.FUNCTION_DATA.NODE_PATH]):
+ return {}
+ if r[ENUMS.FUNCTION_DATA.NAME] is int and !session_controller.has_name_from_index(r[ENUMS.FUNCTION_DATA.NAME]):
+ return {}
+ var id : String = session_controller.get_nodepath_from_index(r[ENUMS.FUNCTION_DATA.NODE_PATH]) if r[ENUMS.FUNCTION_DATA.NODE_PATH] is int else r[ENUMS.FUNCTION_DATA.NODE_PATH]
+ var function_name : String = session_controller.get_name_from_index(r[ENUMS.FUNCTION_DATA.NAME]) if r[ENUMS.FUNCTION_DATA.NAME] is int else r[ENUMS.FUNCTION_DATA.NAME]
+ return {"type" : "call_func optimized", "object" : id, "target" : function_name}
+ ENUMS.REQUEST_TYPE.MESSAGE:
+ return {"type" : "internal", "object" : "GD-Sync", "target" : "Internal Message ("+ENUMS.MESSAGE_TYPE.keys()[r[ENUMS.MESSAGE_DATA.TYPE]].capitalize()+")"}
+ return {}
+
+var _scene_swap_holding : bool = false
+var _join_holding : bool = false
+var _held_requests : Array = []
+
+const _SCENE_SWAP_HANDSHAKE : PackedStringArray = [
+ "load_scene",
+ "mark_scene_ready",
+ "switch_scene_success",
+ "switch_scene_failed",
+]
+
+func begin_scene_swap() -> void:
+ _scene_swap_holding = true
+
+func end_scene_swap() -> void:
+ _scene_swap_holding = false
+ flush_held_requests()
+
+func cancel_scene_swap() -> void:
+ _scene_swap_holding = false
+ flush_held_requests()
+
+func flush_held_requests() -> void:
+ if _scene_swap_holding or _join_holding or _held_requests.is_empty():
+ return
+ var pending : Array = _held_requests
+ _held_requests = []
+ for request in pending:
+ _dispatch_request(request)
+
+func _should_hold_request(request : Array) -> bool:
+ if !(_scene_swap_holding or _join_holding) or _is_scene_swap_handshake(request) or _is_lobby_data_received(request):
+ return false
+ _held_requests.append(request)
+ return true
+
+func _is_lobby_data_received(request : Array) -> bool:
+ if request[ENUMS.DATA.REQUEST_TYPE] != ENUMS.REQUEST_TYPE.MESSAGE:
+ return false
+ if request.size() <= ENUMS.MESSAGE_DATA.TYPE or !(request[ENUMS.MESSAGE_DATA.TYPE] is int):
+ return false
+ return request[ENUMS.MESSAGE_DATA.TYPE] == ENUMS.MESSAGE_TYPE.LOBBY_DATA_RECEIVED
+
+func _is_scene_swap_handshake(request : Array) -> bool:
+ var request_type : int = request[ENUMS.DATA.REQUEST_TYPE]
+ if request_type != ENUMS.REQUEST_TYPE.CALL_FUNCTION and request_type != ENUMS.REQUEST_TYPE.CALL_FUNCTION_CACHED:
+ return false
+ var function_name = request[ENUMS.FUNCTION_DATA.NAME]
+ if function_name is int:
+ if !session_controller.has_name_from_index(function_name):
+ return false
+ function_name = session_controller.get_name_from_index(function_name)
+ return _SCENE_SWAP_HANDSHAKE.has(str(function_name))
+
+func _dispatch_request(request : Array) -> void:
+ match request[ENUMS.DATA.REQUEST_TYPE]:
+ ENUMS.REQUEST_TYPE.SET_VARIABLE:
+ set_variable(request)
+ ENUMS.REQUEST_TYPE.SET_VARIABLE_CACHED:
+ set_variable_cached(request)
+ ENUMS.REQUEST_TYPE.CALL_FUNCTION:
+ call_function(request)
+ ENUMS.REQUEST_TYPE.CALL_FUNCTION_CACHED:
+ call_function_cached(request)
+ ENUMS.REQUEST_TYPE.MESSAGE:
+ process_message(request)
+
+func process_message(request : Array) -> void:
+ if request.size() <= ENUMS.MESSAGE_DATA.TYPE or !(request[ENUMS.MESSAGE_DATA.TYPE] is int):
+ return
+ var message : int = request[ENUMS.MESSAGE_DATA.TYPE]
+
+ if OS.is_debug_build() and message != ENUMS.MESSAGE_TYPE.SET_SENDER_ID:
+ logger.write_log("Message received. <"+str(ENUMS.MESSAGE_TYPE.keys()[message])+"><"+str(request)+">")
+
+ match(message):
+ ENUMS.MESSAGE_TYPE.CRITICAL_ERROR:
+ if request.size() <= ENUMS.MESSAGE_DATA.ERROR: return
+ handle_critical_error(request[ENUMS.MESSAGE_DATA.ERROR])
+ ENUMS.MESSAGE_TYPE.CLIENT_ID_RECEIVED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ connection_controller.set_client_id(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.CLIENT_KEY_RECEIVED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ connection_controller.set_client_key(String(request[ENUMS.MESSAGE_DATA.VALUE]))
+ ENUMS.MESSAGE_TYPE.INVALID_PUBLIC_KEY:
+ logger.write_error("Client key was empty or public key invalid.")
+ connection_controller.reset_multiplayer()
+ GDSync.emit_signal("connection_failed", ENUMS.CONNECTION_FAILED.INVALID_PUBLIC_KEY)
+ ENUMS.MESSAGE_TYPE.SET_NODE_PATH_CACHE:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE2: return
+ session_controller.cache_nodepath(request[ENUMS.MESSAGE_DATA.VALUE], request[ENUMS.MESSAGE_DATA.VALUE2])
+ ENUMS.MESSAGE_TYPE.ERASE_NODE_PATH_CACHE:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ session_controller.erase_nodepath_cache(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.SET_NAME_CACHE:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE2: return
+ session_controller.cache_name(request[ENUMS.MESSAGE_DATA.VALUE], request[ENUMS.MESSAGE_DATA.VALUE2])
+ ENUMS.MESSAGE_TYPE.ERASE_NAME_CACHE:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ session_controller.erase_nodepath_cache(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.SET_GDSYNC_OWNER:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ set_gdsync_owner_remote(request[ENUMS.MESSAGE_DATA.VALUE], request[ENUMS.MESSAGE_DATA.VALUE2] if request.size() > ENUMS.MESSAGE_DATA.VALUE2 else null)
+ ENUMS.MESSAGE_TYPE.HOST_CHANGED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ connection_controller.set_host(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.LOBBY_CREATED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ session_controller.lobby_created()
+ data_controller.set_friend_status()
+ GDSync.lobby_created.emit(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.LOBBY_CREATION_FAILED:
+ if request.size() <= ENUMS.MESSAGE_DATA.ERROR: return
+ GDSync.lobby_creation_failed.emit(request[ENUMS.MESSAGE_DATA.VALUE], request[ENUMS.MESSAGE_DATA.ERROR])
+ ENUMS.MESSAGE_TYPE.LOBBY_JOINED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ if connection_controller.is_local():
+ connection_controller.in_local_lobby = true
+ data_controller.set_friend_status()
+ _join_holding = true
+ server_switch_controller.lobby_joined()
+ matchmaking_controller.lobby_joined()
+ ENUMS.MESSAGE_TYPE.LOBBY_JOIN_FAILED:
+ if request.size() <= ENUMS.MESSAGE_DATA.ERROR: return
+ if connection_controller.is_local():
+ connection_controller.leave_local_lobby_client()
+ server_switch_controller.lobby_join_failed()
+ matchmaking_controller.lobby_join_failed()
+ GDSync.lobby_join_failed.emit(request[ENUMS.MESSAGE_DATA.VALUE], request[ENUMS.MESSAGE_DATA.ERROR])
+ ENUMS.MESSAGE_TYPE.CLIENT_JOINED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ GDSync.client_joined.emit(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.CLIENT_LEFT:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ GDSync.client_left.emit(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.LOBBIES_RECEIVED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ GDSync.lobbies_received.emit(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.LOBBY_DATA_RECEIVED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ session_controller.override_lobby_data(request[ENUMS.MESSAGE_DATA.VALUE])
+ GDSync.lobby_joined.emit(request[ENUMS.MESSAGE_DATA.VALUE]["Name"])
+ await get_tree().process_frame
+ _join_holding = false
+ flush_held_requests()
+ ENUMS.MESSAGE_TYPE.LOBBY_DATA_CHANGED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ session_controller.lobby_data_changed(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.LOBBY_TAGS_CHANGED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ session_controller.lobby_tags_changed(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.PLAYER_DATA_RECEIVED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ session_controller.override_player_data(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.PLAYER_DATA_CHANGED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE2: return
+ session_controller.player_data_changed(request[ENUMS.MESSAGE_DATA.VALUE], request[ENUMS.MESSAGE_DATA.VALUE2])
+ ENUMS.MESSAGE_TYPE.SET_SENDER_ID:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ session_controller.set_sender_id(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.KICKED:
+ var kick_reason : String = ""
+ if request.size() > ENUMS.MESSAGE_DATA.VALUE:
+ kick_reason = str(request[ENUMS.MESSAGE_DATA.VALUE])
+ connection_controller.in_local_lobby = false
+ GDSync.kicked.emit(kick_reason)
+ GDSync.lobby_leave.call_deferred()
+ ENUMS.MESSAGE_TYPE.LOBBY_RECEIVED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ GDSync.lobby_received.emit(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.LOBBY_NAME_CHANGED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ GDSync.lobby_name_changed.emit(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.LOBBY_NAME_CHANGE_FAILED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE2: return
+ GDSync.lobby_name_change_failed.emit(request[ENUMS.MESSAGE_DATA.VALUE], request[ENUMS.MESSAGE_DATA.VALUE2])
+ ENUMS.MESSAGE_TYPE.MATCHMAKING_STARTED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ matchmaking_controller.started(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.MATCHMAKING_STATUS_CHANGED:
+ if request.size() < 5: return
+ matchmaking_controller.status_changed(request[2], request[3], request[4])
+ ENUMS.MESSAGE_TYPE.MATCHMAKING_MATCH_FOUND:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE2: return
+ matchmaking_controller.match_found(request[ENUMS.MESSAGE_DATA.VALUE], request[ENUMS.MESSAGE_DATA.VALUE2])
+ ENUMS.MESSAGE_TYPE.MATCHMAKING_FAILED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE2: return
+ matchmaking_controller.failed(request[ENUMS.MESSAGE_DATA.VALUE], request[ENUMS.MESSAGE_DATA.VALUE2])
+ ENUMS.MESSAGE_TYPE.MATCHMAKING_CANCELLED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE: return
+ matchmaking_controller.cancelled(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.SWITCH_SERVER_PREPARED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE or !(request[ENUMS.MESSAGE_DATA.VALUE] is Dictionary): return
+ server_switch_controller.begin(request[ENUMS.MESSAGE_DATA.VALUE])
+ ENUMS.MESSAGE_TYPE.MATCHMAKING_SWITCH_PREPARED:
+ if request.size() <= ENUMS.MESSAGE_DATA.VALUE or !(request[ENUMS.MESSAGE_DATA.VALUE] is Dictionary): return
+ var switch_data: Dictionary = request[ENUMS.MESSAGE_DATA.VALUE]
+ matchmaking_controller.remote_match_found(
+ switch_data.get("MatchmakingRequestId", 0),
+ str(switch_data.get("LobbyName", "")))
+ server_switch_controller.begin(switch_data)
+ ENUMS.MESSAGE_TYPE.TUNNEL_READY:
+ server_switch_controller.tunnel_ready()
+ ENUMS.MESSAGE_TYPE.TUNNEL_FAILED:
+ server_switch_controller.tunnel_failed()
+ ENUMS.MESSAGE_TYPE.TUNNEL_LOCAL:
+ server_switch_controller.tunnel_local()
+
+func handle_critical_error(error : int) -> void:
+ if error < 0 or error >= ENUMS.CRITICAL_ERROR.keys().size():
+ logger.write_error("CRITICAL ERROR. <"+str(error)+">")
+ return
+ logger.write_error("CRITICAL ERROR. <"+str(ENUMS.CRITICAL_ERROR.keys()[error])+">")
+ match error:
+ ENUMS.CRITICAL_ERROR.LOBBY_DATA_FULL:
+ push_error("
+ CRITICAL ERROR:
+ You tried to add or change lobby data, but the data has reached its maximum capacity.
+ Please remove existing keys or input smaller values.
+ ")
+ ENUMS.CRITICAL_ERROR.LOBBY_TAGS_FULL:
+ push_error("
+ CRITICAL ERROR:
+ You tried to add or change lobby tags, but the tag list has reached its maximum capacity.
+ Please remove existing keys or input smaller values.
+ ")
+ ENUMS.CRITICAL_ERROR.PLAYER_DATA_FULL:
+ push_error("
+ CRITICAL ERROR:
+ You tried to add or change player data, but the data has reached its maximum capacity.
+ Please remove existing keys or input smaller values.
+ ")
+ ENUMS.CRITICAL_ERROR.REQUEST_TOO_LARGE:
+ push_error("
+ CRITICAL ERROR:
+ One or multiple requests have been discarded due to being too large.
+ Please reduce the amount of data each frame or send smaller requests and values.
+ ")
+ ENUMS.CRITICAL_ERROR.OBJECT_IN_REQUEST:
+ push_error("
+ CRITICAL ERROR:
+ A request was discarded because it contained an Object or Node reference.
+ GD-Sync cannot serialize Objects. Sync IDs, paths, or plain data instead of Node/Object references.
+ ")
+
+func set_variable_cached(request : Array) -> void:
+ if !session_controller.has_nodepath_from_index(request[ENUMS.VAR_DATA.NODE_PATH]):
+ logger.write_error("Set variable cached was called but the indexed NodePath was not found. <"+str(request[ENUMS.VAR_DATA.NODE_PATH]+">"))
+ return
+ if !session_controller.has_name_from_index(request[ENUMS.VAR_DATA.NAME]):
+ logger.write_error("Set variable cached was called but the indexed name was not found. <"+str(request[ENUMS.VAR_DATA.NAME])+">")
+ return
+
+ request[ENUMS.VAR_DATA.NODE_PATH] = session_controller.get_nodepath_from_index(request[ENUMS.VAR_DATA.NODE_PATH])
+ request[ENUMS.VAR_DATA.NAME] = session_controller.get_name_from_index(request[ENUMS.VAR_DATA.NAME])
+ set_variable(request)
+
+func set_variable(request : Array) -> void:
+ var request_type : int = request[ENUMS.DATA.REQUEST_TYPE]
+ var caller_id : int = _request_caller_id(request, request_type)
+ session_controller.begin_incoming_request(caller_id)
+
+ var id : String = request[ENUMS.VAR_DATA.NODE_PATH]
+ var property_name : String = request[ENUMS.VAR_DATA.NAME]
+
+ var object : Object
+ if session_controller.has_resource_by_reference(id):
+ object = session_controller.get_resource_by_reference(id)
+ else:
+ object = get_node_or_null(id)
+
+ if object == null:
+ session_controller.end_incoming_request()
+ logger.write_error("Set variable failed since the target Node or Resource was not found. <"+id+"><"+property_name+">")
+ return
+ if connection_controller.PROTECTED:
+ if !session_controller.object_is_exposed(object) and !session_controller.property_is_exposed(object, property_name):
+ session_controller.end_incoming_request()
+ logger.write_error("Set variable failed since the object or variable was not exposed. <"+id+"><"+property_name+">")
+ push_error("Attempted to set a protected property \""+property_name+"\" on "+id+", please expose it using GDSync.expose_property() or GDSync.expose_node()/GDSync.expose_resource().")
+ return
+ if !session_controller.object_is_exposed(object):
+ if !session_controller.is_caller_permitted(session_controller.get_property_permission(object, property_name)):
+ session_controller.end_incoming_request()
+ return
+ if !property_name in object:
+ session_controller.end_incoming_request()
+ logger.write_error("Set variable failed since the Node or Resource does not contain the specified variable. <"+id+"><"+property_name+">")
+ push_error("Attempted to set nonexistent property \""+property_name+"\" on "+id)
+ return
+
+ object.set(property_name, _request_var_value(request, request_type))
+ session_controller.end_incoming_request()
+
+func call_function_cached(request : Array) -> void:
+ if !session_controller.has_nodepath_from_index(request[ENUMS.FUNCTION_DATA.NODE_PATH]):
+ logger.write_error("Call function cached was called but the indexed NodePath was not found. <"+str(request[ENUMS.FUNCTION_DATA.NODE_PATH])+">")
+ return
+ if !session_controller.has_name_from_index(request[ENUMS.FUNCTION_DATA.NAME]):
+ logger.write_error("Call function cached was called but the indexed name was not found. <"+str(request[ENUMS.FUNCTION_DATA.NAME])+">")
+ return
+ request[ENUMS.FUNCTION_DATA.NODE_PATH] = session_controller.get_nodepath_from_index(request[ENUMS.FUNCTION_DATA.NODE_PATH])
+ request[ENUMS.FUNCTION_DATA.NAME] = session_controller.get_name_from_index(request[ENUMS.FUNCTION_DATA.NAME])
+ call_function(request)
+
+func call_function(request : Array) -> void:
+ var request_type : int = request[ENUMS.DATA.REQUEST_TYPE]
+ var caller_id : int = _request_caller_id(request, request_type)
+ session_controller.begin_incoming_request(caller_id)
+
+ var id : String = request[ENUMS.FUNCTION_DATA.NODE_PATH]
+ var function_name : String = request[ENUMS.FUNCTION_DATA.NAME]
+
+ var object : Object
+ if session_controller.has_resource_by_reference(id):
+ object = session_controller.get_resource_by_reference(id)
+ else:
+ object = get_node_or_null(id)
+
+ if object == null:
+ session_controller.end_incoming_request()
+ logger.write_error("Call function failed since the target Node or Resource was not found. <"+id+"><"+function_name+">")
+ return
+ if connection_controller.PROTECTED:
+ if !session_controller.object_is_exposed(object) and !session_controller.function_is_exposed(object, function_name):
+ session_controller.end_incoming_request()
+ logger.write_error("Call function failed since the object or function was not exposed. <"+id+"><"+function_name+">")
+ push_error("Attempted to call a protected function \""+function_name+"\" on "+id+", please expose it using GDSync.expose_func() or GDSync.expose_node()/GDSync.expose_resource().")
+ return
+ if !session_controller.object_is_exposed(object):
+ if !session_controller.is_caller_permitted(session_controller.get_function_permission(object, function_name)):
+ session_controller.end_incoming_request()
+ return
+ if !object.has_method(function_name):
+ session_controller.end_incoming_request()
+ logger.write_error("Call function failed since the Node or Resource does not contain the specified function. <"+id+"><"+function_name+">")
+ push_error("Attempted to call nonexistent function \""+function_name+"\" on "+id)
+ return
+
+ var parameters = _request_func_parameters(request, request_type)
+ if parameters != null:
+ object.callv(function_name, parameters)
+ else:
+ object.call(function_name)
+ session_controller.end_incoming_request()
+
+func set_gdsync_owner_remote(node_path : String, owner) -> void:
+ if get_tree().current_scene != null:
+ var node : Node = get_node_or_null(node_path)
+ if node == null: return
+ session_controller.set_gdsync_owner_remote(node, owner)
+ else:
+ session_controller.set_gdsync_owner_delayed(node_path, owner)
+
+func validate_public_key() -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.VALIDATE_KEY,
+ connection_controller._PUBLIC_KEY,
+ OS.get_unique_id(),
+ true,
+ connection_controller.API_VERSION,
+ connection_controller.PLUGIN_VERSION,
+ OS.get_name(),
+ OS.has_feature("editor"),
+ ]
+
+ requestsSETUP.append(request)
+ logger.write_log("Validating public key.")
+
+func send_client_id() -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.SET_CLIENT_ID,
+ GDSync.get_client_id()
+ ]
+
+ requestsSERV.append(request)
+
+func apply_settings() -> void:
+ var api_version_request : Array = [
+ ENUMS.REQUEST_TYPE.SET_SETTING,
+ ENUMS.SETTING.API_VERSION,
+ connection_controller.API_VERSION
+ ]
+
+ requestsSERV.append(api_version_request)
+
+ settings_applied = true
+ logger.write_log("Applying settings.")
+
+func secure_connection() -> void:
+ var connection_generation : int = connection_controller.connection_i
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.SECURE_CONNECTION
+ ]
+
+ requestsSETUP.append(request)
+
+ await self.packets_processed
+ if connection_generation != connection_controller.connection_i:
+ return
+ await get_tree().create_timer(0.5).timeout
+ if connection_generation != connection_controller.connection_i:
+ return
+ connection_controller.status = ENUMS.CONNECTION_STATUS.CONNECTION_SECURED
+
+ if server_switch_controller.connection_secured():
+ return
+
+ GDSync.emit_signal("connected")
+
+func create_set_var_request(object : Object, variable_name : String, client_id : int, reliable : bool) -> void:
+ var request : Array = []
+ var id : String
+
+ if object is Node:
+ id = String(object.get_path())
+
+ for i in range(10):
+ if object.has_meta("PauseSync"):
+ await get_tree().process_frame
+ elif object is RefCounted:
+ if !session_controller.has_resource_reference(object):
+ logger.write_error("Creating set variable request failed, the Resource was not registered. <"+str(object)+"><"+variable_name+">")
+ push_error("Resource must be registered using GDSync.register_resource()")
+ return
+
+ id = session_controller.get_resource_reference(object)
+ else:
+ return
+
+ var permission : int = session_controller.get_property_permission(object, variable_name)
+
+ var value = null
+ if variable_name in object:
+ value = object.get(variable_name)
+
+ var encoded_target : int = encode_target_client(client_id, permission)
+
+ if !connection_controller.is_local() and session_controller.nodepath_is_cached(id) and session_controller.name_is_cached(variable_name):
+ request = _embed_caller_in_sync_request([
+ ENUMS.REQUEST_TYPE.SET_VARIABLE_CACHED,
+ session_controller.get_nodepath_index(id),
+ session_controller.get_name_index(variable_name),
+ encoded_target,
+ ], value)
+ else:
+ request = _embed_caller_in_sync_request([
+ ENUMS.REQUEST_TYPE.SET_VARIABLE,
+ id,
+ variable_name,
+ encoded_target,
+ ], value)
+
+ create_nodepath_cache(id, variable_name)
+ create_name_cache(id, variable_name)
+
+ _queue_client_request(request, reliable)
+
+func _queue_client_request(request : Array, reliable : bool) -> void:
+ if connection_controller.is_web_export:
+ reliable = true
+ if reliable:
+ requestsRUDP.append(request)
+ else:
+ requestsUDP.append(request)
+
+func create_function_call_request(function : Callable, parameters : Array, client_id : int, reliable : bool, permission_override : int = -1) -> void:
+ var object : Object = function.get_object()
+ var function_name : String = function.get_method()
+ var request : Array = []
+ var id : String
+
+ if object is Node:
+ id = String(object.get_path())
+
+ for i in range(10):
+ if object.has_meta("PauseSync"):
+ await get_tree().process_frame
+ elif object is GDScript:
+ id = object.resource_path
+ elif object is RefCounted:
+ if !session_controller.has_resource_reference(object):
+ logger.write_error("Creating call function request failed, the Resource was not registered. <"+str(object)+"><"+function_name+">")
+ push_error("Resource must be registered using GDSync.register_resource()")
+ return
+
+ id = session_controller.get_resource_reference(object)
+ else:
+ return
+
+ var permission : int = permission_override if permission_override >= 0 else session_controller.get_function_permission(object, function_name)
+
+ var encoded_target : int = encode_target_client(client_id, permission)
+
+ if !connection_controller.is_local() and session_controller.nodepath_is_cached(id) and session_controller.name_is_cached(function_name):
+ request = _embed_caller_in_sync_request([
+ ENUMS.REQUEST_TYPE.CALL_FUNCTION_CACHED,
+ session_controller.get_nodepath_index(id),
+ session_controller.get_name_index(function_name),
+ encoded_target
+ ], parameters if parameters.size() > 0 else null)
+ else:
+ request = _embed_caller_in_sync_request([
+ ENUMS.REQUEST_TYPE.CALL_FUNCTION,
+ id,
+ function_name,
+ encoded_target
+ ], parameters if parameters.size() > 0 else null)
+
+ create_nodepath_cache(id, function_name)
+ create_name_cache(id, function_name)
+
+ _queue_client_request(request, reliable)
+
+func create_nodepath_cache(node_path : String, name : String) -> void:
+ if connection_controller.is_local(): return
+
+ var key : String = node_path+name
+ if !node_path_cache_temp.has(key):
+ node_path_cache_temp[key] = null
+ await get_tree().create_timer(30.0).timeout
+ node_path_cache_temp.erase(key)
+ return
+
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.CACHE_NODE_PATH,
+ node_path
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Creating NodePath cache. <"+node_path+">")
+
+func create_erase_nodepath_cache_request(index : int) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.ERASE_NODE_PATH_CACHE,
+ index
+ ]
+
+ requestsSERV.append(request)
+
+func create_name_cache(node_path : String, name : String) -> void:
+ if connection_controller.is_local(): return
+
+ var key : String = node_path+name
+ if !name_cache_temp.has(key):
+ name_cache_temp[key] = null
+ await get_tree().create_timer(30.0).timeout
+ name_cache_temp.erase(key)
+ return
+
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.CACHE_NAME,
+ name
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Creating name cache. <"+name+">")
+
+func create_erase_name_cache_request(index : int) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.ERASE_NAME_CACHE,
+ index
+ ]
+
+ requestsSERV.append(request)
+
+func get_public_lobbies() -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.GET_PUBLIC_LOBBIES
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Getting public lobbies.")
+
+func create_start_matchmaking_request(parameters: Dictionary) -> void:
+ var request: Array = [
+ ENUMS.REQUEST_TYPE.START_MATCHMAKING,
+ parameters
+ ]
+ requestsSERV.append(request)
+ logger.write_log("Starting matchmaking. <"+str(parameters)+">")
+
+func create_cancel_matchmaking_request(request_id: int) -> void:
+ requestsSERV.append([ENUMS.REQUEST_TYPE.CANCEL_MATCHMAKING, request_id])
+ logger.write_log("Cancelling matchmaking.")
+
+func get_public_lobby(lobby_name : String) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.GET_PUBLIC_LOBBY,
+ lobby_name
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Getting public lobby. <"+str(lobby_name)+">")
+
+func create_new_lobby_request(name : String, password : String, public : bool, playerLimit : int, tags : Dictionary, data : Dictionary) -> void:
+ if var_to_bytes(tags).size() > 2048:
+ process_message.call_deferred([
+ ENUMS.MESSAGE_TYPE.LOBBY_CREATION_FAILED,
+ ENUMS.LOBBY_CREATION_ERROR.TAGS_TOO_LARGE
+ ])
+ return
+ if var_to_bytes(data).size() > 2048:
+ process_message.call_deferred([
+ ENUMS.MESSAGE_TYPE.LOBBY_CREATION_FAILED,
+ ENUMS.LOBBY_CREATION_ERROR.DATA_TOO_LARGE
+ ])
+ return
+
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.CREATE_LOBBY,
+ {
+ "Name" : name,
+ "Password" : password,
+ "Public" : public,
+ "PlayerLimit" : playerLimit,
+ "Tags" : tags,
+ "Data" : data,
+ "UniqueUsernames" : connection_controller.UNIQUE_USERNAMES,
+ "Editor" : OS.has_feature("editor"),
+ }
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Create lobby. <"+str(request[1])+">")
+
+func create_join_lobby_request(name : String, password : String) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.JOIN_LOBBY,
+ name,
+ password
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Join lobby. <"+str(name)+">")
+
+func create_join_lobby_with_ticket_request(reservation_id: String, proof: String) -> void:
+ requestsSERV.append([
+ ENUMS.REQUEST_TYPE.JOIN_LOBBY_WITH_TICKET,
+ reservation_id,
+ proof
+ ])
+ logger.write_log("Joining lobby with reservation.")
+
+func create_tunnel_to_request(destination_address: String) -> void:
+ requestsSERV.append([
+ ENUMS.REQUEST_TYPE.TUNNEL_TO,
+ destination_address
+ ])
+ logger.write_log("Requesting web tunnel. <"+destination_address+">")
+
+func create_commit_server_switch_request(source_address: String, fallback_reservation_id: String) -> void:
+ requestsSERV.append([
+ ENUMS.REQUEST_TYPE.COMMIT_SERVER_SWITCH,
+ source_address,
+ fallback_reservation_id
+ ])
+
+func create_leave_lobby_request() -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.LEAVE_LOBBY
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Leave lobby.")
+
+func create_open_lobby_request() -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.OPEN_LOBBY
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Opening the lobby.")
+
+func create_close_lobby_request() -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.CLOSE_LOBBY
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Closing the lobby.")
+
+func create_lobby_visiblity_request(public : bool) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.SET_LOBBY_VISIBILITY,
+ public
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Changing lobby visibility. <"+str(public)+">")
+
+func create_change_lobby_password_request(password : String) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.CHANGE_PASSWORD,
+ password
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Changing lobby password. <"+str(password)+">")
+
+func create_lobby_name_change_request(name : String) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.CHANGE_LOBBY_NAME,
+ name
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Changing lobby name. <"+str(name)+">")
+
+func create_set_host_request(client_id : int) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.SET_HOST,
+ client_id
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Changing lobby host. <"+str(client_id)+">")
+
+func create_set_username_request(name : String) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.SET_PLAYER_USERNAME,
+ name
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Setting username. <"+str(name)+">")
+
+func create_set_player_data_request(name : String, value) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.SET_PLAYER_DATA,
+ name,
+ value
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Setting player data. <"+str(name)+"><"+str(value)+">")
+
+func create_erase_player_data_request(name : String) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.ERASE_PLAYER_DATA,
+ name
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Erasing player data. <"+str(name)+">")
+
+func create_set_lobby_tag_request(name : String, value) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.SET_LOBBY_TAG,
+ name,
+ value
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Setting lobby tag. <"+str(name)+"><"+str(value)+">")
+
+func create_erase_lobby_tag_request(name : String) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.ERASE_LOBBY_TAG,
+ name
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Erasing lobby tag. <"+str(name)+">")
+
+func create_set_lobby_data_request(name : String, value) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.SET_LOBBY_DATA,
+ name,
+ value
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Setting lobby data. <"+str(name)+"><"+str(value)+">")
+
+func create_erase_lobby_data_request(name : String) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.ERASE_LOBBY_DATA,
+ name
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Erasing lobby data. <"+str(name)+">")
+
+func set_gdsync_owner(node : Node, owner) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.SET_GDSYNC_OWNER,
+ String(node.get_path()),
+ owner
+ ]
+
+ requestsSERV.append(request)
+ logger.write_log("Setting ownership. <"+str(node.get_path())+"><"+str(owner)+">")
+
+func set_connect_time(connect_time : float) -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.SET_CONNECT_TIME,
+ connect_time
+ ]
+
+ requestsSERV.append(request)
+
+func kick_player(client_id : int, reason : String = "") -> void:
+ var request : Array = [
+ ENUMS.REQUEST_TYPE.KICK_PLAYER,
+ client_id
+ ]
+ if !reason.is_empty():
+ request.append(reason)
+
+ requestsSERV.append(request)
+ logger.write_log("Kicking player. <"+str(client_id)+"> Reason: <"+reason+">")
diff --git a/addons/GD-Sync/Scripts/RequestProcessor.gd.uid b/addons/GD-Sync/Scripts/RequestProcessor.gd.uid
new file mode 100644
index 0000000..d84af89
--- /dev/null
+++ b/addons/GD-Sync/Scripts/RequestProcessor.gd.uid
@@ -0,0 +1 @@
+uid://dwrfpxiksh3ve
diff --git a/addons/GD-Sync/Scripts/ServerSwitchController.gd b/addons/GD-Sync/Scripts/ServerSwitchController.gd
new file mode 100644
index 0000000..40ca7c8
--- /dev/null
+++ b/addons/GD-Sync/Scripts/ServerSwitchController.gd
@@ -0,0 +1,287 @@
+extends Node
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+enum _SwitchState {
+ IDLE,
+ CONNECTING_DESTINATION,
+ TUNNELING,
+ JOINING_DESTINATION,
+ ROLLING_BACK,
+ TUNNELING_ROLLBACK,
+ RESTORING_SOURCE,
+}
+
+const _STATE_TIMEOUT_MS : int = 20000
+
+var GDSync
+var connection_controller
+var request_processor
+var session_controller
+var matchmaking_controller
+var logger
+
+var state: _SwitchState = _SwitchState.IDLE
+var _state_deadline: int = 0
+var _reservation_deadline: int = 0
+var source_address: String = ""
+var destination_address: String = ""
+var reservation_id: String = ""
+var proof: String = ""
+var lobby_name: String = ""
+var connect_time: float = 0.0
+var fallback_reservation_id: String = ""
+var rollback_error: int = ENUMS.LOBBY_SWITCH_ERROR.DESTINATION_UNREACHABLE
+var use_websocket: bool = false
+var pending_tunnel_address: String = ""
+
+
+func _ready() -> void:
+ name = "ServerSwitchController"
+ connection_controller = GDSync._connection_controller
+ request_processor = GDSync._request_processor
+ session_controller = GDSync._session_controller
+ matchmaking_controller = GDSync._matchmaking_controller
+ logger = GDSync._logger
+
+
+func begin(data: Dictionary) -> void:
+ reset()
+ source_address = str(data.get("SourceAddress", connection_controller.server_ip))
+ destination_address = str(data.get("Address", ""))
+ reservation_id = str(data.get("ReservationId", ""))
+ proof = str(data.get("Proof", ""))
+ lobby_name = str(data.get("LobbyName", ""))
+ connect_time = float(data.get("ConnectTime", 0.0))
+ fallback_reservation_id = str(data.get("FallbackReservationId", ""))
+ use_websocket = (
+ connection_controller.client is WebSocketPeer
+ or connection_controller.client is WebSocketMultiplayerPeer
+ or connection_controller.is_web_export
+ )
+ if destination_address.is_empty() or reservation_id.is_empty() or proof.is_empty():
+ fail_permanently(ENUMS.LOBBY_SWITCH_ERROR.INVALID_RESERVATION)
+ return
+
+ var expires_in := maxf(float(data.get("ExpiresIn", 20.0)), 1.0)
+ _reservation_deadline = Time.get_ticks_msec() + int(expires_in * 1000.0)
+ _set_state(_SwitchState.CONNECTING_DESTINATION)
+ pending_tunnel_address = destination_address
+ request_processor.clear_for_server_switch()
+ connection_controller.switch_server(destination_address, use_websocket)
+
+
+func is_active() -> bool:
+ return state != _SwitchState.IDLE
+
+
+func _process(_delta : float) -> void:
+ if state == _SwitchState.IDLE: return
+
+ var now : int = Time.get_ticks_msec()
+
+ if _reservation_deadline > 0 and now >= _reservation_deadline:
+ _reservation_deadline = 0
+ _timed_out(ENUMS.LOBBY_SWITCH_ERROR.RESERVATION_EXPIRED)
+ return
+
+ if _state_deadline > 0 and now >= _state_deadline:
+ _timed_out(ENUMS.LOBBY_SWITCH_ERROR.DESTINATION_UNREACHABLE)
+
+
+func _set_state(new_state : _SwitchState) -> void:
+ state = new_state
+
+ if new_state == _SwitchState.IDLE:
+ _state_deadline = 0
+ _reservation_deadline = 0
+ return
+
+ _refresh_state_deadline()
+
+
+func _refresh_state_deadline() -> void:
+ _state_deadline = Time.get_ticks_msec() + _STATE_TIMEOUT_MS
+
+
+func _is_rollback_state() -> bool:
+ return (
+ state == _SwitchState.ROLLING_BACK
+ or state == _SwitchState.TUNNELING_ROLLBACK
+ or state == _SwitchState.RESTORING_SOURCE
+ )
+
+
+func _timed_out(error : int) -> void:
+ logger.write_error("Server switch timed out. <"+str(_SwitchState.keys()[state])+">")
+
+ if _is_rollback_state():
+ fail_permanently(ENUMS.LOBBY_SWITCH_ERROR.ROLLBACK_FAILED)
+ return
+
+ if state == _SwitchState.JOINING_DESTINATION:
+ rollback(ENUMS.LOBBY_SWITCH_ERROR.JOIN_FAILED)
+ return
+
+ rollback(error)
+
+
+func _should_web_tunnel() -> bool:
+ return connection_controller.is_web_export
+
+
+func connection_secured() -> bool:
+ if state == _SwitchState.CONNECTING_DESTINATION:
+ if _should_web_tunnel():
+ _set_state(_SwitchState.TUNNELING)
+ request_processor.create_tunnel_to_request(pending_tunnel_address)
+ return true
+ _join_destination()
+ return true
+ if state == _SwitchState.TUNNELING:
+ _join_destination()
+ return true
+ if state == _SwitchState.ROLLING_BACK:
+ if _should_web_tunnel():
+ _set_state(_SwitchState.TUNNELING_ROLLBACK)
+ request_processor.create_tunnel_to_request(pending_tunnel_address)
+ return true
+ return _restore_source_after_secure()
+ if state == _SwitchState.TUNNELING_ROLLBACK:
+ return _restore_source_after_secure()
+ return false
+
+
+func tunnel_ready() -> void:
+ if state != _SwitchState.TUNNELING and state != _SwitchState.TUNNELING_ROLLBACK:
+ return
+ request_processor.clear_for_server_switch()
+ _refresh_state_deadline()
+ connection_controller.reset_session_keep_socket()
+
+
+func tunnel_local() -> void:
+ if state == _SwitchState.TUNNELING:
+ _join_destination()
+ return
+ if state == _SwitchState.TUNNELING_ROLLBACK:
+ _restore_source_after_secure()
+
+
+func tunnel_failed() -> void:
+ transport_failed()
+
+
+func transport_failed() -> bool:
+ if state == _SwitchState.CONNECTING_DESTINATION or state == _SwitchState.JOINING_DESTINATION or state == _SwitchState.TUNNELING:
+ rollback(ENUMS.LOBBY_SWITCH_ERROR.DESTINATION_UNREACHABLE)
+ return true
+ if state == _SwitchState.ROLLING_BACK or state == _SwitchState.TUNNELING_ROLLBACK or state == _SwitchState.RESTORING_SOURCE:
+ fail_permanently(ENUMS.LOBBY_SWITCH_ERROR.ROLLBACK_FAILED)
+ return true
+ return false
+
+
+func lobby_joined() -> void:
+ if state == _SwitchState.RESTORING_SOURCE:
+ finish_rollback()
+ return
+ if state != _SwitchState.JOINING_DESTINATION:
+ return
+ if !fallback_reservation_id.is_empty():
+ request_processor.create_commit_server_switch_request(
+ source_address,
+ fallback_reservation_id)
+ reset()
+
+
+func lobby_join_failed() -> bool:
+ if state == _SwitchState.RESTORING_SOURCE:
+ fail_permanently(ENUMS.LOBBY_SWITCH_ERROR.ROLLBACK_FAILED)
+ return true
+ if state != _SwitchState.JOINING_DESTINATION:
+ return false
+ rollback(ENUMS.LOBBY_SWITCH_ERROR.JOIN_FAILED)
+ return true
+
+
+func rollback(error: int) -> void:
+ if state == _SwitchState.IDLE or _is_rollback_state():
+ return
+ rollback_error = error
+ _reservation_deadline = 0
+ _set_state(_SwitchState.ROLLING_BACK)
+ pending_tunnel_address = source_address
+ request_processor.clear_for_server_switch()
+ connection_controller.switch_server(source_address, use_websocket)
+
+
+func finish_rollback() -> void:
+ var error := rollback_error
+ reset()
+ GDSync.lobby_switch_failed.emit(error)
+ matchmaking_controller.lobby_join_failed()
+
+
+func fail_permanently(error: int) -> void:
+ var was_switching : bool = state != _SwitchState.IDLE
+ reset()
+
+ if was_switching:
+ connection_controller.reset_multiplayer(true)
+
+ GDSync.lobby_switch_failed.emit(error)
+ matchmaking_controller.lobby_join_failed()
+
+
+func _join_destination() -> void:
+ _set_state(_SwitchState.JOINING_DESTINATION)
+ session_controller.broadcast_player_data()
+ if connect_time > 0.0:
+ request_processor.set_connect_time(connect_time)
+ request_processor.create_join_lobby_with_ticket_request(reservation_id, proof)
+
+
+func _restore_source_after_secure() -> bool:
+ if !fallback_reservation_id.is_empty():
+ _set_state(_SwitchState.RESTORING_SOURCE)
+ request_processor.create_join_lobby_with_ticket_request(fallback_reservation_id, proof)
+ return true
+ finish_rollback()
+ return false
+
+
+func reset() -> void:
+ _set_state(_SwitchState.IDLE)
+ source_address = ""
+ destination_address = ""
+ reservation_id = ""
+ proof = ""
+ lobby_name = ""
+ connect_time = 0.0
+ fallback_reservation_id = ""
+ rollback_error = ENUMS.LOBBY_SWITCH_ERROR.DESTINATION_UNREACHABLE
+ use_websocket = false
+ pending_tunnel_address = ""
diff --git a/addons/GD-Sync/Scripts/ServerSwitchController.gd.uid b/addons/GD-Sync/Scripts/ServerSwitchController.gd.uid
new file mode 100644
index 0000000..0efad20
--- /dev/null
+++ b/addons/GD-Sync/Scripts/ServerSwitchController.gd.uid
@@ -0,0 +1 @@
+uid://blyo1ojsnf7au
diff --git a/addons/GD-Sync/Scripts/SessionController.gd b/addons/GD-Sync/Scripts/SessionController.gd
new file mode 100644
index 0000000..f64f6ca
--- /dev/null
+++ b/addons/GD-Sync/Scripts/SessionController.gd
@@ -0,0 +1,871 @@
+extends Node
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+signal scene_ready
+
+var request_processor
+var connection_controller
+var logger
+var GDSync
+
+var current_client_id : int = -1
+var sender_id : int = -1
+var player_data : Dictionary = {}
+var lobby_data : Dictionary = {}
+
+var node_path_cache : Dictionary = {}
+var node_path_index_cache : Dictionary = {}
+var name_cache : Dictionary = {}
+var name_index_cache : Dictionary = {}
+var resource_reference_cache : Dictionary = {}
+var reference_resource_cache : Dictionary = {}
+
+var owner_cache : Dictionary = {}
+
+var lobby_name : String = ""
+var lobby_password : String = ""
+var own_lobby : bool = false
+var synced_time : float = 0.0
+var multiplayer_clock_synced : bool = false
+var remote_time : float = 0.0
+var remote_time_counter : int = 0
+var remote_time_latency : float = 0.0
+var synced_time_cooldown : float = 0.0
+var events : Array[Dictionary] = []
+
+var current_scene : Node
+var active_scene_change : String = ""
+var scene_ready_list : Array[int] = []
+var _scene_change_elapsed : float = 0.0
+var _scene_change_resolved : bool = false
+
+const _SCENE_CHANGE_TIMEOUT : float = 30.0
+const _SCENE_CHANGE_CLIENT_TIMEOUT : float = 40.0
+
+var ping_sessions : Dictionary = {}
+
+func _ready() -> void:
+ name = "SessionController"
+ GDSync = get_node("/root/GDSync")
+ request_processor = GDSync._request_processor
+ connection_controller = GDSync._connection_controller
+ logger = GDSync._logger
+
+ GDSync.expose_func(sync_timer)
+ GDSync.expose_func(get_timer_latency)
+ GDSync.expose_func(timer_latency_callback)
+ GDSync.expose_func(register_event)
+ GDSync.expose_func(load_scene)
+ GDSync.expose_func(mark_scene_ready)
+ GDSync.expose_func(switch_scene_success)
+ GDSync.expose_func(switch_scene_failed)
+ GDSync.expose_func(ping_send)
+ GDSync.expose_func(ping_return)
+ GDSync.expose_func(emit_signal_remote)
+
+ GDSync.client_joined.connect(client_joined)
+ GDSync.client_left.connect(client_left)
+ GDSync.client_id_changed.connect(client_id_changed)
+ GDSync.host_changed.connect(host_changed)
+
+ get_tree().scene_changed.connect(_on_scene_change)
+ current_scene = get_tree().current_scene
+ if current_scene != null: # Harvest Season patch: no current scene in --script runs (tests, tools)
+ current_scene.tree_exiting.connect(_on_old_scene_exiting)
+
+ randomize()
+ synced_time = randf_range(0, 1000)
+
+func _process(delta):
+ _process_scene_change(delta)
+ if !GDSync.is_active(): return
+ handle_events(delta)
+
+func handle_events(delta : float) -> void:
+ synced_time += delta
+ remote_time += delta
+
+ for event in events:
+ if synced_time >= event["Time"]:
+ GDSync.synced_event_triggered.emit(event["Name"], event["Parameters"])
+ events.erase(event)
+
+ if !GDSync.is_active() || !GDSync.is_host(): return
+
+ synced_time_cooldown -= delta
+ if synced_time_cooldown <= 0.0:
+ synced_time_cooldown = 30.0
+ GDSync.call_func(sync_timer, synced_time)
+
+func sync_timer(time : float) -> void:
+ remote_time = time
+ remote_time_counter = 0
+ remote_time_latency = 0.0
+ multiplayer_clock_synced = true
+
+ if(abs(time - synced_time) > 0.5): synced_time = remote_time
+
+ for i in range(5):
+ await get_tree().process_frame
+ GDSync.call_func_on(GDSync.get_host(), get_timer_latency, GDSync.get_client_id(), Time.get_unix_time_from_system())
+
+func get_timer_latency(client : int, timestamp : float) -> void:
+ GDSync.call_func_on(client, timer_latency_callback, timestamp)
+
+func timer_latency_callback(timestamp : float) -> void:
+ remote_time_counter += 1
+ remote_time_latency += (Time.get_unix_time_from_system()-timestamp)/2.0
+
+ if remote_time_counter >= 5:
+ synced_time = remote_time + remote_time_latency/remote_time_counter
+
+func register_event(event_name : String, time : float, parameters : Array, local : bool = false) -> void:
+ events.append({
+ "Name" : event_name,
+ "Time" : time,
+ "Parameters" : parameters
+ })
+
+ if local:
+ GDSync.call_func(register_event, event_name, time, parameters)
+
+func client_id_changed(client_id : int) -> void:
+ var own_data = null
+ if player_data.has(current_client_id):
+ own_data = player_data[current_client_id]
+ player_data.erase(current_client_id)
+ else:
+ own_data = {
+ "ID" : client_id,
+ "Username" : ""
+ }
+
+ current_client_id = client_id
+ player_data[client_id] = own_data
+
+func broadcast_player_data() -> void:
+ var own_id : int = GDSync.get_client_id()
+ GDSync.player_set_username(get_player_data(own_id, "Username", ""))
+
+ var own_data : Dictionary = GDSync.player_get_all_data(own_id)
+ for key in own_data:
+ if key != "Username":
+ GDSync.player_set_data(key, own_data[key])
+
+func set_lobby_data(name : String, password : String) -> void:
+ synced_time = 0.0
+ multiplayer_clock_synced = false
+ lobby_name = name
+ lobby_password = password
+
+ logger.register_profiler_data("lobby_name", lobby_name)
+ logger.register_profiler_data("lobby_password", password)
+
+func lobby_created() -> void:
+ own_lobby = true
+
+func lobby_left() -> void:
+ var own_id = GDSync.get_client_id()
+
+ lobby_data.clear()
+ node_path_cache.clear()
+ node_path_index_cache.clear()
+ name_cache.clear()
+ name_index_cache.clear()
+ owner_cache.clear()
+ events.clear()
+ sender_id = -1
+ _incoming_caller_id = -1
+
+ lobby_name = ""
+ lobby_password = ""
+ own_lobby = false
+
+ synced_time = 0.0
+ multiplayer_clock_synced = false
+ request_processor.clear_unreliable_nonces()
+
+ if active_scene_change != "":
+ logger.write_error("Scene change aborted, the lobby was left. <"+active_scene_change+">")
+ switch_scene_failed()
+
+ for id in player_data.keys():
+ if id != own_id:
+ player_data.erase(id)
+
+func client_joined(client_id : int) -> void:
+ if client_id == GDSync.get_client_id(): return
+
+ if GDSync.is_host():
+ synced_time_cooldown = 0.0
+
+ for event in events:
+ GDSync.call_func_on(client_id, register_event,
+ event["Name"],
+ event["Time"],
+ event["Parameters"]
+ )
+
+ if active_scene_change != "":
+ GDSync.call_func(load_scene, active_scene_change)
+
+func client_left(id : int) -> void:
+ if player_data.has(id): player_data.erase(id)
+ if scene_ready_list.has(id): scene_ready_list.erase(id)
+ check_scene_ready()
+
+func host_changed(is_host : bool, _new_host_id : int) -> void:
+ if is_host:
+ multiplayer_clock_synced = true
+ check_scene_ready()
+
+func get_all_clients() -> Array:
+ return player_data.keys()
+
+func set_sender_id(id : int) -> void:
+ sender_id = id
+
+func get_sender_id() -> int:
+ return sender_id
+
+var _incoming_caller_id : int = -1
+
+func begin_incoming_request(caller_id : int) -> void:
+ _incoming_caller_id = caller_id
+ if caller_id >= 0:
+ sender_id = caller_id
+
+func end_incoming_request() -> void:
+ _incoming_caller_id = -1
+
+func is_caller_permitted(permission : int, caller_id : int = -1) -> bool:
+ if permission == ENUMS.EXPOSE_PERMISSION.ANYONE:
+ return true
+ if caller_id < 0:
+ caller_id = _incoming_caller_id
+ if caller_id < 0:
+ return false
+ var host_id : int = connection_controller.host
+ match permission:
+ ENUMS.EXPOSE_PERMISSION.HOST:
+ return caller_id == host_id
+ ENUMS.EXPOSE_PERMISSION.CLIENT:
+ return host_id >= 0 and caller_id != host_id
+ return true
+
+func nodepath_is_cached(node_path : String) -> bool:
+ return node_path_cache.has(node_path)
+
+func name_is_cached(name : String) -> bool:
+ return name_cache.has(name)
+
+func get_nodepath_index(node_path : String) -> int:
+ return node_path_cache[node_path]
+
+func get_name_index(name : String) -> int:
+ return name_cache[name]
+
+func get_nodepath_from_index(index : int) -> String:
+ return node_path_index_cache[index]
+
+func get_name_from_index(index : int) -> String:
+ return name_index_cache[index]
+
+func has_nodepath_from_index(index : int) -> bool:
+ return node_path_index_cache.has(index)
+
+func has_name_from_index(index : int) -> bool:
+ return name_index_cache.has(index)
+
+func cache_nodepath(node_path : String, index : int) -> void:
+ if node_path_index_cache.has(index):
+ var oldCachePath : String = node_path_index_cache[index]
+ node_path_cache.erase(oldCachePath)
+
+ node_path_cache[node_path] = index
+ node_path_index_cache[index] = node_path
+
+ var node : Node = get_node_or_null(node_path)
+ if node:
+ var tree : SceneTree = get_tree()
+ await node.tree_exiting
+
+ if !is_instance_valid(tree) or !is_instance_valid(node):
+ return
+
+ await tree.process_frame
+ await tree.process_frame
+ request_processor.create_erase_nodepath_cache_request(index)
+
+func erase_nodepath_cache(index : int) -> void:
+ if node_path_index_cache.has(index):
+ var node_path : String = node_path_index_cache[index]
+ node_path_cache.erase(node_path)
+ node_path_index_cache.erase(index)
+
+func cache_name(name : String, index : int) -> void:
+ if name_index_cache.has(index):
+ var oldCachePath : String = name_index_cache[index]
+ name_cache.erase(oldCachePath)
+
+ name_cache[name] = index
+ name_index_cache[index] = name
+
+func erase_name_cache(index : int) -> void:
+ if name_index_cache.has(index):
+ var name : String = name_index_cache[index]
+ name_cache.erase(name)
+ name_index_cache.erase(index)
+
+func create_resource_reference(resource : RefCounted, id : String) -> void:
+ reference_resource_cache[id] = resource
+ resource_reference_cache[resource] = id
+
+func erase_resource_reference(resource : RefCounted) -> void:
+ if resource_reference_cache.has(resource):
+ var id : String = resource_reference_cache[resource]
+ resource_reference_cache.erase(resource)
+ reference_resource_cache.erase(id)
+
+func has_resource_reference(resource : RefCounted) -> bool:
+ return resource_reference_cache.has(resource)
+
+func get_resource_reference(resource : RefCounted) -> String:
+ return resource_reference_cache[resource]
+
+func has_resource_by_reference(id : String) -> bool:
+ return reference_resource_cache.has(id)
+
+func get_resource_by_reference(id : String) -> RefCounted:
+ return reference_resource_cache[id]
+
+func set_player_data(key : String, value) -> void:
+ player_data[GDSync.get_client_id()][key] = value
+ player_data_changed(GDSync.get_client_id(), key)
+
+func player_data_changed(client_id : int, key : String) -> void:
+ if !player_data.has(client_id): return
+ var data : Dictionary = player_data[client_id]
+ if data.has(key):
+ GDSync.player_data_changed.emit(client_id, key, data[key])
+ else:
+ GDSync.player_data_changed.emit(client_id, key, null)
+
+ logger.register_profiler_data("player_data", player_data)
+
+func erase_player_data(key : String) -> void:
+ if player_data[GDSync.get_client_id()].has(key):
+ player_data[GDSync.get_client_id()].erase(key)
+ player_data_changed(GDSync.get_client_id(), key)
+
+func get_player_data(client_id : int, key : String, default):
+ if player_data.has(client_id):
+ var data : Dictionary = player_data[client_id]
+ if data.has(key):
+ return data[key]
+ return default
+
+func has_player_data(client_id : int, key : String, default) -> bool:
+ if player_data.has(client_id):
+ var data : Dictionary = player_data[client_id]
+ if data.has(key):
+ return true
+ return false
+
+func get_all_player_data(client_id : int) -> Dictionary:
+ if player_data.has(client_id):
+ var data : Dictionary = player_data[client_id]
+ return data
+ return {}
+
+func override_player_data(data : Dictionary) -> void:
+ var id = data["ID"]
+ data.erase(id)
+ if player_data.has(id):
+ player_data[id].clear()
+ else:
+ player_data[id] = {}
+
+ for key in data:
+ player_data[id][key] = data[key]
+
+func override_lobby_data(data : Dictionary) -> void:
+ lobby_data = data
+ logger.register_profiler_data("lobby_data", lobby_data)
+
+func get_lobby_player_limit() -> int:
+ if !lobby_data.has("PlayerLimit"): return 0
+ return lobby_data["PlayerLimit"]
+
+func get_lobby_visibility() -> bool:
+ if !lobby_data.has("Public"): return false
+ return lobby_data["Public"]
+
+func lobby_has_password() -> bool:
+ if lobby_data.has("HasPassword"):
+ return lobby_data["HasPassword"]
+ return false
+
+func lobby_data_changed(key : String) -> void:
+ if !lobby_data.has("Data"): return
+ var data : Dictionary = lobby_data["Data"]
+ if !data.has(key):
+ GDSync.lobby_data_changed.emit(key, null)
+ else:
+ GDSync.lobby_data_changed.emit(key, data[key])
+
+func lobby_tags_changed(key : String) -> void:
+ if !lobby_data.has("Tags"): return
+ var tags : Dictionary = lobby_data["Tags"]
+ if !tags.has(key):
+ GDSync.lobby_tag_changed.emit(key, null)
+ else:
+ GDSync.lobby_tag_changed.emit(key, tags[key])
+
+func has_lobby_data(key : String) -> bool:
+ if !lobby_data.has("Data"): return false
+ var data : Dictionary = lobby_data["Data"]
+ return data.has(key)
+
+func has_lobby_tag(key : String) -> bool:
+ if !lobby_data.has("Tags"): return false
+ var tags : Dictionary = lobby_data["Tags"]
+ return tags.has(key)
+
+func get_lobby_data(key : String, default):
+ if !lobby_data.has("Data"): return
+ var data : Dictionary = lobby_data["Data"]
+ if !data.has(key):
+ return default
+ else:
+ return data[key]
+
+func get_lobby_tag(key : String, default):
+ if !lobby_data.has("Tags"): return
+ var tags : Dictionary = lobby_data["Tags"]
+ if !tags.has(key):
+ return default
+ else:
+ return tags[key]
+
+func get_all_lobby_data() -> Dictionary:
+ if lobby_data.has("Data"):
+ return lobby_data["Data"]
+ else:
+ return {}
+
+func get_all_lobby_tags() -> Dictionary:
+ if lobby_data.has("Tags"):
+ return lobby_data["Tags"]
+ else:
+ return {}
+
+func expose_object(object : Object) -> void:
+ object.set_meta("Exposed", true)
+
+func hide_object(object : Object) -> void:
+ object.set_meta("Exposed", false)
+
+func object_is_exposed(object : Object) -> bool:
+ return object.get_meta("Exposed", false)
+
+func expose_func(function : Callable, permission : int = ENUMS.EXPOSE_PERMISSION.ANYONE) -> void:
+ var object : Object = function.get_object()
+ var functionName : String = function.get_method()
+ var exposedArray : Array = object.get_meta("ExposedFunctions", [])
+ if !exposedArray.has(functionName):
+ exposedArray.append(functionName)
+ object.set_meta("ExposedFunctions", exposedArray)
+
+ var permissions : Dictionary = object.get_meta("ExposedFunctionPermissions", {})
+ permissions[functionName] = permission
+ object.set_meta("ExposedFunctionPermissions", permissions)
+
+ if object is GDScript:
+ create_resource_reference(object, object.resource_path)
+
+func hide_func(function : Callable) -> void:
+ var object : Object = function.get_object()
+ var functionName : String = function.get_method()
+ var exposedArray : Array = object.get_meta("ExposedFunctions", [])
+ if exposedArray.has(functionName): exposedArray.erase(functionName)
+ var permissions : Dictionary = object.get_meta("ExposedFunctionPermissions", {})
+ if permissions.has(functionName): permissions.erase(functionName)
+
+func function_is_exposed(object : Object, function_name : String) -> bool:
+ var exposedArray : Array = object.get_meta("ExposedFunctions", [])
+ return exposedArray.has(function_name)
+
+func get_function_permission(object : Object, function_name : String) -> int:
+ return object.get_meta("ExposedFunctionPermissions", {}).get(function_name, ENUMS.EXPOSE_PERMISSION.ANYONE)
+
+func expose_signal(target_signal : Signal, permission : int = ENUMS.EXPOSE_PERMISSION.ANYONE) -> void:
+ var object : Object = target_signal.get_object()
+ var signal_name : StringName = target_signal.get_name()
+ var exposedArray : Array = object.get_meta("ExposedSignals", [])
+ if !exposedArray.has(signal_name):
+ exposedArray.append(signal_name)
+ object.set_meta("ExposedSignals", exposedArray)
+
+ var permissions : Dictionary = object.get_meta("ExposedSignalPermissions", {})
+ permissions[signal_name] = permission
+ object.set_meta("ExposedSignalPermissions", permissions)
+
+func signal_is_exposed(object : Object, signal_name : StringName) -> bool:
+ var exposedArray : Array = object.get_meta("ExposedSignals", [])
+ return exposedArray.has(signal_name)
+
+func get_signal_permission(object : Object, signal_name : StringName) -> int:
+ return object.get_meta("ExposedSignalPermissions", {}).get(signal_name, ENUMS.EXPOSE_PERMISSION.ANYONE)
+
+func hide_signal(target_signal : Signal) -> void:
+ var exposedArray : Array = target_signal.get_object().get_meta("ExposedSignals", [])
+ var signal_name : StringName = target_signal.get_name()
+ if exposedArray.has(signal_name): exposedArray.erase(signal_name)
+ var permissions : Dictionary = target_signal.get_object().get_meta("ExposedSignalPermissions", {})
+ if permissions.has(signal_name): permissions.erase(signal_name)
+
+func expose_property(object : Object, property_name : String, permission : int = ENUMS.EXPOSE_PERMISSION.ANYONE) -> void:
+ var exposedArray : Array = object.get_meta("ExposedProperties", [])
+ if !exposedArray.has(property_name):
+ exposedArray.append(property_name)
+ object.set_meta("ExposedProperties", exposedArray)
+
+ var permissions : Dictionary = object.get_meta("ExposedPropertyPermissions", {})
+ permissions[property_name] = permission
+ object.set_meta("ExposedPropertyPermissions", permissions)
+
+func hide_property(object : Object, propertyName : String) -> void:
+ var exposedArray : Array = object.get_meta("ExposedProperties", [])
+ if exposedArray.has(propertyName): exposedArray.erase(propertyName)
+ var permissions : Dictionary = object.get_meta("ExposedPropertyPermissions", {})
+ if permissions.has(propertyName): permissions.erase(propertyName)
+
+func property_is_exposed(object : Object, propertyName : String) -> bool:
+ var exposedArray : Array = object.get_meta("ExposedProperties", [])
+ return exposedArray.has(propertyName)
+
+func get_property_permission(object : Object, property_name : String) -> int:
+ return object.get_meta("ExposedPropertyPermissions", {}).get(property_name, ENUMS.EXPOSE_PERMISSION.ANYONE)
+
+func set_gdsync_owner(node : Node, owner) -> void:
+ if owner == null:
+ owner = -1
+ if node.get_meta("gdsyncOwner", -1) == owner:
+ return
+ set_gdsync_owner_remote(node, owner)
+ request_processor.set_gdsync_owner(node, owner)
+
+func set_gdsync_owner_remote(node : Node, owner) -> void:
+ if owner == null:
+ owner = -1
+ var previous_owner = node.get_meta("gdsyncOwner", -1)
+ if previous_owner == owner:
+ return
+
+ var path_string : String = str(node.get_path())
+ if owner_cache.has(path_string): owner_cache.erase(path_string)
+
+ node.set_meta("gdsyncOwner", owner)
+ emit_gdsync_owner_changed(node, owner)
+
+func set_gdsync_owner_delayed(node_path : String, owner) -> void:
+ owner_cache[node_path] = owner
+
+ await get_tree().process_frame
+
+ set_from_owner_cache(node_path)
+
+func set_from_owner_cache(node_path : String) -> void:
+ if !owner_cache.has(node_path): return
+ var owner = owner_cache[node_path]
+ var node : Node = get_node_or_null(node_path)
+ owner_cache.erase(node_path)
+ if node == null: return
+ set_gdsync_owner_remote(node, owner)
+
+func emit_gdsync_owner_changed(node : Node, owner) -> void:
+ if node.has_user_signal("gdsync_owner_changed"): node.emit_signal("gdsync_owner_changed", owner)
+ for child in node.get_children():
+ emit_gdsync_owner_changed(child, owner)
+
+func get_gdsync_owner(node : Node) -> int:
+ if node.is_inside_tree():
+ var path_string : String = str(node.get_path())
+ if owner_cache.has(path_string):
+ set_gdsync_owner_remote(node, owner_cache[path_string])
+
+ var ownerID : int = -1
+ var p : Node = node
+ while p != null and ownerID < 0:
+ if p.has_meta("gdsyncOwner"):
+ var id = p.get_meta("gdsyncOwner", null)
+ if id != null: ownerID = id
+ p = p.get_parent()
+ return ownerID
+
+func is_gdsync_owner(node : Node) -> bool:
+ return get_gdsync_owner(node) == GDSync.get_client_id()
+
+func connect_gdsync_owner_changed(node : Node, callable : Callable) -> void:
+ if !node.has_user_signal("gdsync_owner_changed"):
+ node.add_user_signal("gdsync_owner_changed", ["owner"])
+ node.connect("gdsync_owner_changed", callable)
+
+func disconnect_gdsync_owner_changed(node : Node, callable : Callable) -> void:
+ node.disconnect("gdsync_owner_changed", callable)
+
+func _on_scene_change() -> void:
+ request_processor.end_scene_swap()
+ current_scene = get_tree().current_scene
+ current_scene.tree_exiting.connect(_on_old_scene_exiting)
+
+func _on_old_scene_exiting() -> void:
+ current_scene.tree_exiting.disconnect(_on_old_scene_exiting)
+ request_processor.begin_scene_swap()
+
+func change_scene(scene_path : String) -> void:
+ GDSync.call_func(load_scene, scene_path)
+ load_scene(scene_path)
+
+func load_scene(scene_path : String) -> void:
+ if active_scene_change != "":
+ push_error("Another scene change is already in progress.")
+ return
+
+ scene_ready_list.clear()
+ active_scene_change = scene_path
+ _scene_change_elapsed = 0.0
+ _scene_change_resolved = false
+ GDSync.change_scene_called.emit(scene_path)
+
+ var tree : SceneTree = get_tree()
+ var packed_scene : PackedScene = await load_resource_threaded(tree, scene_path)
+ var new_scene : Node = await instantiate_threaded(tree, packed_scene)
+
+ if new_scene == null:
+ GDSync.call_func(switch_scene_failed)
+ switch_scene_failed()
+ return
+
+ if scene_path != active_scene_change:
+ new_scene.queue_free()
+ return
+
+ var own_id : int = GDSync.get_client_id()
+ GDSync.call_func(mark_scene_ready, own_id)
+ mark_scene_ready(own_id)
+
+ await scene_ready
+ if scene_path != active_scene_change:
+ new_scene.queue_free()
+ return
+
+ var old_scene : Node = tree.current_scene
+
+ new_scene.tree_entered.connect(
+ func set_current_scene() -> void:
+ tree.current_scene = new_scene
+ )
+
+ tree.root.add_child(new_scene)
+ tree.root.remove_child(old_scene)
+ old_scene.free()
+
+ tree.current_scene = new_scene
+
+ active_scene_change = ""
+ request_processor.end_scene_swap()
+
+func _process_scene_change(delta : float) -> void:
+ if active_scene_change == "" or _scene_change_resolved: return
+
+ if !GDSync.is_active():
+ logger.write_error("Scene change aborted, the connection was lost. <"+active_scene_change+">")
+ switch_scene_failed()
+ return
+
+ _scene_change_elapsed += delta
+ var timeout : float = _SCENE_CHANGE_TIMEOUT if GDSync.is_host() else _SCENE_CHANGE_CLIENT_TIMEOUT
+ if _scene_change_elapsed < timeout: return
+
+ logger.write_error("Scene change timed out, not all clients reported ready. <"+active_scene_change+">")
+ if GDSync.is_host(): GDSync.call_func(switch_scene_failed)
+ switch_scene_failed()
+
+func mark_scene_ready(client_id : int) -> void:
+ if active_scene_change == "": return
+ if !scene_ready_list.has(client_id): scene_ready_list.append(client_id)
+ check_scene_ready()
+
+func check_scene_ready() -> void:
+ if active_scene_change == "" or _scene_change_resolved: return
+ if !GDSync.is_host(): return
+
+ for client in get_all_clients():
+ if !scene_ready_list.has(client): return
+
+ GDSync.call_func(switch_scene_success)
+ switch_scene_success()
+
+func switch_scene_success() -> void:
+ if active_scene_change == "": return
+ _scene_change_resolved = true
+ scene_ready_list.clear()
+ GDSync.change_scene_success.emit(active_scene_change)
+ request_processor.begin_scene_swap()
+ scene_ready.emit.call_deferred()
+
+func switch_scene_failed() -> void:
+ if active_scene_change == "": return
+ var scene_path : String = active_scene_change
+ _scene_change_resolved = true
+ scene_ready_list.clear()
+ active_scene_change = ""
+ request_processor.cancel_scene_swap()
+ GDSync.change_scene_failed.emit(scene_path)
+ scene_ready.emit.call_deferred()
+
+func load_resource_threaded(tree : SceneTree, path : String) -> Resource:
+ if connection_controller.is_web_export:
+ return load(path)
+ else:
+ if ResourceLoader.load_threaded_request(path) == OK:
+ while ResourceLoader.load_threaded_get_status(path) == ResourceLoader.ThreadLoadStatus.THREAD_LOAD_IN_PROGRESS:
+ await tree.create_timer(0.05).timeout
+
+ if ResourceLoader.load_threaded_get_status(path) == ResourceLoader.ThreadLoadStatus.THREAD_LOAD_LOADED:
+ return ResourceLoader.load_threaded_get(path)
+
+ return null
+
+func instantiate_threaded(tree : SceneTree, packed_scene : PackedScene) -> Node:
+ if packed_scene == null: return null
+
+ if connection_controller.is_web_export:
+ return packed_scene.instantiate()
+ else:
+ var thread : Thread = Thread.new()
+
+ var callable : Callable = func instantiate(packed_scene : PackedScene):
+ return packed_scene.instantiate()
+
+ thread.start(
+ callable.bind(packed_scene)
+ )
+
+ while thread.is_alive():
+ await tree.create_timer(0.02).timeout
+
+ return thread.wait_to_finish()
+
+func emit_signal_on_clients(clients : Array, target_signal : Signal, params : Array) -> void:
+ var id : String
+ var object : Object = target_signal.get_object()
+ var signal_name : StringName = target_signal.get_name()
+
+ if object is Node:
+ id = String(object.get_path())
+
+ for i in range(10):
+ if object.has_meta("PauseSync"):
+ await get_tree().process_frame
+ elif object is RefCounted:
+ if !has_resource_reference(object):
+ logger.write_error("Creating emit signal request failed, the Resource was not registered. <"+str(object)+"><"+signal_name+">")
+ push_error("Resource must be registered using GDSync.register_resource()")
+ return
+
+ for client in clients:
+ if client == GDSync.get_client_id():
+ emit_signal_remote(id, signal_name, params)
+ else:
+ var permission : int = get_signal_permission(object, signal_name)
+ request_processor.create_function_call_request(emit_signal_remote, [id, signal_name, params], client, true, permission)
+
+func emit_signal_remote(id : String, signal_name : String, params : Array) -> void:
+ var object : Object
+ if has_resource_by_reference(id):
+ object = get_resource_by_reference(id)
+ else:
+ object = get_node_or_null(id)
+
+ if object == null:
+ logger.write_error("Emit signal failed since the Node or Resource was not found. <"+String(id)+"><"+signal_name+">")
+ push_error("Attempted to call nonexistent function \""+signal_name+"\" on "+String(id))
+ return
+
+ if connection_controller.PROTECTED:
+ if !object_is_exposed(object) and !signal_is_exposed(object, signal_name):
+ logger.write_error("Emit signal failed since the object or signal was not exposed. <"+id+"><"+signal_name+">")
+ push_error("Attempted to emit a protected signal \""+signal_name+"\" on "+id+", please expose it using GDSync.expose_signal() or GDSync.expose_node()/GDSync.expose_resource().")
+ return
+ if !object_is_exposed(object):
+ if !is_caller_permitted(get_signal_permission(object, signal_name)):
+ return
+
+ if !object.has_signal(signal_name):
+ logger.write_error("Emit signal failed since the Node or Resource does not contain the specified signal. <"+String(id)+"><"+signal_name+">")
+ push_error("Attempted to emit nonexistent signal \""+signal_name+"\" on "+String(id))
+ return
+
+ var signal_data : Array = [signal_name]
+ signal_data.append_array(params)
+ object.callv("emit_signal", signal_data)
+
+func get_ping(client_id : int, remove_frame_latency : bool) -> float:
+ var rng : RandomNumberGenerator = RandomNumberGenerator.new()
+ rng.randomize()
+ var session_id : int = rng.randi()
+
+ var session_data : Dictionary = {"ping" : 0.0, "count" : 0}
+ ping_sessions[session_id] = session_data
+
+ for i in range(5):
+ var time : float = Time.get_ticks_msec()/1000.0
+ GDSync.call_func_on(client_id, ping_send, GDSync.get_client_id(), session_id, time+(1.0/Engine.get_frames_per_second()) if remove_frame_latency else time, remove_frame_latency)
+ await get_tree().create_timer(0.02).timeout
+
+ for i in range(5):
+ await get_tree().create_timer(0.1).timeout
+ if session_data["count"] == 5: break
+
+ ping_sessions.erase(session_id)
+
+ if session_data["count"] == 0:
+ return -1
+ else:
+ return session_data["ping"]/float(session_data["count"])
+
+func ping_send(origin_client : int, session_id : int, time : float, remove_frame_latency : bool) -> void:
+ GDSync.call_func_on(origin_client, ping_return, session_id, time+(1.0/Engine.get_frames_per_second()) if remove_frame_latency else time, remove_frame_latency)
+
+func ping_return(session_id : int, time : float, remove_frame_latency : bool) -> void:
+ if !ping_sessions.has(session_id): return
+ var ping : float = Time.get_ticks_msec()/1000.0 - (time+(1.0/Engine.get_frames_per_second())) if remove_frame_latency else Time.get_ticks_msec()/1000.0 - time
+ var session_data : Dictionary = ping_sessions[session_id]
+ session_data["count"] = session_data["count"] + 1
+ session_data["ping"] = session_data["ping"] + ping
diff --git a/addons/GD-Sync/Scripts/SessionController.gd.uid b/addons/GD-Sync/Scripts/SessionController.gd.uid
new file mode 100644
index 0000000..bcda0d1
--- /dev/null
+++ b/addons/GD-Sync/Scripts/SessionController.gd.uid
@@ -0,0 +1 @@
+uid://bjit187f25lrk
diff --git a/addons/GD-Sync/Scripts/Steam.gd b/addons/GD-Sync/Scripts/Steam.gd
new file mode 100644
index 0000000..feab596
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Steam.gd
@@ -0,0 +1,138 @@
+extends Node
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+var GDSync
+var data_controller
+var session_controller
+
+var steam_integration_enabled : bool = false
+var steam
+
+var steam_lobby_id : int = 0
+
+func _ready() -> void:
+ name = "Steam"
+ GDSync = get_node("/root/GDSync")
+ data_controller = GDSync._data_controller
+ session_controller = GDSync._session_controller
+
+ steam_integration_enabled = Engine.has_singleton("Steam")
+ if steam_integration_enabled: init_steam()
+
+func init_steam() -> void:
+ steam = Engine.get_singleton("Steam")
+
+ steam.join_requested.connect(_on_lobby_join_requested)
+
+ GDSync.lobby_joined.connect(lobby_joined)
+
+func steam_initialized() -> bool:
+ return steam_integration_enabled and steam.loggedOn()
+
+func _process(delta: float) -> void:
+ if steam_integration_enabled:
+ steam.run_callbacks()
+
+func link_steam_account() -> int:
+ if !steam_initialized():
+ return ENUMS.LINK_STEAM_ACCOUNT_RESPONSE_CODE.STEAM_ERROR
+
+ var ticket_code : int = steam.getAuthTicketForWebApi("gdsync")
+
+ if ticket_code == 0:
+ return ENUMS.LINK_STEAM_ACCOUNT_RESPONSE_CODE.STEAM_ERROR
+
+ var ticket : Array = await steam.get_ticket_for_web_api
+
+ if ticket.size() == 0:
+ return ENUMS.LINK_STEAM_ACCOUNT_RESPONSE_CODE.STEAM_ERROR
+
+ var rawTicket : PackedByteArray = ticket[3]
+ var result : int = await data_controller.link_steam_account(rawTicket, steam.getAppID())
+
+ steam.cancelAuthTicket(ticket_code)
+
+ return result
+
+func unlink_steam_account() -> int:
+ if !steam_initialized():
+ return ENUMS.UNLINK_STEAM_ACCOUNT_RESPONSE_CODE.STEAM_ERROR
+
+ return await data_controller.unlink_steam_account()
+
+func steam_login(valid_time : float) -> Dictionary:
+ if !steam_initialized():
+ return {"Code" : ENUMS.STEAM_LOGIN_RESPONSE_CODE.STEAM_ERROR}
+
+ var ticket_code : int = steam.getAuthTicketForWebApi("gdsync")
+
+ if ticket_code == 0:
+ return {"Code" : ENUMS.STEAM_LOGIN_RESPONSE_CODE.STEAM_ERROR}
+
+ var ticket : Array = await steam.get_ticket_for_web_api
+
+ if ticket.size() == 0:
+ return {"Code" : ENUMS.STEAM_LOGIN_RESPONSE_CODE.STEAM_ERROR}
+
+ var rawTicket : PackedByteArray = ticket[3]
+ var result : Dictionary = await data_controller.steam_login(rawTicket, steam.getAppID(), valid_time)
+
+ steam.cancelAuthTicket(ticket_code)
+
+ return result
+
+func create_steam_lobby() -> void:
+ if !steam_initialized(): return
+ steam.createLobby(steam.LOBBY_TYPE_FRIENDS_ONLY, 250)
+
+ var result : Array = await steam.lobby_created
+
+ if result[0] == 1:
+ steam_lobby_id = result[1]
+
+ steam.setLobbyJoinable(steam_lobby_id, true)
+ steam.setLobbyData(steam_lobby_id, "gdsyncid", session_controller.lobby_name)
+ steam.setLobbyData(steam_lobby_id, "haspassword", str(session_controller.lobby_password != ""))
+
+func leave_steam_lobby() -> void:
+ if !steam_initialized(): return
+ steam.leaveLobby(steam_lobby_id)
+ steam_lobby_id = 0
+
+func _on_lobby_join_requested(lobby_id: int, friend_id: int) -> void:
+ var owner_name : String = steam.getFriendPersonaName(friend_id)
+
+ steam.requestLobbyData(lobby_id)
+ await steam.lobby_data_update
+
+ var lobby_name : String = steam.getLobbyData(lobby_id, "gdsyncid")
+ var has_password : bool = steam.getLobbyData(lobby_id, "haspassword") == "true"
+
+ GDSync.steam_join_request.emit(lobby_name, has_password)
+
+func lobby_joined(lobby_name : String) -> void:
+ if session_controller.own_lobby:
+ create_steam_lobby()
diff --git a/addons/GD-Sync/Scripts/Steam.gd.uid b/addons/GD-Sync/Scripts/Steam.gd.uid
new file mode 100644
index 0000000..9349275
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Steam.gd.uid
@@ -0,0 +1 @@
+uid://dtlmxw5k7qdqa
diff --git a/addons/GD-Sync/Scripts/Types/InterestObject.gd b/addons/GD-Sync/Scripts/Types/InterestObject.gd
new file mode 100644
index 0000000..7e33304
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/InterestObject.gd
@@ -0,0 +1,412 @@
+@tool
+@icon("res://addons/GD-Sync/UI/Icons/InterestObject.png")
+extends Node
+class_name InterestObject
+
+# Copyright (c) 2023-present GD-Sync.
+# All rights reserved.
+#
+# Redistribution and use in source form, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+# 1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+# 2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+## Makes a synchronized entity send its state only to nearby players instead of
+## to everyone. This is the main tool for scaling large worlds without wasting bandwidth.
+## [br][br]Add one InterestObject to every entity you want filtered. That includes players, enemies,
+## projectiles, vehicles, and so on. Players also need an [InterestViewer] so the host
+## knows where they are for distance checks. Spawning is never affected.
+## [NodeInstantiator] always reaches everyone.
+
+signal client_entered(client_id : int)
+signal client_exited(client_id : int)
+
+## Turns range-based filtering on or off for this entity.
+## [br][br]When off, "relevant" calls behave like normal GD-Sync calls and reach every player.
+## Turning this off never affects spawning.
+@export var enabled : bool = true :
+ set(value):
+ enabled = value
+ _force_interest_report()
+## The Node whose position is used as the center of this object.
+## [br][br]Leave this empty to use this node's parent. It must be a [Node2D] or [Node3D].
+## Every synchronizer inside this entity shares this one InterestObject.
+@export var target : NodePath :
+ set(value):
+ target = value
+ _force_interest_report()
+## How far away a player can be and still receive this object's state, in world units (pixels in 2D, meters in 3D).
+## [br][br]The host compares this radius against each player's [InterestViewer] position.
+## Use a larger value for big or important objects, and a smaller one for minor props.
+@export_range(0.0, 1000000.0, 0.1, "or_greater", "suffix:m") var visibility_radius : float = 100.0 :
+ set(value):
+ visibility_radius = value
+ _force_interest_report()
+## Extra distance a player can drift past the radius before this object stops sending to them.
+## [br][br]This stops the object from rapidly starting and stopping updates when a player lingers
+## right at the edge of [member visibility_radius]. Players still have to come within the normal
+## radius to start receiving; they only stop once they move beyond the radius plus this margin.
+@export_range(0.0, 1000000.0, 0.1, "or_greater", "suffix:m") var exit_margin : float = 10.0 :
+ set(value):
+ exit_margin = value
+ _force_interest_report()
+## Which categories this object belongs to.
+## [br][br]A player receives this object only if their [member InterestViewer.interest_layers]
+## shares at least one enabled layer. Use layers to separate things like world objects,
+## indoor areas, teams, or spectator-only content.
+@export_flags_3d_physics var interest_layers : int = 1 :
+ set(value):
+ interest_layers = value
+ _force_interest_report()
+## How many times per second this object rechecks its position to update who is in range.
+## [br][br]Higher values keep the list of nearby players more up to date as the object moves,
+## at a small bandwidth cost. This is ignored when [member is_static] is enabled.
+@export_range(1.0, 30.0, 1.0, "or_greater") var update_rate : float = 5.0
+## Keeps the host receiving this object's state even when the host is out of range.
+## [br][br]Enable this when the host runs authoritative logic such as physics, validation, or
+## anti-cheat and needs every object's state at all times. Disable it when the host is just
+## another player that doesn't need distant objects. Position reports still reach the host either way.
+@export var host_receives_state : bool = true :
+ set(value):
+ host_receives_state = value
+ _force_interest_report()
+## Marks this object as never moving, so it stops re-reporting its position after the first setup.
+## [br][br]Ideal for buildings, pickups, and other fixed props; players moving in and out of range
+## are still handled correctly. Leave this off for anything that can move, such as players,
+## enemies, vehicles, or projectiles.
+@export var is_static : bool = false :
+ set(value):
+ is_static = value
+ _force_interest_report()
+## Hides this entity's parent on your client when you are out of range.
+## [br][br]Works when the parent is a [Node2D], [Node3D], or other [CanvasItem].
+## Does nothing on nodes that cannot be hidden. Your own owned entities are never hidden.
+@export var hide_parent_out_of_range : bool = false :
+ set(value):
+ hide_parent_out_of_range = value
+ notify_property_list_changed()
+ _update_parent_visibility()
+## How long to wait before showing the parent again after you come back in range.
+## [br][br]Only used when [member hide_parent_out_of_range] is enabled. This gives synchronized
+## state time to catch up so the object does not flash at its old position for a frame.
+var show_parent_delay : float = 0.1 :
+ set(value):
+ show_parent_delay = value
+
+var GDSync
+var _recipients : Array[int] = []
+var _cooldown : float = 0.0
+var _force_report : bool = true
+var _last_position : Vector3 = Vector3.INF
+var _last_authority : int = -1
+var _last_settings_hash : int = 0
+var _hid_parent : bool = false
+var _show_parent_token : int = 0
+
+
+func _ready() -> void:
+ if Engine.is_editor_hint():
+ set_process(false)
+ update_configuration_warnings()
+ return
+
+ GDSync = get_node("/root/GDSync")
+ add_to_group("_gdsync_interest")
+ GDSync.host_changed.connect(_host_changed)
+ GDSync.connect_gdsync_owner_changed(self, _owner_changed)
+ GDSync._interest_manager.apply_cached_recipients(self)
+ _force_interest_report()
+ _update_parent_visibility()
+
+
+func _exit_tree() -> void:
+ if Engine.is_editor_hint():
+ return
+ _cancel_scheduled_show()
+ _show_parent_now()
+ if GDSync == null or _last_authority < 0:
+ return
+ GDSync._interest_manager.unregister_object(str(get_path()), _last_authority)
+
+
+func _process(delta : float) -> void:
+ if !GDSync.is_active():
+ return
+ if is_static and !_force_report:
+ return
+
+ var authority_id := _get_authority()
+ if !enabled:
+ if _last_authority == GDSync.get_client_id():
+ GDSync._interest_manager.unregister_object(str(get_path()), _last_authority)
+ _last_authority = -1
+ _recipients.clear()
+ _update_parent_visibility()
+ return
+ if authority_id != GDSync.get_client_id():
+ return
+
+ _cooldown -= delta
+ if !_force_report and _cooldown > 0.0:
+ return
+ _cooldown = 1.0 / maxf(update_rate, 1.0)
+
+ var target_node := _get_target()
+ if target_node == null:
+ return
+ var object_dimension := _get_dimension(target_node)
+ if object_dimension == 0:
+ return
+ var current_position := _get_position(target_node)
+ var settings_hash := hash([
+ object_dimension,
+ visibility_radius,
+ exit_margin,
+ interest_layers,
+ host_receives_state,
+ ])
+ if (
+ !_force_report
+ and current_position.is_equal_approx(_last_position)
+ and authority_id == _last_authority
+ and settings_hash == _last_settings_hash
+ ):
+ return
+
+ _force_report = false
+ _last_position = current_position
+ _last_authority = authority_id
+ _last_settings_hash = settings_hash
+ GDSync._interest_manager.report_object(
+ str(get_path()),
+ authority_id,
+ current_position,
+ object_dimension,
+ visibility_radius,
+ exit_margin,
+ interest_layers,
+ host_receives_state
+ )
+
+
+func _is_gdsync_interest_object_enabled() -> bool:
+ return enabled and GDSync != null and GDSync.is_active()
+
+
+func _get_gdsync_interest_object_recipients() -> Array[int]:
+ return _recipients
+
+
+func _set_gdsync_interest_object_recipients(recipients : Array) -> void:
+ var updated : Array[int] = []
+ for client_id in recipients:
+ updated.append(int(client_id))
+
+ for client_id in updated:
+ if !_recipients.has(client_id):
+ client_entered.emit(client_id)
+ if client_id == GDSync.get_client_id():
+ _notify_synchronized_nodes("_interest_object_local_entered", client_id)
+ elif _last_authority == GDSync.get_client_id():
+ _notify_synchronized_nodes("_interest_object_client_entered", client_id)
+ for client_id in _recipients:
+ if !updated.has(client_id):
+ client_exited.emit(client_id)
+ if client_id != GDSync.get_client_id() and _last_authority == GDSync.get_client_id():
+ _notify_synchronized_nodes("_interest_object_client_exited", client_id)
+ _recipients = updated
+ _update_parent_visibility()
+
+
+func _update_parent_visibility() -> void:
+ if Engine.is_editor_hint() or GDSync == null or !GDSync.is_active():
+ return
+
+ if !hide_parent_out_of_range or !enabled:
+ _restore_parent_visibility()
+ return
+
+ var parent_node := get_parent()
+ if parent_node == null or !_can_hide_node(parent_node):
+ return
+
+ if _get_authority() == GDSync.get_client_id():
+ _restore_parent_visibility()
+ return
+
+ var in_range := _recipients.has(GDSync.get_client_id())
+ if in_range:
+ if _hid_parent:
+ _schedule_show_parent()
+ else:
+ _cancel_scheduled_show()
+ _hide_parent_now()
+
+
+func _hide_parent_now() -> void:
+ var parent_node := get_parent()
+ if parent_node == null or !_can_hide_node(parent_node):
+ return
+ if !_hid_parent:
+ _set_node_visible(parent_node, false)
+ _hid_parent = true
+
+
+func _schedule_show_parent() -> void:
+ _show_parent_token += 1
+ var token := _show_parent_token
+ var delay := maxf(show_parent_delay, 0.0)
+ if delay <= 0.0:
+ _show_parent_now()
+ return
+ _await_show_parent(token, delay)
+
+
+func _await_show_parent(token : int, delay : float) -> void:
+ await get_tree().create_timer(delay).timeout
+ if token != _show_parent_token:
+ return
+ if GDSync == null or !GDSync.is_active() or !hide_parent_out_of_range or !enabled:
+ return
+ if _get_authority() == GDSync.get_client_id():
+ return
+ if !_recipients.has(GDSync.get_client_id()):
+ return
+ _show_parent_now()
+
+
+func _cancel_scheduled_show() -> void:
+ _show_parent_token += 1
+
+
+func _show_parent_now() -> void:
+ if !_hid_parent:
+ return
+ var parent_node := get_parent()
+ if parent_node != null and _can_hide_node(parent_node):
+ _set_node_visible(parent_node, true)
+ _hid_parent = false
+
+
+func _restore_parent_visibility() -> void:
+ _cancel_scheduled_show()
+ _show_parent_now()
+
+
+func _can_hide_node(node : Node) -> bool:
+ return node is CanvasItem or node is Node3D
+
+
+func _set_node_visible(node : Node, visible : bool) -> void:
+ if node is CanvasItem:
+ (node as CanvasItem).visible = visible
+ elif node is Node3D:
+ (node as Node3D).visible = visible
+
+
+func _force_interest_report() -> void:
+ _force_report = true
+ _cooldown = 0.0
+
+
+func _notify_synchronized_nodes(method : StringName, client_id : int) -> void:
+ var branch := get_parent()
+ var candidates : Array[Node] = [branch]
+ candidates.append_array(branch.find_children("*", "", true, false))
+ for candidate in candidates:
+ if (
+ candidate.has_method(method)
+ and GDSync._interest_manager.get_interest_object(candidate) == self
+ ):
+ candidate.call(method, client_id)
+
+
+func _get_authority() -> int:
+ var owner_id : int = GDSync.get_gdsync_owner(self)
+ if owner_id >= 0 and GDSync.lobby_get_all_clients().has(owner_id):
+ return owner_id
+ return GDSync.get_host()
+
+
+func _get_target() -> Node:
+ if target.is_empty():
+ return get_parent()
+ return get_node_or_null(target)
+
+
+func _get_dimension(target_node : Node) -> int:
+ if target_node is Node2D:
+ return 2
+ if target_node is Node3D:
+ return 3
+ return 0
+
+
+func _get_position(target_node : Node) -> Vector3:
+ if target_node is Node2D:
+ var position_2d : Vector2 = target_node.global_position
+ return Vector3(position_2d.x, position_2d.y, 0.0)
+ if target_node is Node3D:
+ return target_node.global_position
+ return Vector3.ZERO
+
+
+func _owner_changed(_owner_id : int) -> void:
+ _force_interest_report()
+
+
+func _host_changed(_is_host : bool, _host_id : int) -> void:
+ _recipients.clear()
+ _force_interest_report()
+ _update_parent_visibility()
+
+
+func _get_property_list() -> Array[Dictionary]:
+ var properties : Array[Dictionary] = []
+ if !hide_parent_out_of_range:
+ return properties
+
+ properties.append({
+ "name": "show_parent_delay",
+ "type": TYPE_FLOAT,
+ "usage": PROPERTY_USAGE_DEFAULT,
+ "hint": PROPERTY_HINT_RANGE,
+ "hint_string": "0,2,0.01,or_greater,suffix:s",
+ })
+ return properties
+
+
+func _get_configuration_warnings() -> PackedStringArray:
+ var warnings : PackedStringArray = []
+ var target_node := _get_target()
+ if target_node == null:
+ warnings.append("Target Node was not found.")
+ elif !(target_node is Node2D) and !(target_node is Node3D):
+ warnings.append("Target must be a Node2D or Node3D.")
+
+ if get_parent() != null:
+ var sibling_count := 0
+ for sibling in get_parent().get_children():
+ if sibling is InterestObject:
+ sibling_count += 1
+ if sibling_count > 1:
+ warnings.append("An entity may have only one sibling InterestObject.")
+ if hide_parent_out_of_range and !_can_hide_node(get_parent()):
+ warnings.append("hide_parent_out_of_range is enabled but the parent cannot be hidden (must be Node2D, Node3D, or CanvasItem).")
+ return warnings
diff --git a/addons/GD-Sync/Scripts/Types/InterestObject.gd.uid b/addons/GD-Sync/Scripts/Types/InterestObject.gd.uid
new file mode 100644
index 0000000..a3afbb0
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/InterestObject.gd.uid
@@ -0,0 +1 @@
+uid://b4rlnnxsj8eak
diff --git a/addons/GD-Sync/Scripts/Types/InterestSource.gd.uid b/addons/GD-Sync/Scripts/Types/InterestSource.gd.uid
new file mode 100644
index 0000000..53bc60d
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/InterestSource.gd.uid
@@ -0,0 +1 @@
+uid://bgowo0c22nfup
diff --git a/addons/GD-Sync/Scripts/Types/InterestViewer.gd b/addons/GD-Sync/Scripts/Types/InterestViewer.gd
new file mode 100644
index 0000000..4647e02
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/InterestViewer.gd
@@ -0,0 +1,141 @@
+@tool
+@icon("res://addons/GD-Sync/UI/Icons/InterestViewer.png")
+extends Node
+class_name InterestViewer
+
+# Copyright (c) 2023-present GD-Sync.
+# All rights reserved.
+#
+# Redistribution and use in source form, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+# 1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+# 2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+## Reports where one player is in the world so the host can run distance checks.
+## [br][br]Add this to every player alongside an [InterestObject]. It only provides the
+## player's viewing position. Range is controlled entirely by each [InterestObject]'s
+## [member InterestObject.visibility_radius]. Enemies, projectiles, and other entities
+## do not need an InterestViewer. They only need an [InterestObject].
+
+## The Node whose position marks where this player is in the world.
+## [br][br]Leave this empty to use this node's parent. It must be a [Node2D] or [Node3D].
+## Only the position is read here, the node itself is never moved or synchronized.
+@export var target : NodePath
+## How many times per second this player's position is sent to the host.
+## [br][br]The host uses this to decide which objects are in range. Higher values make
+## objects appear and disappear more smoothly as the player moves, at a small bandwidth cost.
+## This has nothing to do with how often your actual game state is synchronized.
+@export_range(1.0, 30.0, 1.0, "or_greater") var update_rate : float = 5.0
+## Which categories of objects this player is allowed to receive.
+## [br][br]An [InterestObject] reaches this player only if they share at least one enabled layer.
+## Use layers to group things like world objects, indoor areas, teams, or spectator-only content.
+## Leave every layer enabled if you don't need this kind of separation.
+@export_flags_3d_physics var interest_layers : int = 1
+
+var GDSync
+var _cooldown : float = 0.0
+var _force_report : bool = true
+
+
+func _ready() -> void:
+ if Engine.is_editor_hint():
+ set_process(false)
+ update_configuration_warnings()
+ return
+
+ GDSync = get_node("/root/GDSync")
+ add_to_group("_gdsync_interest")
+ GDSync.host_changed.connect(_host_changed)
+ GDSync.connect_gdsync_owner_changed(self, _owner_changed)
+ _force_interest_report()
+
+func _exit_tree() -> void:
+ if Engine.is_editor_hint() or GDSync == null:
+ return
+ var owner_id : int = GDSync.get_gdsync_owner(self)
+ if owner_id >= 0:
+ GDSync._interest_manager.unregister_viewer(str(get_path()), owner_id)
+
+func _process(delta : float) -> void:
+ if !GDSync.is_active() or !_is_local_viewer():
+ return
+
+ _cooldown -= delta
+ if !_force_report and _cooldown > 0.0:
+ return
+
+ _force_report = false
+ _cooldown = 1.0 / maxf(update_rate, 1.0)
+ var target_node := _get_target()
+ if target_node == null:
+ return
+
+ var viewer_dimension := _get_dimension(target_node)
+ if viewer_dimension == 0:
+ return
+
+ GDSync._interest_manager.report_viewer(
+ str(get_path()),
+ GDSync.get_client_id(),
+ _get_position(target_node),
+ viewer_dimension,
+ interest_layers
+ )
+
+func _force_interest_report() -> void:
+ _force_report = true
+ _cooldown = 0.0
+
+func _is_local_viewer() -> bool:
+ var owner_id : int = GDSync.get_gdsync_owner(self)
+ return owner_id >= 0 and owner_id == GDSync.get_client_id()
+
+func _get_target() -> Node:
+ if target.is_empty():
+ return get_parent()
+ return get_node_or_null(target)
+
+func _get_dimension(target_node : Node) -> int:
+ if target_node is Node2D:
+ return 2
+ if target_node is Node3D:
+ return 3
+ return 0
+
+func _get_position(target_node : Node) -> Vector3:
+ if target_node is Node2D:
+ var position_2d : Vector2 = target_node.global_position
+ return Vector3(position_2d.x, position_2d.y, 0.0)
+ if target_node is Node3D:
+ return target_node.global_position
+ return Vector3.ZERO
+
+func _owner_changed(_owner_id : int) -> void:
+ _force_interest_report()
+
+func _host_changed(_is_host : bool, _host_id : int) -> void:
+ _force_interest_report()
+
+func _get_configuration_warnings() -> PackedStringArray:
+ var target_node := _get_target()
+ if target_node == null:
+ return ["Target Node was not found."]
+ if !(target_node is Node2D) and !(target_node is Node3D):
+ return ["Target must be a Node2D or Node3D."]
+ return []
diff --git a/addons/GD-Sync/Scripts/Types/InterestViewer.gd.uid b/addons/GD-Sync/Scripts/Types/InterestViewer.gd.uid
new file mode 100644
index 0000000..0748367
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/InterestViewer.gd.uid
@@ -0,0 +1 @@
+uid://8f78sl5p1jc5
diff --git a/addons/GD-Sync/Scripts/Types/MatchmakingRequest.gd b/addons/GD-Sync/Scripts/Types/MatchmakingRequest.gd
new file mode 100644
index 0000000..e9ffbe5
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/MatchmakingRequest.gd
@@ -0,0 +1,188 @@
+## Builder for a matchmaking search passed to [method MultiplayerClient.matchmaking_start].
+## [br][br]Construct a request, optionally chain configuration methods, then start matchmaking and handle
+## [signal MultiplayerClient.matchmaking_started], [signal MultiplayerClient.matchmaking_status_changed],
+## [signal MultiplayerClient.matchmaking_match_found], [signal MultiplayerClient.matchmaking_failed], and
+## [signal MultiplayerClient.matchmaking_cancelled]. Starting a new request cancels any active one. Closed
+## lobbies are never joined.
+## [br][br]The constructor [code]player_limit[/code] is the maximum lobby size. [method set_min_players]
+## controls how many queued players are required before a match lobby is created (default: equal to the
+## player limit). After creation, more matching players can join while the lobby stays open.
+## [br][br][b]Methods:[/b] [method set_required_tags], [method set_search_mode],
+## [method set_min_players], [method set_timeout], [method set_skill_rating], [method set_skill_range],
+## [method clear_skill_matching], [method set_lobby_data]. Configuration
+## methods return this request so calls can be chained.
+## [br][br][codeblock]
+## var request := MatchmakingRequest.new(8)
+## request.set_min_players(2)
+## request.set_required_tags({"Mode": "PvP"})
+## request.set_timeout(60.0)
+## GDSync.matchmaking_start(request)
+## [/codeblock]
+class_name MatchmakingRequest
+extends RefCounted
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+## Where a request may find players.
+enum SearchMode {
+ ## Only join existing public lobbies that match tags and player limit. Fails with
+ ## [code]NO_MATCH[/code] if none are available.
+ PUBLIC_ONLY,
+ ## Try public lobbies first, then wait in the matchmaking queue. This is the default.
+ PUBLIC_THEN_MATCHMAKE,
+ ## Skip public lobbies and only use the matchmaking queue.
+ MATCHMAKE_ONLY,
+}
+
+var _player_limit: int
+var _min_players: int = 0
+var _required_tags: Dictionary = {}
+var _search_mode: SearchMode = SearchMode.PUBLIC_THEN_MATCHMAKE
+var _timeout_seconds: float = 0.0
+var _initial_lobby_data: Dictionary = {}
+var _uses_skill: bool = false
+var _skill_rating: float = 0.0
+var _initial_skill_range: float = 0.0
+var _maximum_skill_range: float = 0.0
+var _skill_expansion_per_second: float = 0.0
+
+
+## Creates a request whose lobbies hold up to [param player_limit] players.
+## [br][br]Until [method set_min_players] is called, the minimum to create a lobby equals
+## [param player_limit]. Must be greater than [code]0[/code] and within your plan limit.
+func _init(player_limit: int) -> void:
+ _player_limit = player_limit
+ _min_players = player_limit
+
+
+## Sets all required tags at once, matching [method MultiplayerClient.lobby_create] tags.
+## [br][br]Public lobbies and queued players must include every entry. Replaces any previously
+## set tags. Pass an empty dictionary to clear. Returns this request for chaining.
+func set_required_tags(tags: Dictionary) -> MatchmakingRequest:
+ _required_tags = tags.duplicate(true)
+ return self
+
+
+## Sets whether to search public lobbies, the matchmaking queue, or both.
+## [br][br]See [enum SearchMode]. Defaults to [constant SearchMode.PUBLIC_THEN_MATCHMAKE].
+## Returns this request for chaining.
+func set_search_mode(mode: SearchMode) -> MatchmakingRequest:
+ _search_mode = mode
+ return self
+
+
+## Sets how many queued players are required before a match lobby is created.
+## [br][br]Lobby capacity remains the constructor player limit. For example, a limit of [code]8[/code]
+## with a minimum of [code]2[/code] creates a lobby at two players; others may join until the lobby
+## is full or closed. Must be between [code]1[/code] and the player limit. Defaults to the full
+## player limit. Returns this request for chaining.
+func set_min_players(min_players: int) -> MatchmakingRequest:
+ _min_players = min_players
+ return self
+
+
+## Sets how long to wait before failing with [code]TIMEOUT[/code].
+## [br][br]Use [code]0.0[/code] to wait indefinitely. Returns this request for chaining.
+func set_timeout(seconds: float) -> MatchmakingRequest:
+ _timeout_seconds = seconds
+ return self
+
+
+## Enables skill-based matching using this player's rating.
+## [br][br]If never called, skill is ignored. Use with [method set_skill_range]. Returns this request
+## for chaining.
+func set_skill_rating(rating: float) -> MatchmakingRequest:
+ _uses_skill = true
+ _skill_rating = rating
+ return self
+
+
+## Configures the allowed skill distance from [method set_skill_rating].
+## [br][br]The allowed range starts at [param initial] and may grow toward [param maximum] by
+## [param expansion_per_second] while waiting. Expansion is applied when candidates are evaluated.
+## Returns this request for chaining.
+func set_skill_range(initial: float, maximum: float, expansion_per_second: float = 0.0) -> MatchmakingRequest:
+ _initial_skill_range = initial
+ _maximum_skill_range = maximum
+ _skill_expansion_per_second = expansion_per_second
+ return self
+
+
+## Disables skill matching so only tags, limits, and search mode apply.
+## [br][br]Returns this request for chaining.
+func clear_skill_matching() -> MatchmakingRequest:
+ _uses_skill = false
+ return self
+
+
+## Sets private lobby data at once, matching [method MultiplayerClient.lobby_create] data.
+## [br][br]Applied only to lobbies created by matchmaking (not when joining public lobbies).
+## Replaces any previously set data. Pass an empty dictionary to clear. Returns this request for chaining.
+func set_lobby_data(data: Dictionary) -> MatchmakingRequest:
+ _initial_lobby_data = data.duplicate(true)
+ return self
+
+
+## Returns whether this request can be started. Used internally by the plugin.
+## [br][br]Invalid requests fail with [code]INVALID_REQUEST[/code].
+func _is_valid() -> bool:
+ if _player_limit <= 0:
+ return false
+ var min_players := _min_players if _min_players > 0 else _player_limit
+ if min_players <= 0 or min_players > _player_limit:
+ return false
+ if _search_mode < SearchMode.PUBLIC_ONLY or _search_mode > SearchMode.MATCHMAKE_ONLY:
+ return false
+ if _timeout_seconds < 0.0:
+ return false
+ if var_to_bytes(_required_tags).size() > 2048:
+ return false
+ if var_to_bytes(_initial_lobby_data).size() > 8192:
+ return false
+ if _initial_skill_range < 0.0 or _maximum_skill_range < _initial_skill_range:
+ return false
+ if _skill_expansion_per_second < 0.0:
+ return false
+ return true
+
+
+## Serializes this request for the server. Used internally by the plugin.
+func _to_dictionary() -> Dictionary:
+ var min_players := _min_players if _min_players > 0 else _player_limit
+ var request := {
+ "PlayerLimit": _player_limit,
+ "MinPlayers": min_players,
+ "RequiredTags": _required_tags.duplicate(true),
+ "SearchMode": int(_search_mode),
+ "TimeoutSeconds": _timeout_seconds,
+ "InitialLobbyData": _initial_lobby_data.duplicate(true),
+ "UsesSkill": _uses_skill,
+ }
+ if _uses_skill:
+ request["SkillRating"] = _skill_rating
+ request["InitialSkillRange"] = _initial_skill_range
+ request["MaximumSkillRange"] = _maximum_skill_range
+ request["SkillExpansionPerSecond"] = _skill_expansion_per_second
+ return request
diff --git a/addons/GD-Sync/Scripts/Types/MatchmakingRequest.gd.uid b/addons/GD-Sync/Scripts/Types/MatchmakingRequest.gd.uid
new file mode 100644
index 0000000..5beb788
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/MatchmakingRequest.gd.uid
@@ -0,0 +1 @@
+uid://bai6ti32yg0sj
diff --git a/addons/GD-Sync/Scripts/Types/NodeInstantiator.gd b/addons/GD-Sync/Scripts/Types/NodeInstantiator.gd
new file mode 100644
index 0000000..37a5827
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/NodeInstantiator.gd
@@ -0,0 +1,287 @@
+@tool
+@icon("res://addons/GD-Sync/UI/Icons/NodeInstantiator.png")
+extends Node
+class_name NodeInstantiator
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+func instantiate_node() -> Node:
+ var node : Node = scene.instantiate()
+ read_original_properties(node)
+ var id : int = _assign_instance_id(node)
+ node.name = str(id)
+ node.propagate_call("set_meta", ["PauseSync", false])
+
+ if target:
+ target.add_child(node)
+ else:
+ add_child(node)
+
+ _send_remote_instantiate.call_deferred(node, _original_properties)
+ _call_multiplayer_ready(node)
+ node_instantiated.emit(node)
+ return node
+
+
+
+
+
+#Private functions ----------------------------------------------------------------------
+
+enum SPAWN_TYPE {
+ ## Adds instantiated Nodes to the selected [member target_location].
+ NODE_PATH,
+ ## Adds instantiated Nodes to the current scene.
+ SCENE_ROOT
+}
+
+signal node_instantiated(node : Node)
+
+## Decides where the instantiated Node is added.
+@export var spawn_type : SPAWN_TYPE = SPAWN_TYPE.SCENE_ROOT : set = _set_spawn_type
+## The Node which instantiated Nodes are added to.
+var target_location : NodePath
+var target : Node
+var target_path : String
+## The [PackedScene] which will be instantiated.
+var scene : PackedScene
+## If enabled, when a new Client joins the lobby the NodeInstantiator will make sure
+## to spawn in any Nodes that were spawned in before the Client joined.
+var replicate_on_join : bool = true
+## If enabled, any changes made to the instantiated Node within the same frame will
+## automatically be synchronized across all clients. Changes are only synchronized on the parent Node,
+## not chilren. Also works in combination with [member replicate_on_join].
+## [br][br]As an example, this setting can be useful for when setting the position, direction and
+## speed of a bullet, doing this will set those values on all clients.
+## [br][br]This setting will only synchronize variants, not Objects like Nodes or Resources.
+## If the plugin detects an [Array] or [Dictionary] with an Object in it, it will also not be synchronized.
+var sync_starting_changes : bool = true :
+ set(value):
+ sync_starting_changes = value
+ notify_property_list_changed()
+## Excludes properties from being synced with [member sync_starting_changes].
+var excluded_properties : PackedStringArray = []
+
+const _PERMANENT_EXCLUDED_PROPERTIES : PackedStringArray = [
+ "position",
+ "rotation",
+ "scale"
+]
+
+var GDSync
+
+var _rng : RandomNumberGenerator = RandomNumberGenerator.new()
+var _node_id_list : Dictionary = {}
+
+var _original_properties = null
+
+var replicate_settings = null
+
+func _ready() -> void:
+ if Engine.is_editor_hint(): return
+
+ GDSync = get_node("/root/GDSync")
+ GDSync.expose_func(_instantiate_remote)
+ GDSync.expose_func(_set_target_remote)
+ _rng.randomize()
+
+ if spawn_type == SPAWN_TYPE.SCENE_ROOT:
+ target = get_tree().current_scene
+ elif spawn_type == SPAWN_TYPE.NODE_PATH:
+ target = get_node(target_location)
+
+ if target == null: # Harvest Season patch: no current scene in --script runs (tests, tools)
+ return
+ target_path = str(target.get_path())
+
+ if replicate_settings == null:
+ replicate_settings = [
+ get_path(),
+ sync_starting_changes,
+ excluded_properties,
+ scene.resource_path if scene != null else null,
+ target.get_path(),
+ {}
+ ]
+
+func _call_multiplayer_ready(node : Node) -> void:
+ await get_tree().process_frame
+ if is_instance_valid(node):
+ node.propagate_call("_multiplayer_ready")
+
+func _get_random_id() -> int:
+ var id : int = _rng.randi()
+ if _node_id_list.has(id):
+ return _get_random_id()
+ return id
+
+func _assign_instance_id(node : Node) -> int:
+ var id : int = _get_random_id()
+ var instantiator_path : String = str(get_path())
+ _node_id_list[id] = node
+ node.set_meta("GDID", id)
+ node.set_meta("Instantiator", instantiator_path)
+
+ if replicate_on_join:
+ GDSync._node_tracker.register_replication(node, instantiator_path, replicate_settings)
+
+ _await_id_deletion(node)
+ return id
+
+func _await_id_deletion(node : Node) -> void:
+ await node.tree_exiting
+ var id : int = node.get_meta("GDID")
+
+ if _node_id_list.has(id):
+ _node_id_list.erase(id)
+
+ if replicate_on_join:
+ GDSync._node_tracker.deregister_replication(node)
+
+func _send_remote_instantiate(node : Node, starting_properties : Dictionary) -> void:
+ var changed_properties : Dictionary = {}
+
+ if sync_starting_changes:
+ var new_properties : Dictionary = _get_properties_as_bytes(node)
+
+ for name in starting_properties:
+ if new_properties[name] != starting_properties[name]:
+ var new_value = bytes_to_var(new_properties[name])
+ var type : int = typeof(new_value)
+ match(type):
+ TYPE_OBJECT: continue
+ TYPE_CALLABLE: continue
+ TYPE_SIGNAL: continue
+ TYPE_RID: continue
+ if _PERMANENT_EXCLUDED_PROPERTIES.has(name): continue
+ if excluded_properties.has(name): continue
+ if _contains_object(new_value): continue
+ changed_properties[name] = new_value
+
+ GDSync.call_func(_instantiate_remote, node.get_meta("GDID"), changed_properties)
+ node.propagate_call("remove_meta", ["PauseSync"])
+
+func _contains_object(value) -> bool:
+ if value is Object: return true
+
+ if value is Array:
+ for element in value:
+ if _contains_object(element):
+ return true
+
+ if value is Dictionary:
+ for key in value:
+ if _contains_object(key) or _contains_object(value[key]):
+ return true
+
+ return false
+
+func _set_target_remote(target_path : String) -> void:
+ self.target_path = target_path
+ target = get_node_or_null(target_path)
+
+func _instantiate_remote(id : int, changed_properties : Dictionary) -> void:
+ var instantiator_path : String = str(get_path())
+ var node : Node = scene.instantiate()
+ read_original_properties(node)
+ _node_id_list[id] = node
+ node.set_meta("GDID", id)
+ node.set_meta("Instantiator", instantiator_path)
+ if replicate_on_join:
+ GDSync._node_tracker.register_replication(node, instantiator_path, replicate_settings)
+ _await_id_deletion(node)
+ node.name = str(id)
+
+ if !is_instance_valid(target):
+ target = get_node_or_null(target_path)
+ if target == null:
+ push_error("Instantiate failed, target not found")
+ return
+
+ if target:
+ target.add_child(node)
+ else:
+ add_child(node)
+
+ for name in changed_properties:
+ node.set(name, changed_properties[name])
+
+ node.propagate_call("_multiplayer_ready")
+ node_instantiated.emit(node)
+
+func _get_properties_as_bytes(node : Node) -> Dictionary:
+ var property_values : Dictionary = {}
+ for property in node.get_property_list():
+ var property_name : String = property["name"]
+ if property_name.begins_with("global_"):
+ continue
+ property_values[property_name] = var_to_bytes(node.get(property_name))
+
+ return property_values
+
+func read_original_properties(node : Node) -> void:
+ if _original_properties == null:
+ _original_properties = _get_properties_as_bytes(node)
+ replicate_settings[ENUMS.NODE_REPLICATION_SETTINGS.ORIGINAL_PROPERTIES] = _original_properties
+
+func _set_spawn_type(t : int) -> void:
+ spawn_type = t
+ notify_property_list_changed()
+
+func _get_property_list() -> Array[Dictionary]:
+ var properties : Array[Dictionary] = []
+
+ properties.append({
+ "name" : "target_location",
+ "type" : TYPE_NODE_PATH,
+ "usage" : PROPERTY_USAGE_DEFAULT if spawn_type == SPAWN_TYPE.NODE_PATH else PROPERTY_USAGE_NO_EDITOR
+ })
+
+ properties.append({
+ "name" : "scene",
+ "type" : TYPE_OBJECT,
+ "hint": PROPERTY_HINT_RESOURCE_TYPE,
+ "hint_string" : "PackedScene"
+ })
+
+ properties.append({
+ "name" : "replicate_on_join",
+ "type" : TYPE_BOOL,
+ "usage" : PROPERTY_USAGE_DEFAULT
+ })
+
+ properties.append({
+ "name" : "sync_starting_changes",
+ "type" : TYPE_BOOL,
+ "usage" : PROPERTY_USAGE_DEFAULT
+ })
+
+ properties.append({
+ "name" : "excluded_properties",
+ "type" : TYPE_PACKED_STRING_ARRAY,
+ "usage" : PROPERTY_USAGE_DEFAULT if sync_starting_changes else PROPERTY_USAGE_NO_EDITOR
+ })
+
+ return properties
diff --git a/addons/GD-Sync/Scripts/Types/NodeInstantiator.gd.uid b/addons/GD-Sync/Scripts/Types/NodeInstantiator.gd.uid
new file mode 100644
index 0000000..f2c73eb
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/NodeInstantiator.gd.uid
@@ -0,0 +1 @@
+uid://xe2loijthdk6
diff --git a/addons/GD-Sync/Scripts/Types/PropertySynchronizer.gd b/addons/GD-Sync/Scripts/Types/PropertySynchronizer.gd
new file mode 100644
index 0000000..ef65c4d
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/PropertySynchronizer.gd
@@ -0,0 +1,711 @@
+@tool
+@icon("res://addons/GD-Sync/UI/Icons/SynchronizeIcon.png")
+extends Node
+class_name PropertySynchronizer
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+## Allows you to manually synchronize a property. This function will only synchronize if the
+## property has actually changed.
+## [br][br]If [param forced] is true, it will synchronize regardless of if the property has changed.
+func synchronize(forced : bool = true, force_reliable : bool = false) -> void:
+ for property_index in range(_property_paths.size()):
+ var property_name : String = _property_paths[property_index]
+ if !_property_lookup.has(property_name): continue
+
+ var property_data : Dictionary = _property_lookup[property_name]
+ var new_property = _get_sync_value(property_name)
+ if forced or _check_property_changed(property_data, new_property):
+ var parameters : Array = [
+ _sync_received,
+ property_index,
+ new_property,
+ GDSync.get_multiplayer_time(),
+ ]
+ if force_reliable or reliable:
+ GDSync.call_func_relevant.callv(parameters)
+ else:
+ GDSync.call_func_relevant_unreliable.callv(parameters)
+
+## Temporarily pauses interpolation for [param seconds]. Useful when teleporting a Node from one spot to another to prevent it from gliding there.
+func pause_interpolation(seconds : float) -> void:
+ _pause_interpolation_remote(seconds)
+ GDSync.call_func_relevant(_pause_interpolation_remote, seconds)
+
+
+
+
+
+#Private functions ----------------------------------------------------------------------
+
+enum BROADCAST_MODE {
+ ## Broadcast when you are the host of this lobby.
+ WHEN_HOST,
+ ## Broadcast when you are the not host of this lobby.
+ WHEN_CLIENT,
+ ## Broadcast when you are the owner of this Node or any parent Node.
+ WHEN_OWNER,
+ ## Broadcast on the last valid owner this Node had. If the last valid owner leaves or if no owner was ever assigned, it broadcasts on the host.
+ WHEN_HOST_OR_LAST_VALID_OWNER,
+ ## Broadcast when you are the host of this lobby and this Node has no owner. If it does have an owner, only the owner broadcasts.
+ ## [br]Useful for scenario's like picking up and holding objects, where you want the owner to broadcast
+ ## when the item is picked up. When it is dropped and the owner is removed, the lobby
+ ## host goes back to broadcasting it.
+ WHEN_HOST_AND_NO_OWNER_OR_OWNER,
+ ## Always broadcast. Never recommended.
+ ALWAYS,
+ ## Never broadcast.
+ NEVER,
+}
+
+signal value_changed(property_name : String, new_value)
+
+enum PROCESS_MODE {
+ ## Broadcast during _process().
+ PROCESS,
+ ## Broadcast during _physics_process().
+ PHYSICS_PROCESS,
+}
+
+## Decides when to broadcast the properties to other clients.
+@export var broadcast: BROADCAST_MODE : set = _set_broadcast
+## Whether the properties should synchronize during [method _process] or [method _physics_process].
+@export var process : PROCESS_MODE
+## How many times per second the properties should be synchronized.
+@export var refresh_rate : int = 30
+## The Node on which you want to synchronize properties.
+@export var node_path : NodePath :
+ set(value):
+ node_path = value
+ node = get_node_or_null(node_path)
+ _refresh_property_list()
+ update_configuration_warnings()
+
+## If reliable is enabled, packets that are lost will be
+## resend. We never recommend turning this on unless
+## the synchronized properties are crucial.
+## Enabling this can induce extra latency and data usage.
+@export var reliable : bool = false
+
+## A list of properties you want to synchronize.
+## Supports indexed component paths such as [code]rotation:y[/code] and [code]position:x[/code].
+## Property indices sent over the network are derived from this list's order.
+@export var properties : PackedStringArray = [] : set = _set_properties
+
+## If enabled, properties will be interpolated. This will smooth out the synchronization.
+## Interpolation is only applied to types that support interpolation.
+## [br][br]
+## Interpolation may be temporarily paused with [method pause_interpolation].
+## Useful when teleporting a Node from one spot to another to prevent it from gliding there.
+var interpolated : bool = false :
+ set(value):
+ interpolated = value
+ notify_property_list_changed()
+
+## How fast the chosen property is interpolated.
+## [br][br]It is recommended to keep
+## this number the same or slightly higher than the [member refresh_rate].
+var interpolation_speed : float = 1.0
+
+## If enabled, properties will be extrapolated. This will attempt to slightly mask latency by predicting the next value of the synchronized properties.
+## Extrapolation is applied to floats, Vector2, Vector3, Vector4 and rotation properties.
+var extrapolated : bool = false :
+ set(value):
+ extrapolated = value
+ notify_property_list_changed()
+
+## The maximum amount of time in seconds that extrapolation may predict.
+var max_extrapolation_time : float = 0.2
+
+var GDSync
+
+var node : Node
+
+var _cooldown : float = 0.0
+var _current_cooldown : float = 0.0
+var _interval_cooldown : float = 0.0
+var _should_broadcast : bool = false
+var _last_owner : int = -1
+var _user_wants_interpolation : bool = false
+var _interest_reentry_restore_token : int = 0
+
+var _property_lookup : Dictionary = {}
+var _property_paths : PackedStringArray = []
+
+const _VECTOR2_COMPONENTS : Array[String] = ["x", "y"]
+const _VECTOR3_COMPONENTS : Array[String] = ["x", "y", "z"]
+const _VECTOR4_COMPONENTS : Array[String] = ["x", "y", "z", "w"]
+const _COLOR_COMPONENTS : Array[String] = ["r", "g", "b", "a", "h", "s", "v"]
+
+func _ready() -> void:
+ node = get_node_or_null(node_path)
+ if Engine.is_editor_hint():
+ set_process(false)
+ set_physics_process(false)
+ _refresh_property_lookup()
+ _refresh_property_list()
+ else:
+ assert(node != null, "PropertySynchronizer Node is null")
+
+ GDSync = get_node("/root/GDSync")
+
+ _cooldown = 1.0/refresh_rate
+ _last_owner = GDSync.get_gdsync_owner(self)
+
+ GDSync.expose_func(_sync_received)
+ GDSync.expose_func(_pause_interpolation_remote)
+ GDSync.host_changed.connect(_host_changed)
+ GDSync.client_joined.connect(_client_joined)
+ GDSync.client_left.connect(_client_left)
+ GDSync.connect_gdsync_owner_changed(self, _owner_changed)
+
+ _refresh_property_lookup()
+ _clean_property_lookup()
+ _update_sync_mode()
+ set_process(process == PROCESS_MODE.PROCESS)
+ set_physics_process(process == PROCESS_MODE.PHYSICS_PROCESS)
+
+ if interpolated:
+ interpolated = false
+ await value_changed
+ interpolated = true
+ _user_wants_interpolation = true
+ else:
+ extrapolated = false
+ _user_wants_interpolation = false
+
+func _pause_interpolation_remote(seconds : float) -> void:
+ interpolated = false
+ await get_tree().create_timer(seconds).timeout
+ interpolated = true
+
+func _set_properties(p : PackedStringArray) -> void:
+ properties = p
+ _refresh_property_lookup()
+ update_configuration_warnings()
+
+func _set_broadcast(mode : int) -> void:
+ broadcast = mode
+ _update_sync_mode()
+
+func _owner_changed(owner) -> void:
+ if owner >= 0: _last_owner = owner
+ _update_sync_mode()
+
+func _host_changed(is_host : bool, new_host_id : int) -> void:
+ _update_sync_mode()
+
+func _update_sync_mode() -> void:
+ if Engine.is_editor_hint() || GDSync == null: return
+ var is_host : bool = GDSync.is_host()
+ var is_owner : bool = GDSync.is_gdsync_owner(self)
+ match (broadcast):
+ BROADCAST_MODE.WHEN_HOST:
+ _should_broadcast = is_host
+ BROADCAST_MODE.WHEN_CLIENT:
+ _should_broadcast = !is_host
+ BROADCAST_MODE.WHEN_OWNER:
+ _should_broadcast = is_owner
+ BROADCAST_MODE.WHEN_HOST_OR_LAST_VALID_OWNER:
+ var valid_owner : bool = GDSync.lobby_get_all_clients().has(_last_owner)
+ _should_broadcast = (is_host and !valid_owner) || (valid_owner and _last_owner == GDSync.get_client_id())
+ BROADCAST_MODE.WHEN_HOST_AND_NO_OWNER_OR_OWNER:
+ _should_broadcast = (is_host and GDSync.get_gdsync_owner(self) < 0) || is_owner
+ BROADCAST_MODE.ALWAYS:
+ _should_broadcast = true
+ BROADCAST_MODE.NEVER:
+ _should_broadcast = false
+
+func _process(delta : float) -> void:
+ _check_property_states(delta)
+
+func _physics_process(delta : float) -> void:
+ _check_property_states(delta)
+
+func _check_property_states(delta : float) -> void:
+ if !GDSync.is_active(): return
+ if _should_broadcast:
+ if _may_synchronize(delta):
+ synchronize(false)
+ else:
+ if interpolated: _interpolate(delta)
+ if extrapolated: _extrapolate(delta)
+
+func _check_property_changed(property_data : Dictionary, new_property) -> bool:
+ if property_data["Type"] == TYPE_DICTIONARY:
+ if property_data["TargetValue"] == null or !new_property.recursive_equal(property_data["TargetValue"], 5):
+ property_data["TargetValue"] = new_property.duplicate(true)
+ return true
+
+ if property_data["Type"] == TYPE_ARRAY:
+ if new_property != property_data["TargetValue"]:
+ property_data["TargetValue"] = new_property.duplicate(true)
+ return true
+
+ if new_property != property_data["TargetValue"]:
+ property_data["TargetValue"] = new_property
+ return true
+
+ return false
+
+func _may_synchronize(delta : float) -> bool:
+ _current_cooldown -= delta
+ if _current_cooldown <= 0:
+ _current_cooldown += _cooldown
+ return true
+ return false
+
+func _client_joined(client_id : int) -> void:
+ if GDSync._interest_manager.has_interest_object(self):
+ return
+ if _should_broadcast:
+ synchronize(true, true)
+
+func _interest_object_local_entered(_client_id : int) -> void:
+ if _should_broadcast or !_user_wants_interpolation:
+ return
+ _interest_reentry_restore_token += 1
+ var token := _interest_reentry_restore_token
+ interpolated = false
+ await get_tree().create_timer(0.5).timeout
+ if token != _interest_reentry_restore_token:
+ return
+ if !_should_broadcast and _user_wants_interpolation:
+ interpolated = true
+
+
+func _interest_object_client_entered(client_id : int) -> void:
+ if !_should_broadcast:
+ return
+ for property_index in range(_property_paths.size()):
+ var property_name : String = _property_paths[property_index]
+ if !_property_lookup.has(property_name):
+ continue
+ GDSync.call_func_on(
+ client_id,
+ _sync_received,
+ property_index,
+ _get_sync_value(property_name),
+ GDSync.get_multiplayer_time(),
+ true
+ )
+
+func _client_left(client_id : int) -> void:
+ _update_sync_mode()
+
+func _sync_received(property_index : int, new_value, send_time : float, force_snap : bool = false) -> void:
+ if property_index < 0 or property_index >= _property_paths.size(): return
+
+ var property_name : String = _property_paths[property_index]
+ if !_property_lookup.has(property_name): return
+
+ var property_data : Dictionary = _property_lookup[property_name]
+ property_data["LastValue"] = property_data["TargetValue"]
+ property_data["TargetValue"] = new_value
+ property_data["ReceivedValue"] = new_value
+ property_data["LastSyncTime"] = send_time
+
+ if force_snap:
+ _interest_reentry_restore_token += 1
+ property_data["LastValue"] = new_value
+ _set_sync_value(property_name, new_value)
+ value_changed.emit(property_name, new_value)
+ call_deferred("_restore_interpolation_after_interest_reentry")
+ return
+
+ if !interpolated || !property_data["IsFloating"]:
+ _set_sync_value(property_name, new_value)
+ value_changed.emit(property_name, new_value)
+
+
+func _restore_interpolation_after_interest_reentry() -> void:
+ if _should_broadcast or !_user_wants_interpolation:
+ return
+ interpolated = true
+
+func _is_indexed_property_path(property_path : String) -> bool:
+ return property_path.contains(":")
+
+func _parse_indexed_property_path(property_path : String) -> Dictionary:
+ var parts : PackedStringArray = property_path.split(":", false, 1)
+ return {
+ "BaseName" : parts[0],
+ "Component" : parts[1],
+ }
+
+func _find_property_type(property_name : String, property_list : Array) -> int:
+ for node_property in property_list:
+ if node_property["name"] == property_name:
+ return node_property["type"]
+ return -1
+
+func _is_valid_indexed_component(base_type : int, component : String) -> bool:
+ match base_type:
+ TYPE_VECTOR2:
+ return component in _VECTOR2_COMPONENTS
+ TYPE_VECTOR3:
+ return component in _VECTOR3_COMPONENTS
+ TYPE_VECTOR4:
+ return component in _VECTOR4_COMPONENTS
+ TYPE_COLOR:
+ return component in _COLOR_COMPONENTS
+ return false
+
+func _property_type_is_floating(property_type : int) -> bool:
+ return (
+ property_type == TYPE_INT
+ or property_type == TYPE_FLOAT
+ or property_type == TYPE_VECTOR2
+ or property_type == TYPE_VECTOR3
+ or property_type == TYPE_VECTOR4
+ or property_type == TYPE_COLOR
+ or property_type == TYPE_QUATERNION
+ or property_type == TYPE_BASIS
+ )
+
+func _create_property_metadata(property_path : String, property_list : Array) -> Dictionary:
+ var property_data : Dictionary = {
+ "TargetValue" : null,
+ "ReceivedValue" : null,
+ "LastValue" : null,
+ "LastSyncTime" : 0.0,
+ "Type" : -1,
+ "IsFloating" : false,
+ "Exists" : false,
+ "Indexed" : false,
+ }
+
+ if !_is_indexed_property_path(property_path):
+ var property_type : int = _find_property_type(property_path, property_list)
+ if property_type == -1:
+ return property_data
+
+ property_data["Exists"] = true
+ property_data["Type"] = property_type
+ property_data["IsFloating"] = _property_type_is_floating(property_type)
+ return property_data
+
+ var parsed : Dictionary = _parse_indexed_property_path(property_path)
+ var base_type : int = _find_property_type(parsed["BaseName"], property_list)
+ if base_type == -1 or !_is_valid_indexed_component(base_type, parsed["Component"]):
+ return property_data
+
+ property_data["Indexed"] = true
+ property_data["Exists"] = true
+ property_data["Type"] = TYPE_FLOAT
+ property_data["IsFloating"] = true
+ return property_data
+
+func _get_sync_value(property_path : String):
+ if _is_indexed_property_path(property_path):
+ return node.get_indexed(property_path)
+ return node.get(property_path)
+
+func _set_sync_value(property_path : String, value) -> void:
+ if _is_indexed_property_path(property_path):
+ node.set_indexed(property_path, value)
+ else:
+ node.set(property_path, value)
+
+func _rotation_base_name(property_name : String) -> String:
+ if _is_indexed_property_path(property_name):
+ return _parse_indexed_property_path(property_name)["BaseName"].to_lower()
+ return property_name.to_lower()
+
+func _is_angle_rotation_property(property_name : String, type : int) -> bool:
+ var name : String = _rotation_base_name(property_name)
+ if "degrees" in property_name.to_lower():
+ return false
+ if "velocity" in name or "speed" in name:
+ return false
+ match type:
+ TYPE_FLOAT, TYPE_VECTOR2, TYPE_VECTOR3:
+ return (
+ name == "rotation"
+ or name == "global_rotation"
+ or name.ends_with("_rotation")
+ or name.ends_with("rotation")
+ )
+ return false
+
+func _lerp_rotation_value(current, target, weight : float, type : int):
+ match type:
+ TYPE_FLOAT:
+ return lerp_angle(current, target, weight)
+ TYPE_VECTOR2:
+ return Vector2(
+ lerp_angle(current.x, target.x, weight),
+ lerp_angle(current.y, target.y, weight)
+ )
+ TYPE_VECTOR3:
+ return Vector3(
+ lerp_angle(current.x, target.x, weight),
+ lerp_angle(current.y, target.y, weight),
+ lerp_angle(current.z, target.z, weight)
+ )
+ return lerp(current, target, weight)
+
+func _rotation_delta(last, target, type : int):
+ match type:
+ TYPE_FLOAT:
+ return angle_difference(last, target)
+ TYPE_VECTOR2:
+ return Vector2(
+ angle_difference(last.x, target.x),
+ angle_difference(last.y, target.y)
+ )
+ TYPE_VECTOR3:
+ return Vector3(
+ angle_difference(last.x, target.x),
+ angle_difference(last.y, target.y),
+ angle_difference(last.z, target.z)
+ )
+ return target - last
+
+func _extrapolate_rotation_value(target, delta, extrapolate_time : float, type : int):
+ match type:
+ TYPE_FLOAT:
+ return target + delta * extrapolate_time
+ TYPE_VECTOR2:
+ return Vector2(
+ target.x + delta.x * extrapolate_time,
+ target.y + delta.y * extrapolate_time
+ )
+ TYPE_VECTOR3:
+ return Vector3(
+ target.x + delta.x * extrapolate_time,
+ target.y + delta.y * extrapolate_time,
+ target.z + delta.z * extrapolate_time
+ )
+ return target
+
+func _interpolate(delta : float) -> void:
+ for property_name in _property_lookup:
+ var property_data : Dictionary = _property_lookup[property_name]
+ if !property_data["IsFloating"]: continue
+
+ var current_value = _get_sync_value(property_name)
+ var target_value = property_data.get("TargetValue", current_value)
+
+ if current_value == null || target_value == null: continue
+
+ var weight : float = delta * interpolation_speed
+ var property_type : int = property_data["Type"]
+ var lerped_value
+
+ if property_type == TYPE_BASIS:
+ current_value = current_value.orthonormalized()
+ target_value = target_value.orthonormalized()
+
+ var scale : Vector3 = node.scale
+
+ lerped_value = lerp(current_value, target_value, weight)
+ _set_sync_value(property_name, lerped_value)
+
+ node.scale = scale
+ elif _is_angle_rotation_property(property_name, property_type):
+ lerped_value = _lerp_rotation_value(current_value, target_value, weight, property_type)
+ _set_sync_value(property_name, lerped_value)
+ else:
+ lerped_value = lerp(current_value, target_value, weight)
+ _set_sync_value(property_name, lerped_value)
+
+ value_changed.emit(property_name, lerped_value)
+
+func _extrapolate(delta : float) -> void:
+ for property_name in _property_lookup:
+ var property_data : Dictionary = _property_lookup[property_name]
+ if !property_data["IsFloating"]: continue
+
+ var last_value = property_data.get("LastValue")
+ var target_value = property_data.get("ReceivedValue")
+
+ if last_value == null || target_value == null: continue
+ var extrapolate_time : float = min(GDSync.get_multiplayer_time()-property_data["LastSyncTime"], max_extrapolation_time)
+ var property_type : int = property_data["Type"]
+
+ if _is_angle_rotation_property(property_name, property_type):
+ var angular_delta = _rotation_delta(last_value, target_value, property_type)
+ property_data["TargetValue"] = _extrapolate_rotation_value(target_value, angular_delta, extrapolate_time, property_type)
+ elif (
+ property_type == TYPE_FLOAT
+ or property_type == TYPE_VECTOR2
+ or property_type == TYPE_VECTOR3
+ or property_type == TYPE_VECTOR4
+ ):
+ property_data["TargetValue"] = target_value + (target_value - last_value) * extrapolate_time
+
+func _refresh_property_lookup() -> void:
+ if node == null: return
+ _property_lookup.clear()
+ _property_paths = properties.duplicate()
+
+ var property_list : Array = node.get_property_list()
+ if node.get_script() != null:
+ var script : Script = node.get_script()
+ if script.get_class() != "CSharpScript":
+ property_list.append_array(script.get_script_property_list())
+ elif Engine.is_editor_hint():
+ property_list.append_array(_parse_csharp_properties(script))
+ else:
+ property_list.append_array(script.get_script_property_list())
+ property_list.append_array(_parse_csharp_properties(script))
+
+ for property_name in properties:
+ var property_data : Dictionary = _create_property_metadata(property_name, property_list)
+ if !property_data["Exists"] and !Engine.is_editor_hint():
+ property_data = _create_runtime_property_metadata(property_name)
+ _property_lookup[property_name] = property_data
+
+func _parse_csharp_properties(script : Script) -> Array[Dictionary]:
+ var csharp_code : String = FileAccess.get_file_as_string(script.resource_path)
+ var lines : PackedStringArray = csharp_code.split("\n")
+
+ var variables : Array[Dictionary] = []
+ var inside_method : bool = false
+ var brace_level : int = 0
+ var method_regex : RegEx = RegEx.new()
+ var var_regex : RegEx = RegEx.new()
+ method_regex.compile(r"^(?:public|private|protected|internal|static|virtual|override|sealed|async|new|\s)*\s*\w+\s+\w+\s*\(.*\)\s*\{?$")
+ var_regex.compile(r"^(?:public|private|protected|internal|static|const|readonly|\s)*\s*(\w+)\s+(\w+)\s*(=.*)?;")
+
+ var type_mapping : Dictionary = {
+ "float": TYPE_FLOAT,
+ "Vector2": TYPE_VECTOR2,
+ "Vector3": TYPE_VECTOR3,
+ "Vector4": TYPE_VECTOR4,
+ "Color": TYPE_COLOR,
+ "Quaternion": TYPE_QUATERNION,
+ "Basis": TYPE_BASIS,
+ }
+
+ for line in lines:
+ line = line.strip_edges()
+ if line == "" or line.begins_with("//"):
+ continue
+ brace_level += line.count("{") - line.count("}")
+ if not inside_method:
+ if method_regex.search(line):
+ inside_method = true
+ continue
+ var var_match : RegExMatch = var_regex.search(line)
+ if var_match:
+ var type_name : String = var_match.get_string(1)
+ var var_name : String = var_match.get_string(2)
+ if type_name in type_mapping:
+ variables.append({"name" : var_name, "type" : type_mapping[type_name]})
+ else:
+ if brace_level == 0:
+ inside_method = false
+ return variables
+
+func _create_runtime_property_metadata(property_path : String) -> Dictionary:
+ var property_data : Dictionary = _create_property_metadata(property_path, [])
+ if _is_indexed_property_path(property_path):
+ var parsed : Dictionary = _parse_indexed_property_path(property_path)
+ if !(parsed["BaseName"] in node):
+ return property_data
+ var base_type : int = typeof(node.get(parsed["BaseName"]))
+ if base_type == TYPE_NIL or !_is_valid_indexed_component(base_type, parsed["Component"]):
+ return property_data
+ property_data["Indexed"] = true
+ property_data["Exists"] = true
+ property_data["Type"] = TYPE_FLOAT
+ property_data["IsFloating"] = true
+ return property_data
+ if !(property_path in node):
+ return property_data
+ var value = node.get(property_path)
+ var property_type : int = typeof(value)
+ if property_type == TYPE_NIL:
+ return property_data
+ property_data["Exists"] = true
+ property_data["Type"] = property_type
+ property_data["IsFloating"] = _property_type_is_floating(property_type)
+ return property_data
+
+func _clean_property_lookup() -> void:
+ for property_name in _property_lookup:
+ var property_data : Dictionary = _property_lookup[property_name]
+ if !property_data["Exists"]: _property_lookup.erase(property_name)
+
+func _get_configuration_warnings() -> PackedStringArray:
+ var node : Node = get_node_or_null(node_path)
+ if node == null:
+ return ["No NodePath is specified."]
+
+ var warnings : PackedStringArray = []
+
+ _refresh_property_lookup()
+ for property_name in _property_lookup:
+ var property_data : Dictionary = _property_lookup[property_name]
+ if !property_data["Exists"]:
+ warnings.append("The selected Node does not have the property \""+property_name+"\"")
+
+ return warnings
+
+func _refresh_property_list() -> void:
+ notify_property_list_changed()
+
+func _get_property_list() -> Array[Dictionary]:
+ var properties : Array[Dictionary] = []
+
+ properties.append({
+ "name" : "interpolation",
+ "type" : TYPE_BOOL,
+ "usage" : PROPERTY_USAGE_GROUP
+ })
+
+ properties.append({
+ "name" : "interpolated",
+ "type" : TYPE_BOOL,
+ "usage" : PROPERTY_USAGE_DEFAULT
+ })
+
+ properties.append({
+ "name" : "interpolation_speed",
+ "type" : TYPE_FLOAT,
+ "usage" : PROPERTY_USAGE_DEFAULT if interpolated else PROPERTY_USAGE_NO_EDITOR
+ })
+
+ properties.append({
+ "name" : "extrapolation",
+ "type" : TYPE_BOOL,
+ "usage" : PROPERTY_USAGE_GROUP if interpolated else PROPERTY_USAGE_NO_EDITOR
+ })
+
+ properties.append({
+ "name" : "extrapolated",
+ "type" : TYPE_BOOL,
+ "usage" : PROPERTY_USAGE_DEFAULT if interpolated else PROPERTY_USAGE_NO_EDITOR
+ })
+
+ properties.append({
+ "name" : "max_extrapolation_time",
+ "type" : TYPE_FLOAT,
+ "usage" : PROPERTY_USAGE_DEFAULT if interpolated and extrapolated else PROPERTY_USAGE_NO_EDITOR
+ })
+
+ return properties
diff --git a/addons/GD-Sync/Scripts/Types/PropertySynchronizer.gd.uid b/addons/GD-Sync/Scripts/Types/PropertySynchronizer.gd.uid
new file mode 100644
index 0000000..35fabee
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/PropertySynchronizer.gd.uid
@@ -0,0 +1 @@
+uid://fcoih1ax5dcs
diff --git a/addons/GD-Sync/Scripts/Types/SyncZone.gd.uid b/addons/GD-Sync/Scripts/Types/SyncZone.gd.uid
new file mode 100644
index 0000000..42ed060
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SyncZone.gd.uid
@@ -0,0 +1 @@
+uid://b04bfa1lvmh3h
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedAnimatedSprite2D.gd b/addons/GD-Sync/Scripts/Types/SynchronizedAnimatedSprite2D.gd
new file mode 100644
index 0000000..746239a
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedAnimatedSprite2D.gd
@@ -0,0 +1,197 @@
+@icon("res://addons/GD-Sync/UI/Icons/SynchronizedAnimatedSprite.png")
+extends AnimatedSprite2D
+class_name SynchronizedAnimatedSprite2D
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+func play_synced(name: StringName = &"", custom_speed: float = 1.0, from_end: bool = false) -> void:
+ var send_remote_play : bool = !is_playing() || animation != name
+ play(name, custom_speed, from_end)
+
+ if !GDSync.is_active(): return
+ if !_should_broadcast: return
+ if !send_remote_play: return
+
+ var use_name : bool = name.length() > 0
+ var name_cached : bool = use_name and GDSync._session_controller.name_is_cached(name)
+ var parameters : Array = []
+
+ var defaults_flipped : Array = [false, 1.0, null if name_cached else &""]
+ var actual_values : Array = [
+ from_end,
+ custom_speed,
+ GDSync._session_controller.get_name_index(name) if name_cached else name
+ ]
+
+ var include_all : bool = false
+ for i in range(defaults_flipped.size()):
+ var default = defaults_flipped[i]
+ var actual = actual_values[i]
+ if default != actual:
+ include_all = true
+
+ if include_all:
+ parameters.push_front(actual)
+
+ if name_cached:
+ parameters.push_front(_play_remote_cached)
+ GDSync.call_func_relevant.callv(parameters)
+ else:
+ if use_name:GDSync._request_processor.create_name_cache("", name)
+ parameters.push_front(_play_remote)
+ GDSync.call_func_relevant.callv(parameters)
+
+func play_backwards_synced(name: StringName = &"") -> void:
+ play_backwards(name)
+ if !GDSync.is_active() or !_should_broadcast: return
+ GDSync.call_func_relevant(_play_backwards_remote, name)
+
+func set_frame_and_progress_synced(frame: int, progress: float) -> void:
+ set_frame_and_progress(frame, progress)
+ if !GDSync.is_active() or !_should_broadcast: return
+ GDSync.call_func_relevant(_set_frame_and_progress_remote, frame, progress)
+
+func stop_synced() -> void:
+ stop()
+ if !GDSync.is_active() or !_should_broadcast: return
+ GDSync.call_func_relevant(_stop_remote)
+
+
+
+#Private functions ----------------------------------------------------------------------
+
+var GDSync
+
+var _last_flip_h : bool
+var _last_flip_v : bool
+var _last_speed_scale : float
+var _last_animation : StringName
+var _should_broadcast : bool = false
+var _last_owner : int = -1
+
+func _ready() -> void:
+ GDSync = get_node("/root/GDSync")
+
+ GDSync.expose_func(_play_remote_cached)
+ GDSync.expose_func(_play_remote)
+ GDSync.expose_func(_play_backwards_remote)
+ GDSync.expose_func(_set_frame_and_progress_remote)
+ GDSync.expose_func(_stop_remote)
+ GDSync.expose_func(_refresh_last_changes)
+
+ GDSync.expose_var(self, "flip_h")
+ GDSync.expose_var(self, "flip_v")
+ GDSync.expose_var(self, "speed_scale")
+
+ var timer : Timer = Timer.new()
+ add_child(timer)
+ timer.wait_time = 0.001
+ timer.timeout.connect(_check_for_changes)
+ timer.start()
+
+ _last_owner = GDSync.get_gdsync_owner(self)
+ GDSync.host_changed.connect(_host_changed)
+ GDSync.client_joined.connect(_client_joined)
+ GDSync.connect_gdsync_owner_changed(self, _owner_changed)
+
+ _refresh_last_changes()
+ _update_sync_mode()
+
+func _multiplayer_ready() -> void:
+ _refresh_last_changes()
+ _update_sync_mode()
+
+func _check_for_changes() -> void:
+ if !_has_changed():
+ return
+ if _should_broadcast:
+ _refresh_last_changes()
+ play_synced(animation)
+ GDSync.sync_var_relevant(self, "flip_h")
+ GDSync.sync_var_relevant(self, "flip_v")
+ GDSync.sync_var_relevant(self, "speed_scale")
+ GDSync.call_func_relevant(_refresh_last_changes)
+ else:
+ _refresh_last_changes()
+
+func _refresh_last_changes() -> void:
+ _last_flip_h = flip_h
+ _last_flip_v = flip_v
+ _last_speed_scale = speed_scale
+ _last_animation = animation
+
+func _has_changed() -> bool:
+ return (
+ _last_flip_h != flip_h or
+ _last_flip_v != flip_v or
+ _last_speed_scale != speed_scale or
+ _last_animation != animation
+ )
+
+func _play_remote_cached(name_index = 0, custom_speed : float = 1.0, from_end : bool = false) -> void:
+ if !GDSync._session_controller.has_name_from_index(name_index): return
+ _play_remote(GDSync._session_controller.get_name_from_index(name_index), custom_speed, from_end)
+
+func _play_remote(name : StringName = &"", custom_speed : float = 1.0, from_end : bool = false) -> void:
+ play(name, custom_speed, from_end)
+
+func _play_backwards_remote(name : StringName = &"") -> void:
+ play_backwards(name)
+
+func _set_frame_and_progress_remote(frame : int, progress : float) -> void:
+ set_frame_and_progress(frame, progress)
+
+func _stop_remote() -> void:
+ stop()
+
+func _owner_changed(owner) -> void:
+ if owner >= 0:
+ _last_owner = owner
+ _update_sync_mode()
+
+func _client_joined(_client_id : int) -> void:
+ _update_sync_mode()
+
+func _interest_object_client_entered(client_id : int) -> void:
+ if !_should_broadcast:
+ return
+ GDSync.sync_var_on(client_id, self, "flip_h")
+ GDSync.sync_var_on(client_id, self, "flip_v")
+ GDSync.sync_var_on(client_id, self, "speed_scale")
+ if is_playing():
+ GDSync.call_func_on(client_id, _play_remote, animation, speed_scale, false)
+ GDSync.call_func_on(client_id, _set_frame_and_progress_remote, frame, frame_progress)
+ else:
+ GDSync.call_func_on(client_id, _stop_remote)
+
+func _host_changed(_is_host : bool, _new_host_id : int) -> void:
+ _update_sync_mode()
+
+func _update_sync_mode() -> void:
+ if GDSync == null or !GDSync.is_active():
+ return
+ var is_host : bool = GDSync.is_host()
+ var valid_owner : bool = GDSync.lobby_get_all_clients().has(_last_owner)
+ _should_broadcast = (is_host and !valid_owner) || (valid_owner and _last_owner == GDSync.get_client_id())
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedAnimatedSprite2D.gd.uid b/addons/GD-Sync/Scripts/Types/SynchronizedAnimatedSprite2D.gd.uid
new file mode 100644
index 0000000..3433f32
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedAnimatedSprite2D.gd.uid
@@ -0,0 +1 @@
+uid://dqpkvnosbpdvd
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedAnimationPlayer.gd b/addons/GD-Sync/Scripts/Types/SynchronizedAnimationPlayer.gd
new file mode 100644
index 0000000..ba819fe
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedAnimationPlayer.gd
@@ -0,0 +1,197 @@
+@icon("res://addons/GD-Sync/UI/Icons/SynchronizedAnimationPlayer.png")
+extends AnimationPlayer
+class_name SynchronizedAnimationPlayer
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+## If enabled, GD-Sync will attempt to synchronize the playback of animations across clients.
+@export var sync_playback : bool = true
+
+func play_synced(name: StringName = &"", custom_blend: float = -1, custom_speed: float = 1.0, from_end: bool = false) -> void:
+ var send_remote_play : bool = !is_playing() || current_animation != name
+ play(name, custom_blend, custom_speed, from_end)
+
+ _playing_backwards = from_end
+ _custom_speed = custom_speed
+
+ if !GDSync.is_active(): return
+ if !send_remote_play: return
+
+ var use_name : bool = name.length() > 0
+ var name_cached : bool = use_name and GDSync._session_controller.name_is_cached(name)
+ var parameters : Array = []
+
+ var defaults_flipped : Array = [false, 1.0, -1, null if name_cached else &""]
+ var actual_values : Array = [
+ from_end,
+ custom_speed,
+ custom_blend,
+ GDSync._session_controller.get_name_index(name) if name_cached else name
+ ]
+
+ var include_all : bool = false
+ for i in range(defaults_flipped.size()):
+ var default = defaults_flipped[i]
+ var actual = actual_values[i]
+ if default != actual:
+ include_all = true
+
+ if include_all:
+ parameters.push_front(actual)
+
+ parameters.push_front(GDSync.get_multiplayer_time())
+
+ if name_cached:
+ parameters.push_front(_play_remote_cached)
+ GDSync.call_func_relevant.callv(parameters)
+ else:
+ if use_name:GDSync._request_processor.create_name_cache("", name)
+ parameters.push_front(_play_remote)
+ GDSync.call_func_relevant.callv(parameters)
+
+func play_backwards_synced(name: StringName = &"", custom_blend: float = -1) -> void:
+ self.play(name, custom_blend, -1.0, true)
+
+func pause_synced() -> void:
+ pause()
+ if !GDSync.is_active(): return
+ GDSync.call_func_relevant(_pause_remote)
+
+func stop_synced(keep_state : bool = false) -> void:
+ stop(keep_state)
+ if !GDSync.is_active(): return
+ GDSync.call_func_relevant(_stop_remote, keep_state)
+
+func queue_synced(name : StringName) -> void:
+ queue(name)
+ if !GDSync.is_active(): return
+ GDSync.call_func_relevant(_queue_remote, name)
+
+func seek_synced(seconds : float, update : bool = false, update_only : bool = false) -> void:
+ seek(seconds, update, update_only)
+ if !GDSync.is_active(): return
+
+ var parameters : Array = []
+
+ var defaults_flipped : Array = [false, false]
+ var actual_values : Array = [update_only, update]
+
+ var include_all : bool = false
+ for i in range(defaults_flipped.size()):
+ var default = defaults_flipped[i]
+ var actual = actual_values[i]
+ if default != actual:
+ include_all = true
+
+ if include_all:
+ parameters.push_front(actual)
+
+ parameters.push_front(seconds)
+ parameters.push_front(GDSync.get_multiplayer_time())
+ parameters.push_front(_seek_remote)
+ GDSync.call_func_relevant.callv(parameters)
+
+func advance_synced(delta : float) -> void:
+ advance(delta)
+ if !GDSync.is_active(): return
+ GDSync.call_func_relevant(_advance_remote, delta)
+
+
+
+
+
+
+
+#Private functions ----------------------------------------------------------------------
+
+var GDSync
+
+var _playing_backwards : bool = false
+var _custom_speed : float = 1.0
+
+func _ready() -> void:
+ GDSync = get_node("/root/GDSync")
+
+ GDSync.expose_func(_play_remote)
+ GDSync.expose_func(_play_remote_cached)
+ GDSync.expose_func(_pause_remote)
+ GDSync.expose_func(_stop_remote)
+ GDSync.expose_func(_queue_remote)
+ GDSync.expose_func(_seek_remote)
+ GDSync.expose_func(_advance_remote)
+
+ GDSync.client_joined.connect(_client_joined)
+
+func _client_joined(client_id : int) -> void:
+ if GDSync._interest_manager.has_interest_object(self):
+ return
+ _send_state_to(client_id)
+
+func _interest_object_client_entered(client_id : int) -> void:
+ _send_state_to(client_id)
+
+func _send_state_to(client_id : int) -> void:
+ if is_playing():
+ GDSync.call_func_on(client_id, _stop_remote)
+
+ GDSync.call_func_on(client_id, _play_remote,
+ GDSync.get_multiplayer_time(),
+ current_animation,
+ -1,
+ _custom_speed,
+ _playing_backwards
+ )
+
+ GDSync.call_func_on(client_id, _advance_remote, current_animation_position/_custom_speed)
+
+func _play_remote_cached(start_time : float = 0.0, name_index = 0, custom_blend : float = -1, custom_speed : float = 1.0, from_end : bool = false) -> void:
+ if !GDSync._session_controller.has_name_from_index(name_index): return
+ _play_remote(start_time, GDSync._session_controller.get_name_from_index(name_index), custom_blend, custom_speed, from_end)
+
+func _play_remote(start_time : float = 0.0, name : StringName = &"", custom_blend : float = -1, custom_speed : float = 1.0, from_end : bool = false) -> void:
+ play(name, custom_blend, custom_speed, from_end)
+
+ if sync_playback:
+ var time_passed : float = GDSync.get_multiplayer_time() - start_time
+ if time_passed <= 0.5: advance(time_passed)
+
+func _pause_remote() -> void:
+ pause()
+
+func _queue_remote(name : StringName) -> void:
+ queue(name)
+
+func _stop_remote(keep_state : bool = false) -> void:
+ stop(keep_state)
+
+func _seek_remote(start_time : float, seconds : float, update : bool = false, update_only : bool = false) -> void:
+ seek(seconds, update, update_only)
+
+ if sync_playback:
+ var time_passed : float = GDSync.get_multiplayer_time() - start_time
+ if time_passed < 0.5: advance(time_passed)
+
+func _advance_remote(delta : float) -> void:
+ advance(delta)
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedAnimationPlayer.gd.uid b/addons/GD-Sync/Scripts/Types/SynchronizedAnimationPlayer.gd.uid
new file mode 100644
index 0000000..7c83a64
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedAnimationPlayer.gd.uid
@@ -0,0 +1 @@
+uid://cofugv2v6ssv5
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedAnimationTree.gd b/addons/GD-Sync/Scripts/Types/SynchronizedAnimationTree.gd
new file mode 100644
index 0000000..4a8c1ce
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedAnimationTree.gd
@@ -0,0 +1,214 @@
+@tool
+@icon("res://addons/GD-Sync/UI/Icons/SynchronizedAnimationTree.png")
+extends AnimationTree
+class_name SynchronizedAnimationTree
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+enum BROADCAST_MODE {
+ ## Broadcast when you are the host of this lobby.
+ WHEN_HOST,
+ ## Broadcast when you are the not host of this lobby.
+ WHEN_CLIENT,
+ ## Broadcast when you are the owner of this Node or any parent Node.
+ WHEN_OWNER,
+ ## Broadcast on the last valid owner this Node had. If the last valid owner leaves or if no owner was ever assigned, it broadcasts on the host.
+ WHEN_HOST_OR_LAST_VALID_OWNER,
+ ## Broadcast when you are the host of this lobby and this Node has no owner.
+ ## If it does have an owner, only the owner broadcasts.
+ ## [br]Useful for scenario's like picking up and holding objects, where you want the owner to broadcast
+ ## when the item is picked up. When it is dropped and the owner is removed, the lobby
+ ## host goes back to broadcasting it.
+ WHEN_HOST_AND_NO_OWNER_OR_OWNER,
+ ## Always broadcast. Never recommended.
+ ALWAYS,
+ ## Never broadcast.
+ NEVER,
+}
+
+static var _VARIABLE_INPUTS : PackedStringArray = [
+ "/add_amount",
+ "/blend_amount",
+ "/blend_position"
+]
+
+static var _INSTANT_INPUTS : PackedStringArray = [
+ "/active",
+ "/scale"
+]
+
+## Decides when to broadcast animation changes to other clients.
+@export var broadcast: BROADCAST_MODE : set = _set_broadcast
+## How many times per second the animation tree should check for changes.
+@export var refresh_rate : int = 15
+
+var _current_variable_inputs : Dictionary = {}
+var _current_instant_inputs : Dictionary = {}
+var _state_machines : Dictionary = {}
+var _state_machine_inputs : Dictionary = {}
+
+var _cooldown : float = 0.0
+var _current_cooldown : float = 0.0
+var _should_broadcast : bool = false
+var last_owner : int = -1
+
+var GDSync
+
+func _ready() -> void:
+ if Engine.is_editor_hint():
+ set_process(false)
+ return
+
+ GDSync = get_node("/root/GDSync")
+ _cooldown = 1.0/refresh_rate
+ GDSync.connect_gdsync_owner_changed(self, _owner_changed)
+ GDSync.host_changed.connect(_host_changed)
+ GDSync.expose_func(_travel_remote)
+ GDSync.expose_func(set)
+
+ var property_list : Array = get_property_list()
+
+ for property in property_list:
+ var name : String = property["name"]
+ if "parameters/" in name:
+
+ for variable_input in _VARIABLE_INPUTS:
+ if variable_input in name:
+ _current_variable_inputs[name] = get(name)
+ GDSync.expose_var(self, name)
+ break
+
+ for instant_input in _INSTANT_INPUTS:
+ if instant_input in name:
+ _current_instant_inputs[name] = get(name)
+ GDSync.expose_var(self, name)
+ break
+
+ if "/playback" in name:
+ var state_machine : AnimationNodeStateMachinePlayback = get(name)
+ _state_machines[name] = state_machine
+ _state_machine_inputs[state_machine] = state_machine.get_current_node()
+
+ _update_sync_mode()
+
+ if !_should_broadcast:
+ _update_inputs(_current_variable_inputs, true)
+ _update_inputs(_current_instant_inputs, true)
+ _update_state_machines(true)
+
+func _process(delta: float) -> void:
+ if !_should_broadcast:
+ return
+
+ _update_inputs(_current_instant_inputs)
+
+ _current_cooldown -= delta
+ if _current_cooldown <= 0:
+ _current_cooldown += _cooldown
+
+ _update_inputs(_current_variable_inputs)
+ _update_state_machines()
+
+func _update_inputs(inputs : Dictionary, forced : bool = false) -> void:
+ for input_name in inputs:
+ var old_value = inputs[input_name]
+ var new_value = get(input_name)
+
+ if forced or old_value != new_value:
+ inputs[input_name] = new_value
+
+ if "/active" in input_name:
+ var request : String = input_name.replace("/active", "/request")
+ GDSync.call_func_relevant(
+ set,
+ request,
+ AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE if new_value else AnimationNodeOneShot.ONE_SHOT_REQUEST_ABORT
+ )
+ else:
+ GDSync.sync_var_relevant(self, input_name)
+
+func _update_state_machines(forced : bool = false) -> void:
+ for state_machine_path in _state_machines:
+ var state_machine : AnimationNodeStateMachinePlayback = _state_machines[state_machine_path]
+ var old_node : String = _state_machine_inputs[state_machine]
+ var new_node : String = state_machine.get_current_node()
+
+ if forced or old_node != new_node:
+ _state_machine_inputs[state_machine] = new_node
+ GDSync.call_func_relevant(_travel_remote, state_machine_path, new_node)
+
+func _travel_remote(state_machine_path : String, node_name : String) -> void:
+ var state_machine : AnimationNodeStateMachinePlayback = _state_machines[state_machine_path]
+ state_machine.travel(node_name)
+
+func _interest_object_client_entered(client_id : int) -> void:
+ if !_should_broadcast:
+ return
+ for input_name in _current_variable_inputs:
+ GDSync.sync_var_on(client_id, self, input_name)
+ for input_name in _current_instant_inputs:
+ if "/active" in input_name:
+ var request : String = input_name.replace("/active", "/request")
+ GDSync.call_func_on(
+ client_id,
+ set,
+ request,
+ AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE if get(input_name) else AnimationNodeOneShot.ONE_SHOT_REQUEST_ABORT
+ )
+ for state_machine_path in _state_machines:
+ var state_machine : AnimationNodeStateMachinePlayback = _state_machines[state_machine_path]
+ GDSync.call_func_on(client_id, _travel_remote, state_machine_path, state_machine.get_current_node())
+
+func _host_changed(is_host : bool, new_host_id : int) -> void:
+ _update_sync_mode()
+
+func _owner_changed(owner) -> void:
+ if owner >= 0: last_owner = owner
+ _update_sync_mode()
+
+func _set_broadcast(mode : int) -> void:
+ broadcast = mode
+ _update_sync_mode()
+
+func _update_sync_mode() -> void:
+ if Engine.is_editor_hint() || GDSync == null: return
+ var is_host : bool = GDSync.is_host()
+ var is_owner : bool = GDSync.is_gdsync_owner(self)
+ match (broadcast):
+ BROADCAST_MODE.WHEN_HOST:
+ _should_broadcast = is_host
+ BROADCAST_MODE.WHEN_CLIENT:
+ _should_broadcast = !is_host
+ BROADCAST_MODE.WHEN_OWNER:
+ _should_broadcast = is_owner
+ BROADCAST_MODE.WHEN_HOST_OR_LAST_VALID_OWNER:
+ var valid_owner : bool = GDSync.lobby_get_all_clients().has(last_owner)
+ _should_broadcast = (is_host and !valid_owner) || (valid_owner and last_owner == GDSync.get_client_id())
+ BROADCAST_MODE.WHEN_HOST_AND_NO_OWNER_OR_OWNER:
+ _should_broadcast = (is_host and GDSync.get_gdsync_owner(self) < 0) || is_owner
+ BROADCAST_MODE.ALWAYS:
+ _should_broadcast = true
+ BROADCAST_MODE.NEVER:
+ _should_broadcast = false
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedAnimationTree.gd.uid b/addons/GD-Sync/Scripts/Types/SynchronizedAnimationTree.gd.uid
new file mode 100644
index 0000000..7388a87
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedAnimationTree.gd.uid
@@ -0,0 +1 @@
+uid://blnp51hc3v78q
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer.gd b/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer.gd
new file mode 100644
index 0000000..080617a
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer.gd
@@ -0,0 +1,61 @@
+@icon("res://addons/GD-Sync/UI/Icons/SynchronizedAudioStreamPlayer.png")
+extends AudioStreamPlayer
+class_name SynchronizedAudioStreamPlayer
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+func play_synced(from_position : float = 0.0) -> void:
+ GDSync.sync_var_relevant(self, "volume_db")
+ GDSync.sync_var_relevant(self, "pitch_scale")
+ GDSync.call_func_all_relevant(_play_remote, from_position)
+
+func stop_synced() -> void:
+ GDSync.call_func_all_relevant(_stop_remote)
+
+#Private functions ----------------------------------------------------------------------
+
+var GDSync
+
+func _ready() -> void:
+ GDSync = get_node("/root/GDSync")
+
+ GDSync.expose_var(self, "volume_db")
+ GDSync.expose_var(self, "pitch_scale")
+
+ GDSync.expose_func(_play_remote)
+ GDSync.expose_func(_stop_remote)
+
+func _play_remote(from_position : float) -> void:
+ play(from_position)
+
+func _stop_remote() -> void:
+ stop()
+
+func _interest_object_client_entered(client_id : int) -> void:
+ if !playing:
+ return
+ GDSync.sync_var_on(client_id, self, "volume_db")
+ GDSync.sync_var_on(client_id, self, "pitch_scale")
+ GDSync.call_func_on(client_id, _play_remote, get_playback_position())
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer.gd.uid b/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer.gd.uid
new file mode 100644
index 0000000..dde4f2d
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer.gd.uid
@@ -0,0 +1 @@
+uid://bqmvgr8uw1gt1
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer2D.gd b/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer2D.gd
new file mode 100644
index 0000000..3351da3
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer2D.gd
@@ -0,0 +1,65 @@
+@icon("res://addons/GD-Sync/UI/Icons/SynchronizedAudioStreamPlayer.png")
+extends AudioStreamPlayer2D
+class_name SynchronizedAudioStreamPlayer2D
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+func play_synced(from_position : float = 0.0) -> void:
+ GDSync.sync_var_relevant(self, "volume_db")
+ GDSync.sync_var_relevant(self, "pitch_scale")
+ GDSync.sync_var_relevant(self, "max_distance")
+ GDSync.sync_var_relevant(self, "attenuation")
+ GDSync.call_func_all_relevant(_play_remote, from_position)
+
+func stop_synced() -> void:
+ GDSync.call_func_all_relevant(_stop_remote)
+
+#Private functions ----------------------------------------------------------------------
+
+var GDSync
+
+func _ready() -> void:
+ GDSync = get_node("/root/GDSync")
+
+ GDSync.expose_var(self, "volume_db")
+ GDSync.expose_var(self, "pitch_scale")
+ GDSync.expose_var(self, "max_distance")
+ GDSync.expose_var(self, "attenuation")
+
+ GDSync.expose_func(_play_remote)
+ GDSync.expose_func(_stop_remote)
+
+func _play_remote(from_position : float) -> void:
+ play(from_position)
+
+func _stop_remote() -> void:
+ stop()
+
+func _interest_object_client_entered(client_id : int) -> void:
+ if !playing:
+ return
+ for property_name in ["volume_db", "pitch_scale", "max_distance", "attenuation"]:
+ GDSync.sync_var_on(client_id, self, property_name)
+ GDSync.call_func_on(client_id, _play_remote, get_playback_position())
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer2D.gd.uid b/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer2D.gd.uid
new file mode 100644
index 0000000..38622c5
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer2D.gd.uid
@@ -0,0 +1 @@
+uid://bktq6dqr2x8j5
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer3D.gd b/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer3D.gd
new file mode 100644
index 0000000..6eff2d6
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer3D.gd
@@ -0,0 +1,69 @@
+@icon("res://addons/GD-Sync/UI/Icons/SynchronizedAudioStreamPlayer.png")
+extends AudioStreamPlayer3D
+class_name SynchronizedAudioStreamPlayer3D
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+func play_synced(from_position : float = 0.0) -> void:
+ GDSync.sync_var_relevant(self, "volume_db")
+ GDSync.sync_var_relevant(self, "unit_size")
+ GDSync.sync_var_relevant(self, "max_db")
+ GDSync.sync_var_relevant(self, "pitch_scale")
+ GDSync.sync_var_relevant(self, "max_distance")
+ GDSync.sync_var_relevant(self, "attenuation")
+ GDSync.call_func_all_relevant(_play_remote, from_position)
+
+func stop_synced() -> void:
+ GDSync.call_func_all_relevant(_stop_remote)
+
+#Private functions ----------------------------------------------------------------------
+
+var GDSync
+
+func _ready() -> void:
+ GDSync = get_node("/root/GDSync")
+
+ GDSync.expose_var(self, "volume_db")
+ GDSync.expose_var(self, "unit_size")
+ GDSync.expose_var(self, "max_db")
+ GDSync.expose_var(self, "pitch_scale")
+ GDSync.expose_var(self, "max_distance")
+ GDSync.expose_var(self, "attenuation")
+
+ GDSync.expose_func(_play_remote)
+ GDSync.expose_func(_stop_remote)
+
+func _play_remote(from_position : float) -> void:
+ play(from_position)
+
+func _stop_remote() -> void:
+ stop()
+
+func _interest_object_client_entered(client_id : int) -> void:
+ if !playing:
+ return
+ for property_name in ["volume_db", "unit_size", "max_db", "pitch_scale", "max_distance", "attenuation"]:
+ GDSync.sync_var_on(client_id, self, property_name)
+ GDSync.call_func_on(client_id, _play_remote, get_playback_position())
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer3D.gd.uid b/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer3D.gd.uid
new file mode 100644
index 0000000..4bb2b65
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedAudioStreamPlayer3D.gd.uid
@@ -0,0 +1 @@
+uid://ce0kf7sfcsjfw
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedGPUParticles2D.gd b/addons/GD-Sync/Scripts/Types/SynchronizedGPUParticles2D.gd
new file mode 100644
index 0000000..d9b7d7a
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedGPUParticles2D.gd
@@ -0,0 +1,110 @@
+@icon("res://addons/GD-Sync/UI/Icons/SynchronizedGPUParticles.png")
+extends GPUParticles2D
+class_name SynchronizedGPUParticles2D
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+## Restarts this particle system on all relevant clients with a shared random seed.
+## Useful for one-shot effects such as explosions, impacts, and bursts.
+func restart_synced() -> void:
+ var particle_seed : int = _generate_seed()
+ _sync_particle_properties()
+ GDSync.call_func_all_relevant(_restart_remote, particle_seed)
+
+## Starts emitting on all relevant clients with a shared random seed so the
+## particle look matches across clients.
+func emit_synced() -> void:
+ var particle_seed : int = _generate_seed()
+ _sync_particle_properties()
+ GDSync.call_func_all_relevant(_emit_remote, particle_seed)
+
+## Stops emitting on all relevant clients.
+func stop_synced() -> void:
+ GDSync.call_func_all_relevant(_stop_remote)
+
+
+
+
+#Private functions ----------------------------------------------------------------------
+
+const _SYNCED_PROPERTIES : PackedStringArray = [
+ "amount",
+ "lifetime",
+ "one_shot",
+ "preprocess",
+ "speed_scale",
+ "explosiveness",
+ "randomness",
+ "fixed_fps",
+ "fract_delta",
+ "interpolate",
+ "local_coords",
+]
+
+var GDSync
+var _last_seed : int = 0
+
+func _ready() -> void:
+ use_fixed_seed = true
+ GDSync = get_node("/root/GDSync")
+
+ for property_name in _SYNCED_PROPERTIES:
+ GDSync.expose_var(self, property_name)
+
+ GDSync.expose_func(_restart_remote)
+ GDSync.expose_func(_emit_remote)
+ GDSync.expose_func(_stop_remote)
+
+func _generate_seed() -> int:
+ _last_seed = randi()
+ return _last_seed
+
+func _apply_seed(particle_seed : int) -> void:
+ use_fixed_seed = true
+ seed = particle_seed
+ _last_seed = particle_seed
+
+func _sync_particle_properties() -> void:
+ for property_name in _SYNCED_PROPERTIES:
+ GDSync.sync_var_relevant(self, property_name)
+
+func _restart_remote(particle_seed : int) -> void:
+ _apply_seed(particle_seed)
+ restart(true)
+
+func _emit_remote(particle_seed : int) -> void:
+ _apply_seed(particle_seed)
+ emitting = true
+ restart(true)
+
+func _stop_remote() -> void:
+ emitting = false
+
+func _interest_object_client_entered(client_id : int) -> void:
+ if !emitting:
+ return
+ for property_name in _SYNCED_PROPERTIES:
+ GDSync.sync_var_on(client_id, self, property_name)
+ GDSync.call_func_on(client_id, _restart_remote, _last_seed)
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedGPUParticles2D.gd.uid b/addons/GD-Sync/Scripts/Types/SynchronizedGPUParticles2D.gd.uid
new file mode 100644
index 0000000..35a2b71
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedGPUParticles2D.gd.uid
@@ -0,0 +1 @@
+uid://cla81vxh3ep7b
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedGPUParticles3D.gd b/addons/GD-Sync/Scripts/Types/SynchronizedGPUParticles3D.gd
new file mode 100644
index 0000000..b985cfa
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedGPUParticles3D.gd
@@ -0,0 +1,110 @@
+@icon("res://addons/GD-Sync/UI/Icons/SynchronizedGPUParticles.png")
+extends GPUParticles3D
+class_name SynchronizedGPUParticles3D
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+## Restarts this particle system on all relevant clients with a shared random seed.
+## Useful for one-shot effects such as explosions, impacts, and bursts.
+func restart_synced() -> void:
+ var particle_seed : int = _generate_seed()
+ _sync_particle_properties()
+ GDSync.call_func_all_relevant(_restart_remote, particle_seed)
+
+## Starts emitting on all relevant clients with a shared random seed so the
+## particle look matches across clients.
+func emit_synced() -> void:
+ var particle_seed : int = _generate_seed()
+ _sync_particle_properties()
+ GDSync.call_func_all_relevant(_emit_remote, particle_seed)
+
+## Stops emitting on all relevant clients.
+func stop_synced() -> void:
+ GDSync.call_func_all_relevant(_stop_remote)
+
+
+
+
+#Private functions ----------------------------------------------------------------------
+
+const _SYNCED_PROPERTIES : PackedStringArray = [
+ "amount",
+ "lifetime",
+ "one_shot",
+ "preprocess",
+ "speed_scale",
+ "explosiveness",
+ "randomness",
+ "fixed_fps",
+ "fract_delta",
+ "interpolate",
+ "local_coords",
+]
+
+var GDSync
+var _last_seed : int = 0
+
+func _ready() -> void:
+ use_fixed_seed = true
+ GDSync = get_node("/root/GDSync")
+
+ for property_name in _SYNCED_PROPERTIES:
+ GDSync.expose_var(self, property_name)
+
+ GDSync.expose_func(_restart_remote)
+ GDSync.expose_func(_emit_remote)
+ GDSync.expose_func(_stop_remote)
+
+func _generate_seed() -> int:
+ _last_seed = randi()
+ return _last_seed
+
+func _apply_seed(particle_seed : int) -> void:
+ use_fixed_seed = true
+ seed = particle_seed
+ _last_seed = particle_seed
+
+func _sync_particle_properties() -> void:
+ for property_name in _SYNCED_PROPERTIES:
+ GDSync.sync_var_relevant(self, property_name)
+
+func _restart_remote(particle_seed : int) -> void:
+ _apply_seed(particle_seed)
+ restart(true)
+
+func _emit_remote(particle_seed : int) -> void:
+ _apply_seed(particle_seed)
+ emitting = true
+ restart(true)
+
+func _stop_remote() -> void:
+ emitting = false
+
+func _interest_object_client_entered(client_id : int) -> void:
+ if !emitting:
+ return
+ for property_name in _SYNCED_PROPERTIES:
+ GDSync.sync_var_on(client_id, self, property_name)
+ GDSync.call_func_on(client_id, _restart_remote, _last_seed)
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedGPUParticles3D.gd.uid b/addons/GD-Sync/Scripts/Types/SynchronizedGPUParticles3D.gd.uid
new file mode 100644
index 0000000..ec4a200
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedGPUParticles3D.gd.uid
@@ -0,0 +1 @@
+uid://dhtpleux5en4e
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedRigidBody2D.gd b/addons/GD-Sync/Scripts/Types/SynchronizedRigidBody2D.gd
new file mode 100644
index 0000000..bc997e8
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedRigidBody2D.gd
@@ -0,0 +1,247 @@
+@tool
+@icon("res://addons/GD-Sync/UI/Icons/SynchronizedRigidBody3D.png")
+extends RigidBody2D
+class_name SynchronizedRigidBody2D
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+## How many times per second the body should be synchronized.
+@export var refresh_rate : int = 30
+
+func apply_central_impulse_synced(impulse : Vector2 = Vector2.ZERO) -> void:
+ super.apply_central_impulse(impulse)
+ await get_tree().physics_frame
+ if !GDSync.is_gdsync_owner(self):
+ GDSync.set_gdsync_owner(self, GDSync.get_client_id())
+
+func apply_central_force_synced(force : Vector2) -> void:
+ super.apply_central_force(force)
+ await get_tree().physics_frame
+ if !GDSync.is_gdsync_owner(self):
+ GDSync.set_gdsync_owner(self, GDSync.get_client_id())
+
+func apply_impulse_synced(impulse: Vector2, position: Vector2 = Vector2(0, 0)) -> void:
+ super.apply_impulse(impulse, position)
+ await get_tree().physics_frame
+ if !GDSync.is_gdsync_owner(self):
+ GDSync.set_gdsync_owner(self, GDSync.get_client_id())
+
+func apply_force_synced(force: Vector2, position: Vector2 = Vector2(0, 0)) -> void:
+ super.apply_force(force, position)
+ await get_tree().physics_frame
+ if !GDSync.is_gdsync_owner(self):
+ GDSync.set_gdsync_owner(self, GDSync.get_client_id())
+
+func apply_torque_synced(torque: float) -> void:
+ super.apply_torque(torque)
+ await get_tree().physics_frame
+ if !GDSync.is_gdsync_owner(self):
+ GDSync.set_gdsync_owner(self, GDSync.get_client_id())
+
+func apply_torque_impulse_synced(impulse: float) -> void:
+ super.apply_torque_impulse(impulse)
+ await get_tree().physics_frame
+ if !GDSync.is_gdsync_owner(self):
+ GDSync.set_gdsync_owner(self, GDSync.get_client_id())
+
+
+
+
+
+#Private functions ----------------------------------------------------------------------
+
+var GDSync
+
+var _cooldown : float = 0.0
+var _current_cooldown : float = 0.0
+var _current_fixed_cooldown : float = 0.0
+var _should_broadcast : bool = false
+var _last_owner : int = -1
+
+var _pending_sync : bool = true
+var _force_sync : bool = false
+var _pending_correction : bool = false
+
+var _remote_position : Vector2
+var _remote_rotation : float
+var _remote_linear_velocity : Vector2
+var _remote_angular_velocity : float
+
+var _disable_correction_counter : int = 0
+
+var _last_sync_position : Vector2 = Vector2.ZERO
+var _last_sync_rotation : float = 0.0
+var _last_sync_linear_velocity : Vector2 = Vector2.ZERO
+var _last_sync_angular_velocity : float = 0.0
+
+const _FIXED_COOLDOWN : float = 10.0
+const _SYNC_LINEAR_VELOCITY_THRESHOLD : float = 0.1
+const _SYNC_ANGULAR_VELOCITY_THRESHOLD : float = 0.05
+const _SYNC_ROTATION_THRESHOLD : float = 0.01
+const _SYNC_POSITION_THRESHOLD : float = 0.01
+const _CORRECTION_ROTATION_THRESHOLD : float = 0.03
+const _CORRECTION_LINEAR_VELOCITY_THRESHOLD : float = 0.1
+const _CORRECTION_ANGULAR_VELOCITY_THRESHOLD : float = 0.05
+const _CORRECTION_POSITION_THRESHOLD : float = 0.01
+
+func _ready() -> void:
+ if !Engine.is_editor_hint():
+ GDSync = get_node("/root/GDSync")
+
+ _cooldown = 1.0/refresh_rate
+ _last_owner = GDSync.get_gdsync_owner(self)
+ can_sleep = false
+
+ GDSync.expose_func(_sync_received)
+
+ GDSync.host_changed.connect(_host_changed)
+ GDSync.client_joined.connect(_client_joined)
+ GDSync.connect_gdsync_owner_changed(self, _owner_changed)
+
+ _update_sync_mode()
+ _current_fixed_cooldown = 2.0
+
+func _physics_process(delta: float) -> void:
+ if _should_broadcast:
+ if _may_synchronize(delta):
+ var current_rot : float = global_transform.get_rotation()
+ var rot_diff : float = current_rot - _last_sync_rotation
+ if (
+ _force_sync or
+ abs((global_transform.origin - _last_sync_position).length_squared()) > _SYNC_POSITION_THRESHOLD or
+ abs((linear_velocity - _last_sync_linear_velocity).length_squared()) > _SYNC_LINEAR_VELOCITY_THRESHOLD or
+ abs(angular_velocity - _last_sync_angular_velocity) > _SYNC_ANGULAR_VELOCITY_THRESHOLD or
+ abs(rot_diff) > _SYNC_ROTATION_THRESHOLD
+ ):
+ _last_sync_linear_velocity = linear_velocity
+ _last_sync_angular_velocity = angular_velocity
+ _last_sync_position = global_transform.origin
+ _last_sync_rotation = current_rot
+ _pending_sync = true
+ _force_sync = false
+ else:
+ _remote_position += _remote_linear_velocity * delta
+ _remote_rotation += _remote_angular_velocity * delta
+
+func _may_synchronize(delta : float) -> bool:
+ _current_cooldown -= delta
+ if _current_cooldown <= 0:
+ _current_cooldown += _cooldown
+ return true
+
+ _current_fixed_cooldown -= delta
+ if _current_fixed_cooldown <= 0.0:
+ _current_fixed_cooldown += _FIXED_COOLDOWN
+ _force_sync = true
+ return true
+ return false
+
+func _integrate_forces(state: PhysicsDirectBodyState2D) -> void:
+ if _should_broadcast:
+ if _pending_correction:
+ _pending_correction = false
+ state.linear_velocity = _remote_linear_velocity
+ state.angular_velocity = _remote_angular_velocity
+ state.transform = Transform2D(_remote_rotation, _remote_position)
+
+ if _pending_sync:
+ _pending_sync = false
+ GDSync.call_func_relevant(
+ _sync_received,
+ GDSync.get_multiplayer_time(),
+ state.linear_velocity,
+ state.angular_velocity,
+ state.transform.origin,
+ state.transform.get_rotation()
+ )
+ _sync_received(GDSync.get_multiplayer_time(),
+ state.linear_velocity,
+ state.angular_velocity,
+ state.transform.origin,
+ state.transform.get_rotation())
+ else:
+ var rot_diff : float = state.transform.get_rotation() - _remote_rotation
+ if (
+ _disable_correction_counter == 0 and (
+ abs((state.linear_velocity - _remote_linear_velocity).length_squared()) > _CORRECTION_LINEAR_VELOCITY_THRESHOLD or
+ abs(state.angular_velocity - _remote_angular_velocity) > _CORRECTION_ANGULAR_VELOCITY_THRESHOLD or
+ abs((state.transform.origin - _remote_position).length_squared()) > _CORRECTION_POSITION_THRESHOLD or
+ abs(rot_diff) > _CORRECTION_ROTATION_THRESHOLD
+ )):
+ state.linear_velocity = _remote_linear_velocity
+ state.angular_velocity = _remote_angular_velocity
+ state.transform = Transform2D(
+ lerp_angle(state.transform.get_rotation(), _remote_rotation, 0.3),
+ lerp(state.transform.origin, _remote_position, 0.3))
+
+func _sync_received(time : float, lv : Vector2, av : float, pos : Vector2, rotation : float) -> void:
+ var delta : float = min(GDSync.get_multiplayer_time() - time, 0.3)
+ _remote_linear_velocity = lv
+ _remote_angular_velocity = av
+ _remote_position = pos + _remote_linear_velocity * delta
+ _remote_rotation = rotation + _remote_angular_velocity * delta
+ _last_sync_linear_velocity = _remote_linear_velocity
+ _last_sync_angular_velocity = _remote_angular_velocity
+ _last_sync_position = pos
+ _last_sync_rotation = rotation
+ sleeping = false
+
+func _interest_object_client_entered(client_id : int) -> void:
+ if !_should_broadcast:
+ return
+ GDSync.call_func_on(
+ client_id,
+ _sync_received,
+ GDSync.get_multiplayer_time(),
+ linear_velocity,
+ angular_velocity,
+ global_position,
+ global_rotation
+ )
+
+func _owner_changed(owner) -> void:
+ if owner >= 0: _last_owner = owner
+ _update_sync_mode()
+
+func _client_joined(client_id : int) -> void:
+ if _should_broadcast:
+ _pending_sync = true
+
+func _host_changed(is_host : bool, new_host_id : int) -> void:
+ _update_sync_mode()
+
+func _update_sync_mode() -> void:
+ if Engine.is_editor_hint() || GDSync == null: return
+ var is_host : bool = GDSync.is_host()
+ var is_owner : bool = GDSync.is_gdsync_owner(self)
+ var valid_owner : bool = GDSync.lobby_get_all_clients().has(_last_owner)
+ _should_broadcast = (is_host and !valid_owner) || (valid_owner and _last_owner == GDSync.get_client_id())
+
+func _get_configuration_warnings() -> PackedStringArray:
+ var warnings : PackedStringArray = []
+
+ warnings.append("The SynchronizedRigidBody2D Node is experimental. Please report any issues on GitHub.")
+
+ return warnings
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedRigidBody2D.gd.uid b/addons/GD-Sync/Scripts/Types/SynchronizedRigidBody2D.gd.uid
new file mode 100644
index 0000000..2ee7249
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedRigidBody2D.gd.uid
@@ -0,0 +1 @@
+uid://b78awbtrt2vik
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedRigidBody3D.gd b/addons/GD-Sync/Scripts/Types/SynchronizedRigidBody3D.gd
new file mode 100644
index 0000000..bb71f1f
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedRigidBody3D.gd
@@ -0,0 +1,251 @@
+@tool
+@icon("res://addons/GD-Sync/UI/Icons/SynchronizedRigidBody3D.png")
+extends RigidBody3D
+class_name SynchronizedRigidBody3D
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+## How many times per second the body should be synchronized.
+@export var refresh_rate : int = 30
+
+func apply_central_impulse_synced(impulse : Vector3) -> void:
+ super.apply_central_impulse(impulse)
+ await get_tree().physics_frame
+ if !GDSync.is_gdsync_owner(self):
+ GDSync.set_gdsync_owner(self, GDSync.get_client_id())
+
+func apply_central_force_synced(force : Vector3) -> void:
+ super.apply_central_force(force)
+ await get_tree().physics_frame
+ if !GDSync.is_gdsync_owner(self):
+ GDSync.set_gdsync_owner(self, GDSync.get_client_id())
+
+func apply_impulse_synced(impulse: Vector3, position: Vector3 = Vector3(0, 0, 0)) -> void:
+ super.apply_impulse(impulse, position)
+ await get_tree().physics_frame
+ if !GDSync.is_gdsync_owner(self):
+ GDSync.set_gdsync_owner(self, GDSync.get_client_id())
+
+func apply_force_synced(force: Vector3, position: Vector3 = Vector3(0, 0, 0)) -> void:
+ super.apply_force(force, position)
+ await get_tree().physics_frame
+ if !GDSync.is_gdsync_owner(self):
+ GDSync.set_gdsync_owner(self, GDSync.get_client_id())
+
+func apply_torque_synced(torque: Vector3) -> void:
+ super.apply_torque(torque)
+ await get_tree().physics_frame
+ if !GDSync.is_gdsync_owner(self):
+ GDSync.set_gdsync_owner(self, GDSync.get_client_id())
+
+func apply_torque_impulse_synced(impulse: Vector3) -> void:
+ super.apply_torque_impulse(impulse)
+ await get_tree().physics_frame
+ if !GDSync.is_gdsync_owner(self):
+ GDSync.set_gdsync_owner(self, GDSync.get_client_id())
+
+
+
+
+
+#Private functions ----------------------------------------------------------------------
+
+var GDSync
+
+var _cooldown : float = 0.0
+var _current_cooldown : float = 0.0
+var _current_fixed_cooldown : float = 0.0
+var _should_broadcast : bool = false
+var _last_owner : int = -1
+
+var _pending_sync : bool = true
+var _force_sync : bool = false
+var _pending_correction : bool = false
+
+var _remote_position : Vector3
+var _remote_euler : Vector3
+var _remote_linear_velocity : Vector3
+var _remote_angular_velocity : Vector3
+
+var _disable_correction_counter : int = 0
+
+var _last_sync_position : Vector3 = Vector3.ZERO
+var _last_sync_rotation : Vector3 = Vector3.UP
+var _last_sync_linear_velocity : Vector3 = Vector3.ZERO
+var _last_sync_angular_velocity : Vector3 = Vector3.ZERO
+
+const _FIXED_COOLDOWN : float = 10.0
+const _SYNC_LINEAR_VELOCITY_THRESHOLD : float = 0.1
+const _SYNC_ANGULAR_VELOCITY_THRESHOLD : float = 0.05
+const _SYNC_ROTATION_THRESHOLD : float = 0.01
+const _SYNC_POSITION_THRESHOLD : float = 0.01
+const _CORRECTION_ROTATION_THRESHOLD : float = 0.03
+const _CORRECTION_LINEAR_VELOCITY_THRESHOLD : float = 0.1
+const _CORRECTION_ANGULAR_VELOCITY_THRESHOLD : float = 0.05
+const _CORRECTION_POSITION_THRESHOLD : float = 0.01
+
+func _ready() -> void:
+ if !Engine.is_editor_hint():
+ GDSync = get_node("/root/GDSync")
+
+ _cooldown = 1.0/refresh_rate
+ _last_owner = GDSync.get_gdsync_owner(self)
+ can_sleep = false
+
+ GDSync.expose_func(_sync_received)
+
+ GDSync.host_changed.connect(_host_changed)
+ GDSync.client_joined.connect(_client_joined)
+ GDSync.connect_gdsync_owner_changed(self, _owner_changed)
+
+ _update_sync_mode()
+ _current_fixed_cooldown = 2.0
+
+func _physics_process(delta: float) -> void:
+ if _should_broadcast:
+ if _may_synchronize(delta):
+ var current_rot : Vector3 = global_transform.basis.get_euler()
+ var rot_diff : Vector3 = current_rot-_last_sync_rotation
+ if (
+ _force_sync or
+ abs((global_transform.origin-_last_sync_position).length_squared()) > _SYNC_POSITION_THRESHOLD or
+ abs((linear_velocity-_last_sync_linear_velocity).length_squared()) > _SYNC_LINEAR_VELOCITY_THRESHOLD or
+ abs((angular_velocity-_last_sync_angular_velocity).length_squared()) > _SYNC_ANGULAR_VELOCITY_THRESHOLD or
+ abs(rot_diff.x) > _SYNC_ROTATION_THRESHOLD or
+ abs(rot_diff.y) > _SYNC_ROTATION_THRESHOLD or
+ abs(rot_diff.z) > _SYNC_ROTATION_THRESHOLD
+ ):
+ _last_sync_linear_velocity = linear_velocity
+ _last_sync_angular_velocity = angular_velocity
+ _last_sync_position = global_transform.origin
+ _last_sync_rotation = current_rot
+ _pending_sync = true
+ _force_sync = false
+
+ #_remote_position += _remote_linear_velocity * delta
+ #_remote_euler += _remote_angular_velocity*delta
+
+func _may_synchronize(delta : float) -> bool:
+ _current_cooldown -= delta
+ if _current_cooldown <= 0:
+ _current_cooldown += _cooldown
+ return true
+
+ _current_fixed_cooldown -= delta
+ if _current_fixed_cooldown <= 0.0:
+ _current_fixed_cooldown += _FIXED_COOLDOWN
+ _force_sync = true
+ return true
+ return false
+
+func _integrate_forces(state: PhysicsDirectBodyState3D) -> void:
+ if _should_broadcast:
+ if _pending_correction:
+ _pending_correction = false
+ state.linear_velocity = _remote_linear_velocity
+ state.angular_velocity = _remote_angular_velocity
+ state.transform.origin = _remote_position
+ state.transform.basis = Basis(Quaternion.from_euler(_remote_euler))
+
+ if _pending_sync:
+ _pending_sync = false
+ GDSync.call_func_relevant(
+ _sync_received,
+ GDSync.get_multiplayer_time(),
+ state.linear_velocity,
+ state.angular_velocity,
+ state.transform.origin,
+ state.transform.basis.get_euler()
+ )
+ _sync_received(GDSync.get_multiplayer_time(),
+ state.linear_velocity,
+ state.angular_velocity,
+ state.transform.origin,
+ state.transform.basis.get_euler())
+ else:
+ var rot_diff : Vector3 = state.transform.basis.get_euler()-_remote_euler
+ if (
+ _disable_correction_counter == 0 and (
+ abs((state.linear_velocity-_remote_linear_velocity).length_squared()) > _CORRECTION_LINEAR_VELOCITY_THRESHOLD or
+ abs((state.angular_velocity-_remote_angular_velocity).length_squared()) > _CORRECTION_ANGULAR_VELOCITY_THRESHOLD or
+ abs((state.transform.origin-_remote_position).length_squared()) > _CORRECTION_POSITION_THRESHOLD or
+ abs(rot_diff.x) > _CORRECTION_ROTATION_THRESHOLD or
+ abs(rot_diff.y) > _CORRECTION_ROTATION_THRESHOLD or
+ abs(rot_diff.z) > _CORRECTION_ROTATION_THRESHOLD
+ )):
+ state.linear_velocity = _remote_linear_velocity
+ state.angular_velocity = _remote_angular_velocity
+ state.transform.origin = lerp(state.transform.origin, _remote_position, 0.3)
+ state.transform.basis = state.transform.basis.slerp(Basis(Quaternion.from_euler(_remote_euler)), 0.3)
+
+func _sync_received(time : float, lv : Vector3, av : Vector3, pos : Vector3, euler : Vector3) -> void:
+ var delta : float = min(GDSync.get_multiplayer_time()-time, 0.3)
+ _remote_linear_velocity = lv
+ _remote_angular_velocity = av
+ _remote_position = pos + _remote_linear_velocity*delta
+ _remote_euler = euler + _remote_angular_velocity*delta
+ _last_sync_linear_velocity = _remote_linear_velocity
+ _last_sync_angular_velocity = _remote_angular_velocity
+ _last_sync_position = pos
+ _last_sync_rotation = euler
+ sleeping = false
+
+func _interest_object_client_entered(client_id : int) -> void:
+ if !_should_broadcast:
+ return
+ GDSync.call_func_on(
+ client_id,
+ _sync_received,
+ GDSync.get_multiplayer_time(),
+ linear_velocity,
+ angular_velocity,
+ global_position,
+ global_rotation
+ )
+
+func _owner_changed(owner) -> void:
+ if owner >= 0: _last_owner = owner
+ _update_sync_mode()
+
+func _client_joined(client_id : int) -> void:
+ if _should_broadcast:
+ _pending_sync = true
+
+func _host_changed(is_host : bool, new_host_id : int) -> void:
+ _update_sync_mode()
+
+func _update_sync_mode() -> void:
+ if Engine.is_editor_hint() || GDSync == null: return
+ var is_host : bool = GDSync.is_host()
+ var is_owner : bool = GDSync.is_gdsync_owner(self)
+ var valid_owner : bool = GDSync.lobby_get_all_clients().has(_last_owner)
+ _should_broadcast = (is_host and !valid_owner) || (valid_owner and _last_owner == GDSync.get_client_id())
+
+func _get_configuration_warnings() -> PackedStringArray:
+ var warnings : PackedStringArray = []
+
+ warnings.append("The SynchronizedRigidBody3D Node is experimental. Please report any issues on GitHub.")
+
+ return warnings
diff --git a/addons/GD-Sync/Scripts/Types/SynchronizedRigidBody3D.gd.uid b/addons/GD-Sync/Scripts/Types/SynchronizedRigidBody3D.gd.uid
new file mode 100644
index 0000000..17c540c
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/SynchronizedRigidBody3D.gd.uid
@@ -0,0 +1 @@
+uid://doew6w5001xmd
diff --git a/addons/GD-Sync/Scripts/Types/VoiceChat.gd b/addons/GD-Sync/Scripts/Types/VoiceChat.gd
new file mode 100644
index 0000000..2bcd085
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/VoiceChat.gd
@@ -0,0 +1,267 @@
+@tool
+@icon("res://addons/GD-Sync/UI/Icons/VoiceChatIcon.png")
+extends Node
+class_name VoiceChat
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+## The minimum input volume at which the audio is broadcasted to other players.
+@export var input_volume_threshold : float = 0.01
+## The audio quality. Not recommended to go above Medium.
+@export_enum("Very High", "High", "Medium", "Low") var audio_quality : int = 2 :
+ set(value):
+ audio_quality = value
+ update_configuration_warnings()
+
+@export_group("Audio Bus")
+## Any extra effects you would like to be added to the record bus.
+@export var record_effects : Array[AudioEffect] = []
+
+@export_group("Output")
+## Allows you to create 2D or 3D spatial audio, where players can only hear each other when close ingame.
+@export_enum("None", "2D", "3D") var spatial_mode : int :
+ set(value):
+ spatial_mode = value
+ notify_property_list_changed()
+
+var _bus_index : int = -1
+var _bus_name : String = "GDRecord"
+
+var _microphone_stream : AudioStreamMicrophone
+var _record_effect : AudioEffectCapture
+
+var _output_stream : AudioStreamGenerator
+var _output_stream_playback : AudioStreamGeneratorPlayback
+## The output player which will play received voice samples.
+var _output_player : Node : set = set_output_player
+
+var _input_configured : bool = false
+var _output_configured : bool = false
+var _muted : bool = false
+
+var GDSync
+
+func set_input_device(device_name : String) -> void:
+ AudioServer.input_device = device_name
+
+func get_input_devices() -> PackedStringArray:
+ return AudioServer.get_input_device_list()
+
+func mute_microphone() -> void:
+ _muted = true
+
+func unmute_microphone() -> void:
+ _muted = false
+
+func _ready() -> void:
+ if Engine.is_editor_hint():
+ set_process(false)
+ return
+
+ GDSync = get_node("/root/GDSync")
+ GDSync.expose_func(_process_audio)
+ GDSync.connect_gdsync_owner_changed(self, _owner_changed)
+
+ _configure_bus()
+
+ if _output_player == null:
+ push_error("Output Node is null.")
+ set_process(false)
+ return
+
+ if GDSync.is_gdsync_owner(self):
+ _configure_input()
+ else:
+ _configure_output()
+
+func _owner_changed(owner_id : int) -> void:
+ if GDSync.is_gdsync_owner(self):
+ _configure_input()
+ else:
+ _configure_output()
+
+func _process(delta: float) -> void:
+ if !GDSync.is_gdsync_owner(self):
+ return
+
+ if _input_configured and _record_effect.get_frames_available() > 0:
+ if _muted:
+ _record_effect.clear_buffer()
+ return
+
+ var recording_data : PackedVector2Array = _record_effect.get_buffer(_record_effect.get_frames_available())
+ var data : PackedFloat32Array = PackedFloat32Array()
+
+ var sr : float = AudioServer.get_mix_rate()
+ match(audio_quality):
+ 0:
+ _sample_raw(recording_data, data)
+ 1:
+ _downsample_half(recording_data, data)
+ sr /= 2.0
+ 2:
+ _downsample_quarter(recording_data, data)
+ sr /= 4.0
+ 3:
+ _downsample_eighth(recording_data, data)
+ sr /= 8.0
+
+ var max_amp : float = 0.0
+ for i in range(data.size()):
+ max_amp = max(abs(data[i]), max_amp)
+
+ if max_amp > input_volume_threshold:
+ GDSync.call_func_relevant_unreliable(_process_audio, data, sr)
+
+func _process_audio(audio : PackedFloat32Array, mixrate : float) -> void:
+ if _output_stream.mix_rate != mixrate: _output_stream.mix_rate = mixrate
+ for i in range(min(_output_stream_playback.get_frames_available(), audio.size())):
+ var d : float = audio[i]
+ _output_stream_playback.push_frame(Vector2(d, d))
+
+func _sample_raw(recording_data: PackedVector2Array, data : PackedFloat32Array) -> PackedFloat32Array:
+ var frames : int = recording_data.size()
+ data.resize(frames)
+ for i in range(frames):
+ data[i] = (recording_data[i].x + recording_data[i].y) / 2
+ return data
+
+func _downsample_half(recording_data: PackedVector2Array, data : PackedFloat32Array) -> PackedFloat32Array:
+ var frames : int = recording_data.size()
+ var half_frames : int = frames / 2
+ data.resize(half_frames)
+ for i in range(half_frames):
+ var v1 : float = (recording_data[i * 2].x + recording_data[i * 2].y) / 2
+ var v2 : float = (recording_data[i * 2 + 1].x + recording_data[i * 2 + 1].y) / 2
+ data[i] = (v1 + v2) / 2
+ return data
+
+func _downsample_quarter(recording_data: PackedVector2Array, data : PackedFloat32Array) -> PackedFloat32Array:
+ var frames : int = recording_data.size()
+ var quarter_frames : int = frames / 4
+ data.resize(quarter_frames)
+ for i in range(quarter_frames):
+ var v0 : float = (recording_data[i * 4].x + recording_data[i * 4].y) / 2
+ var v1 : float = (recording_data[i * 4 + 1].x + recording_data[i * 4 + 1].y) / 2
+ var v2 : float = (recording_data[i * 4 + 2].x + recording_data[i * 4 + 2].y) / 2
+ var v3 : float = (recording_data[i * 4 + 3].x + recording_data[i * 4 + 3].y) / 2
+ data[i] = (v0 + v1 + v2 + v3) / 4
+ return data
+
+func _downsample_eighth(recording_data: PackedVector2Array, data : PackedFloat32Array) -> PackedFloat32Array:
+ var frames : int = recording_data.size()
+ var eighth_frames : int = frames / 8
+ data.resize(eighth_frames)
+ for i in range(eighth_frames):
+ var sum : float = 0.0
+ for j in range(8):
+ sum += (recording_data[i * 8 + j].x + recording_data[i * 8 + j].y) / 2
+ data[i] = sum / 8
+ return data
+
+func _configure_bus() -> void:
+ for i in range(AudioServer.bus_count):
+ if AudioServer.get_bus_name(i) == _bus_name:
+ _record_effect = AudioServer.get_bus_effect(i, AudioServer.get_bus_effect_count(i)-1)
+ _bus_index = i
+
+ if _bus_index >= 0:
+ return
+
+ _bus_index = AudioServer.bus_count
+ AudioServer.add_bus(_bus_index)
+ AudioServer.set_bus_name(_bus_index, _bus_name)
+ AudioServer.set_bus_mute(_bus_index, true)
+
+ for effect in record_effects:
+ AudioServer.add_bus_effect(_bus_index, effect)
+
+ _record_effect = AudioEffectCapture.new()
+ AudioServer.add_bus_effect(_bus_index, _record_effect)
+
+func _configure_input() -> void:
+ if _input_configured:
+ return
+ _input_configured = true
+
+ _microphone_stream = AudioStreamMicrophone.new()
+
+ var microphone_player : AudioStreamPlayer = AudioStreamPlayer.new()
+ microphone_player.name = "MicIn"
+ add_child(microphone_player)
+ microphone_player.bus = _bus_name
+ microphone_player.stream = _microphone_stream
+ microphone_player.play()
+
+func _configure_output() -> void:
+ if _output_configured:
+ return
+ _output_configured = true
+
+ _output_stream = AudioStreamGenerator.new()
+ _output_stream.buffer_length = 0.1
+ _output_player.stream = _output_stream
+ _output_player.play()
+
+ _output_stream_playback = _output_player.get_stream_playback()
+
+func set_output_player(p : Node) -> void:
+ _output_player = p
+ update_configuration_warnings()
+
+func _get_property_list() -> Array[Dictionary]:
+ var properties : Array[Dictionary] = []
+
+ var type : String = ""
+ match(spatial_mode):
+ 0:
+ type = "AudioStreamPlayer"
+ 1:
+ type = "AudioStreamPlayer2D"
+ 2:
+ type = "AudioStreamPlayer3D"
+
+ properties.append({
+ "name" : "_output_player",
+ "type" : TYPE_OBJECT,
+ "hint" : PROPERTY_HINT_NODE_TYPE,
+ "hint_string" : type,
+ "usage" : PROPERTY_USAGE_DEFAULT
+ })
+
+ return properties
+
+func _get_configuration_warnings() -> PackedStringArray:
+ var warnings : PackedStringArray = []
+
+ warnings.append("The VoiceChat Node is experimental. Please report any issues on GitHub.")
+
+ if _output_player == null:
+ warnings.append("No output AudioStreamPlayer assigned.")
+
+ if audio_quality < 2:
+ warnings.append("Higher audio quality will use up significantly more data.")
+
+ return warnings
diff --git a/addons/GD-Sync/Scripts/Types/VoiceChat.gd.uid b/addons/GD-Sync/Scripts/Types/VoiceChat.gd.uid
new file mode 100644
index 0000000..adb5a46
--- /dev/null
+++ b/addons/GD-Sync/Scripts/Types/VoiceChat.gd.uid
@@ -0,0 +1 @@
+uid://b53bpow4wicbi
diff --git a/addons/GD-Sync/UI/ConfigMenu/ConfigMenu.gd b/addons/GD-Sync/UI/ConfigMenu/ConfigMenu.gd
new file mode 100644
index 0000000..2d38428
--- /dev/null
+++ b/addons/GD-Sync/UI/ConfigMenu/ConfigMenu.gd
@@ -0,0 +1,125 @@
+@tool
+extends Control
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+const KeyStore = preload("res://addons/GD-Sync/Scripts/KeyStore.gd")
+
+var plugin
+
+var menu_open : bool = false
+
+var updater : Updater
+
+func _ready():
+ if plugin == null: return
+
+ var keys : Dictionary = KeyStore.load_keys()
+ %PublicKey.text = keys["PublicKey"]
+ %PrivateKey.text = keys["PrivateKey"]
+
+ if ProjectSettings.has_setting("GD-Sync/protectedMode"):
+ %Protected.button_pressed = ProjectSettings.get_setting("GD-Sync/protectedMode")
+ if ProjectSettings.has_setting("GD-Sync/csharp"):
+ %CSharpSupport.button_pressed = ProjectSettings.get_setting("GD-Sync/csharp")
+ if ProjectSettings.has_setting("GD-Sync/uniqueUsername"):
+ %UniqueUsernames.button_pressed = ProjectSettings.get_setting("GD-Sync/uniqueUsername")
+ if ProjectSettings.has_setting("GD-Sync/scriptValidation"):
+ %ScriptValidation.button_pressed = ProjectSettings.get_setting("GD-Sync/scriptValidation")
+
+ updater = Updater.new()
+ updater.update_label = %UpdateLabel
+ add_child(updater)
+
+func update_ready() -> void:
+ %DefaultPannel.visible = false
+ %UpdatePanel.visible = true
+
+func _input(event):
+ if !menu_open: return
+ if event is InputEventKey:
+ if event.is_pressed() and event.keycode == KEY_ESCAPE:
+ close()
+
+func open():
+ menu_open = true
+ $AnimationPlayer.play("Open")
+
+ var scale : float = size.y/1080.0
+ $CenterContainer/LogoAnchor/Logo.scale = Vector2.ONE*scale
+ $CenterContainer/UIAnchor/UI.scale = Vector2.ONE*scale
+
+func close():
+ menu_open = false
+ $AnimationPlayer.play_backwards("Open")
+
+func _on_PublicKey_text_changed(new_text):
+ KeyStore.ensure_gitignore()
+ KeyStore.save_keys(new_text, %PrivateKey.text)
+
+func _on_PrivateKey_text_changed(new_text):
+ KeyStore.ensure_gitignore()
+ KeyStore.save_keys(%PublicKey.text, new_text)
+
+func _on_c_sharp_support_toggled(button_pressed):
+ ProjectSettings.set_setting("GD-Sync/csharp", button_pressed)
+ ProjectSettings.save()
+
+ if button_pressed:
+ plugin.enable_csharp_api()
+ else:
+ plugin.disable_csharp_api()
+
+func _on_protected_toggled(button_pressed):
+ ProjectSettings.set_setting("GD-Sync/protectedMode", button_pressed)
+ ProjectSettings.save()
+
+func _on_unique_usernames_toggled(button_pressed):
+ ProjectSettings.set_setting("GD-Sync/uniqueUsername", button_pressed)
+ ProjectSettings.save()
+
+func _on_script_validation_toggled(button_pressed) -> void:
+ ProjectSettings.set_setting("GD-Sync/scriptValidation", button_pressed)
+ ProjectSettings.save()
+
+func _on_description_meta_clicked(meta):
+ if meta == "log":
+ meta = OS.get_user_data_dir()+"/GD-Sync/logs"
+ OS.shell_open(meta)
+
+func _on_update_button_pressed() -> void:
+ %LoadIcon.play()
+ $AnimationPlayer.play("Downloading")
+
+ var result : bool = await updater.update_repo()
+
+ %DefaultPannel.visible = true
+ %UpdatePanel.visible = false
+ $AnimationPlayer.play_backwards("Downloading")
+
+ if result:
+ plugin.show_message("[color=#61ff71][b]The newest version of GD-Sync has been installed. Please restart the engine to complete the update.[/b][/color]", 10.0)
+ else:
+ plugin.show_message("[color=indianred][b]GD-Sync failed to update. Please try downloading it from the Godot Asset Library instead.[/b][/color]")
diff --git a/addons/GD-Sync/UI/ConfigMenu/ConfigMenu.gd.uid b/addons/GD-Sync/UI/ConfigMenu/ConfigMenu.gd.uid
new file mode 100644
index 0000000..d4aab32
--- /dev/null
+++ b/addons/GD-Sync/UI/ConfigMenu/ConfigMenu.gd.uid
@@ -0,0 +1 @@
+uid://ctbm12j05lk6h
diff --git a/addons/GD-Sync/UI/ConfigMenu/ConfigMenu.tscn b/addons/GD-Sync/UI/ConfigMenu/ConfigMenu.tscn
new file mode 100644
index 0000000..1560e39
--- /dev/null
+++ b/addons/GD-Sync/UI/ConfigMenu/ConfigMenu.tscn
@@ -0,0 +1,916 @@
+[gd_scene format=3 uid="uid://1ho7vq1qum7y"]
+
+[ext_resource type="Script" uid="uid://ctbm12j05lk6h" path="res://addons/GD-Sync/UI/ConfigMenu/ConfigMenu.gd" id="1"]
+[ext_resource type="Theme" uid="uid://5whm1igkt23h" path="res://addons/GD-Sync/UI/ConfigMenu/GD-Theme.tres" id="2_wd24h"]
+[ext_resource type="Texture2D" uid="uid://d2pl6xyfyub5k" path="res://addons/GD-Sync/UI/ConfigMenu/GDSLogo.png" id="3_eccmp"]
+[ext_resource type="Texture2D" uid="uid://o7408i2pu2eb" path="res://addons/GD-Sync/UI/Icons/LoadIcon.png" id="3_k7k3v"]
+
+[sub_resource type="Animation" id="Animation_p5x7e"]
+resource_name = "Downloading"
+length = 1.8
+step = 0.1
+tracks/0/type = "bezier"
+tracks/0/imported = false
+tracks/0/enabled = true
+tracks/0/path = NodePath("CenterContainer/LogoAnchor/Logo/Logo:position:y")
+tracks/0/interp = 1
+tracks/0/loop_wrap = true
+tracks/0/keys = {
+"handle_modes": PackedInt32Array(0, 0),
+"points": PackedFloat32Array(-350, -0.25, 0, 0.25, 0, 0, -0.25, 0, 0.25, 0),
+"times": PackedFloat32Array(0, 1)
+}
+tracks/1/type = "bezier"
+tracks/1/imported = false
+tracks/1/enabled = true
+tracks/1/path = NodePath("CenterContainer/LogoAnchor/Logo/Logo:scale:x")
+tracks/1/interp = 1
+tracks/1/loop_wrap = true
+tracks/1/keys = {
+"handle_modes": PackedInt32Array(0, 0),
+"points": PackedFloat32Array(0.5, -0.25, 0, 0.25, 0, 1, -0.25, 0, 0.25, 0),
+"times": PackedFloat32Array(0, 1)
+}
+tracks/2/type = "bezier"
+tracks/2/imported = false
+tracks/2/enabled = true
+tracks/2/path = NodePath("CenterContainer/LogoAnchor/Logo/Logo:scale:y")
+tracks/2/interp = 1
+tracks/2/loop_wrap = true
+tracks/2/keys = {
+"handle_modes": PackedInt32Array(0, 0),
+"points": PackedFloat32Array(0.5, -0.25, 0, 0.25, 0, 1, -0.25, 0, 0.25, 0),
+"times": PackedFloat32Array(0, 1)
+}
+tracks/3/type = "value"
+tracks/3/imported = false
+tracks/3/enabled = true
+tracks/3/path = NodePath("CenterContainer/UIAnchor:modulate")
+tracks/3/interp = 1
+tracks/3/loop_wrap = true
+tracks/3/keys = {
+"times": PackedFloat32Array(0.0333333, 0.366667),
+"transitions": PackedFloat32Array(1, 1),
+"update": 0,
+"values": [Color(1, 1, 1, 1), Color(1, 1, 1, 0)]
+}
+tracks/4/type = "value"
+tracks/4/imported = false
+tracks/4/enabled = true
+tracks/4/path = NodePath("CenterContainer/LogoAnchor/Logo/LoadIcon:modulate")
+tracks/4/interp = 1
+tracks/4/loop_wrap = true
+tracks/4/keys = {
+"times": PackedFloat32Array(0, 1, 1.76667),
+"transitions": PackedFloat32Array(1, 1, 1),
+"update": 0,
+"values": [Color(1, 1, 1, 0), Color(1, 1, 1, 0), Color(1, 1, 1, 1)]
+}
+tracks/5/type = "value"
+tracks/5/imported = false
+tracks/5/enabled = true
+tracks/5/path = NodePath("CenterContainer/LogoAnchor/Logo/UpdateLabel:modulate")
+tracks/5/interp = 1
+tracks/5/loop_wrap = true
+tracks/5/keys = {
+"times": PackedFloat32Array(0, 1, 1.8),
+"transitions": PackedFloat32Array(1, 1, 1),
+"update": 0,
+"values": [Color(1, 1, 1, 0), Color(1, 1, 1, 0), Color(1, 1, 1, 1)]
+}
+
+[sub_resource type="Animation" id="Animation_x05bw"]
+resource_name = "Open"
+length = 1.8
+tracks/0/type = "value"
+tracks/0/imported = false
+tracks/0/enabled = true
+tracks/0/path = NodePath(".:visible")
+tracks/0/interp = 1
+tracks/0/loop_wrap = true
+tracks/0/keys = {
+"times": PackedFloat32Array(0, 0.1),
+"transitions": PackedFloat32Array(1, 1),
+"update": 1,
+"values": [false, true]
+}
+tracks/1/type = "value"
+tracks/1/imported = false
+tracks/1/enabled = true
+tracks/1/path = NodePath("Background:modulate")
+tracks/1/interp = 1
+tracks/1/loop_wrap = true
+tracks/1/keys = {
+"times": PackedFloat32Array(0.1, 0.3),
+"transitions": PackedFloat32Array(1, 1),
+"update": 0,
+"values": [Color(0, 0, 0, 0), Color(0, 0, 0, 0.78431374)]
+}
+tracks/2/type = "value"
+tracks/2/imported = false
+tracks/2/enabled = true
+tracks/2/path = NodePath("CenterContainer/LogoAnchor:modulate")
+tracks/2/interp = 1
+tracks/2/loop_wrap = true
+tracks/2/keys = {
+"times": PackedFloat32Array(0.2, 0.5),
+"transitions": PackedFloat32Array(1, 1),
+"update": 0,
+"values": [Color(1, 1, 1, 0), Color(1, 1, 1, 1)]
+}
+tracks/3/type = "bezier"
+tracks/3/imported = false
+tracks/3/enabled = true
+tracks/3/path = NodePath("CenterContainer/LogoAnchor/Logo/Logo:position:y")
+tracks/3/interp = 1
+tracks/3/loop_wrap = true
+tracks/3/keys = {
+"handle_modes": PackedInt32Array(0, 0),
+"points": PackedFloat32Array(0, -0.25, 0, 0.25, 0, -350, -0.25, 0, 0.25, 0),
+"times": PackedFloat32Array(1, 1.5)
+}
+tracks/4/type = "bezier"
+tracks/4/imported = false
+tracks/4/enabled = true
+tracks/4/path = NodePath("CenterContainer/LogoAnchor/Logo/Logo:scale:x")
+tracks/4/interp = 1
+tracks/4/loop_wrap = true
+tracks/4/keys = {
+"handle_modes": PackedInt32Array(0, 0),
+"points": PackedFloat32Array(1, -0.25, 0, 0.25, 0, 0.5, -0.25, 0, 0.25, 0),
+"times": PackedFloat32Array(1, 1.5)
+}
+tracks/5/type = "bezier"
+tracks/5/imported = false
+tracks/5/enabled = true
+tracks/5/path = NodePath("CenterContainer/LogoAnchor/Logo/Logo:scale:y")
+tracks/5/interp = 1
+tracks/5/loop_wrap = true
+tracks/5/keys = {
+"handle_modes": PackedInt32Array(0, 0),
+"points": PackedFloat32Array(1, -0.25, 0, 0.25, 0, 0.5, -0.25, 0, 0.25, 0),
+"times": PackedFloat32Array(1, 1.5)
+}
+tracks/6/type = "value"
+tracks/6/imported = false
+tracks/6/enabled = true
+tracks/6/path = NodePath("CenterContainer/UIAnchor:modulate")
+tracks/6/interp = 1
+tracks/6/loop_wrap = true
+tracks/6/keys = {
+"times": PackedFloat32Array(1.3, 1.8),
+"transitions": PackedFloat32Array(1, 1),
+"update": 0,
+"values": [Color(1, 1, 1, 0), Color(1, 1, 1, 1)]
+}
+
+[sub_resource type="Animation" id="Animation_qx43o"]
+length = 0.001
+tracks/0/type = "value"
+tracks/0/imported = false
+tracks/0/enabled = true
+tracks/0/path = NodePath(".:visible")
+tracks/0/interp = 1
+tracks/0/loop_wrap = true
+tracks/0/keys = {
+"times": PackedFloat32Array(0),
+"transitions": PackedFloat32Array(1),
+"update": 1,
+"values": [false]
+}
+tracks/1/type = "value"
+tracks/1/imported = false
+tracks/1/enabled = true
+tracks/1/path = NodePath("Background:modulate")
+tracks/1/interp = 1
+tracks/1/loop_wrap = true
+tracks/1/keys = {
+"times": PackedFloat32Array(0),
+"transitions": PackedFloat32Array(1),
+"update": 0,
+"values": [Color(0, 0, 0, 0)]
+}
+tracks/2/type = "value"
+tracks/2/imported = false
+tracks/2/enabled = true
+tracks/2/path = NodePath("CenterContainer/LogoAnchor:modulate")
+tracks/2/interp = 1
+tracks/2/loop_wrap = true
+tracks/2/keys = {
+"times": PackedFloat32Array(0),
+"transitions": PackedFloat32Array(1),
+"update": 0,
+"values": [Color(1, 1, 1, 0)]
+}
+tracks/3/type = "bezier"
+tracks/3/imported = false
+tracks/3/enabled = true
+tracks/3/path = NodePath("CenterContainer/LogoAnchor/Logo/Logo:position:y")
+tracks/3/interp = 1
+tracks/3/loop_wrap = true
+tracks/3/keys = {
+"handle_modes": PackedInt32Array(0),
+"points": PackedFloat32Array(0, -0.25, 0, 0.25, 0),
+"times": PackedFloat32Array(0)
+}
+tracks/4/type = "bezier"
+tracks/4/imported = false
+tracks/4/enabled = true
+tracks/4/path = NodePath("CenterContainer/LogoAnchor/Logo/Logo:scale:x")
+tracks/4/interp = 1
+tracks/4/loop_wrap = true
+tracks/4/keys = {
+"handle_modes": PackedInt32Array(0),
+"points": PackedFloat32Array(1, -0.25, 0, 0.25, 0),
+"times": PackedFloat32Array(0)
+}
+tracks/5/type = "bezier"
+tracks/5/imported = false
+tracks/5/enabled = true
+tracks/5/path = NodePath("CenterContainer/LogoAnchor/Logo/Logo:scale:y")
+tracks/5/interp = 1
+tracks/5/loop_wrap = true
+tracks/5/keys = {
+"handle_modes": PackedInt32Array(0),
+"points": PackedFloat32Array(1, -0.25, 0, 0.25, 0),
+"times": PackedFloat32Array(0)
+}
+tracks/6/type = "value"
+tracks/6/imported = false
+tracks/6/enabled = true
+tracks/6/path = NodePath("CenterContainer/UIAnchor:modulate")
+tracks/6/interp = 1
+tracks/6/loop_wrap = true
+tracks/6/keys = {
+"times": PackedFloat32Array(0),
+"transitions": PackedFloat32Array(1),
+"update": 0,
+"values": [Color(1, 1, 1, 0)]
+}
+tracks/7/type = "value"
+tracks/7/imported = false
+tracks/7/enabled = true
+tracks/7/path = NodePath("CenterContainer/LogoAnchor/Logo/LoadIcon:modulate")
+tracks/7/interp = 1
+tracks/7/loop_wrap = true
+tracks/7/keys = {
+"times": PackedFloat32Array(0),
+"transitions": PackedFloat32Array(1),
+"update": 0,
+"values": [Color(1, 1, 1, 0)]
+}
+tracks/8/type = "value"
+tracks/8/imported = false
+tracks/8/enabled = true
+tracks/8/path = NodePath("CenterContainer/LogoAnchor/Logo/UpdateLabel:modulate")
+tracks/8/interp = 1
+tracks/8/loop_wrap = true
+tracks/8/keys = {
+"times": PackedFloat32Array(0),
+"transitions": PackedFloat32Array(1),
+"update": 0,
+"values": [Color(1, 1, 1, 0)]
+}
+
+[sub_resource type="AnimationLibrary" id="AnimationLibrary_d74rd"]
+_data = {
+&"Downloading": SubResource("Animation_p5x7e"),
+&"Open": SubResource("Animation_x05bw"),
+&"RESET": SubResource("Animation_qx43o")
+}
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_gw5my"]
+bg_color = Color(1, 1, 1, 1)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_7n4q8"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(0, 0, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_cpyqf"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(166, 0, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_xrhuh"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(332, 0, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_yg1kq"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(498, 0, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_q6pvr"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(664, 0, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_dr3eh"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(0, 166, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_l308m"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(166, 166, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_bo1b1"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(332, 166, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_qnxdd"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(498, 166, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_1m25y"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(664, 166, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_3ir2b"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(0, 332, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_psoh2"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(166, 332, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_f7j2m"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(332, 332, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_ucpbx"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(498, 332, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_nbmvf"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(664, 332, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_38ar6"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(0, 498, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_h5tbl"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(166, 498, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_ijnjl"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(332, 498, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_u7mul"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(498, 498, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_vpehh"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(664, 498, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_4max4"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(0, 664, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_ud1gk"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(166, 664, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_1qysi"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(332, 664, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_1ygi4"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(498, 664, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_qtqjo"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(664, 664, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_bcmcd"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(0, 830, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_ukgla"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(166, 830, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_5m3dn"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(332, 830, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_pgi17"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(498, 830, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_o14da"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(664, 830, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_wnnec"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(0, 996, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_wm8ux"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(166, 996, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_fa2em"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(332, 996, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_2dq2p"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(498, 996, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_p0gcl"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(664, 996, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_hd6io"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(0, 1162, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_hrq83"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(166, 1162, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_gvthg"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(332, 1162, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_wkeq8"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(498, 1162, 166, 166)
+
+[sub_resource type="AtlasTexture" id="AtlasTexture_oxpxj"]
+atlas = ExtResource("3_k7k3v")
+region = Rect2(664, 1162, 166, 166)
+
+[sub_resource type="SpriteFrames" id="SpriteFrames_m25b5"]
+animations = [{
+"frames": [{
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_7n4q8")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_cpyqf")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_xrhuh")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_yg1kq")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_q6pvr")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_dr3eh")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_l308m")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_bo1b1")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_qnxdd")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_1m25y")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_3ir2b")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_psoh2")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_f7j2m")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_ucpbx")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_nbmvf")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_38ar6")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_h5tbl")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_ijnjl")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_u7mul")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_vpehh")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_4max4")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_ud1gk")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_1qysi")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_1ygi4")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_qtqjo")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_bcmcd")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_ukgla")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_5m3dn")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_pgi17")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_o14da")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_wnnec")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_wm8ux")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_fa2em")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_2dq2p")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_p0gcl")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_hd6io")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_hrq83")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_gvthg")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_wkeq8")
+}, {
+"duration": 1.0,
+"texture": SubResource("AtlasTexture_oxpxj")
+}],
+"loop": 1,
+"name": &"default",
+"speed": 25.0
+}]
+
+[node name="ConfigMenu" type="Control" unique_id=1575433482]
+visible = false
+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("1")
+
+[node name="AnimationPlayer" type="AnimationPlayer" parent="." unique_id=1828917672]
+libraries/ = SubResource("AnimationLibrary_d74rd")
+speed_scale = 2.0
+
+[node name="Background" type="PanelContainer" parent="." unique_id=981966733]
+modulate = Color(0, 0, 0, 0)
+layout_mode = 1
+anchors_preset = 15
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 2
+grow_vertical = 2
+mouse_filter = 2
+theme_override_styles/panel = SubResource("StyleBoxFlat_gw5my")
+
+[node name="CenterContainer" type="CenterContainer" parent="." unique_id=776130872]
+layout_mode = 1
+anchors_preset = 15
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 2
+grow_vertical = 2
+
+[node name="LogoAnchor" type="Control" parent="CenterContainer" unique_id=802190337]
+modulate = Color(1, 1, 1, 0)
+layout_mode = 2
+
+[node name="Logo" type="Control" parent="CenterContainer/LogoAnchor" unique_id=169430659]
+anchors_preset = 0
+theme = ExtResource("2_wd24h")
+
+[node name="Logo" type="Sprite2D" parent="CenterContainer/LogoAnchor/Logo" unique_id=1768483165]
+unique_name_in_owner = true
+texture = ExtResource("3_eccmp")
+
+[node name="LoadIcon" type="AnimatedSprite2D" parent="CenterContainer/LogoAnchor/Logo" unique_id=981153261]
+unique_name_in_owner = true
+modulate = Color(1, 1, 1, 0)
+position = Vector2(0, 172.975)
+scale = Vector2(0.5, 0.5)
+sprite_frames = SubResource("SpriteFrames_m25b5")
+autoplay = "default"
+frame_progress = 0.471284
+
+[node name="UpdateLabel" type="Label" parent="CenterContainer/LogoAnchor/Logo" unique_id=1648919198]
+unique_name_in_owner = true
+modulate = Color(1, 1, 1, 0)
+custom_minimum_size = Vector2(400, 30)
+layout_mode = 1
+anchors_preset = 8
+anchor_left = 0.5
+anchor_top = 0.5
+anchor_right = 0.5
+anchor_bottom = 0.5
+offset_left = -200.0
+offset_top = 220.0
+offset_right = 200.0
+offset_bottom = 250.0
+grow_horizontal = 2
+grow_vertical = 2
+text = "Updating gd-sync"
+horizontal_alignment = 1
+
+[node name="UIAnchor" type="Control" parent="CenterContainer" unique_id=72271274]
+modulate = Color(1, 1, 1, 0)
+layout_mode = 2
+
+[node name="UI" type="Control" parent="CenterContainer/UIAnchor" unique_id=1371490478]
+anchors_preset = 0
+
+[node name="PanelContainer" type="PanelContainer" parent="CenterContainer/UIAnchor/UI" unique_id=2130273074]
+layout_mode = 0
+offset_left = -475.0
+offset_top = -275.0
+offset_right = 475.0
+offset_bottom = 342.0
+theme = ExtResource("2_wd24h")
+
+[node name="DefaultPannel" type="PanelContainer" parent="CenterContainer/UIAnchor/UI" unique_id=649474670]
+unique_name_in_owner = true
+layout_mode = 0
+offset_left = -450.0
+offset_top = -250.0
+offset_right = -50.0
+theme = ExtResource("2_wd24h")
+theme_type_variation = &"GDPanel"
+
+[node name="Description" type="RichTextLabel" parent="CenterContainer/UIAnchor/UI/DefaultPannel" unique_id=644519758]
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+bbcode_enabled = true
+text = "Welcome to the GD-Sync configuration menu. Here you can find basic settings and links to official resources.
+
+- [url=https://www.gd-sync.com]Official Website[/url]
+- [url=https://www.gd-sync.com/documentation]Documentation[/url]
+- [url=https://www.gd-sync.com/app/api-keys-settings]API Key Generation[/url]
+
+- [url=log]Log Directory[/url]"
+
+[node name="UpdatePanel" type="PanelContainer" parent="CenterContainer/UIAnchor/UI" unique_id=162433719]
+unique_name_in_owner = true
+visible = false
+layout_mode = 0
+offset_left = -450.0
+offset_top = -250.0
+offset_right = -50.0
+theme = ExtResource("2_wd24h")
+theme_type_variation = &"GDPanel"
+
+[node name="Description" type="RichTextLabel" parent="CenterContainer/UIAnchor/UI/UpdatePanel" unique_id=1740086594]
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+bbcode_enabled = true
+text = "A new update for GD-Sync is available. Press the button below to automatically update to the newest version.
+
+- [url=https://www.gd-sync.com]Official Website[/url]
+- [url=https://www.gd-sync.com/documentation]Documentation[/url]
+- [url=https://www.gd-sync.com/app/api-keys-settings]API Key Generation[/url]"
+
+[node name="ButtonContainer" type="PanelContainer" parent="CenterContainer/UIAnchor/UI/UpdatePanel" unique_id=965317605]
+clip_children = 1
+clip_contents = true
+layout_mode = 2
+size_flags_vertical = 8
+focus_mode = 2
+theme_type_variation = &"EmptyPanel"
+
+[node name="UpdateButton" type="Button" parent="CenterContainer/UIAnchor/UI/UpdatePanel/ButtonContainer" unique_id=1679435974]
+layout_mode = 2
+size_flags_vertical = 8
+theme_type_variation = &"UpdateButton"
+text = "Update"
+
+[node name="Panel2" type="PanelContainer" parent="CenterContainer/UIAnchor/UI" unique_id=221407985]
+layout_mode = 0
+offset_left = -450.0
+offset_top = 25.0
+offset_right = -50.0
+offset_bottom = 250.0
+theme = ExtResource("2_wd24h")
+theme_type_variation = &"GDPanel"
+
+[node name="VBoxContainer" type="VBoxContainer" parent="CenterContainer/UIAnchor/UI/Panel2" unique_id=196865433]
+layout_mode = 2
+
+[node name="RichTextLabel" type="RichTextLabel" parent="CenterContainer/UIAnchor/UI/Panel2/VBoxContainer" unique_id=437873018]
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+text = "Please fill in an API Key so the engine may connect to the GD-Sync network."
+fit_content = true
+
+[node name="PublicLabel" type="Label" parent="CenterContainer/UIAnchor/UI/Panel2/VBoxContainer" unique_id=44499523]
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+text = "Public Key"
+
+[node name="PublicKey" type="LineEdit" parent="CenterContainer/UIAnchor/UI/Panel2/VBoxContainer" unique_id=372373993]
+unique_name_in_owner = true
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+caret_blink = true
+
+[node name="PrivateLabel" type="Label" parent="CenterContainer/UIAnchor/UI/Panel2/VBoxContainer" unique_id=206925556]
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+text = "Private Key"
+
+[node name="PrivateKey" type="LineEdit" parent="CenterContainer/UIAnchor/UI/Panel2/VBoxContainer" unique_id=1449264830]
+unique_name_in_owner = true
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+caret_blink = true
+
+[node name="Settings" type="PanelContainer" parent="CenterContainer/UIAnchor/UI" unique_id=1034112752]
+layout_mode = 0
+offset_left = 50.0
+offset_top = -250.0
+offset_right = 450.0
+offset_bottom = 250.0
+theme = ExtResource("2_wd24h")
+theme_type_variation = &"GDPanel"
+
+[node name="ScrollContainer" type="ScrollContainer" parent="CenterContainer/UIAnchor/UI/Settings" unique_id=453237216]
+layout_mode = 2
+size_flags_vertical = 3
+
+[node name="VBoxContainer" type="VBoxContainer" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer" unique_id=1339546343]
+layout_mode = 2
+size_flags_horizontal = 3
+
+[node name="ProtectionMode2" type="VBoxContainer" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer" unique_id=596699874]
+layout_mode = 2
+
+[node name="HBoxContainer" type="HBoxContainer" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/ProtectionMode2" unique_id=1142965809]
+layout_mode = 2
+
+[node name="CSharpSupport" type="CheckButton" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/ProtectionMode2/HBoxContainer" unique_id=1143148508]
+unique_name_in_owner = true
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+
+[node name="Label" type="Label" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/ProtectionMode2/HBoxContainer" unique_id=2048167211]
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+text = "C# Support"
+
+[node name="RichTextLabel" type="RichTextLabel" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/ProtectionMode2" unique_id=2131636992]
+custom_minimum_size = Vector2(0, 125)
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+bbcode_enabled = true
+text = "If enabled, the C# API of the GD-Sync plugin will be installed and enabled.
+
+After enabling you need to restart and build your project."
+fit_content = true
+
+[node name="Spacing1" type="Control" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer" unique_id=1495858133]
+custom_minimum_size = Vector2(0, 35)
+layout_mode = 2
+
+[node name="ProtectionMode" type="VBoxContainer" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer" unique_id=951164412]
+layout_mode = 2
+
+[node name="HBoxContainer" type="HBoxContainer" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/ProtectionMode" unique_id=2007314682]
+layout_mode = 2
+
+[node name="Protected" type="CheckButton" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/ProtectionMode/HBoxContainer" unique_id=1544686272]
+unique_name_in_owner = true
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+button_pressed = true
+
+[node name="Label" type="Label" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/ProtectionMode/HBoxContainer" unique_id=935600713]
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+text = "Protected Mode"
+
+[node name="RichTextLabel" type="RichTextLabel" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/ProtectionMode" unique_id=471701220]
+custom_minimum_size = Vector2(0, 100)
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+bbcode_enabled = true
+text = "Blocks remote calls on Nodes. Use [color=#408eab]GDSync.expose_func()[/color] and [color=#408eab]GDSync.expose_var()[/color] to allow the plugin to access Nodes remotely.
+
+[color=indianred]WARNING: Disabling this will allow other clients to call any function on any Node. Use at your own risk and only during testing."
+fit_content = true
+
+[node name="Spacing2" type="Control" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer" unique_id=1664573910]
+custom_minimum_size = Vector2(0, 35)
+layout_mode = 2
+
+[node name="UniqueUsernames" type="VBoxContainer" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer" unique_id=779527313]
+layout_mode = 2
+
+[node name="HBoxContainer" type="HBoxContainer" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/UniqueUsernames" unique_id=860810844]
+layout_mode = 2
+
+[node name="UniqueUsernames" type="CheckButton" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/UniqueUsernames/HBoxContainer" unique_id=1468164783]
+unique_name_in_owner = true
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+
+[node name="Label" type="Label" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/UniqueUsernames/HBoxContainer" unique_id=73397071]
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+text = "Unique Usernames"
+
+[node name="RichTextLabel" type="RichTextLabel" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/UniqueUsernames" unique_id=134873602]
+custom_minimum_size = Vector2(0, 100)
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+bbcode_enabled = true
+text = "Tells the server whether it should allow duplicate usernames when joining a lobby. If enabled, a username can only appear once inside a lobby.
+
+Usernames can be set using [color=#408eab]GDSync.player_set_username()[/color]."
+fit_content = true
+
+[node name="Spacing3" type="Control" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer" unique_id=688157772]
+custom_minimum_size = Vector2(0, 35)
+layout_mode = 2
+
+[node name="ScriptValidation" type="VBoxContainer" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer" unique_id=1790531497]
+layout_mode = 2
+
+[node name="HBoxContainer" type="HBoxContainer" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/ScriptValidation" unique_id=1585099442]
+layout_mode = 2
+
+[node name="ScriptValidation" type="CheckButton" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/ScriptValidation/HBoxContainer" unique_id=1439107572]
+unique_name_in_owner = true
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+button_pressed = true
+
+[node name="Label" type="Label" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/ScriptValidation/HBoxContainer" unique_id=1198682568]
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+text = "Script Validation"
+
+[node name="RichTextLabel" type="RichTextLabel" parent="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/ScriptValidation" unique_id=2054963013]
+custom_minimum_size = Vector2(0, 100)
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+bbcode_enabled = true
+text = "Script validation scans the script you are currently working on to detect possible mistakes and errors. If the plugin detects incorrect function usage or unexposed remote calls, a warning will be displayed in the Godot editor. This helps you catch common issues early, reducing debugging time and preventing runtime errors."
+fit_content = true
+
+[node name="ButtonContainer" type="PanelContainer" parent="CenterContainer/UIAnchor/UI" unique_id=1736452814]
+clip_children = 1
+clip_contents = true
+layout_mode = 0
+offset_left = -135.0
+offset_top = 280.0
+offset_right = 115.0
+offset_bottom = 320.0
+focus_mode = 2
+theme = ExtResource("2_wd24h")
+theme_type_variation = &"EmptyPanel"
+
+[node name="Close" type="Button" parent="CenterContainer/UIAnchor/UI/ButtonContainer" unique_id=1256304310]
+layout_mode = 2
+theme = ExtResource("2_wd24h")
+text = "Close"
+
+[connection signal="meta_clicked" from="CenterContainer/UIAnchor/UI/DefaultPannel/Description" to="." method="_on_description_meta_clicked"]
+[connection signal="meta_clicked" from="CenterContainer/UIAnchor/UI/UpdatePanel/Description" to="." method="_on_description_meta_clicked"]
+[connection signal="pressed" from="CenterContainer/UIAnchor/UI/UpdatePanel/ButtonContainer/UpdateButton" to="." method="_on_update_button_pressed"]
+[connection signal="text_changed" from="CenterContainer/UIAnchor/UI/Panel2/VBoxContainer/PublicKey" to="." method="_on_PublicKey_text_changed"]
+[connection signal="text_changed" from="CenterContainer/UIAnchor/UI/Panel2/VBoxContainer/PrivateKey" to="." method="_on_PrivateKey_text_changed"]
+[connection signal="toggled" from="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/ProtectionMode2/HBoxContainer/CSharpSupport" to="." method="_on_c_sharp_support_toggled"]
+[connection signal="toggled" from="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/ProtectionMode/HBoxContainer/Protected" to="." method="_on_protected_toggled"]
+[connection signal="toggled" from="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/UniqueUsernames/HBoxContainer/UniqueUsernames" to="." method="_on_unique_usernames_toggled"]
+[connection signal="toggled" from="CenterContainer/UIAnchor/UI/Settings/ScrollContainer/VBoxContainer/ScriptValidation/HBoxContainer/ScriptValidation" to="." method="_on_script_validation_toggled"]
+[connection signal="pressed" from="CenterContainer/UIAnchor/UI/ButtonContainer/Close" to="." method="close"]
diff --git a/addons/GD-Sync/UI/ConfigMenu/GD-Theme.tres b/addons/GD-Sync/UI/ConfigMenu/GD-Theme.tres
new file mode 100644
index 0000000..531d1ba
--- /dev/null
+++ b/addons/GD-Sync/UI/ConfigMenu/GD-Theme.tres
@@ -0,0 +1,200 @@
+[gd_resource type="Theme" format=3 uid="uid://5whm1igkt23h"]
+
+[ext_resource type="FontFile" uid="uid://bnjmhin4fqi2u" path="res://addons/GD-Sync/UI/Fonts/Outfit-Regular.ttf" id="1_15q4e"]
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_0vk81"]
+bg_color = Color(0.18431373, 0.18431373, 0.18431373, 0)
+border_width_left = 1
+border_width_top = 1
+border_width_right = 1
+border_width_bottom = 1
+border_color = Color(0.3125, 0.3125, 0.3125, 1)
+corner_radius_top_left = 10
+corner_radius_top_right = 10
+corner_radius_bottom_right = 10
+corner_radius_bottom_left = 10
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_ywbrc"]
+bg_color = Color(0.2509804, 0.5568628, 0.67058825, 1)
+border_width_left = 1
+border_width_top = 1
+border_width_right = 1
+border_width_bottom = 1
+corner_radius_top_left = 10
+corner_radius_top_right = 10
+corner_radius_bottom_right = 10
+corner_radius_bottom_left = 10
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_g3h2g"]
+bg_color = Color(0.2509804, 0.5568628, 0.67058825, 1)
+border_width_left = 1
+border_width_top = 1
+border_width_right = 1
+border_width_bottom = 1
+border_color = Color(0.2509804, 0.5568628, 0.67058825, 1)
+corner_radius_top_left = 10
+corner_radius_top_right = 10
+corner_radius_bottom_right = 10
+corner_radius_bottom_left = 10
+
+[sub_resource type="StyleBoxEmpty" id="StyleBoxEmpty_egfui"]
+
+[sub_resource type="StyleBoxEmpty" id="StyleBoxEmpty_ltv7d"]
+
+[sub_resource type="StyleBoxEmpty" id="StyleBoxEmpty_nr1xf"]
+
+[sub_resource type="StyleBoxEmpty" id="StyleBoxEmpty_ywlyk"]
+
+[sub_resource type="StyleBoxEmpty" id="StyleBoxEmpty_4x111"]
+
+[sub_resource type="StyleBoxEmpty" id="StyleBoxEmpty_ggeya"]
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_d26q0"]
+bg_color = Color(1, 1, 1, 1)
+corner_radius_top_left = 10
+corner_radius_top_right = 10
+corner_radius_bottom_right = 10
+corner_radius_bottom_left = 10
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_3a5b6"]
+content_margin_left = 15.0
+content_margin_top = 15.0
+content_margin_right = 15.0
+content_margin_bottom = 15.0
+bg_color = Color(0.08235294, 0.08235294, 0.08235294, 1)
+corner_radius_top_left = 20
+corner_radius_top_right = 20
+corner_radius_bottom_right = 20
+corner_radius_bottom_left = 20
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_rqrgd"]
+content_margin_left = 15.0
+content_margin_top = 8.0
+content_margin_right = 15.0
+content_margin_bottom = 8.0
+bg_color = Color(0.18028846, 0.18028846, 0.1875, 1)
+border_width_left = 1
+border_width_top = 1
+border_width_right = 1
+border_width_bottom = 1
+border_color = Color(0.25098, 0.556863, 0.670588, 1)
+corner_radius_top_left = 10
+corner_radius_top_right = 10
+corner_radius_bottom_right = 10
+corner_radius_bottom_left = 10
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_w5agy"]
+content_margin_left = 15.0
+content_margin_top = 8.0
+content_margin_right = 15.0
+content_margin_bottom = 8.0
+bg_color = Color(0.13719513, 0.13719513, 0.140625, 1)
+border_width_left = 1
+border_width_top = 1
+border_width_right = 1
+border_width_bottom = 1
+border_color = Color(0.25098, 0.556863, 0.670588, 1)
+corner_radius_top_left = 10
+corner_radius_top_right = 10
+corner_radius_bottom_right = 10
+corner_radius_bottom_left = 10
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_15q4e"]
+content_margin_left = 15.0
+content_margin_top = 15.0
+content_margin_right = 15.0
+content_margin_bottom = 15.0
+bg_color = Color(0.10980392, 0.10980392, 0.11372549, 1)
+border_width_left = 2
+border_width_top = 2
+border_width_right = 2
+border_width_bottom = 2
+border_color = Color(0.25098, 0.556863, 0.670588, 1)
+corner_radius_top_left = 20
+corner_radius_top_right = 20
+corner_radius_bottom_right = 20
+corner_radius_bottom_left = 20
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_7410l"]
+content_margin_left = 15.0
+content_margin_top = 15.0
+content_margin_right = 15.0
+content_margin_bottom = 15.0
+bg_color = Color(0.10980392, 0.10980392, 0.11372549, 1)
+border_width_left = 1
+border_width_top = 1
+border_width_right = 1
+border_width_bottom = 1
+border_color = Color(0.25098, 0.556863, 0.670588, 1)
+corner_radius_top_left = 20
+corner_radius_top_right = 20
+corner_radius_bottom_right = 20
+corner_radius_bottom_left = 20
+
+[sub_resource type="StyleBoxEmpty" id="StyleBoxEmpty_eb10s"]
+
+[sub_resource type="StyleBoxEmpty" id="StyleBoxEmpty_tcim6"]
+
+[sub_resource type="Gradient" id="Gradient_d26q0"]
+offsets = PackedFloat32Array(0.0016835016, 0.99579126)
+colors = PackedColorArray(0.16470589, 0.5254902, 0.21176471, 1, 0.3372549, 0.7882353, 0.27058825, 1)
+
+[sub_resource type="GradientTexture2D" id="GradientTexture2D_ywbrc"]
+gradient = SubResource("Gradient_d26q0")
+fill_from = Vector2(0, 1)
+fill_to = Vector2(0, 0)
+
+[sub_resource type="StyleBoxTexture" id="StyleBoxTexture_0vk81"]
+content_margin_top = 5.0
+content_margin_bottom = 5.0
+texture = SubResource("GradientTexture2D_ywbrc")
+
+[sub_resource type="Gradient" id="Gradient_oeli6"]
+offsets = PackedFloat32Array(0.0016835016, 0.99579126)
+colors = PackedColorArray(0.20796129, 0.6584021, 0.26671442, 1, 0.39228585, 0.9027938, 0.31681958, 1)
+
+[sub_resource type="GradientTexture2D" id="GradientTexture2D_jlle7"]
+gradient = SubResource("Gradient_oeli6")
+fill_from = Vector2(0, 1)
+fill_to = Vector2(0, 0)
+
+[sub_resource type="StyleBoxTexture" id="StyleBoxTexture_sr822"]
+content_margin_top = 5.0
+content_margin_bottom = 5.0
+texture = SubResource("GradientTexture2D_jlle7")
+
+[resource]
+default_font = ExtResource("1_15q4e")
+default_font_size = 16
+Button/colors/font_color = Color(0.87723213, 0.87723213, 0.87723213, 1)
+Button/colors/font_focus_color = Color(1, 1, 1, 1)
+Button/colors/font_hover_color = Color(1, 1, 1, 1)
+Button/colors/font_hover_pressed_color = Color(1, 1, 1, 1)
+Button/styles/disabled = SubResource("StyleBoxFlat_0vk81")
+Button/styles/hover = SubResource("StyleBoxFlat_ywbrc")
+Button/styles/normal = SubResource("StyleBoxFlat_g3h2g")
+Button/styles/pressed = SubResource("StyleBoxFlat_g3h2g")
+CheckButton/styles/disabled = SubResource("StyleBoxEmpty_egfui")
+CheckButton/styles/focus = SubResource("StyleBoxEmpty_ltv7d")
+CheckButton/styles/hover = SubResource("StyleBoxEmpty_nr1xf")
+CheckButton/styles/hover_pressed = SubResource("StyleBoxEmpty_ywlyk")
+CheckButton/styles/normal = SubResource("StyleBoxEmpty_4x111")
+CheckButton/styles/pressed = SubResource("StyleBoxEmpty_ggeya")
+EmptyPanel/base_type = &"PanelContainer"
+EmptyPanel/styles/panel = SubResource("StyleBoxFlat_d26q0")
+GDPanel/base_type = &"PanelContainer"
+GDPanel/styles/panel = SubResource("StyleBoxFlat_3a5b6")
+Label/colors/font_color = Color(1, 1, 1, 1)
+LineEdit/colors/font_color = Color(1, 1, 1, 1)
+LineEdit/styles/focus = SubResource("StyleBoxFlat_rqrgd")
+LineEdit/styles/normal = SubResource("StyleBoxFlat_w5agy")
+MessageLabel/base_type = &"RichTextLabel"
+MessageLabel/styles/normal = SubResource("StyleBoxFlat_15q4e")
+PanelContainer/styles/panel = SubResource("StyleBoxFlat_7410l")
+RichTextLabel/styles/focus = SubResource("StyleBoxEmpty_eb10s")
+RichTextLabel/styles/normal = SubResource("StyleBoxEmpty_tcim6")
+UpdateButton/base_type = &"Button"
+UpdateButton/styles/focus = SubResource("StyleBoxTexture_0vk81")
+UpdateButton/styles/hover = SubResource("StyleBoxTexture_sr822")
+UpdateButton/styles/normal = SubResource("StyleBoxTexture_0vk81")
+UpdateButton/styles/pressed = SubResource("StyleBoxTexture_0vk81")
diff --git a/addons/GD-Sync/UI/ConfigMenu/GDSLogo.png b/addons/GD-Sync/UI/ConfigMenu/GDSLogo.png
new file mode 100644
index 0000000..58dd1a9
Binary files /dev/null and b/addons/GD-Sync/UI/ConfigMenu/GDSLogo.png differ
diff --git a/addons/GD-Sync/UI/ConfigMenu/GDSLogo.png.import b/addons/GD-Sync/UI/ConfigMenu/GDSLogo.png.import
new file mode 100644
index 0000000..871a052
--- /dev/null
+++ b/addons/GD-Sync/UI/ConfigMenu/GDSLogo.png.import
@@ -0,0 +1,40 @@
+[remap]
+
+importer="texture"
+type="CompressedTexture2D"
+uid="uid://d2pl6xyfyub5k"
+path="res://.godot/imported/GDSLogo.png-f71dad2ce9e497aa8e805547e20fd4d7.ctex"
+metadata={
+"vram_texture": false
+}
+
+[deps]
+
+source_file="res://addons/GD-Sync/UI/ConfigMenu/GDSLogo.png"
+dest_files=["res://.godot/imported/GDSLogo.png-f71dad2ce9e497aa8e805547e20fd4d7.ctex"]
+
+[params]
+
+compress/mode=0
+compress/high_quality=false
+compress/lossy_quality=0.7
+compress/uastc_level=0
+compress/rdo_quality_loss=0.0
+compress/hdr_compression=1
+compress/normal_map=0
+compress/channel_pack=0
+mipmaps/generate=false
+mipmaps/limit=-1
+roughness/mode=0
+roughness/src_normal=""
+process/channel_remap/red=0
+process/channel_remap/green=1
+process/channel_remap/blue=2
+process/channel_remap/alpha=3
+process/fix_alpha_border=true
+process/premult_alpha=false
+process/normal_map_invert_y=false
+process/hdr_as_srgb=false
+process/hdr_clamp_exposure=false
+process/size_limit=0
+detect_3d/compress_to=1
diff --git a/addons/GD-Sync/UI/Fonts/Outfit-Regular.ttf b/addons/GD-Sync/UI/Fonts/Outfit-Regular.ttf
new file mode 100644
index 0000000..3939ab2
Binary files /dev/null and b/addons/GD-Sync/UI/Fonts/Outfit-Regular.ttf differ
diff --git a/addons/GD-Sync/UI/Fonts/Outfit-Regular.ttf.import b/addons/GD-Sync/UI/Fonts/Outfit-Regular.ttf.import
new file mode 100644
index 0000000..dc32e8b
--- /dev/null
+++ b/addons/GD-Sync/UI/Fonts/Outfit-Regular.ttf.import
@@ -0,0 +1,41 @@
+[remap]
+
+importer="font_data_dynamic"
+type="FontFile"
+uid="uid://bnjmhin4fqi2u"
+path="res://.godot/imported/Outfit-Regular.ttf-b3e20891c08db9fe7cabafc627c030a5.fontdata"
+
+[deps]
+
+source_file="res://addons/GD-Sync/UI/Fonts/Outfit-Regular.ttf"
+dest_files=["res://.godot/imported/Outfit-Regular.ttf-b3e20891c08db9fe7cabafc627c030a5.fontdata"]
+
+[params]
+
+Rendering=null
+antialiasing=1
+generate_mipmaps=false
+disable_embedded_bitmaps=true
+multichannel_signed_distance_field=false
+msdf_pixel_range=8
+msdf_size=48
+allow_system_fallback=true
+force_autohinter=false
+modulate_color_glyphs=false
+hinting=1
+subpixel_positioning=4
+keep_rounding_remainders=true
+oversampling=0.0
+Fallbacks=null
+fallbacks=[]
+Compress=null
+compress=true
+preload=[{
+"chars": [],
+"glyphs": [],
+"name": "New Configuration",
+"size": Vector2i(16, 0)
+}]
+language_support={}
+script_support={}
+opentype_features={}
diff --git a/addons/GD-Sync/UI/Icons/InterestObject.png b/addons/GD-Sync/UI/Icons/InterestObject.png
new file mode 100644
index 0000000..dca86a7
Binary files /dev/null and b/addons/GD-Sync/UI/Icons/InterestObject.png differ
diff --git a/addons/GD-Sync/UI/Icons/InterestObject.png.import b/addons/GD-Sync/UI/Icons/InterestObject.png.import
new file mode 100644
index 0000000..fe8e312
--- /dev/null
+++ b/addons/GD-Sync/UI/Icons/InterestObject.png.import
@@ -0,0 +1,40 @@
+[remap]
+
+importer="texture"
+type="CompressedTexture2D"
+uid="uid://daa7ckgyvsm1f"
+path="res://.godot/imported/InterestObject.png-c5a7a47000021e80ac7852ab8cf2f77d.ctex"
+metadata={
+"vram_texture": false
+}
+
+[deps]
+
+source_file="res://addons/GD-Sync/UI/Icons/InterestObject.png"
+dest_files=["res://.godot/imported/InterestObject.png-c5a7a47000021e80ac7852ab8cf2f77d.ctex"]
+
+[params]
+
+compress/mode=0
+compress/high_quality=false
+compress/lossy_quality=0.7
+compress/uastc_level=0
+compress/rdo_quality_loss=0.0
+compress/hdr_compression=1
+compress/normal_map=0
+compress/channel_pack=0
+mipmaps/generate=false
+mipmaps/limit=-1
+roughness/mode=0
+roughness/src_normal=""
+process/channel_remap/red=0
+process/channel_remap/green=1
+process/channel_remap/blue=2
+process/channel_remap/alpha=3
+process/fix_alpha_border=true
+process/premult_alpha=false
+process/normal_map_invert_y=false
+process/hdr_as_srgb=false
+process/hdr_clamp_exposure=false
+process/size_limit=0
+detect_3d/compress_to=1
diff --git a/addons/GD-Sync/UI/Icons/InterestViewer.png b/addons/GD-Sync/UI/Icons/InterestViewer.png
new file mode 100644
index 0000000..abaac9d
Binary files /dev/null and b/addons/GD-Sync/UI/Icons/InterestViewer.png differ
diff --git a/addons/GD-Sync/UI/Icons/InterestViewer.png.import b/addons/GD-Sync/UI/Icons/InterestViewer.png.import
new file mode 100644
index 0000000..58e8405
--- /dev/null
+++ b/addons/GD-Sync/UI/Icons/InterestViewer.png.import
@@ -0,0 +1,40 @@
+[remap]
+
+importer="texture"
+type="CompressedTexture2D"
+uid="uid://qx5gljo241ff"
+path="res://.godot/imported/InterestViewer.png-53536e16fa71a8ef727b5e731ddd842e.ctex"
+metadata={
+"vram_texture": false
+}
+
+[deps]
+
+source_file="res://addons/GD-Sync/UI/Icons/InterestViewer.png"
+dest_files=["res://.godot/imported/InterestViewer.png-53536e16fa71a8ef727b5e731ddd842e.ctex"]
+
+[params]
+
+compress/mode=0
+compress/high_quality=false
+compress/lossy_quality=0.7
+compress/uastc_level=0
+compress/rdo_quality_loss=0.0
+compress/hdr_compression=1
+compress/normal_map=0
+compress/channel_pack=0
+mipmaps/generate=false
+mipmaps/limit=-1
+roughness/mode=0
+roughness/src_normal=""
+process/channel_remap/red=0
+process/channel_remap/green=1
+process/channel_remap/blue=2
+process/channel_remap/alpha=3
+process/fix_alpha_border=true
+process/premult_alpha=false
+process/normal_map_invert_y=false
+process/hdr_as_srgb=false
+process/hdr_clamp_exposure=false
+process/size_limit=0
+detect_3d/compress_to=1
diff --git a/addons/GD-Sync/UI/Icons/LoadIcon.png b/addons/GD-Sync/UI/Icons/LoadIcon.png
new file mode 100644
index 0000000..2b673eb
Binary files /dev/null and b/addons/GD-Sync/UI/Icons/LoadIcon.png differ
diff --git a/addons/GD-Sync/UI/Icons/LoadIcon.png.import b/addons/GD-Sync/UI/Icons/LoadIcon.png.import
new file mode 100644
index 0000000..cf8a8e1
--- /dev/null
+++ b/addons/GD-Sync/UI/Icons/LoadIcon.png.import
@@ -0,0 +1,40 @@
+[remap]
+
+importer="texture"
+type="CompressedTexture2D"
+uid="uid://o7408i2pu2eb"
+path="res://.godot/imported/LoadIcon.png-be6aa56249fc38ca15dc8abba0037a0c.ctex"
+metadata={
+"vram_texture": false
+}
+
+[deps]
+
+source_file="res://addons/GD-Sync/UI/Icons/LoadIcon.png"
+dest_files=["res://.godot/imported/LoadIcon.png-be6aa56249fc38ca15dc8abba0037a0c.ctex"]
+
+[params]
+
+compress/mode=0
+compress/high_quality=false
+compress/lossy_quality=0.7
+compress/uastc_level=0
+compress/rdo_quality_loss=0.0
+compress/hdr_compression=1
+compress/normal_map=0
+compress/channel_pack=0
+mipmaps/generate=false
+mipmaps/limit=-1
+roughness/mode=0
+roughness/src_normal=""
+process/channel_remap/red=0
+process/channel_remap/green=1
+process/channel_remap/blue=2
+process/channel_remap/alpha=3
+process/fix_alpha_border=true
+process/premult_alpha=false
+process/normal_map_invert_y=false
+process/hdr_as_srgb=false
+process/hdr_clamp_exposure=false
+process/size_limit=0
+detect_3d/compress_to=1
diff --git a/addons/GD-Sync/UI/Icons/NodeInstantiator.png b/addons/GD-Sync/UI/Icons/NodeInstantiator.png
new file mode 100644
index 0000000..f60d71e
Binary files /dev/null and b/addons/GD-Sync/UI/Icons/NodeInstantiator.png differ
diff --git a/addons/GD-Sync/UI/Icons/NodeInstantiator.png.import b/addons/GD-Sync/UI/Icons/NodeInstantiator.png.import
new file mode 100644
index 0000000..5a212b8
--- /dev/null
+++ b/addons/GD-Sync/UI/Icons/NodeInstantiator.png.import
@@ -0,0 +1,40 @@
+[remap]
+
+importer="texture"
+type="CompressedTexture2D"
+uid="uid://dixhk6d1hn2et"
+path="res://.godot/imported/NodeInstantiator.png-40efd1f6857451b6a0ca56562b4c914b.ctex"
+metadata={
+"vram_texture": false
+}
+
+[deps]
+
+source_file="res://addons/GD-Sync/UI/Icons/NodeInstantiator.png"
+dest_files=["res://.godot/imported/NodeInstantiator.png-40efd1f6857451b6a0ca56562b4c914b.ctex"]
+
+[params]
+
+compress/mode=0
+compress/high_quality=false
+compress/lossy_quality=0.7
+compress/uastc_level=0
+compress/rdo_quality_loss=0.0
+compress/hdr_compression=1
+compress/normal_map=0
+compress/channel_pack=0
+mipmaps/generate=false
+mipmaps/limit=-1
+roughness/mode=0
+roughness/src_normal=""
+process/channel_remap/red=0
+process/channel_remap/green=1
+process/channel_remap/blue=2
+process/channel_remap/alpha=3
+process/fix_alpha_border=true
+process/premult_alpha=false
+process/normal_map_invert_y=false
+process/hdr_as_srgb=false
+process/hdr_clamp_exposure=false
+process/size_limit=0
+detect_3d/compress_to=1
diff --git a/addons/GD-Sync/UI/Icons/SynchronizeIcon.png b/addons/GD-Sync/UI/Icons/SynchronizeIcon.png
new file mode 100644
index 0000000..f2008ce
Binary files /dev/null and b/addons/GD-Sync/UI/Icons/SynchronizeIcon.png differ
diff --git a/addons/GD-Sync/UI/Icons/SynchronizeIcon.png.import b/addons/GD-Sync/UI/Icons/SynchronizeIcon.png.import
new file mode 100644
index 0000000..3f66f27
--- /dev/null
+++ b/addons/GD-Sync/UI/Icons/SynchronizeIcon.png.import
@@ -0,0 +1,40 @@
+[remap]
+
+importer="texture"
+type="CompressedTexture2D"
+uid="uid://waebdswld7o0"
+path="res://.godot/imported/SynchronizeIcon.png-1ab42da4ce082c51caf3ddd6acec7d17.ctex"
+metadata={
+"vram_texture": false
+}
+
+[deps]
+
+source_file="res://addons/GD-Sync/UI/Icons/SynchronizeIcon.png"
+dest_files=["res://.godot/imported/SynchronizeIcon.png-1ab42da4ce082c51caf3ddd6acec7d17.ctex"]
+
+[params]
+
+compress/mode=0
+compress/high_quality=false
+compress/lossy_quality=0.7
+compress/uastc_level=0
+compress/rdo_quality_loss=0.0
+compress/hdr_compression=1
+compress/normal_map=0
+compress/channel_pack=0
+mipmaps/generate=false
+mipmaps/limit=-1
+roughness/mode=0
+roughness/src_normal=""
+process/channel_remap/red=0
+process/channel_remap/green=1
+process/channel_remap/blue=2
+process/channel_remap/alpha=3
+process/fix_alpha_border=true
+process/premult_alpha=false
+process/normal_map_invert_y=false
+process/hdr_as_srgb=false
+process/hdr_clamp_exposure=false
+process/size_limit=0
+detect_3d/compress_to=1
diff --git a/addons/GD-Sync/UI/Icons/SynchronizedAnimatedSprite.png b/addons/GD-Sync/UI/Icons/SynchronizedAnimatedSprite.png
new file mode 100644
index 0000000..0128942
Binary files /dev/null and b/addons/GD-Sync/UI/Icons/SynchronizedAnimatedSprite.png differ
diff --git a/addons/GD-Sync/UI/Icons/SynchronizedAnimatedSprite.png.import b/addons/GD-Sync/UI/Icons/SynchronizedAnimatedSprite.png.import
new file mode 100644
index 0000000..a8cf2e5
--- /dev/null
+++ b/addons/GD-Sync/UI/Icons/SynchronizedAnimatedSprite.png.import
@@ -0,0 +1,40 @@
+[remap]
+
+importer="texture"
+type="CompressedTexture2D"
+uid="uid://cblirsycl5x8s"
+path="res://.godot/imported/SynchronizedAnimatedSprite.png-7403a5b0d42ca34336b023409e59a6da.ctex"
+metadata={
+"vram_texture": false
+}
+
+[deps]
+
+source_file="res://addons/GD-Sync/UI/Icons/SynchronizedAnimatedSprite.png"
+dest_files=["res://.godot/imported/SynchronizedAnimatedSprite.png-7403a5b0d42ca34336b023409e59a6da.ctex"]
+
+[params]
+
+compress/mode=0
+compress/high_quality=false
+compress/lossy_quality=0.7
+compress/uastc_level=0
+compress/rdo_quality_loss=0.0
+compress/hdr_compression=1
+compress/normal_map=0
+compress/channel_pack=0
+mipmaps/generate=false
+mipmaps/limit=-1
+roughness/mode=0
+roughness/src_normal=""
+process/channel_remap/red=0
+process/channel_remap/green=1
+process/channel_remap/blue=2
+process/channel_remap/alpha=3
+process/fix_alpha_border=true
+process/premult_alpha=false
+process/normal_map_invert_y=false
+process/hdr_as_srgb=false
+process/hdr_clamp_exposure=false
+process/size_limit=0
+detect_3d/compress_to=1
diff --git a/addons/GD-Sync/UI/Icons/SynchronizedAnimationPlayer.png b/addons/GD-Sync/UI/Icons/SynchronizedAnimationPlayer.png
new file mode 100644
index 0000000..b98475f
Binary files /dev/null and b/addons/GD-Sync/UI/Icons/SynchronizedAnimationPlayer.png differ
diff --git a/addons/GD-Sync/UI/Icons/SynchronizedAnimationPlayer.png.import b/addons/GD-Sync/UI/Icons/SynchronizedAnimationPlayer.png.import
new file mode 100644
index 0000000..7ac4e32
--- /dev/null
+++ b/addons/GD-Sync/UI/Icons/SynchronizedAnimationPlayer.png.import
@@ -0,0 +1,40 @@
+[remap]
+
+importer="texture"
+type="CompressedTexture2D"
+uid="uid://cyuilt0ssxo1l"
+path="res://.godot/imported/SynchronizedAnimationPlayer.png-cf401b327846a3ae860c30dae862914e.ctex"
+metadata={
+"vram_texture": false
+}
+
+[deps]
+
+source_file="res://addons/GD-Sync/UI/Icons/SynchronizedAnimationPlayer.png"
+dest_files=["res://.godot/imported/SynchronizedAnimationPlayer.png-cf401b327846a3ae860c30dae862914e.ctex"]
+
+[params]
+
+compress/mode=0
+compress/high_quality=false
+compress/lossy_quality=0.7
+compress/uastc_level=0
+compress/rdo_quality_loss=0.0
+compress/hdr_compression=1
+compress/normal_map=0
+compress/channel_pack=0
+mipmaps/generate=false
+mipmaps/limit=-1
+roughness/mode=0
+roughness/src_normal=""
+process/channel_remap/red=0
+process/channel_remap/green=1
+process/channel_remap/blue=2
+process/channel_remap/alpha=3
+process/fix_alpha_border=true
+process/premult_alpha=false
+process/normal_map_invert_y=false
+process/hdr_as_srgb=false
+process/hdr_clamp_exposure=false
+process/size_limit=0
+detect_3d/compress_to=1
diff --git a/addons/GD-Sync/UI/Icons/SynchronizedAnimationTree.png b/addons/GD-Sync/UI/Icons/SynchronizedAnimationTree.png
new file mode 100644
index 0000000..ee6a7ca
Binary files /dev/null and b/addons/GD-Sync/UI/Icons/SynchronizedAnimationTree.png differ
diff --git a/addons/GD-Sync/UI/Icons/SynchronizedAnimationTree.png.import b/addons/GD-Sync/UI/Icons/SynchronizedAnimationTree.png.import
new file mode 100644
index 0000000..b58a6cf
--- /dev/null
+++ b/addons/GD-Sync/UI/Icons/SynchronizedAnimationTree.png.import
@@ -0,0 +1,40 @@
+[remap]
+
+importer="texture"
+type="CompressedTexture2D"
+uid="uid://cjm4ioceaef46"
+path="res://.godot/imported/SynchronizedAnimationTree.png-c98b0b98c2f6a99853b10a2d7f88422f.ctex"
+metadata={
+"vram_texture": false
+}
+
+[deps]
+
+source_file="res://addons/GD-Sync/UI/Icons/SynchronizedAnimationTree.png"
+dest_files=["res://.godot/imported/SynchronizedAnimationTree.png-c98b0b98c2f6a99853b10a2d7f88422f.ctex"]
+
+[params]
+
+compress/mode=0
+compress/high_quality=false
+compress/lossy_quality=0.7
+compress/uastc_level=0
+compress/rdo_quality_loss=0.0
+compress/hdr_compression=1
+compress/normal_map=0
+compress/channel_pack=0
+mipmaps/generate=false
+mipmaps/limit=-1
+roughness/mode=0
+roughness/src_normal=""
+process/channel_remap/red=0
+process/channel_remap/green=1
+process/channel_remap/blue=2
+process/channel_remap/alpha=3
+process/fix_alpha_border=true
+process/premult_alpha=false
+process/normal_map_invert_y=false
+process/hdr_as_srgb=false
+process/hdr_clamp_exposure=false
+process/size_limit=0
+detect_3d/compress_to=1
diff --git a/addons/GD-Sync/UI/Icons/SynchronizedAudioStreamPlayer.png b/addons/GD-Sync/UI/Icons/SynchronizedAudioStreamPlayer.png
new file mode 100644
index 0000000..966c82e
Binary files /dev/null and b/addons/GD-Sync/UI/Icons/SynchronizedAudioStreamPlayer.png differ
diff --git a/addons/GD-Sync/UI/Icons/SynchronizedAudioStreamPlayer.png.import b/addons/GD-Sync/UI/Icons/SynchronizedAudioStreamPlayer.png.import
new file mode 100644
index 0000000..02859e0
--- /dev/null
+++ b/addons/GD-Sync/UI/Icons/SynchronizedAudioStreamPlayer.png.import
@@ -0,0 +1,40 @@
+[remap]
+
+importer="texture"
+type="CompressedTexture2D"
+uid="uid://cymoc01vc7y44"
+path="res://.godot/imported/SynchronizedAudioStreamPlayer.png-1b503a1d618928852a445ac19a62d5bb.ctex"
+metadata={
+"vram_texture": false
+}
+
+[deps]
+
+source_file="res://addons/GD-Sync/UI/Icons/SynchronizedAudioStreamPlayer.png"
+dest_files=["res://.godot/imported/SynchronizedAudioStreamPlayer.png-1b503a1d618928852a445ac19a62d5bb.ctex"]
+
+[params]
+
+compress/mode=0
+compress/high_quality=false
+compress/lossy_quality=0.7
+compress/uastc_level=0
+compress/rdo_quality_loss=0.0
+compress/hdr_compression=1
+compress/normal_map=0
+compress/channel_pack=0
+mipmaps/generate=false
+mipmaps/limit=-1
+roughness/mode=0
+roughness/src_normal=""
+process/channel_remap/red=0
+process/channel_remap/green=1
+process/channel_remap/blue=2
+process/channel_remap/alpha=3
+process/fix_alpha_border=true
+process/premult_alpha=false
+process/normal_map_invert_y=false
+process/hdr_as_srgb=false
+process/hdr_clamp_exposure=false
+process/size_limit=0
+detect_3d/compress_to=1
diff --git a/addons/GD-Sync/UI/Icons/SynchronizedGPUParticles.png b/addons/GD-Sync/UI/Icons/SynchronizedGPUParticles.png
new file mode 100644
index 0000000..5f92403
Binary files /dev/null and b/addons/GD-Sync/UI/Icons/SynchronizedGPUParticles.png differ
diff --git a/addons/GD-Sync/UI/Icons/SynchronizedGPUParticles.png.import b/addons/GD-Sync/UI/Icons/SynchronizedGPUParticles.png.import
new file mode 100644
index 0000000..5caf6cc
--- /dev/null
+++ b/addons/GD-Sync/UI/Icons/SynchronizedGPUParticles.png.import
@@ -0,0 +1,40 @@
+[remap]
+
+importer="texture"
+type="CompressedTexture2D"
+uid="uid://dlmumb0bych13"
+path="res://.godot/imported/SynchronizedGPUParticles.png-d319605cd8face1d60a71c5fed589c03.ctex"
+metadata={
+"vram_texture": false
+}
+
+[deps]
+
+source_file="res://addons/GD-Sync/UI/Icons/SynchronizedGPUParticles.png"
+dest_files=["res://.godot/imported/SynchronizedGPUParticles.png-d319605cd8face1d60a71c5fed589c03.ctex"]
+
+[params]
+
+compress/mode=0
+compress/high_quality=false
+compress/lossy_quality=0.7
+compress/uastc_level=0
+compress/rdo_quality_loss=0.0
+compress/hdr_compression=1
+compress/normal_map=0
+compress/channel_pack=0
+mipmaps/generate=false
+mipmaps/limit=-1
+roughness/mode=0
+roughness/src_normal=""
+process/channel_remap/red=0
+process/channel_remap/green=1
+process/channel_remap/blue=2
+process/channel_remap/alpha=3
+process/fix_alpha_border=true
+process/premult_alpha=false
+process/normal_map_invert_y=false
+process/hdr_as_srgb=false
+process/hdr_clamp_exposure=false
+process/size_limit=0
+detect_3d/compress_to=1
diff --git a/addons/GD-Sync/UI/Icons/SynchronizedRigidBody3D.png b/addons/GD-Sync/UI/Icons/SynchronizedRigidBody3D.png
new file mode 100644
index 0000000..eb40d24
Binary files /dev/null and b/addons/GD-Sync/UI/Icons/SynchronizedRigidBody3D.png differ
diff --git a/addons/GD-Sync/UI/Icons/SynchronizedRigidBody3D.png.import b/addons/GD-Sync/UI/Icons/SynchronizedRigidBody3D.png.import
new file mode 100644
index 0000000..0a3e208
--- /dev/null
+++ b/addons/GD-Sync/UI/Icons/SynchronizedRigidBody3D.png.import
@@ -0,0 +1,40 @@
+[remap]
+
+importer="texture"
+type="CompressedTexture2D"
+uid="uid://cx5aov1b58ju2"
+path="res://.godot/imported/SynchronizedRigidBody3D.png-31f6bd5e655d6d4c7f4d4ca500c52d26.ctex"
+metadata={
+"vram_texture": false
+}
+
+[deps]
+
+source_file="res://addons/GD-Sync/UI/Icons/SynchronizedRigidBody3D.png"
+dest_files=["res://.godot/imported/SynchronizedRigidBody3D.png-31f6bd5e655d6d4c7f4d4ca500c52d26.ctex"]
+
+[params]
+
+compress/mode=0
+compress/high_quality=false
+compress/lossy_quality=0.7
+compress/uastc_level=0
+compress/rdo_quality_loss=0.0
+compress/hdr_compression=1
+compress/normal_map=0
+compress/channel_pack=0
+mipmaps/generate=false
+mipmaps/limit=-1
+roughness/mode=0
+roughness/src_normal=""
+process/channel_remap/red=0
+process/channel_remap/green=1
+process/channel_remap/blue=2
+process/channel_remap/alpha=3
+process/fix_alpha_border=true
+process/premult_alpha=false
+process/normal_map_invert_y=false
+process/hdr_as_srgb=false
+process/hdr_clamp_exposure=false
+process/size_limit=0
+detect_3d/compress_to=1
diff --git a/addons/GD-Sync/UI/Icons/VoiceChatIcon.png b/addons/GD-Sync/UI/Icons/VoiceChatIcon.png
new file mode 100644
index 0000000..ab3bd1b
Binary files /dev/null and b/addons/GD-Sync/UI/Icons/VoiceChatIcon.png differ
diff --git a/addons/GD-Sync/UI/Icons/VoiceChatIcon.png.import b/addons/GD-Sync/UI/Icons/VoiceChatIcon.png.import
new file mode 100644
index 0000000..659dcc5
--- /dev/null
+++ b/addons/GD-Sync/UI/Icons/VoiceChatIcon.png.import
@@ -0,0 +1,40 @@
+[remap]
+
+importer="texture"
+type="CompressedTexture2D"
+uid="uid://coo0gdr0wbjah"
+path="res://.godot/imported/VoiceChatIcon.png-e78177b9beb132e5a547d5c650bc9a37.ctex"
+metadata={
+"vram_texture": false
+}
+
+[deps]
+
+source_file="res://addons/GD-Sync/UI/Icons/VoiceChatIcon.png"
+dest_files=["res://.godot/imported/VoiceChatIcon.png-e78177b9beb132e5a547d5c650bc9a37.ctex"]
+
+[params]
+
+compress/mode=0
+compress/high_quality=false
+compress/lossy_quality=0.7
+compress/uastc_level=0
+compress/rdo_quality_loss=0.0
+compress/hdr_compression=1
+compress/normal_map=0
+compress/channel_pack=0
+mipmaps/generate=false
+mipmaps/limit=-1
+roughness/mode=0
+roughness/src_normal=""
+process/channel_remap/red=0
+process/channel_remap/green=1
+process/channel_remap/blue=2
+process/channel_remap/alpha=3
+process/fix_alpha_border=true
+process/premult_alpha=false
+process/normal_map_invert_y=false
+process/hdr_as_srgb=false
+process/hdr_clamp_exposure=false
+process/size_limit=0
+detect_3d/compress_to=1
diff --git a/addons/GD-Sync/UI/Messages/ToastMessage.gd b/addons/GD-Sync/UI/Messages/ToastMessage.gd
new file mode 100644
index 0000000..137fee5
--- /dev/null
+++ b/addons/GD-Sync/UI/Messages/ToastMessage.gd
@@ -0,0 +1,88 @@
+@tool
+extends Control
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+var slide_tween : Tween = null
+var main_tween : Tween = null
+var is_hovered : bool = false
+var can_pause : bool = false
+
+func set_message(message : String, destroy : bool = true, duration : float = 5.0) -> void:
+ var scale : float = size.y/1080.0
+ $Anchor.scale = Vector2.ONE*scale
+
+ var label : Control = $Anchor/Label
+ label.text = message
+ label.visible = true
+
+ var original_position : Vector2 = label.position
+ var offscreen_position : Vector2 = original_position + Vector2(1000, 0)
+ label.position = offscreen_position
+
+ main_tween = create_tween()
+ main_tween.set_ease(Tween.EASE_OUT)
+ main_tween.set_trans(Tween.TRANS_CUBIC)
+ main_tween.tween_property(label, "position", original_position, 0.5)
+ main_tween.tween_callback(func():
+ can_pause = true
+ if is_hovered: main_tween.pause())
+
+ if destroy:
+ main_tween.tween_interval(duration)
+ main_tween.tween_callback(func(): can_pause = false)
+
+ main_tween.set_ease(Tween.EASE_IN)
+ main_tween.tween_property(label, "position", offscreen_position, 0.5)
+
+ await main_tween.finished
+ queue_free()
+
+func update_position(target_height : float) -> void:
+ var target_y : float = -target_height
+
+ if slide_tween:
+ slide_tween.kill()
+
+ slide_tween = create_tween()
+ slide_tween.set_ease(Tween.EASE_OUT)
+ slide_tween.set_trans(Tween.TRANS_CUBIC)
+ slide_tween.tween_property(self, "position:y", target_y, 0.3)
+
+func get_height() -> float:
+ var scale : float = size.y/1080.0
+ return ($Anchor/Label.size.y + 20)*scale
+
+func _on_label_meta_clicked(meta: Variant) -> void:
+ OS.shell_open(str(meta))
+
+func _on_label_mouse_entered() -> void:
+ is_hovered = true
+ if main_tween and main_tween.is_running() and can_pause:
+ main_tween.pause()
+
+func _on_label_mouse_exited() -> void:
+ is_hovered = false
+ if main_tween and main_tween.is_valid() and can_pause:
+ main_tween.play()
diff --git a/addons/GD-Sync/UI/Messages/ToastMessage.gd.uid b/addons/GD-Sync/UI/Messages/ToastMessage.gd.uid
new file mode 100644
index 0000000..0add19d
--- /dev/null
+++ b/addons/GD-Sync/UI/Messages/ToastMessage.gd.uid
@@ -0,0 +1 @@
+uid://cv2owqer2ekyg
diff --git a/addons/GD-Sync/UI/Messages/ToastMessage.tscn b/addons/GD-Sync/UI/Messages/ToastMessage.tscn
new file mode 100644
index 0000000..ac6643e
--- /dev/null
+++ b/addons/GD-Sync/UI/Messages/ToastMessage.tscn
@@ -0,0 +1,48 @@
+[gd_scene load_steps=3 format=3 uid="uid://dewhdphifjt15"]
+
+[ext_resource type="Script" uid="uid://cv2owqer2ekyg" path="res://addons/GD-Sync/UI/Messages/ToastMessage.gd" id="1_2ijdd"]
+[ext_resource type="Theme" uid="uid://5whm1igkt23h" path="res://addons/GD-Sync/UI/ConfigMenu/GD-Theme.tres" id="1_nql3a"]
+
+[node name="ToastMessage" type="Control"]
+layout_mode = 3
+anchors_preset = 15
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 2
+grow_vertical = 2
+mouse_filter = 2
+theme = ExtResource("1_nql3a")
+script = ExtResource("1_2ijdd")
+
+[node name="Anchor" type="Control" parent="."]
+layout_mode = 1
+anchors_preset = 3
+anchor_left = 1.0
+anchor_top = 1.0
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 0
+grow_vertical = 0
+mouse_filter = 2
+
+[node name="Label" type="RichTextLabel" parent="Anchor"]
+layout_mode = 1
+anchors_preset = 3
+anchor_left = 1.0
+anchor_top = 1.0
+anchor_right = 1.0
+anchor_bottom = 1.0
+offset_left = -553.0
+offset_top = -66.0
+offset_right = -13.880005
+offset_bottom = -15.0
+grow_horizontal = 0
+grow_vertical = 0
+theme_type_variation = &"MessageLabel"
+bbcode_enabled = true
+text = "Epic cool message!"
+fit_content = true
+
+[connection signal="meta_clicked" from="Anchor/Label" to="." method="_on_label_meta_clicked"]
+[connection signal="mouse_entered" from="Anchor/Label" to="." method="_on_label_mouse_entered"]
+[connection signal="mouse_exited" from="Anchor/Label" to="." method="_on_label_mouse_exited"]
diff --git a/addons/GD-Sync/UI/Profiler/GDSyncProfiler.gd b/addons/GD-Sync/UI/Profiler/GDSyncProfiler.gd
new file mode 100644
index 0000000..5dc8519
--- /dev/null
+++ b/addons/GD-Sync/UI/Profiler/GDSyncProfiler.gd
@@ -0,0 +1,266 @@
+@tool
+extends Control
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+signal stats_updated(client_id : int, stats : Dictionary)
+signal custom_data_updated(data : Dictionary)
+signal message_details_updated(details : Dictionary)
+signal client_joined(client_id : int)
+signal client_left(client_id : int)
+signal ping_measured(client_id : int, ping : float, perceived_ping : float)
+signal start_monitoring_connections
+signal stop_monitoring_connections
+signal artificial_latency_changed(latency_ms : int)
+signal profiler_cleared()
+signal profiler_started()
+signal profiler_stopped()
+
+@export var start_button : Button = null : set = _set_start_button
+@export var stop_button : Button = null : set = _set_stop_button
+
+var auto_start : bool = false
+var artificial_latency_ms : int = 0
+
+var valid_session : bool = false
+var global_stats : Dictionary = {
+ "up":0,"down":0,"pkts_up":0,"pkts_down":0,
+ "up_sec":0.0,"down_sec":0.0,"pkts_up_sec":0.0,"pkts_down_sec":0.0,
+ "avg_msg_up":0.0,"avg_msg_down":0.0,"avg_msg_up_sec":0.0,"avg_msg_down_sec":0.0,
+ "last":0.0,"hist":[],
+ "total_sec": 0.0
+}
+var client_stats : Dictionary = {}
+var custom_data : Dictionary = {}
+var message_details_up : Dictionary = {}
+var message_details_down : Dictionary = {}
+var last_details_emit : float = 0.0
+const DETAILS_EMIT_INTERVAL : float = 5.0
+
+func _ready() -> void:
+ stop()
+ clear()
+ invalidate_session()
+ _update_button_states()
+
+func _on_auto_start_toggled(toggled_on: bool) -> void:
+ auto_start = true
+
+func _on_artificial_latency_changed(value : float) -> void:
+ artificial_latency_ms = int(value)
+ artificial_latency_changed.emit(artificial_latency_ms)
+
+func _set_start_button(btn) -> void:
+ start_button = btn
+ _update_button_states()
+
+func _set_stop_button(btn) -> void:
+ stop_button = btn
+ _update_button_states()
+
+func _update_button_states() -> void:
+ if start_button:
+ start_button.disabled = is_processing() or !valid_session
+ if stop_button:
+ stop_button.disabled = !is_processing() or !valid_session
+
+func start() -> void:
+ if is_processing(): return
+ set_process(true)
+ profiler_started.emit()
+ _update_button_states()
+
+func stop() -> void:
+ if not is_processing(): return
+ set_process(false)
+ profiler_stopped.emit()
+ _update_button_states()
+
+func clear() -> void:
+ global_stats = {
+ "up":0,"down":0,"pkts_up":0,"pkts_down":0,
+ "up_sec":0.0,"down_sec":0.0,"pkts_up_sec":0.0,"pkts_down_sec":0.0,
+ "avg_msg_up":0.0,"avg_msg_down":0.0,"avg_msg_up_sec":0.0,"avg_msg_down_sec":0.0,
+ "last":0.0,"hist":[],
+ "total_sec": 0.0
+ }
+ client_stats.clear()
+ custom_data.clear()
+ message_details_up.clear()
+ message_details_down.clear()
+ last_details_emit = 0.0
+ profiler_cleared.emit()
+ custom_data_updated.emit(custom_data)
+ message_details_updated.emit({"up": {}, "down": {}})
+
+func validate_session() -> void:
+ valid_session = true
+ _update_button_states()
+
+func invalidate_session() -> void:
+ valid_session = false
+ _update_button_states()
+
+func game_started() -> void:
+ if auto_start:
+ start()
+
+func register_transfer_usage(client_id : int, origin : Dictionary, byte_count : int, upload : bool, details : String) -> void:
+ if client_id <= 0: return
+ var dir = "up" if upload else "down"
+ var pkt_key = "pkts_" + dir
+ global_stats[dir] += byte_count
+ global_stats[pkt_key] += 1
+ var c = client_stats.get(client_id, {
+ "up":0,"down":0,"pkts_up":0,"pkts_down":0,
+ "up_sec":0.0,"down_sec":0.0,"pkts_up_sec":0.0,"pkts_down_sec":0.0,
+ "avg_msg_up":0.0,"avg_msg_down":0.0,"avg_msg_up_sec":0.0,"avg_msg_down_sec":0.0,
+ "last":0.0,"hist":[],
+ "total_sec": 0.0
+ })
+ c[dir] += byte_count
+ c[pkt_key] += 1
+ client_stats[client_id] = c
+
+ var key = "%s-%s-%s" % [origin.get("type", ""), origin.get("object", ""), origin.get("target", "")]
+ if key == "--":
+ return
+
+ var details_dict = message_details_up if upload else message_details_down
+ var entry = details_dict.get(key, {
+ "type": origin.get("type", ""),
+ "object": origin.get("object", ""),
+ "target": origin.get("target", ""),
+ "count": 0,
+ "total_bytes": 0,
+ "avg_bytes": 0.0,
+ "percent": 0.0,
+ "last_details": []
+ })
+ entry.count += 1
+ entry.total_bytes += byte_count
+ entry.avg_bytes = entry.total_bytes / entry.count
+
+ entry.last_details.append(details)
+ if entry.last_details.size() > 3:
+ entry.last_details.pop_front()
+
+ details_dict[key] = entry
+
+func register_custom_data(data : Dictionary) -> void:
+ for key in data.keys():
+ custom_data[key] = data[key]
+ custom_data_updated.emit(custom_data)
+
+func _process(_delta):
+ var now = Time.get_ticks_msec() / 1000.0
+ if now - global_stats.last >= 1.0:
+ _update_rates(global_stats, now)
+ _update_rates_all_clients(now)
+ _emit_all()
+ global_stats.last = now
+
+ if now - last_details_emit >= DETAILS_EMIT_INTERVAL:
+ _update_message_percentages()
+ var combined = {
+ "up": message_details_up.duplicate(),
+ "down": message_details_down.duplicate()
+ }
+ message_details_updated.emit(combined)
+ last_details_emit = now
+
+func _update_message_percentages() -> void:
+ _update_percentages_for(message_details_up)
+ _update_percentages_for(message_details_down)
+
+func _update_percentages_for(dict : Dictionary) -> void:
+ var total_bytes : int = 0
+ for key in dict.keys():
+ total_bytes += dict[key].total_bytes
+ if total_bytes == 0:
+ for key in dict.keys():
+ dict[key].percent = 0.0
+ else:
+ for key in dict.keys():
+ var entry = dict[key]
+ entry.percent = (entry.total_bytes as float / total_bytes) * 100.0
+ dict[key] = entry
+
+func _update_rates(stats : Dictionary, now : float) -> void:
+ var h = stats.hist
+ h.append({
+ "t":now,
+ "up":stats.up,"down":stats.down,
+ "pkts_up":stats.pkts_up,"pkts_down":stats.pkts_down
+ })
+ while h.size() > 0 and now - h[0].t > 5.0:
+ h.pop_front()
+ if h.size() < 2:
+ stats.up_sec = 0.0
+ stats.down_sec = 0.0
+ stats.pkts_up_sec = 0.0
+ stats.pkts_down_sec = 0.0
+ stats.avg_msg_up = 0.0
+ stats.avg_msg_down = 0.0
+ stats.avg_msg_up_sec = 0.0
+ stats.avg_msg_down_sec = 0.0
+ stats.total_sec = 0.0
+ return
+ var first = h[0]
+ var last = h[-1]
+ var dt = last.t - first.t
+ if dt <= 0.0:
+ stats.up_sec = 0.0
+ stats.down_sec = 0.0
+ stats.pkts_up_sec = 0.0
+ stats.pkts_down_sec = 0.0
+ stats.avg_msg_up_sec = 0.0
+ stats.avg_msg_down_sec = 0.0
+ stats.total_sec = 0.0
+ return
+ var delta_up = last.up - first.up
+ var delta_down = last.down - first.down
+ var delta_pkts_up = last.pkts_up - first.pkts_up
+ var delta_pkts_down = last.pkts_down - first.pkts_down
+ stats.up_sec = delta_up / dt
+ stats.down_sec = delta_down / dt
+ stats.pkts_up_sec = delta_pkts_up / dt
+ stats.pkts_down_sec = delta_pkts_down / dt
+ stats.avg_msg_up_sec = delta_up / delta_pkts_up if delta_pkts_up > 0 else 0.0
+ stats.avg_msg_down_sec = delta_down / delta_pkts_down if delta_pkts_down > 0 else 0.0
+ var total_pkts_up = stats.pkts_up
+ var total_pkts_down = stats.pkts_down
+ stats.avg_msg_up = stats.up / total_pkts_up if total_pkts_up > 0 else 0.0
+ stats.avg_msg_down = stats.down / total_pkts_down if total_pkts_down > 0 else 0.0
+ stats.total_sec = stats.up_sec + stats.down_sec
+
+func _update_rates_all_clients(now : float) -> void:
+ for cid in client_stats.keys():
+ _update_rates(client_stats[cid], now)
+
+func _emit_all() -> void:
+ stats_updated.emit(-1, global_stats)
+ for cid in client_stats.keys():
+ stats_updated.emit(cid, client_stats[cid])
diff --git a/addons/GD-Sync/UI/Profiler/GDSyncProfiler.gd.uid b/addons/GD-Sync/UI/Profiler/GDSyncProfiler.gd.uid
new file mode 100644
index 0000000..b902237
--- /dev/null
+++ b/addons/GD-Sync/UI/Profiler/GDSyncProfiler.gd.uid
@@ -0,0 +1 @@
+uid://c00gfpya5uiw0
diff --git a/addons/GD-Sync/UI/Profiler/GDSyncProfiler.tscn b/addons/GD-Sync/UI/Profiler/GDSyncProfiler.tscn
new file mode 100644
index 0000000..fb78dbf
--- /dev/null
+++ b/addons/GD-Sync/UI/Profiler/GDSyncProfiler.tscn
@@ -0,0 +1,810 @@
+[gd_scene load_steps=6 format=3 uid="uid://c3udn6jwoy6an"]
+
+[ext_resource type="Script" uid="uid://c00gfpya5uiw0" path="res://addons/GD-Sync/UI/Profiler/GDSyncProfiler.gd" id="1_ysct5"]
+[ext_resource type="Script" uid="uid://b3p26nyamgl8j" path="res://addons/GD-Sync/UI/Profiler/ProfilerLabel.gd" id="2_5m75r"]
+[ext_resource type="Script" uid="uid://8618gttywoy6" path="res://addons/GD-Sync/UI/Profiler/ProfilerGraph.gd" id="3_hrjsf"]
+[ext_resource type="Script" uid="uid://4b1i1ihfsqdf" path="res://addons/GD-Sync/UI/Profiler/ProfilerDetailsDisplay.gd" id="4_bk6j0"]
+[ext_resource type="Script" uid="uid://frgb8qcxxcoj" path="res://addons/GD-Sync/UI/Profiler/ProfilerConnectionMonitor.gd" id="4_gnjya"]
+
+[node name="GDSyncProfiler" type="Control" node_paths=PackedStringArray("start_button", "stop_button")]
+layout_mode = 3
+anchors_preset = 15
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 2
+grow_vertical = 2
+script = ExtResource("1_ysct5")
+start_button = NodePath("VBoxContainer/HBoxContainer/Start")
+stop_button = NodePath("VBoxContainer/HBoxContainer/Stop")
+
+[node name="VBoxContainer" type="VBoxContainer" parent="."]
+layout_mode = 1
+anchors_preset = 15
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 2
+grow_vertical = 2
+
+[node name="HBoxContainer" type="HBoxContainer" parent="VBoxContainer"]
+layout_mode = 2
+
+[node name="Title" type="Label" parent="VBoxContainer/HBoxContainer"]
+layout_mode = 2
+text = "GD-Sync Network Profiler"
+
+[node name="VSeparator" type="VSeparator" parent="VBoxContainer/HBoxContainer"]
+layout_mode = 2
+
+[node name="Start" type="Button" parent="VBoxContainer/HBoxContainer"]
+layout_mode = 2
+disabled = true
+text = "Start Profiler"
+
+[node name="Stop" type="Button" parent="VBoxContainer/HBoxContainer"]
+layout_mode = 2
+disabled = true
+text = "Stop Profiler"
+
+[node name="Clear" type="Button" parent="VBoxContainer/HBoxContainer"]
+layout_mode = 2
+text = "Clear Profiler"
+
+[node name="VSeparator2" type="VSeparator" parent="VBoxContainer/HBoxContainer"]
+layout_mode = 2
+
+[node name="AutoStart" type="CheckButton" parent="VBoxContainer/HBoxContainer"]
+layout_mode = 2
+text = "Auto Start"
+
+[node name="VSeparator3" type="VSeparator" parent="VBoxContainer/HBoxContainer"]
+layout_mode = 2
+
+[node name="LatencyLabel" type="Label" parent="VBoxContainer/HBoxContainer"]
+layout_mode = 2
+tooltip_text = "Adds artificial send and receive latency to this client for debugging. Set to 0 to disable."
+text = "Artificial Latency (ms)"
+
+[node name="LatencySpinBox" type="SpinBox" parent="VBoxContainer/HBoxContainer"]
+layout_mode = 2
+tooltip_text = "Adds artificial send and receive latency to this client for debugging. Set to 0 to disable."
+max_value = 5000.0
+prefix = ""
+suffix = "ms"
+
+[node name="HSeparator" type="HSeparator" parent="VBoxContainer"]
+layout_mode = 2
+
+[node name="TabContainer" type="TabContainer" parent="VBoxContainer"]
+layout_mode = 2
+size_flags_vertical = 3
+current_tab = 1
+
+[node name="General" type="TabBar" parent="VBoxContainer/TabContainer"]
+visible = false
+layout_mode = 2
+metadata/_tab_index = 0
+
+[node name="ScrollContainer" type="ScrollContainer" parent="VBoxContainer/TabContainer/General"]
+layout_mode = 1
+anchors_preset = 15
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 2
+grow_vertical = 2
+
+[node name="VBoxContainer" type="VBoxContainer" parent="VBoxContainer/TabContainer/General/ScrollContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+
+[node name="PanelContainer" type="PanelContainer" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer"]
+layout_mode = 2
+
+[node name="HBoxContainer" type="HBoxContainer" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer"]
+layout_mode = 2
+
+[node name="HBoxContainer" type="HBoxContainer" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+
+[node name="VBoxContainer" type="VBoxContainer" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+
+[node name="Incoming" type="Label" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer"]
+layout_mode = 2
+text = "Incoming:"
+
+[node name="Label1" type="RichTextLabel" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer" node_paths=PackedStringArray("profiler")]
+unique_name_in_owner = true
+layout_mode = 2
+tooltip_text = "The total amount of bytes that have been received from both the server and other clients."
+bbcode_enabled = true
+text = "[color=#ffffff]Total Bytes Received: ...[/color]"
+fit_content = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../../../../..")
+stat_key = "down"
+decimal_places = 2
+suffix = ""
+label_text = "Total Bytes Received"
+
+[node name="Label2" type="RichTextLabel" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer" node_paths=PackedStringArray("profiler")]
+unique_name_in_owner = true
+layout_mode = 2
+tooltip_text = "The total amount of messages that have been received from both the server and other clients."
+bbcode_enabled = true
+text = "[color=#ffffff]Total Messages Received: ...[/color]"
+fit_content = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../../../../..")
+stat_key = "pkts_down"
+is_bytes = false
+decimal_places = 0
+suffix = ""
+label_text = "Total Messages Received"
+
+[node name="Label3" type="RichTextLabel" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer" node_paths=PackedStringArray("profiler")]
+unique_name_in_owner = true
+layout_mode = 2
+tooltip_text = "The total amount of bytes that are being received per second from both the server and other clients."
+bbcode_enabled = true
+text = "[color=#ffffff]Bytes Received Per Second: ...[/color]"
+fit_content = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../../../../..")
+stat_key = "down_sec"
+decimal_places = 2
+label_text = "Bytes Received Per Second"
+
+[node name="Label4" type="RichTextLabel" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer" node_paths=PackedStringArray("profiler")]
+unique_name_in_owner = true
+layout_mode = 2
+tooltip_text = "The total amount of messages that are being received per second from both the server and other clients."
+bbcode_enabled = true
+text = "[color=#ffffff]Messages Received Per Second: ...[/color]"
+fit_content = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../../../../..")
+stat_key = "pkts_down_sec"
+is_bytes = false
+decimal_places = 0
+label_text = "Messages Received Per Second"
+
+[node name="Label5" type="RichTextLabel" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer" node_paths=PackedStringArray("profiler")]
+unique_name_in_owner = true
+layout_mode = 2
+tooltip_text = "The average size of all received messages."
+bbcode_enabled = true
+text = "[color=#ffffff]Average Message Size: ...[/color]"
+fit_content = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../../../../..")
+stat_key = "avg_msg_down"
+suffix = ""
+label_text = "Average Message Size"
+
+[node name="VBoxContainer3" type="VBoxContainer" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+
+[node name="Outgoing" type="Label" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer3"]
+layout_mode = 2
+text = "Outgoing:"
+
+[node name="Label1" type="RichTextLabel" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer3" node_paths=PackedStringArray("profiler")]
+layout_mode = 2
+tooltip_text = "The total amount of bytes that have been sent to both the server and other clients."
+bbcode_enabled = true
+text = "[color=#ffffff]Total Bytes Sent: ...[/color]"
+fit_content = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../../../../..")
+stat_key = "up"
+decimal_places = 2
+suffix = ""
+label_text = "Total Bytes Sent"
+
+[node name="Label2" type="RichTextLabel" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer3" node_paths=PackedStringArray("profiler")]
+layout_mode = 2
+tooltip_text = "The total amount of messages that have been sent to both the server and other clients."
+bbcode_enabled = true
+text = "[color=#ffffff]Total Messages Sent: ...[/color]"
+fit_content = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../../../../..")
+stat_key = "pkts_up"
+is_bytes = false
+decimal_places = 0
+suffix = ""
+label_text = "Total Messages Sent"
+
+[node name="Label3" type="RichTextLabel" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer3" node_paths=PackedStringArray("profiler")]
+layout_mode = 2
+tooltip_text = "The total amount of bytes that are being sent per second to both the server and other clients."
+bbcode_enabled = true
+text = "[color=#ffffff]Bytes Sent Per Second: ...[/color]"
+fit_content = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../../../../..")
+decimal_places = 2
+label_text = "Bytes Sent Per Second"
+
+[node name="Label4" type="RichTextLabel" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer3" node_paths=PackedStringArray("profiler")]
+layout_mode = 2
+tooltip_text = "The total amount of messages that are being sent per second to both the server and other clients."
+bbcode_enabled = true
+text = "[color=#ffffff]Messages Sent Per Second: ...[/color]"
+fit_content = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../../../../..")
+stat_key = "pkts_up_sec"
+is_bytes = false
+decimal_places = 0
+label_text = "Messages Sent Per Second"
+
+[node name="Label5" type="RichTextLabel" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer3" node_paths=PackedStringArray("profiler")]
+layout_mode = 2
+tooltip_text = "The average size of all sent messages."
+bbcode_enabled = true
+text = "[color=#ffffff]Average Message Size: ...[/color]"
+fit_content = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../../../../..")
+stat_key = "avg_msg_up"
+suffix = ""
+label_text = "Average Message Size"
+
+[node name="VSeparator2" type="VSeparator" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer"]
+layout_mode = 2
+
+[node name="VBoxContainer2" type="VBoxContainer" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+
+[node name="Graph" type="Control" parent="VBoxContainer/TabContainer/General/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/VBoxContainer2" node_paths=PackedStringArray("profiler")]
+layout_mode = 2
+size_flags_vertical = 3
+script = ExtResource("3_hrjsf")
+profiler = NodePath("../../../../../../../../..")
+series = Array[Dictionary]([{
+"color": Color(0.290196, 0.870588, 0.501961, 1),
+"key": "down_sec",
+"label": "Incoming"
+}, {
+"color": Color(0.376471, 0.647059, 0.980392, 1),
+"key": "up_sec",
+"label": "Outgoing"
+}, {
+"color": Color(0.574867, 0.498099, 0.980392, 1),
+"key": "total_sec",
+"label": "Total"
+}])
+
+[node name="Connections" type="TabBar" parent="VBoxContainer/TabContainer"]
+layout_mode = 2
+metadata/_tab_index = 1
+
+[node name="ScrollContainer" type="ScrollContainer" parent="VBoxContainer/TabContainer/Connections"]
+layout_mode = 1
+anchors_preset = 15
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 2
+grow_vertical = 2
+
+[node name="VBoxContainer" type="VBoxContainer" parent="VBoxContainer/TabContainer/Connections/ScrollContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+
+[node name="PanelContainer" type="PanelContainer" parent="VBoxContainer/TabContainer/Connections/ScrollContainer/VBoxContainer" node_paths=PackedStringArray("profiler", "button_template", "latency_graph_template", "jitter_graph_template")]
+layout_mode = 2
+script = ExtResource("4_gnjya")
+profiler = NodePath("../../../../../..")
+button_template = NodePath("HBoxContainer/HBoxContainer/VBoxContainer/ButtonTemplate")
+latency_graph_template = NodePath("HBoxContainer/VBoxContainer2/LatencyGraph")
+jitter_graph_template = NodePath("HBoxContainer/VBoxContainer3/JitterGraph")
+
+[node name="HBoxContainer" type="HBoxContainer" parent="VBoxContainer/TabContainer/Connections/ScrollContainer/VBoxContainer/PanelContainer"]
+layout_mode = 2
+
+[node name="HBoxContainer" type="HBoxContainer" parent="VBoxContainer/TabContainer/Connections/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+
+[node name="VBoxContainer" type="VBoxContainer" parent="VBoxContainer/TabContainer/Connections/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+
+[node name="HSeparator" type="HSeparator" parent="VBoxContainer/TabContainer/Connections/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer"]
+layout_mode = 2
+
+[node name="MonitorButton" type="CheckButton" parent="VBoxContainer/TabContainer/Connections/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer"]
+layout_mode = 2
+tooltip_text = "Start monitoring the connections between clients. This will measure the ping and jitter and slightly increase transfer usage will enabled."
+text = "Monitor Connections"
+
+[node name="HSeparator2" type="HSeparator" parent="VBoxContainer/TabContainer/Connections/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer"]
+layout_mode = 2
+
+[node name="ButtonTemplate" type="Button" parent="VBoxContainer/TabContainer/Connections/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer"]
+visible = false
+layout_mode = 2
+tooltip_text = "Press to show the latency and jitter to this client."
+text = "Client: 123"
+
+[node name="VSeparator2" type="VSeparator" parent="VBoxContainer/TabContainer/Connections/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer"]
+layout_mode = 2
+
+[node name="VBoxContainer2" type="VBoxContainer" parent="VBoxContainer/TabContainer/Connections/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+
+[node name="LatencyGraph" type="Control" parent="VBoxContainer/TabContainer/Connections/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/VBoxContainer2" node_paths=PackedStringArray("profiler")]
+custom_minimum_size = Vector2(0, 200)
+layout_mode = 2
+size_flags_vertical = 3
+tooltip_text = "Latency is the raw network round-trip time in milliseconds: the time for a message to go to the other client and return.
+
+Perceived latency is the same trip, plus extra delay from frame timing and message handling, representing what the player actually experiences."
+script = ExtResource("3_hrjsf")
+profiler = NodePath("../../..")
+series = Array[Dictionary]([{
+"color": Color(0.376471, 0.647059, 0.980392, 1),
+"key": "latency",
+"label": "Latency"
+}, {
+"color": Color(0.6431373, 1, 0.76932174, 1),
+"key": "perceived_latency",
+"label": "Perceived Latency"
+}])
+display_mode = 1
+
+[node name="VBoxContainer3" type="VBoxContainer" parent="VBoxContainer/TabContainer/Connections/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+
+[node name="JitterGraph" type="Control" parent="VBoxContainer/TabContainer/Connections/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/VBoxContainer3" node_paths=PackedStringArray("profiler")]
+custom_minimum_size = Vector2(0, 200)
+layout_mode = 2
+size_flags_vertical = 3
+tooltip_text = "The jitter between this and the selected client. Jitter is the difference between latency between now and last second.
+
+High jitter indicates an unstable connection. Little to no jitter indicates a stable connection."
+script = ExtResource("3_hrjsf")
+profiler = NodePath("../../..")
+series = Array[Dictionary]([{
+"color": Color(0.952941, 0.545098, 0.658824, 1),
+"key": "jitter",
+"label": "Jitter"
+}])
+display_mode = 1
+
+[node name="Session" type="TabBar" parent="VBoxContainer/TabContainer"]
+visible = false
+layout_mode = 2
+metadata/_tab_index = 2
+
+[node name="ScrollContainer" type="ScrollContainer" parent="VBoxContainer/TabContainer/Session"]
+layout_mode = 1
+anchors_preset = 15
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 2
+grow_vertical = 2
+
+[node name="HBoxContainer" type="HBoxContainer" parent="VBoxContainer/TabContainer/Session/ScrollContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+size_flags_vertical = 3
+
+[node name="VBoxContainer2" type="VBoxContainer" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+
+[node name="Label" type="Label" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer/VBoxContainer2"]
+layout_mode = 2
+text = "Session Information"
+
+[node name="HSeparator" type="HSeparator" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer/VBoxContainer2"]
+layout_mode = 2
+
+[node name="VBoxContainer" type="VBoxContainer" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer/VBoxContainer2"]
+layout_mode = 2
+size_flags_vertical = 3
+
+[node name="Label1" type="RichTextLabel" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer/VBoxContainer2/VBoxContainer" node_paths=PackedStringArray("profiler")]
+layout_mode = 2
+tooltip_text = "The Client ID that is assigned to this session."
+bbcode_enabled = true
+text = "[color=#ffffff]Client ID: N/A[/color]"
+fit_content = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../../..")
+stat_key = "client_id"
+is_bytes = false
+suffix = ""
+label_text = "Client ID"
+use_custom_data = true
+
+[node name="Label2" type="RichTextLabel" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer/VBoxContainer2/VBoxContainer" node_paths=PackedStringArray("profiler")]
+layout_mode = 2
+tooltip_text = "If the client in this session is the host of the current lobby or not."
+bbcode_enabled = true
+text = "[color=#ffffff]Is Host: N/A[/color]"
+fit_content = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../../..")
+stat_key = "is_host"
+is_bytes = false
+suffix = ""
+label_text = "Is Host"
+use_custom_data = true
+
+[node name="Label3" type="RichTextLabel" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer/VBoxContainer2/VBoxContainer" node_paths=PackedStringArray("profiler")]
+layout_mode = 2
+tooltip_text = "If the client in this session is the host of the current lobby or not."
+bbcode_enabled = true
+text = "[color=#ffffff]Host ID: N/A[/color]"
+fit_content = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../../..")
+stat_key = "host"
+is_bytes = false
+suffix = ""
+label_text = "Host ID"
+use_custom_data = true
+
+[node name="HSeparator2" type="HSeparator" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer/VBoxContainer2"]
+layout_mode = 2
+
+[node name="VBoxContainer2" type="VBoxContainer" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer/VBoxContainer2"]
+layout_mode = 2
+size_flags_vertical = 3
+
+[node name="Label3" type="RichTextLabel" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer/VBoxContainer2/VBoxContainer2" node_paths=PackedStringArray("profiler")]
+layout_mode = 2
+tooltip_text = "The name of the lobby the client of this session is currently in."
+bbcode_enabled = true
+text = "[color=#ffffff]Lobby Name: N/A[/color]"
+fit_content = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../../..")
+stat_key = "lobby_name"
+is_bytes = false
+suffix = ""
+label_text = "Lobby Name"
+use_custom_data = true
+
+[node name="Label4" type="RichTextLabel" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer/VBoxContainer2/VBoxContainer2" node_paths=PackedStringArray("profiler")]
+layout_mode = 2
+tooltip_text = "The password of the lobby the client of this session is currently in."
+bbcode_enabled = true
+text = "[color=#ffffff]Lobby Password: N/A[/color]"
+fit_content = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../../..")
+stat_key = "lobby_password"
+is_bytes = false
+suffix = ""
+label_text = "Lobby Password"
+use_custom_data = true
+
+[node name="VSeparator" type="VSeparator" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer"]
+layout_mode = 2
+
+[node name="VBoxContainer" type="VBoxContainer" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+
+[node name="Label" type="Label" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer/VBoxContainer"]
+layout_mode = 2
+text = "Player Data"
+
+[node name="HSeparator" type="HSeparator" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer/VBoxContainer"]
+layout_mode = 2
+
+[node name="Label1" type="RichTextLabel" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer/VBoxContainer" node_paths=PackedStringArray("profiler")]
+layout_mode = 2
+size_flags_vertical = 3
+focus_mode = 2
+bbcode_enabled = true
+text = "[color=#ffffff]{}[/color]"
+selection_enabled = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../..")
+stat_key = "player_data"
+is_bytes = false
+suffix = ""
+label_text = "Player Data"
+show_label_text = false
+use_custom_data = true
+missing_text = "{}"
+
+[node name="VSeparator2" type="VSeparator" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer"]
+layout_mode = 2
+
+[node name="VBoxContainer3" type="VBoxContainer" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+
+[node name="Label" type="Label" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer/VBoxContainer3"]
+layout_mode = 2
+text = "Lobby Data"
+
+[node name="HSeparator" type="HSeparator" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer/VBoxContainer3"]
+layout_mode = 2
+
+[node name="Label1" type="RichTextLabel" parent="VBoxContainer/TabContainer/Session/ScrollContainer/HBoxContainer/VBoxContainer3" node_paths=PackedStringArray("profiler")]
+layout_mode = 2
+size_flags_vertical = 3
+focus_mode = 2
+bbcode_enabled = true
+text = "[color=#ffffff]{}[/color]"
+selection_enabled = true
+script = ExtResource("2_5m75r")
+profiler = NodePath("../../../../../../..")
+stat_key = "lobby_data"
+is_bytes = false
+suffix = ""
+label_text = "Player Data"
+show_label_text = false
+use_custom_data = true
+missing_text = "{}"
+
+[node name="Incoming Details" type="TabBar" parent="VBoxContainer/TabContainer"]
+visible = false
+layout_mode = 2
+metadata/_tab_index = 3
+
+[node name="ScrollContainer" type="ScrollContainer" parent="VBoxContainer/TabContainer/Incoming Details"]
+layout_mode = 1
+anchors_preset = 15
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 2
+grow_vertical = 2
+
+[node name="VBoxContainer" type="VBoxContainer" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+size_flags_vertical = 3
+
+[node name="HBoxContainer" type="HBoxContainer" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer"]
+layout_mode = 2
+size_flags_vertical = 3
+
+[node name="VBoxContainer2" type="VBoxContainer" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+
+[node name="Label" type="Label" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2"]
+layout_mode = 2
+text = "Incoming Usage Details"
+
+[node name="HBoxContainer" type="HBoxContainer" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2"]
+layout_mode = 2
+
+[node name="Label" type="Button" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+text = "Type"
+
+[node name="Label2" type="Button" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+text = "Object"
+
+[node name="Label3" type="Button" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+text = "Target"
+
+[node name="Label4" type="Button" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+text = "Count"
+
+[node name="Label5" type="Button" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+text = "Total Bytes (descending)"
+
+[node name="Label6" type="Button" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+text = "Percent"
+
+[node name="VBoxContainer" type="VBoxContainer" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2" node_paths=PackedStringArray("type_sort_button", "object_sort_button", "target_sort_button", "count_sort_button", "usage_sort_button", "percent_sort_button", "profiler", "label_template")]
+layout_mode = 2
+script = ExtResource("4_bk6j0")
+type_sort_button = NodePath("../HBoxContainer/Label")
+object_sort_button = NodePath("../HBoxContainer/Label2")
+target_sort_button = NodePath("../HBoxContainer/Label3")
+count_sort_button = NodePath("../HBoxContainer/Label4")
+usage_sort_button = NodePath("../HBoxContainer/Label5")
+percent_sort_button = NodePath("../HBoxContainer/Label6")
+listen_key = "down"
+profiler = NodePath("../../../../../../../..")
+label_template = NodePath("PanelContainer")
+
+[node name="PanelContainer" type="PanelContainer" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/VBoxContainer"]
+visible = false
+self_modulate = Color(0.734375, 0.734375, 0.734375, 1)
+layout_mode = 2
+
+[node name="Data" type="HBoxContainer" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/VBoxContainer/PanelContainer"]
+layout_mode = 2
+
+[node name="Type" type="RichTextLabel" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/VBoxContainer/PanelContainer/Data"]
+layout_mode = 2
+size_flags_horizontal = 3
+bbcode_enabled = true
+text = "Sync Var"
+fit_content = true
+
+[node name="Object" type="RichTextLabel" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/VBoxContainer/PanelContainer/Data"]
+layout_mode = 2
+size_flags_horizontal = 3
+bbcode_enabled = true
+text = "Node123"
+fit_content = true
+
+[node name="Target" type="RichTextLabel" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/VBoxContainer/PanelContainer/Data"]
+layout_mode = 2
+size_flags_horizontal = 3
+bbcode_enabled = true
+text = "Property Name"
+fit_content = true
+
+[node name="Count" type="RichTextLabel" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/VBoxContainer/PanelContainer/Data"]
+layout_mode = 2
+size_flags_horizontal = 3
+bbcode_enabled = true
+text = "0"
+fit_content = true
+
+[node name="Usage" type="RichTextLabel" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/VBoxContainer/PanelContainer/Data"]
+layout_mode = 2
+size_flags_horizontal = 3
+bbcode_enabled = true
+text = "0B"
+fit_content = true
+
+[node name="Percentage" type="RichTextLabel" parent="VBoxContainer/TabContainer/Incoming Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/VBoxContainer/PanelContainer/Data"]
+layout_mode = 2
+size_flags_horizontal = 3
+bbcode_enabled = true
+text = "0%"
+fit_content = true
+
+[node name="Outgoing Details" type="TabBar" parent="VBoxContainer/TabContainer"]
+visible = false
+layout_mode = 2
+metadata/_tab_index = 4
+
+[node name="ScrollContainer" type="ScrollContainer" parent="VBoxContainer/TabContainer/Outgoing Details"]
+layout_mode = 1
+anchors_preset = 15
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 2
+grow_vertical = 2
+
+[node name="VBoxContainer" type="VBoxContainer" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+size_flags_vertical = 3
+
+[node name="HBoxContainer" type="HBoxContainer" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer"]
+layout_mode = 2
+size_flags_vertical = 3
+
+[node name="VBoxContainer2" type="VBoxContainer" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+
+[node name="Label" type="Label" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2"]
+layout_mode = 2
+text = "Incoming Usage Details"
+
+[node name="HBoxContainer" type="HBoxContainer" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2"]
+layout_mode = 2
+
+[node name="Label" type="Button" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+text = "Type"
+
+[node name="Label2" type="Button" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+text = "Object"
+
+[node name="Label3" type="Button" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+text = "Target"
+
+[node name="Label4" type="Button" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+text = "Count"
+
+[node name="Label5" type="Button" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+text = "Total Bytes (descending)"
+
+[node name="Label6" type="Button" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/HBoxContainer"]
+layout_mode = 2
+size_flags_horizontal = 3
+text = "Percent"
+
+[node name="VBoxContainer" type="VBoxContainer" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2" node_paths=PackedStringArray("type_sort_button", "object_sort_button", "target_sort_button", "count_sort_button", "usage_sort_button", "percent_sort_button", "profiler", "label_template")]
+layout_mode = 2
+script = ExtResource("4_bk6j0")
+type_sort_button = NodePath("../HBoxContainer/Label")
+object_sort_button = NodePath("../HBoxContainer/Label2")
+target_sort_button = NodePath("../HBoxContainer/Label3")
+count_sort_button = NodePath("../HBoxContainer/Label4")
+usage_sort_button = NodePath("../HBoxContainer/Label5")
+percent_sort_button = NodePath("../HBoxContainer/Label6")
+profiler = NodePath("../../../../../../../..")
+label_template = NodePath("PanelContainer")
+
+[node name="PanelContainer" type="PanelContainer" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/VBoxContainer"]
+visible = false
+self_modulate = Color(0.734375, 0.734375, 0.734375, 1)
+layout_mode = 2
+
+[node name="Data" type="HBoxContainer" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/VBoxContainer/PanelContainer"]
+layout_mode = 2
+
+[node name="Type" type="RichTextLabel" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/VBoxContainer/PanelContainer/Data"]
+layout_mode = 2
+size_flags_horizontal = 3
+bbcode_enabled = true
+text = "Sync Var"
+fit_content = true
+
+[node name="Object" type="RichTextLabel" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/VBoxContainer/PanelContainer/Data"]
+layout_mode = 2
+size_flags_horizontal = 3
+bbcode_enabled = true
+text = "Node123"
+fit_content = true
+
+[node name="Target" type="RichTextLabel" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/VBoxContainer/PanelContainer/Data"]
+layout_mode = 2
+size_flags_horizontal = 3
+bbcode_enabled = true
+text = "Property Name"
+fit_content = true
+
+[node name="Count" type="RichTextLabel" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/VBoxContainer/PanelContainer/Data"]
+layout_mode = 2
+size_flags_horizontal = 3
+bbcode_enabled = true
+text = "0"
+fit_content = true
+
+[node name="Usage" type="RichTextLabel" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/VBoxContainer/PanelContainer/Data"]
+layout_mode = 2
+size_flags_horizontal = 3
+bbcode_enabled = true
+text = "0B"
+fit_content = true
+
+[node name="Percentage" type="RichTextLabel" parent="VBoxContainer/TabContainer/Outgoing Details/ScrollContainer/VBoxContainer/HBoxContainer/VBoxContainer2/VBoxContainer/PanelContainer/Data"]
+layout_mode = 2
+size_flags_horizontal = 3
+bbcode_enabled = true
+text = "0%"
+fit_content = true
+
+[connection signal="pressed" from="VBoxContainer/HBoxContainer/Start" to="." method="start"]
+[connection signal="pressed" from="VBoxContainer/HBoxContainer/Stop" to="." method="stop"]
+[connection signal="pressed" from="VBoxContainer/HBoxContainer/Clear" to="." method="clear"]
+[connection signal="toggled" from="VBoxContainer/HBoxContainer/AutoStart" to="." method="_on_auto_start_toggled"]
+[connection signal="value_changed" from="VBoxContainer/HBoxContainer/LatencySpinBox" to="." method="_on_artificial_latency_changed"]
+[connection signal="toggled" from="VBoxContainer/TabContainer/Connections/ScrollContainer/VBoxContainer/PanelContainer/HBoxContainer/HBoxContainer/VBoxContainer/MonitorButton" to="VBoxContainer/TabContainer/Connections/ScrollContainer/VBoxContainer/PanelContainer" method="_on_monitor_button_toggled"]
diff --git a/addons/GD-Sync/UI/Profiler/ProfilerConnectionMonitor.gd b/addons/GD-Sync/UI/Profiler/ProfilerConnectionMonitor.gd
new file mode 100644
index 0000000..8276b96
--- /dev/null
+++ b/addons/GD-Sync/UI/Profiler/ProfilerConnectionMonitor.gd
@@ -0,0 +1,207 @@
+@tool
+extends Node
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+signal stats_updated(client_id : int, stats : Dictionary)
+signal profiler_cleared
+
+@export var profiler : Node = null : set = _set_profiler
+@export var button_template : Control = null
+@export var latency_graph_template : Control = null
+@export var jitter_graph_template : Control = null
+
+var client_data : Dictionary = {}
+var client_buttons : Dictionary = {}
+var client_latency_graphs : Dictionary = {}
+var client_jitter_graphs : Dictionary = {}
+var own_id : int = -1
+var monitoring : bool = false
+
+func _ready():
+ button_template.visible = false
+
+ if profiler:
+ _connect_signal()
+
+func _set_profiler(v):
+ if profiler == v: return
+ if profiler:
+ _disconnect_signal()
+ profiler = v
+ if profiler:
+ _connect_signal()
+
+func _connect_signal():
+ if not profiler: return
+ if profiler.has_signal("profiler_started") and not profiler.profiler_started.is_connected(_on_profiler_started):
+ profiler.profiler_started.connect(_on_profiler_started)
+ if profiler.has_signal("profiler_stopped") and not profiler.profiler_stopped.is_connected(_on_profiler_stopped):
+ profiler.profiler_stopped.connect(_on_profiler_stopped)
+ if profiler.has_signal("client_joined") and not profiler.client_joined.is_connected(_on_client_joined):
+ profiler.client_joined.connect(_on_client_joined)
+ if profiler.has_signal("client_left") and not profiler.client_left.is_connected(_on_client_left):
+ profiler.client_left.connect(_on_client_left)
+ if profiler.has_signal("ping_measured") and not profiler.ping_measured.is_connected(_on_ping_measured):
+ profiler.ping_measured.connect(_on_ping_measured)
+ if profiler.has_signal("profiler_cleared") and not profiler.profiler_cleared.is_connected(_on_profiler_cleared):
+ profiler.profiler_cleared.connect(_on_profiler_cleared)
+ if profiler.has_signal("custom_data_updated") and not profiler.custom_data_updated.is_connected(_on_custom_data):
+ profiler.custom_data_updated.connect(_on_custom_data)
+
+func _disconnect_signal():
+ if not profiler: return
+ if profiler.has_signal("profiler_started") and profiler.profiler_started.is_connected(_on_profiler_started):
+ profiler.profiler_started.disconnect(_on_profiler_started)
+ if profiler.has_signal("profiler_stopped") and profiler.profiler_stopped.is_connected(_on_profiler_stopped):
+ profiler.profiler_stopped.disconnect(_on_profiler_stopped)
+ if profiler.has_signal("client_joined") and profiler.client_joined.is_connected(_on_client_joined):
+ profiler.client_joined.disconnect(_on_client_joined)
+ if profiler.has_signal("client_left") and profiler.client_left.is_connected(_on_client_left):
+ profiler.client_left.disconnect(_on_client_left)
+ if profiler.has_signal("ping_measured") and profiler.ping_measured.is_connected(_on_ping_measured):
+ profiler.ping_measured.disconnect(_on_ping_measured)
+ if profiler.has_signal("profiler_cleared") and profiler.profiler_cleared.is_connected(_on_profiler_cleared):
+ profiler.profiler_cleared.disconnect(_on_profiler_cleared)
+ if profiler.has_signal("custom_data_updated") and profiler.custom_data_updated.is_connected(_on_custom_data):
+ profiler.custom_data_updated.disconnect(_on_custom_data)
+
+func _on_custom_data(data : Dictionary) -> void:
+ if !data.has("client_id"): return
+ own_id = data["client_id"]
+
+func _on_monitor_button_toggled(toggled_on: bool) -> void:
+ monitoring = toggled_on
+
+ if monitoring:
+ profiler.start_monitoring_connections.emit()
+ else:
+ profiler.stop_monitoring_connections.emit()
+
+func _on_profiler_started() -> void:
+ if monitoring:
+ profiler.start_monitoring_connections.emit()
+
+func _on_profiler_stopped() -> void:
+ profiler.stop_monitoring_connections.emit()
+
+func _on_profiler_cleared() -> void:
+ client_data.clear()
+
+ for button in client_buttons.values():
+ button.queue_free()
+
+ for graph in client_latency_graphs.values():
+ graph.queue_free()
+
+ for graph in client_jitter_graphs.values():
+ graph.queue_free()
+
+ client_buttons.clear()
+ client_latency_graphs.clear()
+ client_jitter_graphs.clear()
+
+ latency_graph_template.visible = true
+ jitter_graph_template.visible = true
+
+ profiler_cleared.emit()
+
+func _on_client_joined(client_id : int) -> void:
+ if client_id == own_id: return
+
+ client_data[client_id] = {"latency" : 0.0, "jitter" : 0.0}
+
+ var button : Button = button_template.duplicate()
+ button_template.get_parent().add_child(button)
+
+ button.text = "Client %s" % [client_id]
+ button.pressed.connect(_show_client_graph.bind(client_id))
+ button.visible = true
+ client_buttons[client_id] = button
+
+ var latency_graph : Control = latency_graph_template.duplicate()
+ latency_graph_template.get_parent().add_child(latency_graph)
+
+ latency_graph.visible = true
+ latency_graph.client_id = client_id
+ latency_graph.data_series[0]["label"] = "Latency to client "+str(client_id)
+ latency_graph.data_series[1]["label"] = "Perceived latency to client "+str(client_id)
+ client_latency_graphs[client_id] = latency_graph
+
+ var jitter_graph : Control = jitter_graph_template.duplicate()
+ jitter_graph_template.get_parent().add_child(jitter_graph)
+
+ jitter_graph.visible = true
+ jitter_graph.client_id = client_id
+ jitter_graph.data_series[0]["label"] = "Jitter to client "+str(client_id)
+ client_jitter_graphs[client_id] = jitter_graph
+
+ if client_data.size() == 1:
+ _show_client_graph(client_id)
+
+func _show_client_graph(client_id : int) -> void:
+ latency_graph_template.visible = false
+ jitter_graph_template.visible = false
+
+ for graph in client_latency_graphs.values():
+ graph.visible = false
+ for graph in client_jitter_graphs.values():
+ graph.visible = false
+
+ client_latency_graphs[client_id].visible = true
+ client_jitter_graphs[client_id].visible = true
+
+func _on_client_left(client_id : int) -> void:
+ if client_data.has(client_id):
+ client_data.erase(client_id)
+
+ if client_buttons.has(client_id):
+ client_buttons[client_id].queue_free()
+ client_buttons.erase(client_id)
+
+ if client_latency_graphs.has(client_id):
+ client_latency_graphs[client_id].queue_free()
+ client_latency_graphs.erase(client_id)
+
+ if client_jitter_graphs.has(client_id):
+ client_jitter_graphs[client_id].queue_free()
+ client_jitter_graphs.erase(client_id)
+
+func _on_ping_measured(client_id : int, ping : float, perceived_ping : float) -> void:
+ if !client_latency_graphs.has(client_id): return
+ ping *= 1000.0
+ perceived_ping *= 1000.0
+
+ ping = max(0, ping)
+ perceived_ping = max(0, perceived_ping)
+
+ var data : Dictionary = client_data[client_id]
+ var last_latency : float = data["latency"]
+ var jitter : float = abs(last_latency-ping) if last_latency > 0 else 0.0
+ data["latency"] = ping
+ data["perceived_latency"] = perceived_ping
+ data["jitter"] = jitter
+
+ stats_updated.emit(client_id, data)
diff --git a/addons/GD-Sync/UI/Profiler/ProfilerConnectionMonitor.gd.uid b/addons/GD-Sync/UI/Profiler/ProfilerConnectionMonitor.gd.uid
new file mode 100644
index 0000000..154eab9
--- /dev/null
+++ b/addons/GD-Sync/UI/Profiler/ProfilerConnectionMonitor.gd.uid
@@ -0,0 +1 @@
+uid://frgb8qcxxcoj
diff --git a/addons/GD-Sync/UI/Profiler/ProfilerDetailsBar.gd b/addons/GD-Sync/UI/Profiler/ProfilerDetailsBar.gd
new file mode 100644
index 0000000..6f9f262
--- /dev/null
+++ b/addons/GD-Sync/UI/Profiler/ProfilerDetailsBar.gd
@@ -0,0 +1,216 @@
+@tool
+extends HBoxContainer
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+@export var profiler : Node = null
+@export var listen_key : String = "up"
+@export var other_threshold : float = 2.0
+@export var bar_segment_template : Control = null
+@export var other_color : Color = Color("#888888")
+@export var color_palette : Array[Color] = [
+ Color("#e6194b"), Color("#3cb44b"), Color("#ffe119"), Color("#4363d8"),
+ Color("#f58231"), Color("#911eb4"), Color("#46f0f0"), Color("#f032e6"),
+ Color("#bcf60c"), Color("#fabebe"), Color("#008080"), Color("#e6beff")
+]
+
+var segment_cache : Dictionary = {}
+var data_cache : Dictionary = {}
+var rebuild_scheduled : bool = false
+
+func _ready() -> void:
+ if bar_segment_template:
+ bar_segment_template.visible = false
+
+ if profiler:
+ _connect_signals()
+
+func _connect_signals() -> void:
+ if profiler.has_signal("message_details_updated") and not profiler.message_details_updated.is_connected(_on_details):
+ profiler.message_details_updated.connect(_on_details)
+ if profiler.has_signal("profiler_cleared") and not profiler.profiler_cleared.is_connected(_on_clear):
+ profiler.profiler_cleared.connect(_on_clear)
+
+func _disconnect_signals() -> void:
+ if profiler and profiler.message_details_updated.is_connected(_on_details):
+ profiler.message_details_updated.disconnect(_on_details)
+ if profiler and profiler.profiler_cleared.is_connected(_on_clear):
+ profiler.profiler_cleared.disconnect(_on_clear)
+
+func _on_clear() -> void:
+ for seg in segment_cache.values():
+ seg.queue_free()
+ segment_cache.clear()
+ data_cache.clear()
+ _schedule_rebuild()
+
+func _on_details(details : Dictionary) -> void:
+ if !details.has(listen_key): return
+ var raw_data : Dictionary = details[listen_key]
+
+ var object_stats : Dictionary = {}
+ for key in raw_data.keys():
+ var entry = raw_data[key]
+ var obj = entry.object
+ if not object_stats.has(obj):
+ object_stats[obj] = { "total_bytes": 0, "percent": 0.0, "keys": [] }
+ object_stats[obj].total_bytes += entry.total_bytes
+ object_stats[obj].keys.append(key)
+
+ var total_bytes : int = 0
+ for obj in object_stats.keys():
+ total_bytes += object_stats[obj].total_bytes
+
+ if total_bytes == 0:
+ _clear_all_segments()
+ return
+
+ for obj in object_stats.keys():
+ var bytes = object_stats[obj].total_bytes
+ object_stats[obj].percent = (bytes as float / total_bytes) * 100.0
+
+ var major_objects : Array = []
+ var other_bytes : int = 0
+ var other_keys : Array = []
+
+ for obj in object_stats.keys():
+ var pct = object_stats[obj].percent
+ if pct >= other_threshold:
+ major_objects.append({
+ "name": obj,
+ "percent": pct,
+ "bytes": object_stats[obj].total_bytes,
+ "keys": object_stats[obj].keys
+ })
+ else:
+ other_bytes += object_stats[obj].total_bytes
+ other_keys.append_array(object_stats[obj].keys)
+
+ var other_pct = (other_bytes as float / total_bytes) * 100.0 if total_bytes > 0 else 0.0
+ if other_pct > 0.0:
+ major_objects.append({
+ "name": "Other",
+ "percent": other_pct,
+ "bytes": other_bytes,
+ "keys": other_keys
+ })
+
+ major_objects.sort_custom(func(a, b): return a.percent > b.percent)
+
+ data_cache.clear()
+ for item in major_objects:
+ data_cache[item.name] = item
+
+ _schedule_rebuild()
+
+func _schedule_rebuild() -> void:
+ if rebuild_scheduled: return
+ rebuild_scheduled = true
+ call_deferred("_rebuild_bar_deferred")
+
+func _rebuild_bar_deferred() -> void:
+ if not rebuild_scheduled: return
+ rebuild_scheduled = false
+
+ var ordered_names : Array = data_cache.keys()
+ ordered_names.sort_custom(func(a, b):
+ return data_cache[a].percent > data_cache[b].percent
+ )
+
+ var total_percent : float = 0.0
+ for item in data_cache.values():
+ total_percent += item.percent
+ total_percent = max(total_percent, 100.0)
+
+ var color_idx = 0
+ for obj_name in ordered_names:
+ var item = data_cache[obj_name]
+ var seg = _get_or_create_segment(obj_name)
+
+ var col = other_color if obj_name == "Other" else color_palette[color_idx % color_palette.size()]
+ seg.modulate = col
+ color_idx += 1
+
+ var ratio = item.percent / total_percent * 100.0
+ seg.size_flags_stretch_ratio = ratio
+
+ var tooltip = "%s\n%.2f%% (%s)" % [
+ obj_name,
+ item.percent,
+ _format_bytes(item.bytes)
+ ]
+ seg.tooltip_text = tooltip
+
+ seg.set_meta("keys", item.keys)
+
+ if seg.get_index() != get_child_count() - 1:
+ move_child(seg, -1)
+
+ _remove_unused_segments(ordered_names)
+
+func _get_or_create_segment(obj_name : String) -> Control:
+ if segment_cache.has(obj_name):
+ return segment_cache[obj_name]
+
+ var seg = bar_segment_template.duplicate()
+ add_child(seg)
+ seg.visible = true
+ seg.size_flags_horizontal = Control.SIZE_EXPAND_FILL
+ seg.mouse_filter = Control.MOUSE_FILTER_PASS
+
+ seg.connect("mouse_entered", func():
+ seg.modulate.a = 0.8
+ )
+ seg.connect("mouse_exited", func():
+ seg.modulate.a = 1.0
+ )
+
+ segment_cache[obj_name] = seg
+ return seg
+
+func _remove_unused_segments(current_objects : Array) -> void:
+ var to_remove = []
+ for name in segment_cache.keys():
+ if !current_objects.has(name):
+ to_remove.append(name)
+
+ for name in to_remove:
+ segment_cache[name].queue_free()
+ segment_cache.erase(name)
+
+func _clear_all_segments() -> void:
+ for seg in segment_cache.values():
+ seg.queue_free()
+ segment_cache.clear()
+
+func _format_bytes(b : int) -> String:
+ if b <= 0: return "0 B"
+ var u = ["B","KB","MB","GB"]
+ var i = 0
+ var v = float(b)
+ while v >= 1000.0 and i < 3:
+ v /= 1000.0
+ i += 1
+ return "%.*f %s" % [1 if i > 0 else 0, v, u[i]]
diff --git a/addons/GD-Sync/UI/Profiler/ProfilerDetailsBar.gd.uid b/addons/GD-Sync/UI/Profiler/ProfilerDetailsBar.gd.uid
new file mode 100644
index 0000000..28c3685
--- /dev/null
+++ b/addons/GD-Sync/UI/Profiler/ProfilerDetailsBar.gd.uid
@@ -0,0 +1 @@
+uid://bvluikq25m4rv
diff --git a/addons/GD-Sync/UI/Profiler/ProfilerDetailsDisplay.gd b/addons/GD-Sync/UI/Profiler/ProfilerDetailsDisplay.gd
new file mode 100644
index 0000000..c56eccb
--- /dev/null
+++ b/addons/GD-Sync/UI/Profiler/ProfilerDetailsDisplay.gd
@@ -0,0 +1,384 @@
+@tool
+extends Control
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+@export var type_sort_button : Button
+@export var object_sort_button : Button
+@export var target_sort_button : Button
+@export var count_sort_button : Button
+@export var usage_sort_button : Button
+@export var percent_sort_button : Button
+@export var listen_key : String = "up"
+@export var profiler : Node = null
+@export var label_template : Node = null
+
+var existing_labels : Dictionary = {}
+var current_sort_key : String = "total_bytes"
+var sort_reversed : bool = false
+var sorted_keys : Array = []
+var data_cache : Dictionary = {}
+
+var sort_thread : Thread
+var data_mutex : Mutex
+var pending_data_update : Dictionary = {}
+var pending_remove_keys : Array = []
+var has_pending_changes : bool = false
+var should_stop_thread : bool = false
+
+func _ready() -> void:
+ data_mutex = Mutex.new()
+
+ if label_template:
+ label_template.visible = false
+
+ if profiler:
+ _connect_signals()
+
+ _connect_sort_buttons()
+ _update_button_states()
+
+func _exit_tree() -> void:
+ _stop_thread()
+ _disconnect_signals()
+
+func _stop_thread() -> void:
+ should_stop_thread = true
+ if sort_thread and sort_thread.is_started():
+ sort_thread.wait_to_finish()
+
+func _start_thread_if_needed() -> void:
+ if not sort_thread or not sort_thread.is_started():
+ sort_thread = Thread.new()
+ should_stop_thread = false
+ sort_thread.start(_thread_process)
+
+func _thread_process() -> void:
+ while not should_stop_thread:
+ data_mutex.lock()
+ var has_changes = has_pending_changes
+ var local_data_update = pending_data_update.duplicate(true)
+ var local_remove_keys = pending_remove_keys.duplicate()
+ var local_data_cache = data_cache.duplicate(true)
+ var local_existing_keys = existing_labels.keys()
+ var local_sort_key = current_sort_key
+ var local_sort_reversed = sort_reversed
+
+ if has_changes:
+ pending_data_update.clear()
+ pending_remove_keys.clear()
+ has_pending_changes = false
+ data_mutex.unlock()
+
+ if has_changes:
+ var new_data_cache = local_data_cache.duplicate(true)
+
+ for key in local_data_update.keys():
+ new_data_cache[key] = {
+ "type": local_data_update[key].type,
+ "object": local_data_update[key].object,
+ "target": local_data_update[key].target,
+ "count": local_data_update[key].count,
+ "total_bytes": local_data_update[key].total_bytes,
+ "percent": local_data_update[key].percent
+ }
+
+ for key in local_remove_keys:
+ new_data_cache.erase(key)
+
+ var new_sorted_keys = local_existing_keys.duplicate()
+
+ if not local_sort_key.is_empty():
+ new_sorted_keys.sort_custom(func(a, b):
+ var va = _get_raw_sort_value_thread(a, new_data_cache, local_sort_key)
+ var vb = _get_raw_sort_value_thread(b, new_data_cache, local_sort_key)
+
+ if va == vb:
+ return a < b
+
+ if local_sort_reversed:
+ return va > vb
+ else:
+ return va < vb
+ )
+ else:
+ new_sorted_keys.sort()
+
+ call_deferred("_apply_thread_results", new_sorted_keys, new_data_cache)
+
+ OS.delay_msec(16)
+
+func _get_raw_sort_value_thread(key : String, cache : Dictionary, sort_key : String) -> Variant:
+ if not cache.has(key):
+ return key
+ var e = cache[key]
+ match sort_key:
+ "type": return e.type
+ "object": return e.object
+ "target": return e.target
+ "count": return e.count
+ "total_bytes": return e.total_bytes
+ "percent": return e.percent
+ _: return key
+
+func _apply_thread_results(new_sorted_keys : Array, new_data_cache : Dictionary) -> void:
+ data_mutex.lock()
+ data_cache = new_data_cache
+ sorted_keys = new_sorted_keys
+ data_mutex.unlock()
+
+ _reorder_labels_ui()
+
+# -------------------------------------------------------------------------
+# Signal handling
+# -------------------------------------------------------------------------
+func _connect_signals() -> void:
+ if profiler.has_signal("message_details_updated") and not profiler.message_details_updated.is_connected(_on_message_details):
+ profiler.message_details_updated.connect(_on_message_details)
+ if profiler.has_signal("profiler_cleared") and not profiler.profiler_cleared.is_connected(_on_clear):
+ profiler.profiler_cleared.connect(_on_clear)
+
+func _disconnect_signals() -> void:
+ if profiler and profiler.message_details_updated.is_connected(_on_message_details):
+ profiler.message_details_updated.disconnect(_on_message_details)
+ if profiler and profiler.profiler_cleared.is_connected(_on_clear):
+ profiler.profiler_cleared.disconnect(_on_clear)
+
+func _on_clear() -> void:
+ data_mutex.lock()
+ for l in existing_labels.values():
+ l.queue_free()
+ existing_labels.clear()
+ data_cache.clear()
+ sorted_keys.clear()
+ pending_data_update.clear()
+ pending_remove_keys.clear()
+ has_pending_changes = false
+ data_mutex.unlock()
+
+ current_sort_key = "total_bytes"
+ sort_reversed = false
+ _update_button_states()
+
+# -------------------------------------------------------------------------
+# Sort-button handling
+# -------------------------------------------------------------------------
+func _connect_sort_buttons() -> void:
+ var map = {
+ "type": type_sort_button,
+ "object": object_sort_button,
+ "target": target_sort_button,
+ "count": count_sort_button,
+ "total_bytes": usage_sort_button,
+ "percent": percent_sort_button
+ }
+ for k in map.keys():
+ var btn = map[k]
+ if btn and btn.pressed.get_connections().size() == 0:
+ btn.pressed.connect(func(): _sort_by(k))
+
+func _sort_by(key : String) -> void:
+ if current_sort_key == key:
+ sort_reversed = !sort_reversed # toggle direction
+ else:
+ current_sort_key = key
+ sort_reversed = false # default = descending (biggest on top)
+ _update_button_states()
+ _schedule_rebuild()
+
+func _update_button_states() -> void:
+ var map = {
+ "type": type_sort_button,
+ "object": object_sort_button,
+ "target": target_sort_button,
+ "count": count_sort_button,
+ "total_bytes": usage_sort_button,
+ "percent": percent_sort_button
+ }
+ for k in map.keys():
+ var btn = map[k]
+ if btn:
+ btn.text = _get_button_text(k)
+
+func _get_button_text(key : String) -> String:
+ var base = key.capitalize()
+ if current_sort_key == key:
+ return base + (" (descending)" if !sort_reversed else " (ascending)")
+ return base
+
+# -------------------------------------------------------------------------
+# Data → UI
+# -------------------------------------------------------------------------
+func _on_message_details(details : Dictionary) -> void:
+ if !details.has(listen_key): return
+ var data : Dictionary = details[listen_key]
+
+ data_mutex.lock()
+
+ var changed = false
+ for k in data.keys():
+ if not existing_labels.has(k):
+ changed = true
+ # Create label immediately on main thread
+ var label = label_template.duplicate()
+ add_child(label)
+ label.visible = true
+ existing_labels[k] = label
+
+ # Update UI immediately
+ _populate_label(k, data[k])
+
+ # Queue data for thread processing
+ pending_data_update[k] = {
+ "type": data[k].type,
+ "object": data[k].object,
+ "target": data[k].target,
+ "count": data[k].count,
+ "total_bytes": data[k].total_bytes,
+ "percent": data[k].percent
+ }
+
+ # Find keys to remove
+ var current_keys = data.keys()
+ var to_remove = []
+ for k in existing_labels.keys():
+ if !current_keys.has(k):
+ to_remove.append(k)
+ changed = true
+
+ # Remove labels immediately from UI but keep in cache for thread
+ for k in to_remove:
+ existing_labels[k].queue_free()
+ existing_labels.erase(k)
+ pending_remove_keys.append(k)
+
+ if changed:
+ has_pending_changes = true
+ _start_thread_if_needed()
+
+ data_mutex.unlock()
+
+func _populate_label(key : String, data : Dictionary) -> void:
+ var label = existing_labels.get(key)
+ if not label:
+ return
+
+ label.get_node("Data/Object").text = get_final_segment(data["object"])
+ label.get_node("Data/Object").tooltip_text = data["object"]
+ label.get_node("Data/Target").text = data["target"]
+ label.get_node("Data/Count").text = _format_number(data["count"])
+ label.get_node("Data/Count").tooltip_text = "This message was sent %s times." % [_format_number(data["count"])]
+ label.get_node("Data/Usage").text = _format_bytes(data["total_bytes"])
+ label.get_node("Data/Usage").tooltip_text = "These messages have used %s of transfer." % [_format_bytes(data["total_bytes"])]
+
+ var percent : float = data["percent"]
+ var color_value_yellow : float = percent / 100.0
+ var color_value_red : float = color_value_yellow*2.0-1.0
+ color_value_yellow = min(color_value_yellow*2.0, 1.0)
+ color_value_red = max(color_value_red, 0.0)
+
+ var color = Color.CHARTREUSE.lerp(Color.GOLD, color_value_yellow).lerp(Color.TOMATO, color_value_red)
+ var color_hex = color.to_html(false)
+
+ var percent_text = "[color=%s]%.*f%%[/color]" % [color_hex, 2, percent]
+ label.get_node("Data/Percentage").text = percent_text
+ label.get_node("Data/Percentage").tooltip_text = "These messages contributed %.*f%% of the total %s transfer." % [2, percent, "incoming" if listen_key == "down" else "outgoing"]
+
+ var type_tooltip : String = data["type"]
+ var type_color : String = Color.WHITE.to_html(false)
+ match(data["type"]):
+ "internal":
+ type_tooltip = "An internal message of GD-Sync which may provide extra functionality or optimizations."
+ type_color = "#f5c2e7"
+ "call_func":
+ type_tooltip = "A script used call_func, call_func_on or call_func_all to remotely call a function on a Node or Resource."
+ type_color = "#a6e3a1"
+ "call_func optimized":
+ type_tooltip = "A script used call_func, call_func_on or call_func_all to remotely call a function on a Node or Resource. \nThis is an optimized version which caches caches the NodePath and function name and replaces them with integers to save transfer."
+ type_color = "#a6e3a1"
+ "sync_var":
+ type_tooltip = "A script used sync_var or sync_var_on to synchronize the value of a property on all clients."
+ type_color = "#89b4fa"
+ "sync_var optimized":
+ type_tooltip = "A script used sync_var or sync_var_on to synchronize the value of a property on all clients. \nThis is an optimized version which caches caches the NodePath and property name and replaces them with integers to save transfer."
+ type_color = "#89b4fa"
+ label.get_node("Data/Type").text = "[color=%s]%s[/color]" % [type_color, data["type"]]
+ label.get_node("Data/Type").tooltip_text = type_tooltip
+
+ var target_node = label.get_node("Data/Target")
+ if data.has("last_details") and data["last_details"] is Array and not data["last_details"].is_empty():
+ var details_list = data["last_details"]
+ var tooltip_text = data["target"]
+ tooltip_text += "\n\nLast messages:\n" + "─".repeat(20) + "\n"
+
+ for i in range(details_list.size() - 1, -1, -1):
+ tooltip_text += details_list[i] + "\n"
+ if i > 0:
+ tooltip_text += "─".repeat(20) + "\n"
+
+ target_node.tooltip_text = tooltip_text
+ else:
+ target_node.tooltip_text = data["target"]
+
+func get_final_segment(path: String) -> String:
+ var parts = path.strip_edges().split("/")
+ return parts[-1] if parts.size() > 0 else path
+
+func _format_number(n : int) -> String:
+ var s = str(abs(n))
+ var result = ""
+ for i in range(s.length() - 1, -1, -1):
+ if (s.length() - 1 - i) % 3 == 0 and i < s.length() - 1:
+ result = "." + result
+ result = s[i] + result
+ return ("-" if n < 0 else "") + result
+
+func _format_bytes(b : int) -> String:
+ if b <= 0: return "0 B"
+ var u = ["B","KB","MB","GB"]
+ var i = 0
+ var v = float(b)
+ while v >= 1000.0 and i < 3:
+ v /= 1000.0
+ i += 1
+ return "%.*f %s" % [1 if i > 0 else 0, v, u[i]]
+
+func _schedule_rebuild() -> void:
+ data_mutex.lock()
+ has_pending_changes = true
+ data_mutex.unlock()
+ _start_thread_if_needed()
+
+func _reorder_labels_ui() -> void:
+ data_mutex.lock()
+ var local_sorted_keys = sorted_keys.duplicate()
+ data_mutex.unlock()
+
+ var idx = get_child_count() - 1
+ for k in local_sorted_keys:
+ var label = existing_labels.get(k)
+ if label and label.get_index() != idx:
+ move_child(label, idx)
+ idx -= 1
diff --git a/addons/GD-Sync/UI/Profiler/ProfilerDetailsDisplay.gd.uid b/addons/GD-Sync/UI/Profiler/ProfilerDetailsDisplay.gd.uid
new file mode 100644
index 0000000..af63537
--- /dev/null
+++ b/addons/GD-Sync/UI/Profiler/ProfilerDetailsDisplay.gd.uid
@@ -0,0 +1 @@
+uid://4b1i1ihfsqdf
diff --git a/addons/GD-Sync/UI/Profiler/ProfilerGraph.gd b/addons/GD-Sync/UI/Profiler/ProfilerGraph.gd
new file mode 100644
index 0000000..e4c5dca
--- /dev/null
+++ b/addons/GD-Sync/UI/Profiler/ProfilerGraph.gd
@@ -0,0 +1,184 @@
+@tool
+extends Control
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+@export var profiler : Node = null : set = _set_profiler
+@export var client_id : int = -1
+@export var series : Array[Dictionary] = [
+ {"key": "up_sec", "color": Color("#4ade80"), "label": "Upload"},
+ {"key": "down_sec", "color": Color("#60a5fa"), "label": "Download"}
+]
+@export var history_seconds : int = 60
+@export var padding := Vector2(40, 30)
+@export var grid_color := Color(0.3, 0.3, 0.3, 0.5)
+@export var text_color := Color.WHITE
+@export var bg_color := Color(0.1, 0.1, 0.1, 0.8)
+@export var font_size := 12
+@export_enum("Bytes", "Milliseconds") var display_mode : int = 0:
+ set = _set_display_mode
+
+var data_series : Array = []
+
+func _ready():
+ _setup_series()
+ if profiler:
+ _connect_signal()
+
+func _set_display_mode(mode):
+ display_mode = mode
+ queue_redraw()
+
+func _set_profiler(v):
+ if profiler == v: return
+ if profiler:
+ _disconnect_signal()
+ profiler = v
+ if profiler:
+ _connect_signal()
+
+func _setup_series():
+ data_series.clear()
+ for s in series:
+ var ds = {
+ "values": [],
+ "color": s.color,
+ "label": s.label
+ }
+ ds.values.resize(history_seconds)
+ ds.values.fill(0.0)
+ data_series.append(ds)
+
+func _connect_signal():
+ if not profiler: return
+ if profiler.has_signal("stats_updated") and not profiler.stats_updated.is_connected(_on_stats_updated):
+ profiler.stats_updated.connect(_on_stats_updated)
+ if profiler.has_signal("profiler_cleared") and not profiler.profiler_cleared.is_connected(_on_clear):
+ profiler.profiler_cleared.connect(_on_clear)
+
+func _disconnect_signal():
+ if not profiler: return
+ if profiler.has_signal("stats_updated") and profiler.stats_updated.is_connected(_on_stats_updated):
+ profiler.stats_updated.disconnect(_on_stats_updated)
+ if profiler.has_signal("profiler_cleared") and profiler.profiler_cleared.is_connected(_on_clear):
+ profiler.profiler_cleared.disconnect(_on_clear)
+
+func _on_stats_updated(cid : int, stats : Dictionary):
+ if client_id != -1 and cid != client_id: return
+ if client_id == -1 and cid != -1: return
+ for i in data_series.size():
+ var key = series[i].key
+ var val = stats.get(key, 0.0)
+ var ds = data_series[i]
+ ds.values.pop_back()
+ ds.values.push_front(val)
+ queue_redraw()
+
+func _on_clear():
+ _setup_series()
+ queue_redraw()
+
+func _nice_number(value : float, round_up : bool) -> float:
+ var exponent = floor(log(value) / log(10.0))
+ var fraction = value / pow(10.0, exponent)
+ var nice_fraction = 10.0 if round_up else 1.0
+ if fraction <= 1.0: nice_fraction = 1.0
+ elif fraction <= 2.0: nice_fraction = 2.0
+ elif fraction <= 5.0: nice_fraction = 5.0
+ else: nice_fraction = 10.0
+ return nice_fraction * pow(10.0, exponent)
+
+func _draw():
+ var rect = get_rect()
+ draw_rect(rect, bg_color)
+
+ if data_series.is_empty(): return
+
+ var graph_rect = rect.grow_individual(-padding.x, -padding.y, -padding.x, -padding.y)
+ var w = graph_rect.size.x
+ var h = graph_rect.size.y
+ var x0 = graph_rect.position.x
+ var y0 = graph_rect.position.y
+
+ var all_vals : Array = []
+ for ds in data_series:
+ for v in ds.values:
+ if v > 0: all_vals.append(v)
+ var raw_max = all_vals.max() if not all_vals.is_empty() else 1000.0
+ var max_val = _nice_number(raw_max * 1.05, true)
+ max_val = max(max_val, 1.0)
+
+ var grid_levels = 5
+ for i in range(grid_levels + 1):
+ var y = y0 + h * i / float(grid_levels)
+ draw_line(Vector2(x0, y), Vector2(x0 + w, y), grid_color, 1.0)
+ var label_val = max_val * (1.0 - i / float(grid_levels))
+ var label = _format_value(label_val, 1)
+ draw_string(ThemeDB.fallback_font, Vector2(x0 - 5, y + 5), label, HORIZONTAL_ALIGNMENT_RIGHT, -1, font_size, text_color)
+
+ for idx in data_series.size():
+ var ds = data_series[idx]
+ var points : Array = []
+ for i in history_seconds:
+ var v = ds.values[i]
+ var x = x0 + w * (1.0 - i / float(history_seconds - 1))
+ var y = y0 + h * (1.0 - v / max_val)
+ points.append(Vector2(x, y))
+ if points.size() > 1:
+ draw_polyline(points, ds.color, 2.0)
+
+ var total_width := 0.0
+ var label_widths : Array = []
+ for ds in data_series:
+ var size = ThemeDB.fallback_font.get_string_size(ds.label, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size)
+ label_widths.append(size.x)
+ total_width += size.x
+ total_width += (data_series.size() - 1) * 10
+ var start_x = x0 + (w - total_width) / 2.0
+ var legend_y = y0 + h + 14
+ var current_x = start_x
+ for i in data_series.size():
+ var ds = data_series[i]
+ draw_string(ThemeDB.fallback_font, Vector2(current_x, legend_y), ds.label, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, ds.color)
+ current_x += label_widths[i] + 10
+
+func _format_value(value : float, d := 1) -> String:
+ match display_mode:
+ 0:
+ return _format_bytes(value, d) + "/s"
+ 1:
+ return "%.*f ms" % [d, value]
+ _:
+ return "%.*f" % [d, value]
+
+func _format_bytes(b : float, d := 1) -> String:
+ if b <= 0: return "0 B"
+ var u = ["B","KB","MB","GB"]
+ var i = 0
+ var v = abs(b)
+ while v >= 1000.0 and i < 3:
+ v /= 1000.0
+ i += 1
+ return "%.*f %s" % [d, v, u[i]]
diff --git a/addons/GD-Sync/UI/Profiler/ProfilerGraph.gd.uid b/addons/GD-Sync/UI/Profiler/ProfilerGraph.gd.uid
new file mode 100644
index 0000000..dc30e3c
--- /dev/null
+++ b/addons/GD-Sync/UI/Profiler/ProfilerGraph.gd.uid
@@ -0,0 +1 @@
+uid://8618gttywoy6
diff --git a/addons/GD-Sync/UI/Profiler/ProfilerLabel.gd b/addons/GD-Sync/UI/Profiler/ProfilerLabel.gd
new file mode 100644
index 0000000..5e32e99
--- /dev/null
+++ b/addons/GD-Sync/UI/Profiler/ProfilerLabel.gd
@@ -0,0 +1,256 @@
+@tool
+extends RichTextLabel
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+@export var profiler : Node = null : set = _set_profiler
+@export var client_id : int = -1
+@export var stat_key : String = "up_sec"
+@export var is_bytes : bool = true
+@export var decimal_places : int = 1
+@export var suffix : String = "/s"
+@export var color_hex : String = "#ffffff"
+@export var label_text : String = "Upload" : set = _set_label_text
+@export var show_label_text : bool = true
+@export_group("Custom Data")
+@export var use_custom_data : bool = false
+@export var show_missing : bool = true
+@export var missing_text : String = "N/A"
+
+func _ready():
+ bbcode_enabled = true
+ _update_display()
+ if profiler:
+ _connect_signal()
+
+func _set_profiler(v):
+ if profiler == v: return
+ if profiler:
+ _disconnect_signal()
+ profiler = v
+ if profiler:
+ _connect_signal()
+ _update_display()
+
+func _set_label_text(v):
+ label_text = v
+ _update_display()
+
+func _connect_signal():
+ if not profiler: return
+ if profiler.has_signal("stats_updated") and not profiler.stats_updated.is_connected(_on_stats_updated):
+ profiler.stats_updated.connect(_on_stats_updated)
+ if profiler.has_signal("custom_data_updated") and not profiler.custom_data_updated.is_connected(_on_custom_data):
+ profiler.custom_data_updated.connect(_on_custom_data)
+ if profiler.has_signal("profiler_cleared") and not profiler.profiler_cleared.is_connected(_on_clear):
+ profiler.profiler_cleared.connect(_on_clear)
+
+func _disconnect_signal():
+ if not profiler: return
+ if profiler.has_signal("stats_updated") and profiler.stats_updated.is_connected(_on_stats_updated):
+ profiler.stats_updated.disconnect(_on_stats_updated)
+ if profiler.has_signal("custom_data_updated") and profiler.custom_data_updated.is_connected(_on_custom_data):
+ profiler.custom_data_updated.disconnect(_on_custom_data)
+ if profiler.has_signal("profiler_cleared") and profiler.profiler_cleared.is_connected(_on_clear):
+ profiler.profiler_cleared.disconnect(_on_clear)
+
+func _on_stats_updated(cid : int, stats : Dictionary):
+ if use_custom_data: return
+ if client_id != -1 and cid != client_id: return
+ if client_id == -1 and cid != -1: return
+ var val = stats.get(stat_key, 0.0)
+ var value_str = _format_value(val)
+ _set_text(value_str)
+
+func _on_custom_data(data : Dictionary):
+ if not use_custom_data: return
+ _update_from_custom_data(data)
+
+func _on_clear():
+ if use_custom_data:
+ _update_from_custom_data({})
+ else:
+ _update_display()
+
+func _update_from_custom_data(data : Dictionary):
+ var val = data.get(stat_key, null)
+ if val == null:
+ if show_missing:
+ _set_text(missing_text)
+ else:
+ text = ""
+ else:
+ var formatted = _format_custom_value(val)
+ _set_text(formatted)
+
+func _update_display():
+ if use_custom_data:
+ _update_from_custom_data({})
+ else:
+ _set_text("...")
+
+func _set_text(value_str : String):
+ var prefix = label_text + ": " if show_label_text else ""
+ text = "[color=%s]%s%s[/color]" % [color_hex, prefix, value_str]
+
+func _format_value(b) -> String:
+ if is_nan(b) or is_inf(b):
+ return "0 B" + suffix
+ if not is_bytes:
+ return _format_number(int(b)) + suffix
+ if b == 0:
+ return "0 B" + suffix
+ var u = ["B","KB","MB","GB"]
+ var i = 0
+ var v = abs(b)
+ while v >= 1000.0 and i < 3:
+ v /= 1000.0
+ i += 1
+ var formatted = "%.*f" % [decimal_places, v]
+ var parts = formatted.split(".")
+ var int_part = _format_number(int(parts[0]))
+ var frac_part = ("." + parts[1]) if parts.size() > 1 else ""
+ return ("-" if b < 0 else "") + int_part + frac_part + " " + u[i] + suffix
+
+func _format_custom_value(val) -> String:
+ match typeof(val):
+ TYPE_FLOAT, TYPE_INT:
+ if abs(val) >= 1000.0 and is_bytes:
+ return _format_bytes(float(val), decimal_places)
+ else:
+ return "%.*f" % [decimal_places, val] if typeof(val) == TYPE_FLOAT else str(val)
+ TYPE_BOOL:
+ return "True" if val else "False"
+ TYPE_STRING:
+ return val
+ TYPE_ARRAY, TYPE_PACKED_BYTE_ARRAY, TYPE_PACKED_INT32_ARRAY, TYPE_PACKED_INT64_ARRAY, \
+ TYPE_PACKED_FLOAT32_ARRAY, TYPE_PACKED_FLOAT64_ARRAY, TYPE_PACKED_STRING_ARRAY, \
+ TYPE_PACKED_VECTOR2_ARRAY, TYPE_PACKED_VECTOR3_ARRAY, TYPE_PACKED_VECTOR4_ARRAY, \
+ TYPE_PACKED_COLOR_ARRAY:
+ return _pretty_print_array(val)
+ TYPE_DICTIONARY:
+ return _pretty_print_dict(val)
+ TYPE_COLOR:
+ return _format_color(val)
+ _:
+ return str(val)
+
+func _pretty_print_array(arr, indent_level := 0) -> String:
+ if arr.is_empty():
+ return "[]"
+ var indent := " "
+ var result := "[\n"
+ for i in arr.size():
+ var item = arr[i]
+ var formatted = _pretty_print_value(item, indent_level + 1)
+ result += indent.repeat(indent_level + 1) + formatted
+ if i < arr.size() - 1:
+ result += ","
+ result += "\n"
+ result += indent.repeat(indent_level) + "]"
+ return result
+
+func _pretty_print_dict(dict : Dictionary, indent_level := 0) -> String:
+ if dict.is_empty():
+ return "{}"
+ var indent := " "
+ var result := "{\n"
+ var keys = dict.keys()
+ keys.sort()
+ for i in keys.size():
+ var key = keys[i]
+ var value = dict[key]
+ var key_type = typeof(key)
+ var key_str = _escape_string(str(key))
+ var key_color = _get_type_color(key_type)
+ var formatted = _pretty_print_value(value, indent_level + 1)
+ result += indent.repeat(indent_level + 1) + "[color=%s]%s[/color]: %s" % [key_color, key_str, formatted]
+ if i < keys.size() - 1:
+ result += ","
+ result += "\n"
+ result += indent.repeat(indent_level) + "}"
+ return result
+
+func _pretty_print_value(val, indent_level := 0) -> String:
+ match typeof(val):
+ TYPE_ARRAY, TYPE_PACKED_BYTE_ARRAY, TYPE_PACKED_INT32_ARRAY, TYPE_PACKED_INT64_ARRAY, \
+ TYPE_PACKED_FLOAT32_ARRAY, TYPE_PACKED_FLOAT64_ARRAY, TYPE_PACKED_STRING_ARRAY, \
+ TYPE_PACKED_VECTOR2_ARRAY, TYPE_PACKED_VECTOR3_ARRAY, TYPE_PACKED_VECTOR4_ARRAY, \
+ TYPE_PACKED_COLOR_ARRAY:
+ return _pretty_print_array(val, indent_level)
+ TYPE_DICTIONARY:
+ return _pretty_print_dict(val, indent_level)
+ TYPE_COLOR:
+ return _format_color(val)
+ TYPE_STRING:
+ if val.is_valid_int() or val.is_valid_float():
+ return "[color=#f5c2e7]%s[/color]" % _escape_string(val)
+ else:
+ return "[color=#a6e3a1]%s[/color]" % _escape_string(val)
+ TYPE_INT, TYPE_FLOAT:
+ return "[color=#89b4fa]%s[/color]" % _format_custom_value(val)
+ TYPE_BOOL:
+ return "[color=#f38ba8]Yes[/color]" if val else "[color=#f38ba8]No[/color]"
+ _:
+ return "[color=#cdd6f4]%s[/color]" % str(val)
+
+func _format_color(col : Color) -> String:
+ var hex = col.to_html(false)
+ return "[color=#%s]██[/color] %s" % [hex, col]
+
+func _escape_string(s : String) -> String:
+ return "\"" + s.replace("\"", "\\\"") + "\""
+
+func _get_type_color(t : int) -> String:
+ match t:
+ TYPE_STRING: return "#f5c2e7"
+ TYPE_INT, TYPE_FLOAT: return "#89b4fa"
+ TYPE_BOOL: return "#f38ba8"
+ TYPE_ARRAY, TYPE_PACKED_BYTE_ARRAY, TYPE_PACKED_INT32_ARRAY, TYPE_PACKED_INT64_ARRAY, \
+ TYPE_PACKED_FLOAT32_ARRAY, TYPE_PACKED_FLOAT64_ARRAY, TYPE_PACKED_STRING_ARRAY, \
+ TYPE_PACKED_VECTOR2_ARRAY, TYPE_PACKED_VECTOR3_ARRAY, TYPE_PACKED_VECTOR4_ARRAY, \
+ TYPE_PACKED_COLOR_ARRAY: return "#cba6f7"
+ TYPE_DICTIONARY: return "#f9e2af"
+ TYPE_COLOR: return "#94e2d5"
+ _: return "#cdd6f4"
+
+func _format_bytes(b : float, d := 1) -> String:
+ if b <= 0: return "0 B"
+ var u = ["B","KB","MB","GB"]
+ var i = 0
+ var v = abs(b)
+ while v >= 1000.0 and i < 3:
+ v /= 1000.0
+ i += 1
+ return "%.*f %s" % [d, v, u[i]]
+
+func _format_number(n : float) -> String:
+ var s = str(int(abs(n)))
+ var result = ""
+ for i in range(s.length() - 1, -1, -1):
+ if (s.length() - 1 - i) % 3 == 0 and i < s.length() - 1:
+ result = "." + result
+ result = s[i] + result
+ return ("-" if n < 0 else "") + result
diff --git a/addons/GD-Sync/UI/Profiler/ProfilerLabel.gd.uid b/addons/GD-Sync/UI/Profiler/ProfilerLabel.gd.uid
new file mode 100644
index 0000000..5d112f6
--- /dev/null
+++ b/addons/GD-Sync/UI/Profiler/ProfilerLabel.gd.uid
@@ -0,0 +1 @@
+uid://b3p26nyamgl8j
diff --git a/addons/GD-Sync/Updater.gd b/addons/GD-Sync/Updater.gd
new file mode 100644
index 0000000..fcacead
--- /dev/null
+++ b/addons/GD-Sync/Updater.gd
@@ -0,0 +1,171 @@
+@tool
+class_name Updater
+extends Node
+
+#Copyright (c) 2023-present GD-Sync.
+#All rights reserved.
+#
+#Redistribution and use in source form, with or without modification,
+#are permitted provided that the following conditions are met:
+#
+#1. Redistributions of source code must retain the above copyright notice,
+# this list of conditions and the following disclaimer.
+#
+#2. Neither the name of GD-Sync nor the names of its contributors may be used
+# to endorse or promote products derived from this software without specific
+# prior written permission.
+#
+#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+#SUCH DAMAGE.
+
+const API_ROOT : String = "https://api.github.com/repos/GD-Sync/GD-Sync/contents/"
+const API_REF : String = "main"
+const LOCAL_ROOT : String = "res://"
+const PLUGIN_PATH : String = "addons/GD-Sync"
+
+const MAX_TRIES : int = 5
+const RETRY_DELAY : float = 1.0
+const REQUEST_TIMEOUT : float = 20.0
+
+const API_HEADERS : Array = [
+ "User-Agent: GD-Sync-Updater",
+ "Accept: application/vnd.github.v3+json"
+]
+
+const EXCLUDED_FILES : Array = [
+ PLUGIN_PATH+"/GDSync.cs",
+ PLUGIN_PATH+"/GDSync.cs.uid",
+ PLUGIN_PATH+"/keys.cfg",
+]
+
+var update_label : Label
+
+func _set_status(text : String) -> void:
+ if update_label:
+ update_label.text = text
+
+func update_repo(path : String = PLUGIN_PATH) -> bool:
+ if path.is_empty(): path = PLUGIN_PATH
+
+ _set_status("Connecting to GitHub...")
+
+ var files : Array = []
+ if not await _collect_files(path, files):
+ return false
+
+ if files.is_empty():
+ push_error("GD-Sync failed to update, no files were found at "+path+".")
+ return false
+
+ for file in files:
+ if not await _download(file[0], file[1], file[2]):
+ return false
+
+ return true
+
+func _collect_files(path : String, files : Array) -> bool:
+ var entries = await _request_json(API_ROOT+path+"?ref="+API_REF)
+ if entries == null: return false
+
+ if typeof(entries) == TYPE_DICTIONARY: entries = [entries]
+ if typeof(entries) != TYPE_ARRAY:
+ push_error("GD-Sync failed to update, unexpected response for "+path+".")
+ return false
+
+ for entry in entries:
+ if typeof(entry) != TYPE_DICTIONARY: continue
+
+ var entry_path : String = str(entry.get("path", ""))
+ if _is_excluded(entry_path): continue
+
+ match str(entry.get("type", "")):
+ "file":
+ if entry.get("download_url") == null: continue
+ files.append([
+ str(entry["download_url"]),
+ entry_path,
+ int(entry.get("size", 0))
+ ])
+ "dir":
+ if not await _collect_files(entry_path, files):
+ return false
+
+ return true
+
+func _is_excluded(path : String) -> bool:
+ if !path.begins_with(PLUGIN_PATH): return true
+ if EXCLUDED_FILES.has(path): return true
+ return "template" in path.to_lower()
+
+func _download(url : String, rel : String, expected_size : int) -> bool:
+ var dst : String = LOCAL_ROOT+rel
+ var filename : String = rel.get_file()
+ _set_status("Updating "+filename)
+ print_rich("[color=#8b8d8f]- Updating file " + dst + "[/color]")
+
+ var body : PackedByteArray = await _request_bytes(url, [])
+ if body.is_empty(): return false
+
+ if expected_size > 0 and body.size() != expected_size:
+ push_error("GD-Sync failed to update, "+rel+" was downloaded incompletely ("+str(body.size())+" of "+str(expected_size)+" bytes).")
+ return false
+
+ if DirAccess.make_dir_recursive_absolute(dst.get_base_dir()) != OK:
+ push_error("GD-Sync failed to update, could not create directory "+dst.get_base_dir()+".")
+ return false
+
+ var file : FileAccess = FileAccess.open(dst, FileAccess.WRITE)
+ if file == null:
+ push_error("GD-Sync failed to update, could not write to "+dst+".")
+ return false
+
+ file.store_buffer(body)
+ file.close()
+ return true
+
+func _request_json(url : String):
+ var body : PackedByteArray = await _request_bytes(url, API_HEADERS)
+ if body.is_empty(): return null
+ return JSON.parse_string(body.get_string_from_utf8())
+
+func _request_bytes(url : String, headers : Array) -> PackedByteArray:
+ var last_code : int = 0
+
+ for attempt in range(MAX_TRIES):
+ if attempt > 0:
+ await get_tree().create_timer(RETRY_DELAY).timeout
+
+ var http : HTTPRequest = HTTPRequest.new()
+ http.timeout = REQUEST_TIMEOUT
+ add_child(http)
+
+ var result : Array = []
+ if http.request(url, headers, HTTPClient.METHOD_GET) == OK:
+ result = await http.request_completed
+
+ if is_instance_valid(http): http.queue_free()
+
+ if result.size() < 4:
+ continue
+
+ last_code = result[1]
+ if last_code == 200:
+ return result[3]
+
+ if last_code == 403 or last_code == 404 or last_code == 429:
+ break
+
+ if last_code == 403 or last_code == 429:
+ push_error("GD-Sync failed to update, the GitHub API rate limit was reached. Please try again later or download the plugin from the Godot Asset Library.")
+ else:
+ push_error("GD-Sync failed to update, could not download "+url+" (status "+str(last_code)+").")
+
+ return PackedByteArray()
diff --git a/addons/GD-Sync/Updater.gd.uid b/addons/GD-Sync/Updater.gd.uid
new file mode 100644
index 0000000..0ab0b81
--- /dev/null
+++ b/addons/GD-Sync/Updater.gd.uid
@@ -0,0 +1 @@
+uid://cilpy466eqdah
diff --git a/addons/GD-Sync/plugin.cfg b/addons/GD-Sync/plugin.cfg
new file mode 100644
index 0000000..4ebe10c
--- /dev/null
+++ b/addons/GD-Sync/plugin.cfg
@@ -0,0 +1,7 @@
+[plugin]
+
+name="GD-Sync"
+description="Cloud multiplayer plugin for Godot. Lobbies, replication, accounts and matchmaking."
+author="GD-Sync"
+version="1.0.2"
+script="GD-Sync.gd"
diff --git a/assets/audio/CREDITS.md b/assets/audio/CREDITS.md
new file mode 100644
index 0000000..9b5103f
--- /dev/null
+++ b/assets/audio/CREDITS.md
@@ -0,0 +1,35 @@
+# Harvest Season — audio credits
+
+Every sound the game plays is listed by cue in `game/scripts/farm_audio.gd` (`FarmAudio.CUES`).
+
+## Kenney (CC0)
+
+Public domain (Creative Commons Zero, ), by
+Kenney Vleugels (). Downloaded 2026-10-03; only the files the game uses were
+copied, unchanged, with each pack's `License.txt`.
+
+| Folder | Pack | Source |
+|---|---|---|
+| `kenney/impact/` | Impact Sounds | |
+| `kenney/interface/` | Interface Sounds | |
+| `kenney/rpg/` | RPG Audio | |
+| `kenney/ui/` | UI Audio | |
+| `kenney/digital/` | Digital Audio | |
+| `kenney/jingles/` | Music Jingles (pizzicato set) | |
+
+## Music
+
+Provided by the project's owner (2026-10-03); check each source's license for the credit it asks
+for before release.
+
+| File | Track | Plays |
+|---|---|---|
+| `music/on_the_farm.wav` | "On the Farm" | Title screen, morning, day, the farmers' return |
+| `music/purgatory.ogg` | DavidKBD, *Purgatory Pack*: "Purgatory" | Night |
+
+## Made for the game
+
+`synth/` is generated by `game/tools/synth_audio.gd` (deterministic, fixed seeds): the day and
+night ambience loops, the crow caws and squawk, the farmers' car (engine loop and horn), the
+pitchfork's whoosh, and the pumpkin bomb's burst. Kenney's packs have no farm ambience, birds,
+vehicles, or explosions. Re-run the tool to regenerate them.
diff --git a/assets/audio/kenney/digital/License.txt b/assets/audio/kenney/digital/License.txt
new file mode 100644
index 0000000..e94d157
--- /dev/null
+++ b/assets/audio/kenney/digital/License.txt
@@ -0,0 +1,21 @@
+
+
+ Digital Audio
+
+ by Kenney Vleugels (Kenney.nl)
+
+ ------------------------------
+
+ License (Creative Commons Zero, CC0)
+ http://creativecommons.org/publicdomain/zero/1.0/
+
+ You may use these assets in personal and commercial projects.
+ Credit (Kenney or www.kenney.nl) would be nice but is not mandatory.
+
+ ------------------------------
+
+ Donate: http://support.kenney.nl
+ Request: http://request.kenney.nl
+
+ Follow on Twitter for updates:
+ @KenneyNL
\ No newline at end of file
diff --git a/assets/audio/kenney/digital/lowDown.ogg b/assets/audio/kenney/digital/lowDown.ogg
new file mode 100644
index 0000000..802ab13
Binary files /dev/null and b/assets/audio/kenney/digital/lowDown.ogg differ
diff --git a/assets/audio/kenney/digital/lowDown.ogg.import b/assets/audio/kenney/digital/lowDown.ogg.import
new file mode 100644
index 0000000..a120223
--- /dev/null
+++ b/assets/audio/kenney/digital/lowDown.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://buo1h525hpol4"
+path="res://.godot/imported/lowDown.ogg-c14b442aefbce17749683284ac2ac7dc.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/digital/lowDown.ogg"
+dest_files=["res://.godot/imported/lowDown.ogg-c14b442aefbce17749683284ac2ac7dc.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/digital/lowThreeTone.ogg b/assets/audio/kenney/digital/lowThreeTone.ogg
new file mode 100644
index 0000000..c257518
Binary files /dev/null and b/assets/audio/kenney/digital/lowThreeTone.ogg differ
diff --git a/assets/audio/kenney/digital/lowThreeTone.ogg.import b/assets/audio/kenney/digital/lowThreeTone.ogg.import
new file mode 100644
index 0000000..3212076
--- /dev/null
+++ b/assets/audio/kenney/digital/lowThreeTone.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dcncwgk34hyan"
+path="res://.godot/imported/lowThreeTone.ogg-9b91c904b1614fe37ffed1e568f2e6cd.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/digital/lowThreeTone.ogg"
+dest_files=["res://.godot/imported/lowThreeTone.ogg-9b91c904b1614fe37ffed1e568f2e6cd.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/digital/phaserDown2.ogg b/assets/audio/kenney/digital/phaserDown2.ogg
new file mode 100644
index 0000000..c85f98b
Binary files /dev/null and b/assets/audio/kenney/digital/phaserDown2.ogg differ
diff --git a/assets/audio/kenney/digital/phaserDown2.ogg.import b/assets/audio/kenney/digital/phaserDown2.ogg.import
new file mode 100644
index 0000000..823b83e
--- /dev/null
+++ b/assets/audio/kenney/digital/phaserDown2.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dwhyndkbljmpl"
+path="res://.godot/imported/phaserDown2.ogg-9daacf86a627294d1836e253acaf4dd3.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/digital/phaserDown2.ogg"
+dest_files=["res://.godot/imported/phaserDown2.ogg-9daacf86a627294d1836e253acaf4dd3.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/digital/powerUp2.ogg b/assets/audio/kenney/digital/powerUp2.ogg
new file mode 100644
index 0000000..7872a4b
Binary files /dev/null and b/assets/audio/kenney/digital/powerUp2.ogg differ
diff --git a/assets/audio/kenney/digital/powerUp2.ogg.import b/assets/audio/kenney/digital/powerUp2.ogg.import
new file mode 100644
index 0000000..203a772
--- /dev/null
+++ b/assets/audio/kenney/digital/powerUp2.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://itn3d74sb0mg"
+path="res://.godot/imported/powerUp2.ogg-68ed81b1c949aa869a19d262da7f79d8.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/digital/powerUp2.ogg"
+dest_files=["res://.godot/imported/powerUp2.ogg-68ed81b1c949aa869a19d262da7f79d8.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/digital/twoTone1.ogg b/assets/audio/kenney/digital/twoTone1.ogg
new file mode 100644
index 0000000..82653ad
Binary files /dev/null and b/assets/audio/kenney/digital/twoTone1.ogg differ
diff --git a/assets/audio/kenney/digital/twoTone1.ogg.import b/assets/audio/kenney/digital/twoTone1.ogg.import
new file mode 100644
index 0000000..a558fd1
--- /dev/null
+++ b/assets/audio/kenney/digital/twoTone1.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://cl7q1u35feso"
+path="res://.godot/imported/twoTone1.ogg-6658dc5a62216034b2494f99ea3578ea.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/digital/twoTone1.ogg"
+dest_files=["res://.godot/imported/twoTone1.ogg-6658dc5a62216034b2494f99ea3578ea.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/License.txt b/assets/audio/kenney/impact/License.txt
new file mode 100644
index 0000000..4890fe5
--- /dev/null
+++ b/assets/audio/kenney/impact/License.txt
@@ -0,0 +1,23 @@
+
+
+ Impact Sounds (1.0)
+
+ Created/distributed by Kenney (www.kenney.nl)
+ Creation date: 19-12-2019
+
+ ------------------------------
+
+ License: (Creative Commons Zero, CC0)
+ http://creativecommons.org/publicdomain/zero/1.0/
+
+ This content is free to use in personal, educational and commercial projects.
+ Support us by crediting Kenney or www.kenney.nl (this is not mandatory)
+
+ ------------------------------
+
+ Donate: http://support.kenney.nl
+ Request: http://request.kenney.nl
+ Patreon: http://patreon.com/kenney/
+
+ Follow on Twitter for updates:
+ http://twitter.com/KenneyNL
\ No newline at end of file
diff --git a/assets/audio/kenney/impact/footstep_grass_000.ogg b/assets/audio/kenney/impact/footstep_grass_000.ogg
new file mode 100644
index 0000000..5b5ec87
Binary files /dev/null and b/assets/audio/kenney/impact/footstep_grass_000.ogg differ
diff --git a/assets/audio/kenney/impact/footstep_grass_000.ogg.import b/assets/audio/kenney/impact/footstep_grass_000.ogg.import
new file mode 100644
index 0000000..013944c
--- /dev/null
+++ b/assets/audio/kenney/impact/footstep_grass_000.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://bglv36mepq5wu"
+path="res://.godot/imported/footstep_grass_000.ogg-1b9ca7be18a887ac77a35e1e272d4976.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/footstep_grass_000.ogg"
+dest_files=["res://.godot/imported/footstep_grass_000.ogg-1b9ca7be18a887ac77a35e1e272d4976.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/footstep_grass_001.ogg b/assets/audio/kenney/impact/footstep_grass_001.ogg
new file mode 100644
index 0000000..56c3a84
Binary files /dev/null and b/assets/audio/kenney/impact/footstep_grass_001.ogg differ
diff --git a/assets/audio/kenney/impact/footstep_grass_001.ogg.import b/assets/audio/kenney/impact/footstep_grass_001.ogg.import
new file mode 100644
index 0000000..9308611
--- /dev/null
+++ b/assets/audio/kenney/impact/footstep_grass_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://gqfin5puiw83"
+path="res://.godot/imported/footstep_grass_001.ogg-78a3f47818f26603b6b68b229c4729cf.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/footstep_grass_001.ogg"
+dest_files=["res://.godot/imported/footstep_grass_001.ogg-78a3f47818f26603b6b68b229c4729cf.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/footstep_grass_002.ogg b/assets/audio/kenney/impact/footstep_grass_002.ogg
new file mode 100644
index 0000000..aa0b414
Binary files /dev/null and b/assets/audio/kenney/impact/footstep_grass_002.ogg differ
diff --git a/assets/audio/kenney/impact/footstep_grass_002.ogg.import b/assets/audio/kenney/impact/footstep_grass_002.ogg.import
new file mode 100644
index 0000000..8f9e1ea
--- /dev/null
+++ b/assets/audio/kenney/impact/footstep_grass_002.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://by1vuyow0bfe"
+path="res://.godot/imported/footstep_grass_002.ogg-ae7a7a0c23db15614dcec5e3b056092f.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/footstep_grass_002.ogg"
+dest_files=["res://.godot/imported/footstep_grass_002.ogg-ae7a7a0c23db15614dcec5e3b056092f.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/footstep_grass_003.ogg b/assets/audio/kenney/impact/footstep_grass_003.ogg
new file mode 100644
index 0000000..fe9e119
Binary files /dev/null and b/assets/audio/kenney/impact/footstep_grass_003.ogg differ
diff --git a/assets/audio/kenney/impact/footstep_grass_003.ogg.import b/assets/audio/kenney/impact/footstep_grass_003.ogg.import
new file mode 100644
index 0000000..350cedf
--- /dev/null
+++ b/assets/audio/kenney/impact/footstep_grass_003.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://baa8js48ib7cp"
+path="res://.godot/imported/footstep_grass_003.ogg-bb5e7417214e40dddcea28b1fd20fa9f.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/footstep_grass_003.ogg"
+dest_files=["res://.godot/imported/footstep_grass_003.ogg-bb5e7417214e40dddcea28b1fd20fa9f.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/footstep_grass_004.ogg b/assets/audio/kenney/impact/footstep_grass_004.ogg
new file mode 100644
index 0000000..0dcff84
Binary files /dev/null and b/assets/audio/kenney/impact/footstep_grass_004.ogg differ
diff --git a/assets/audio/kenney/impact/footstep_grass_004.ogg.import b/assets/audio/kenney/impact/footstep_grass_004.ogg.import
new file mode 100644
index 0000000..0e462f9
--- /dev/null
+++ b/assets/audio/kenney/impact/footstep_grass_004.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://nulkqncmyr5j"
+path="res://.godot/imported/footstep_grass_004.ogg-60f25cbe2800c8b2cb31912aa12e5424.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/footstep_grass_004.ogg"
+dest_files=["res://.godot/imported/footstep_grass_004.ogg-60f25cbe2800c8b2cb31912aa12e5424.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactBell_heavy_000.ogg b/assets/audio/kenney/impact/impactBell_heavy_000.ogg
new file mode 100644
index 0000000..20299c4
Binary files /dev/null and b/assets/audio/kenney/impact/impactBell_heavy_000.ogg differ
diff --git a/assets/audio/kenney/impact/impactBell_heavy_000.ogg.import b/assets/audio/kenney/impact/impactBell_heavy_000.ogg.import
new file mode 100644
index 0000000..781a006
--- /dev/null
+++ b/assets/audio/kenney/impact/impactBell_heavy_000.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://ckmpbuk8toqsr"
+path="res://.godot/imported/impactBell_heavy_000.ogg-728cddbe9ae3c9424b0bbf03b202630d.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactBell_heavy_000.ogg"
+dest_files=["res://.godot/imported/impactBell_heavy_000.ogg-728cddbe9ae3c9424b0bbf03b202630d.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactBell_heavy_001.ogg b/assets/audio/kenney/impact/impactBell_heavy_001.ogg
new file mode 100644
index 0000000..9e5da82
Binary files /dev/null and b/assets/audio/kenney/impact/impactBell_heavy_001.ogg differ
diff --git a/assets/audio/kenney/impact/impactBell_heavy_001.ogg.import b/assets/audio/kenney/impact/impactBell_heavy_001.ogg.import
new file mode 100644
index 0000000..c4a1fd4
--- /dev/null
+++ b/assets/audio/kenney/impact/impactBell_heavy_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dt6ftpnlwuwk6"
+path="res://.godot/imported/impactBell_heavy_001.ogg-8cec69d2527f4706367c7c087cfd1794.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactBell_heavy_001.ogg"
+dest_files=["res://.godot/imported/impactBell_heavy_001.ogg-8cec69d2527f4706367c7c087cfd1794.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactGeneric_light_000.ogg b/assets/audio/kenney/impact/impactGeneric_light_000.ogg
new file mode 100644
index 0000000..d0a32de
Binary files /dev/null and b/assets/audio/kenney/impact/impactGeneric_light_000.ogg differ
diff --git a/assets/audio/kenney/impact/impactGeneric_light_000.ogg.import b/assets/audio/kenney/impact/impactGeneric_light_000.ogg.import
new file mode 100644
index 0000000..9948f90
--- /dev/null
+++ b/assets/audio/kenney/impact/impactGeneric_light_000.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://d3wqsjlc3xui0"
+path="res://.godot/imported/impactGeneric_light_000.ogg-95050be420a03781f7fc44a6c9a8d2ae.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactGeneric_light_000.ogg"
+dest_files=["res://.godot/imported/impactGeneric_light_000.ogg-95050be420a03781f7fc44a6c9a8d2ae.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactGeneric_light_001.ogg b/assets/audio/kenney/impact/impactGeneric_light_001.ogg
new file mode 100644
index 0000000..42eae91
Binary files /dev/null and b/assets/audio/kenney/impact/impactGeneric_light_001.ogg differ
diff --git a/assets/audio/kenney/impact/impactGeneric_light_001.ogg.import b/assets/audio/kenney/impact/impactGeneric_light_001.ogg.import
new file mode 100644
index 0000000..cd70367
--- /dev/null
+++ b/assets/audio/kenney/impact/impactGeneric_light_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://d234xj41l4pq5"
+path="res://.godot/imported/impactGeneric_light_001.ogg-f34452097b63f176fd2ce0a9721a4fe3.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactGeneric_light_001.ogg"
+dest_files=["res://.godot/imported/impactGeneric_light_001.ogg-f34452097b63f176fd2ce0a9721a4fe3.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactGeneric_light_002.ogg b/assets/audio/kenney/impact/impactGeneric_light_002.ogg
new file mode 100644
index 0000000..6c1cb47
Binary files /dev/null and b/assets/audio/kenney/impact/impactGeneric_light_002.ogg differ
diff --git a/assets/audio/kenney/impact/impactGeneric_light_002.ogg.import b/assets/audio/kenney/impact/impactGeneric_light_002.ogg.import
new file mode 100644
index 0000000..ebd56cc
--- /dev/null
+++ b/assets/audio/kenney/impact/impactGeneric_light_002.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://bt4yfx3c76psl"
+path="res://.godot/imported/impactGeneric_light_002.ogg-5526203c64d96d9154811a3fc458de5e.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactGeneric_light_002.ogg"
+dest_files=["res://.godot/imported/impactGeneric_light_002.ogg-5526203c64d96d9154811a3fc458de5e.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactGeneric_light_003.ogg b/assets/audio/kenney/impact/impactGeneric_light_003.ogg
new file mode 100644
index 0000000..f83dedf
Binary files /dev/null and b/assets/audio/kenney/impact/impactGeneric_light_003.ogg differ
diff --git a/assets/audio/kenney/impact/impactGeneric_light_003.ogg.import b/assets/audio/kenney/impact/impactGeneric_light_003.ogg.import
new file mode 100644
index 0000000..7c9f910
--- /dev/null
+++ b/assets/audio/kenney/impact/impactGeneric_light_003.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dwvevlkhtbxt0"
+path="res://.godot/imported/impactGeneric_light_003.ogg-057649ea5f61141b8d1f6ee78dbae026.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactGeneric_light_003.ogg"
+dest_files=["res://.godot/imported/impactGeneric_light_003.ogg-057649ea5f61141b8d1f6ee78dbae026.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactGeneric_light_004.ogg b/assets/audio/kenney/impact/impactGeneric_light_004.ogg
new file mode 100644
index 0000000..adfb63b
Binary files /dev/null and b/assets/audio/kenney/impact/impactGeneric_light_004.ogg differ
diff --git a/assets/audio/kenney/impact/impactGeneric_light_004.ogg.import b/assets/audio/kenney/impact/impactGeneric_light_004.ogg.import
new file mode 100644
index 0000000..0bddd72
--- /dev/null
+++ b/assets/audio/kenney/impact/impactGeneric_light_004.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://b06lb7qmt03go"
+path="res://.godot/imported/impactGeneric_light_004.ogg-a72c96dd8dc5850c31638bf1b1decad3.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactGeneric_light_004.ogg"
+dest_files=["res://.godot/imported/impactGeneric_light_004.ogg-a72c96dd8dc5850c31638bf1b1decad3.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactMetal_light_000.ogg b/assets/audio/kenney/impact/impactMetal_light_000.ogg
new file mode 100644
index 0000000..7d49262
Binary files /dev/null and b/assets/audio/kenney/impact/impactMetal_light_000.ogg differ
diff --git a/assets/audio/kenney/impact/impactMetal_light_000.ogg.import b/assets/audio/kenney/impact/impactMetal_light_000.ogg.import
new file mode 100644
index 0000000..e7b6f04
--- /dev/null
+++ b/assets/audio/kenney/impact/impactMetal_light_000.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://bdyt4p72xcvo8"
+path="res://.godot/imported/impactMetal_light_000.ogg-125acd62cfb9a631d59d28200f7b2ed3.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactMetal_light_000.ogg"
+dest_files=["res://.godot/imported/impactMetal_light_000.ogg-125acd62cfb9a631d59d28200f7b2ed3.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactMetal_light_001.ogg b/assets/audio/kenney/impact/impactMetal_light_001.ogg
new file mode 100644
index 0000000..ff73e4a
Binary files /dev/null and b/assets/audio/kenney/impact/impactMetal_light_001.ogg differ
diff --git a/assets/audio/kenney/impact/impactMetal_light_001.ogg.import b/assets/audio/kenney/impact/impactMetal_light_001.ogg.import
new file mode 100644
index 0000000..363129c
--- /dev/null
+++ b/assets/audio/kenney/impact/impactMetal_light_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://cccdd15ir01gg"
+path="res://.godot/imported/impactMetal_light_001.ogg-2565dcf6216a8026b0874440d5b6df2a.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactMetal_light_001.ogg"
+dest_files=["res://.godot/imported/impactMetal_light_001.ogg-2565dcf6216a8026b0874440d5b6df2a.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactMetal_light_002.ogg b/assets/audio/kenney/impact/impactMetal_light_002.ogg
new file mode 100644
index 0000000..c18f397
Binary files /dev/null and b/assets/audio/kenney/impact/impactMetal_light_002.ogg differ
diff --git a/assets/audio/kenney/impact/impactMetal_light_002.ogg.import b/assets/audio/kenney/impact/impactMetal_light_002.ogg.import
new file mode 100644
index 0000000..626a1c9
--- /dev/null
+++ b/assets/audio/kenney/impact/impactMetal_light_002.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://d4j6652f5px6x"
+path="res://.godot/imported/impactMetal_light_002.ogg-9ebdb1a29bf7b0d77b0d8c54d07c5c59.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactMetal_light_002.ogg"
+dest_files=["res://.godot/imported/impactMetal_light_002.ogg-9ebdb1a29bf7b0d77b0d8c54d07c5c59.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactMetal_light_003.ogg b/assets/audio/kenney/impact/impactMetal_light_003.ogg
new file mode 100644
index 0000000..59b6c25
Binary files /dev/null and b/assets/audio/kenney/impact/impactMetal_light_003.ogg differ
diff --git a/assets/audio/kenney/impact/impactMetal_light_003.ogg.import b/assets/audio/kenney/impact/impactMetal_light_003.ogg.import
new file mode 100644
index 0000000..5ca0f61
--- /dev/null
+++ b/assets/audio/kenney/impact/impactMetal_light_003.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://bsfnkvbn1ltmc"
+path="res://.godot/imported/impactMetal_light_003.ogg-439b131c4bf10e1c7a3d2787a777817d.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactMetal_light_003.ogg"
+dest_files=["res://.godot/imported/impactMetal_light_003.ogg-439b131c4bf10e1c7a3d2787a777817d.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactMetal_light_004.ogg b/assets/audio/kenney/impact/impactMetal_light_004.ogg
new file mode 100644
index 0000000..7c7de6e
Binary files /dev/null and b/assets/audio/kenney/impact/impactMetal_light_004.ogg differ
diff --git a/assets/audio/kenney/impact/impactMetal_light_004.ogg.import b/assets/audio/kenney/impact/impactMetal_light_004.ogg.import
new file mode 100644
index 0000000..34da682
--- /dev/null
+++ b/assets/audio/kenney/impact/impactMetal_light_004.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://776slta2naf2"
+path="res://.godot/imported/impactMetal_light_004.ogg-2d41f013aa7b786fa0baa8bf27c5cf4c.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactMetal_light_004.ogg"
+dest_files=["res://.godot/imported/impactMetal_light_004.ogg-2d41f013aa7b786fa0baa8bf27c5cf4c.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactPlank_medium_000.ogg b/assets/audio/kenney/impact/impactPlank_medium_000.ogg
new file mode 100644
index 0000000..70d13ee
Binary files /dev/null and b/assets/audio/kenney/impact/impactPlank_medium_000.ogg differ
diff --git a/assets/audio/kenney/impact/impactPlank_medium_000.ogg.import b/assets/audio/kenney/impact/impactPlank_medium_000.ogg.import
new file mode 100644
index 0000000..d35aa7d
--- /dev/null
+++ b/assets/audio/kenney/impact/impactPlank_medium_000.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://b01ahnpc2b4i6"
+path="res://.godot/imported/impactPlank_medium_000.ogg-cd51e97fcd008b8c66f9363f22e64e5b.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactPlank_medium_000.ogg"
+dest_files=["res://.godot/imported/impactPlank_medium_000.ogg-cd51e97fcd008b8c66f9363f22e64e5b.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactPlank_medium_001.ogg b/assets/audio/kenney/impact/impactPlank_medium_001.ogg
new file mode 100644
index 0000000..2c53b78
Binary files /dev/null and b/assets/audio/kenney/impact/impactPlank_medium_001.ogg differ
diff --git a/assets/audio/kenney/impact/impactPlank_medium_001.ogg.import b/assets/audio/kenney/impact/impactPlank_medium_001.ogg.import
new file mode 100644
index 0000000..e218630
--- /dev/null
+++ b/assets/audio/kenney/impact/impactPlank_medium_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://2jblvdjhd75y"
+path="res://.godot/imported/impactPlank_medium_001.ogg-b09270bfec800419f6730262ea640ad4.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactPlank_medium_001.ogg"
+dest_files=["res://.godot/imported/impactPlank_medium_001.ogg-b09270bfec800419f6730262ea640ad4.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactPlank_medium_002.ogg b/assets/audio/kenney/impact/impactPlank_medium_002.ogg
new file mode 100644
index 0000000..922a6db
Binary files /dev/null and b/assets/audio/kenney/impact/impactPlank_medium_002.ogg differ
diff --git a/assets/audio/kenney/impact/impactPlank_medium_002.ogg.import b/assets/audio/kenney/impact/impactPlank_medium_002.ogg.import
new file mode 100644
index 0000000..25bb2a5
--- /dev/null
+++ b/assets/audio/kenney/impact/impactPlank_medium_002.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dra0x4b5nfu47"
+path="res://.godot/imported/impactPlank_medium_002.ogg-786ad1febf85612979f778f59bc5bd0b.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactPlank_medium_002.ogg"
+dest_files=["res://.godot/imported/impactPlank_medium_002.ogg-786ad1febf85612979f778f59bc5bd0b.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactPlank_medium_003.ogg b/assets/audio/kenney/impact/impactPlank_medium_003.ogg
new file mode 100644
index 0000000..fad0463
Binary files /dev/null and b/assets/audio/kenney/impact/impactPlank_medium_003.ogg differ
diff --git a/assets/audio/kenney/impact/impactPlank_medium_003.ogg.import b/assets/audio/kenney/impact/impactPlank_medium_003.ogg.import
new file mode 100644
index 0000000..7738ecd
--- /dev/null
+++ b/assets/audio/kenney/impact/impactPlank_medium_003.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://l8cd46dsrflk"
+path="res://.godot/imported/impactPlank_medium_003.ogg-f2704d352f92f644aa889a2d0f393062.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactPlank_medium_003.ogg"
+dest_files=["res://.godot/imported/impactPlank_medium_003.ogg-f2704d352f92f644aa889a2d0f393062.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactPlank_medium_004.ogg b/assets/audio/kenney/impact/impactPlank_medium_004.ogg
new file mode 100644
index 0000000..ffe3719
Binary files /dev/null and b/assets/audio/kenney/impact/impactPlank_medium_004.ogg differ
diff --git a/assets/audio/kenney/impact/impactPlank_medium_004.ogg.import b/assets/audio/kenney/impact/impactPlank_medium_004.ogg.import
new file mode 100644
index 0000000..df42684
--- /dev/null
+++ b/assets/audio/kenney/impact/impactPlank_medium_004.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dadcbujasvqwh"
+path="res://.godot/imported/impactPlank_medium_004.ogg-05a601b71446269b79c53e55d97a72c0.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactPlank_medium_004.ogg"
+dest_files=["res://.godot/imported/impactPlank_medium_004.ogg-05a601b71446269b79c53e55d97a72c0.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactPunch_heavy_000.ogg b/assets/audio/kenney/impact/impactPunch_heavy_000.ogg
new file mode 100644
index 0000000..55e70b5
Binary files /dev/null and b/assets/audio/kenney/impact/impactPunch_heavy_000.ogg differ
diff --git a/assets/audio/kenney/impact/impactPunch_heavy_000.ogg.import b/assets/audio/kenney/impact/impactPunch_heavy_000.ogg.import
new file mode 100644
index 0000000..5c52a13
--- /dev/null
+++ b/assets/audio/kenney/impact/impactPunch_heavy_000.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dj01rtin4fm3g"
+path="res://.godot/imported/impactPunch_heavy_000.ogg-e1bf9604b128aef5b0f10a5bbd6fdd38.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactPunch_heavy_000.ogg"
+dest_files=["res://.godot/imported/impactPunch_heavy_000.ogg-e1bf9604b128aef5b0f10a5bbd6fdd38.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactPunch_heavy_001.ogg b/assets/audio/kenney/impact/impactPunch_heavy_001.ogg
new file mode 100644
index 0000000..6655951
Binary files /dev/null and b/assets/audio/kenney/impact/impactPunch_heavy_001.ogg differ
diff --git a/assets/audio/kenney/impact/impactPunch_heavy_001.ogg.import b/assets/audio/kenney/impact/impactPunch_heavy_001.ogg.import
new file mode 100644
index 0000000..d7a1895
--- /dev/null
+++ b/assets/audio/kenney/impact/impactPunch_heavy_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://3d0kqc3t0vbl"
+path="res://.godot/imported/impactPunch_heavy_001.ogg-7e03a2caab7f66a5829e4ed493b21a9d.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactPunch_heavy_001.ogg"
+dest_files=["res://.godot/imported/impactPunch_heavy_001.ogg-7e03a2caab7f66a5829e4ed493b21a9d.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactPunch_heavy_002.ogg b/assets/audio/kenney/impact/impactPunch_heavy_002.ogg
new file mode 100644
index 0000000..8573e89
Binary files /dev/null and b/assets/audio/kenney/impact/impactPunch_heavy_002.ogg differ
diff --git a/assets/audio/kenney/impact/impactPunch_heavy_002.ogg.import b/assets/audio/kenney/impact/impactPunch_heavy_002.ogg.import
new file mode 100644
index 0000000..cbee72d
--- /dev/null
+++ b/assets/audio/kenney/impact/impactPunch_heavy_002.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://b8cs54bv2m1sh"
+path="res://.godot/imported/impactPunch_heavy_002.ogg-9ded3c1d7250e89925e7bd2b48b8d259.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactPunch_heavy_002.ogg"
+dest_files=["res://.godot/imported/impactPunch_heavy_002.ogg-9ded3c1d7250e89925e7bd2b48b8d259.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactPunch_heavy_003.ogg b/assets/audio/kenney/impact/impactPunch_heavy_003.ogg
new file mode 100644
index 0000000..78cc8ab
Binary files /dev/null and b/assets/audio/kenney/impact/impactPunch_heavy_003.ogg differ
diff --git a/assets/audio/kenney/impact/impactPunch_heavy_003.ogg.import b/assets/audio/kenney/impact/impactPunch_heavy_003.ogg.import
new file mode 100644
index 0000000..531202d
--- /dev/null
+++ b/assets/audio/kenney/impact/impactPunch_heavy_003.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dkk07r0fw1oyp"
+path="res://.godot/imported/impactPunch_heavy_003.ogg-235970b5f7ea552a0ff1d88af983ec29.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactPunch_heavy_003.ogg"
+dest_files=["res://.godot/imported/impactPunch_heavy_003.ogg-235970b5f7ea552a0ff1d88af983ec29.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactPunch_heavy_004.ogg b/assets/audio/kenney/impact/impactPunch_heavy_004.ogg
new file mode 100644
index 0000000..e7ceea0
Binary files /dev/null and b/assets/audio/kenney/impact/impactPunch_heavy_004.ogg differ
diff --git a/assets/audio/kenney/impact/impactPunch_heavy_004.ogg.import b/assets/audio/kenney/impact/impactPunch_heavy_004.ogg.import
new file mode 100644
index 0000000..8fd504f
--- /dev/null
+++ b/assets/audio/kenney/impact/impactPunch_heavy_004.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://drqj4xa8etdft"
+path="res://.godot/imported/impactPunch_heavy_004.ogg-3144cfba37bcc8b567b79cd5c7ac24a8.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactPunch_heavy_004.ogg"
+dest_files=["res://.godot/imported/impactPunch_heavy_004.ogg-3144cfba37bcc8b567b79cd5c7ac24a8.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactPunch_medium_000.ogg b/assets/audio/kenney/impact/impactPunch_medium_000.ogg
new file mode 100644
index 0000000..d8e0b89
Binary files /dev/null and b/assets/audio/kenney/impact/impactPunch_medium_000.ogg differ
diff --git a/assets/audio/kenney/impact/impactPunch_medium_000.ogg.import b/assets/audio/kenney/impact/impactPunch_medium_000.ogg.import
new file mode 100644
index 0000000..be602d0
--- /dev/null
+++ b/assets/audio/kenney/impact/impactPunch_medium_000.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://8661qoon8mq7"
+path="res://.godot/imported/impactPunch_medium_000.ogg-7e5b1d5f97cd75585f7d5221c3754556.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactPunch_medium_000.ogg"
+dest_files=["res://.godot/imported/impactPunch_medium_000.ogg-7e5b1d5f97cd75585f7d5221c3754556.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactPunch_medium_001.ogg b/assets/audio/kenney/impact/impactPunch_medium_001.ogg
new file mode 100644
index 0000000..3308046
Binary files /dev/null and b/assets/audio/kenney/impact/impactPunch_medium_001.ogg differ
diff --git a/assets/audio/kenney/impact/impactPunch_medium_001.ogg.import b/assets/audio/kenney/impact/impactPunch_medium_001.ogg.import
new file mode 100644
index 0000000..7db3127
--- /dev/null
+++ b/assets/audio/kenney/impact/impactPunch_medium_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dd1d05b2ybqke"
+path="res://.godot/imported/impactPunch_medium_001.ogg-de300e13467eeeed5ec9d1e71cba8d94.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactPunch_medium_001.ogg"
+dest_files=["res://.godot/imported/impactPunch_medium_001.ogg-de300e13467eeeed5ec9d1e71cba8d94.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactPunch_medium_002.ogg b/assets/audio/kenney/impact/impactPunch_medium_002.ogg
new file mode 100644
index 0000000..9704fd2
Binary files /dev/null and b/assets/audio/kenney/impact/impactPunch_medium_002.ogg differ
diff --git a/assets/audio/kenney/impact/impactPunch_medium_002.ogg.import b/assets/audio/kenney/impact/impactPunch_medium_002.ogg.import
new file mode 100644
index 0000000..8614cf5
--- /dev/null
+++ b/assets/audio/kenney/impact/impactPunch_medium_002.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://bk6ntw4hivjp"
+path="res://.godot/imported/impactPunch_medium_002.ogg-91bf2d3a364feed054d2b9fc21060568.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactPunch_medium_002.ogg"
+dest_files=["res://.godot/imported/impactPunch_medium_002.ogg-91bf2d3a364feed054d2b9fc21060568.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactPunch_medium_003.ogg b/assets/audio/kenney/impact/impactPunch_medium_003.ogg
new file mode 100644
index 0000000..32ac6c2
Binary files /dev/null and b/assets/audio/kenney/impact/impactPunch_medium_003.ogg differ
diff --git a/assets/audio/kenney/impact/impactPunch_medium_003.ogg.import b/assets/audio/kenney/impact/impactPunch_medium_003.ogg.import
new file mode 100644
index 0000000..7dc150e
--- /dev/null
+++ b/assets/audio/kenney/impact/impactPunch_medium_003.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://r0fmvr6j4366"
+path="res://.godot/imported/impactPunch_medium_003.ogg-91c18f1e02bd66252723cfe4349bbb06.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactPunch_medium_003.ogg"
+dest_files=["res://.godot/imported/impactPunch_medium_003.ogg-91c18f1e02bd66252723cfe4349bbb06.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactPunch_medium_004.ogg b/assets/audio/kenney/impact/impactPunch_medium_004.ogg
new file mode 100644
index 0000000..1620aa9
Binary files /dev/null and b/assets/audio/kenney/impact/impactPunch_medium_004.ogg differ
diff --git a/assets/audio/kenney/impact/impactPunch_medium_004.ogg.import b/assets/audio/kenney/impact/impactPunch_medium_004.ogg.import
new file mode 100644
index 0000000..e85f324
--- /dev/null
+++ b/assets/audio/kenney/impact/impactPunch_medium_004.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://cwp1f1rx4j3d0"
+path="res://.godot/imported/impactPunch_medium_004.ogg-d2a1ccaf8d3176e4c6626407a51257be.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactPunch_medium_004.ogg"
+dest_files=["res://.godot/imported/impactPunch_medium_004.ogg-d2a1ccaf8d3176e4c6626407a51257be.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactSoft_heavy_000.ogg b/assets/audio/kenney/impact/impactSoft_heavy_000.ogg
new file mode 100644
index 0000000..1c321ef
Binary files /dev/null and b/assets/audio/kenney/impact/impactSoft_heavy_000.ogg differ
diff --git a/assets/audio/kenney/impact/impactSoft_heavy_000.ogg.import b/assets/audio/kenney/impact/impactSoft_heavy_000.ogg.import
new file mode 100644
index 0000000..139ea77
--- /dev/null
+++ b/assets/audio/kenney/impact/impactSoft_heavy_000.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dfqude7d0ul8j"
+path="res://.godot/imported/impactSoft_heavy_000.ogg-948b0297f54ab6d9e865a20737c7b743.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactSoft_heavy_000.ogg"
+dest_files=["res://.godot/imported/impactSoft_heavy_000.ogg-948b0297f54ab6d9e865a20737c7b743.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactSoft_heavy_001.ogg b/assets/audio/kenney/impact/impactSoft_heavy_001.ogg
new file mode 100644
index 0000000..d7fbb0f
Binary files /dev/null and b/assets/audio/kenney/impact/impactSoft_heavy_001.ogg differ
diff --git a/assets/audio/kenney/impact/impactSoft_heavy_001.ogg.import b/assets/audio/kenney/impact/impactSoft_heavy_001.ogg.import
new file mode 100644
index 0000000..d95b0f2
--- /dev/null
+++ b/assets/audio/kenney/impact/impactSoft_heavy_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://6bp8o2hoqlls"
+path="res://.godot/imported/impactSoft_heavy_001.ogg-6666e44724abff4a1588426ae1f38d5f.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactSoft_heavy_001.ogg"
+dest_files=["res://.godot/imported/impactSoft_heavy_001.ogg-6666e44724abff4a1588426ae1f38d5f.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactSoft_heavy_002.ogg b/assets/audio/kenney/impact/impactSoft_heavy_002.ogg
new file mode 100644
index 0000000..4748c69
Binary files /dev/null and b/assets/audio/kenney/impact/impactSoft_heavy_002.ogg differ
diff --git a/assets/audio/kenney/impact/impactSoft_heavy_002.ogg.import b/assets/audio/kenney/impact/impactSoft_heavy_002.ogg.import
new file mode 100644
index 0000000..90554e1
--- /dev/null
+++ b/assets/audio/kenney/impact/impactSoft_heavy_002.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://ctd8gjrd6uj8y"
+path="res://.godot/imported/impactSoft_heavy_002.ogg-0b722fb6c05c0756b8ab71418f53de88.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactSoft_heavy_002.ogg"
+dest_files=["res://.godot/imported/impactSoft_heavy_002.ogg-0b722fb6c05c0756b8ab71418f53de88.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactSoft_heavy_003.ogg b/assets/audio/kenney/impact/impactSoft_heavy_003.ogg
new file mode 100644
index 0000000..417cacc
Binary files /dev/null and b/assets/audio/kenney/impact/impactSoft_heavy_003.ogg differ
diff --git a/assets/audio/kenney/impact/impactSoft_heavy_003.ogg.import b/assets/audio/kenney/impact/impactSoft_heavy_003.ogg.import
new file mode 100644
index 0000000..61a80b3
--- /dev/null
+++ b/assets/audio/kenney/impact/impactSoft_heavy_003.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://bki2kuva1wrbf"
+path="res://.godot/imported/impactSoft_heavy_003.ogg-ffeb051c96db131d04a9df0b029b69b1.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactSoft_heavy_003.ogg"
+dest_files=["res://.godot/imported/impactSoft_heavy_003.ogg-ffeb051c96db131d04a9df0b029b69b1.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactSoft_heavy_004.ogg b/assets/audio/kenney/impact/impactSoft_heavy_004.ogg
new file mode 100644
index 0000000..c42b1d5
Binary files /dev/null and b/assets/audio/kenney/impact/impactSoft_heavy_004.ogg differ
diff --git a/assets/audio/kenney/impact/impactSoft_heavy_004.ogg.import b/assets/audio/kenney/impact/impactSoft_heavy_004.ogg.import
new file mode 100644
index 0000000..99d151d
--- /dev/null
+++ b/assets/audio/kenney/impact/impactSoft_heavy_004.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://b866y420dhpjr"
+path="res://.godot/imported/impactSoft_heavy_004.ogg-06d4e4ef3646c56174a75ca78bc1760f.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactSoft_heavy_004.ogg"
+dest_files=["res://.godot/imported/impactSoft_heavy_004.ogg-06d4e4ef3646c56174a75ca78bc1760f.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactSoft_medium_000.ogg b/assets/audio/kenney/impact/impactSoft_medium_000.ogg
new file mode 100644
index 0000000..bf1027b
Binary files /dev/null and b/assets/audio/kenney/impact/impactSoft_medium_000.ogg differ
diff --git a/assets/audio/kenney/impact/impactSoft_medium_000.ogg.import b/assets/audio/kenney/impact/impactSoft_medium_000.ogg.import
new file mode 100644
index 0000000..3b35f1a
--- /dev/null
+++ b/assets/audio/kenney/impact/impactSoft_medium_000.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://6k82em8jn7cn"
+path="res://.godot/imported/impactSoft_medium_000.ogg-4070b0e182fb8fadb455c125892c6f97.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactSoft_medium_000.ogg"
+dest_files=["res://.godot/imported/impactSoft_medium_000.ogg-4070b0e182fb8fadb455c125892c6f97.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactSoft_medium_001.ogg b/assets/audio/kenney/impact/impactSoft_medium_001.ogg
new file mode 100644
index 0000000..a8c6434
Binary files /dev/null and b/assets/audio/kenney/impact/impactSoft_medium_001.ogg differ
diff --git a/assets/audio/kenney/impact/impactSoft_medium_001.ogg.import b/assets/audio/kenney/impact/impactSoft_medium_001.ogg.import
new file mode 100644
index 0000000..b4ca8e1
--- /dev/null
+++ b/assets/audio/kenney/impact/impactSoft_medium_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://crfs0oerqcjaw"
+path="res://.godot/imported/impactSoft_medium_001.ogg-41c1ba2cbec5098431110f5e5f5f3360.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactSoft_medium_001.ogg"
+dest_files=["res://.godot/imported/impactSoft_medium_001.ogg-41c1ba2cbec5098431110f5e5f5f3360.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactSoft_medium_002.ogg b/assets/audio/kenney/impact/impactSoft_medium_002.ogg
new file mode 100644
index 0000000..5409c00
Binary files /dev/null and b/assets/audio/kenney/impact/impactSoft_medium_002.ogg differ
diff --git a/assets/audio/kenney/impact/impactSoft_medium_002.ogg.import b/assets/audio/kenney/impact/impactSoft_medium_002.ogg.import
new file mode 100644
index 0000000..4c0765c
--- /dev/null
+++ b/assets/audio/kenney/impact/impactSoft_medium_002.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://na4khpyjph3r"
+path="res://.godot/imported/impactSoft_medium_002.ogg-a743a1f4830dd76fdb93821dd9460937.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactSoft_medium_002.ogg"
+dest_files=["res://.godot/imported/impactSoft_medium_002.ogg-a743a1f4830dd76fdb93821dd9460937.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactSoft_medium_003.ogg b/assets/audio/kenney/impact/impactSoft_medium_003.ogg
new file mode 100644
index 0000000..13b5247
Binary files /dev/null and b/assets/audio/kenney/impact/impactSoft_medium_003.ogg differ
diff --git a/assets/audio/kenney/impact/impactSoft_medium_003.ogg.import b/assets/audio/kenney/impact/impactSoft_medium_003.ogg.import
new file mode 100644
index 0000000..0dec0b6
--- /dev/null
+++ b/assets/audio/kenney/impact/impactSoft_medium_003.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://cgmffxc7ep8w1"
+path="res://.godot/imported/impactSoft_medium_003.ogg-2686066895598a5bf2f52d417717c7c2.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactSoft_medium_003.ogg"
+dest_files=["res://.godot/imported/impactSoft_medium_003.ogg-2686066895598a5bf2f52d417717c7c2.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactSoft_medium_004.ogg b/assets/audio/kenney/impact/impactSoft_medium_004.ogg
new file mode 100644
index 0000000..532f620
Binary files /dev/null and b/assets/audio/kenney/impact/impactSoft_medium_004.ogg differ
diff --git a/assets/audio/kenney/impact/impactSoft_medium_004.ogg.import b/assets/audio/kenney/impact/impactSoft_medium_004.ogg.import
new file mode 100644
index 0000000..14cfaef
--- /dev/null
+++ b/assets/audio/kenney/impact/impactSoft_medium_004.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://th02nc2a3mse"
+path="res://.godot/imported/impactSoft_medium_004.ogg-bb3885a858bc276a31abfe8e1a9f14cf.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactSoft_medium_004.ogg"
+dest_files=["res://.godot/imported/impactSoft_medium_004.ogg-bb3885a858bc276a31abfe8e1a9f14cf.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactWood_heavy_000.ogg b/assets/audio/kenney/impact/impactWood_heavy_000.ogg
new file mode 100644
index 0000000..30fb995
Binary files /dev/null and b/assets/audio/kenney/impact/impactWood_heavy_000.ogg differ
diff --git a/assets/audio/kenney/impact/impactWood_heavy_000.ogg.import b/assets/audio/kenney/impact/impactWood_heavy_000.ogg.import
new file mode 100644
index 0000000..697bea8
--- /dev/null
+++ b/assets/audio/kenney/impact/impactWood_heavy_000.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://cuvbgyxsojbdt"
+path="res://.godot/imported/impactWood_heavy_000.ogg-8993e4a9a1e82372adaa554ad109950f.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactWood_heavy_000.ogg"
+dest_files=["res://.godot/imported/impactWood_heavy_000.ogg-8993e4a9a1e82372adaa554ad109950f.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactWood_heavy_001.ogg b/assets/audio/kenney/impact/impactWood_heavy_001.ogg
new file mode 100644
index 0000000..1ec513e
Binary files /dev/null and b/assets/audio/kenney/impact/impactWood_heavy_001.ogg differ
diff --git a/assets/audio/kenney/impact/impactWood_heavy_001.ogg.import b/assets/audio/kenney/impact/impactWood_heavy_001.ogg.import
new file mode 100644
index 0000000..cdfb7e0
--- /dev/null
+++ b/assets/audio/kenney/impact/impactWood_heavy_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dk3mob3qjilde"
+path="res://.godot/imported/impactWood_heavy_001.ogg-7cd1ba6f7c0c24880b965b22af9e7ccb.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactWood_heavy_001.ogg"
+dest_files=["res://.godot/imported/impactWood_heavy_001.ogg-7cd1ba6f7c0c24880b965b22af9e7ccb.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactWood_heavy_002.ogg b/assets/audio/kenney/impact/impactWood_heavy_002.ogg
new file mode 100644
index 0000000..17f4e31
Binary files /dev/null and b/assets/audio/kenney/impact/impactWood_heavy_002.ogg differ
diff --git a/assets/audio/kenney/impact/impactWood_heavy_002.ogg.import b/assets/audio/kenney/impact/impactWood_heavy_002.ogg.import
new file mode 100644
index 0000000..5cec26a
--- /dev/null
+++ b/assets/audio/kenney/impact/impactWood_heavy_002.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dkt2ejmqvhsmd"
+path="res://.godot/imported/impactWood_heavy_002.ogg-74cc181be698934d71c5f2ebf3520bcb.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactWood_heavy_002.ogg"
+dest_files=["res://.godot/imported/impactWood_heavy_002.ogg-74cc181be698934d71c5f2ebf3520bcb.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactWood_heavy_003.ogg b/assets/audio/kenney/impact/impactWood_heavy_003.ogg
new file mode 100644
index 0000000..fb6e75f
Binary files /dev/null and b/assets/audio/kenney/impact/impactWood_heavy_003.ogg differ
diff --git a/assets/audio/kenney/impact/impactWood_heavy_003.ogg.import b/assets/audio/kenney/impact/impactWood_heavy_003.ogg.import
new file mode 100644
index 0000000..e2fe530
--- /dev/null
+++ b/assets/audio/kenney/impact/impactWood_heavy_003.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://h641508g5sdi"
+path="res://.godot/imported/impactWood_heavy_003.ogg-e9315c22a35599ed02423fdb018fcf35.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactWood_heavy_003.ogg"
+dest_files=["res://.godot/imported/impactWood_heavy_003.ogg-e9315c22a35599ed02423fdb018fcf35.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactWood_heavy_004.ogg b/assets/audio/kenney/impact/impactWood_heavy_004.ogg
new file mode 100644
index 0000000..ebca8ef
Binary files /dev/null and b/assets/audio/kenney/impact/impactWood_heavy_004.ogg differ
diff --git a/assets/audio/kenney/impact/impactWood_heavy_004.ogg.import b/assets/audio/kenney/impact/impactWood_heavy_004.ogg.import
new file mode 100644
index 0000000..6b81015
--- /dev/null
+++ b/assets/audio/kenney/impact/impactWood_heavy_004.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://cphq5bqg3gmh1"
+path="res://.godot/imported/impactWood_heavy_004.ogg-7df96e1c9e6525d2cdf44b7ea638e408.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactWood_heavy_004.ogg"
+dest_files=["res://.godot/imported/impactWood_heavy_004.ogg-7df96e1c9e6525d2cdf44b7ea638e408.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactWood_light_000.ogg b/assets/audio/kenney/impact/impactWood_light_000.ogg
new file mode 100644
index 0000000..4bf6be6
Binary files /dev/null and b/assets/audio/kenney/impact/impactWood_light_000.ogg differ
diff --git a/assets/audio/kenney/impact/impactWood_light_000.ogg.import b/assets/audio/kenney/impact/impactWood_light_000.ogg.import
new file mode 100644
index 0000000..a02d6f6
--- /dev/null
+++ b/assets/audio/kenney/impact/impactWood_light_000.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://sfqx82npo1xj"
+path="res://.godot/imported/impactWood_light_000.ogg-2cc789299a720df5a68ba82ffa5753f6.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactWood_light_000.ogg"
+dest_files=["res://.godot/imported/impactWood_light_000.ogg-2cc789299a720df5a68ba82ffa5753f6.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactWood_light_001.ogg b/assets/audio/kenney/impact/impactWood_light_001.ogg
new file mode 100644
index 0000000..2184d05
Binary files /dev/null and b/assets/audio/kenney/impact/impactWood_light_001.ogg differ
diff --git a/assets/audio/kenney/impact/impactWood_light_001.ogg.import b/assets/audio/kenney/impact/impactWood_light_001.ogg.import
new file mode 100644
index 0000000..643887d
--- /dev/null
+++ b/assets/audio/kenney/impact/impactWood_light_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dpjnv7vx46pud"
+path="res://.godot/imported/impactWood_light_001.ogg-5cdfc79f98769575bba63fb05c14d110.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactWood_light_001.ogg"
+dest_files=["res://.godot/imported/impactWood_light_001.ogg-5cdfc79f98769575bba63fb05c14d110.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactWood_light_002.ogg b/assets/audio/kenney/impact/impactWood_light_002.ogg
new file mode 100644
index 0000000..c27596a
Binary files /dev/null and b/assets/audio/kenney/impact/impactWood_light_002.ogg differ
diff --git a/assets/audio/kenney/impact/impactWood_light_002.ogg.import b/assets/audio/kenney/impact/impactWood_light_002.ogg.import
new file mode 100644
index 0000000..01d229f
--- /dev/null
+++ b/assets/audio/kenney/impact/impactWood_light_002.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://fooakxppyfo2"
+path="res://.godot/imported/impactWood_light_002.ogg-f0fa17eb64890e73529b478709e28446.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactWood_light_002.ogg"
+dest_files=["res://.godot/imported/impactWood_light_002.ogg-f0fa17eb64890e73529b478709e28446.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactWood_light_003.ogg b/assets/audio/kenney/impact/impactWood_light_003.ogg
new file mode 100644
index 0000000..88359d1
Binary files /dev/null and b/assets/audio/kenney/impact/impactWood_light_003.ogg differ
diff --git a/assets/audio/kenney/impact/impactWood_light_003.ogg.import b/assets/audio/kenney/impact/impactWood_light_003.ogg.import
new file mode 100644
index 0000000..9eb4445
--- /dev/null
+++ b/assets/audio/kenney/impact/impactWood_light_003.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://wsxlcps41i2x"
+path="res://.godot/imported/impactWood_light_003.ogg-c34b26d40728aba31fa1ef103eeb8a87.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactWood_light_003.ogg"
+dest_files=["res://.godot/imported/impactWood_light_003.ogg-c34b26d40728aba31fa1ef103eeb8a87.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactWood_light_004.ogg b/assets/audio/kenney/impact/impactWood_light_004.ogg
new file mode 100644
index 0000000..b7a35eb
Binary files /dev/null and b/assets/audio/kenney/impact/impactWood_light_004.ogg differ
diff --git a/assets/audio/kenney/impact/impactWood_light_004.ogg.import b/assets/audio/kenney/impact/impactWood_light_004.ogg.import
new file mode 100644
index 0000000..d44dfb7
--- /dev/null
+++ b/assets/audio/kenney/impact/impactWood_light_004.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://rfjvtq116w44"
+path="res://.godot/imported/impactWood_light_004.ogg-b10a99fac97ec917f8581dcf1aed38ca.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactWood_light_004.ogg"
+dest_files=["res://.godot/imported/impactWood_light_004.ogg-b10a99fac97ec917f8581dcf1aed38ca.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactWood_medium_000.ogg b/assets/audio/kenney/impact/impactWood_medium_000.ogg
new file mode 100644
index 0000000..97735ff
Binary files /dev/null and b/assets/audio/kenney/impact/impactWood_medium_000.ogg differ
diff --git a/assets/audio/kenney/impact/impactWood_medium_000.ogg.import b/assets/audio/kenney/impact/impactWood_medium_000.ogg.import
new file mode 100644
index 0000000..1cd3e00
--- /dev/null
+++ b/assets/audio/kenney/impact/impactWood_medium_000.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://5ourrh3ro7i"
+path="res://.godot/imported/impactWood_medium_000.ogg-21bba93ea80b822608400e2d6457c4bd.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactWood_medium_000.ogg"
+dest_files=["res://.godot/imported/impactWood_medium_000.ogg-21bba93ea80b822608400e2d6457c4bd.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactWood_medium_001.ogg b/assets/audio/kenney/impact/impactWood_medium_001.ogg
new file mode 100644
index 0000000..a314921
Binary files /dev/null and b/assets/audio/kenney/impact/impactWood_medium_001.ogg differ
diff --git a/assets/audio/kenney/impact/impactWood_medium_001.ogg.import b/assets/audio/kenney/impact/impactWood_medium_001.ogg.import
new file mode 100644
index 0000000..bac86e9
--- /dev/null
+++ b/assets/audio/kenney/impact/impactWood_medium_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://cvk0qhxna65t2"
+path="res://.godot/imported/impactWood_medium_001.ogg-e0b0f503f706320ba8b394a2fb7380a8.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactWood_medium_001.ogg"
+dest_files=["res://.godot/imported/impactWood_medium_001.ogg-e0b0f503f706320ba8b394a2fb7380a8.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactWood_medium_002.ogg b/assets/audio/kenney/impact/impactWood_medium_002.ogg
new file mode 100644
index 0000000..d5cf1d0
Binary files /dev/null and b/assets/audio/kenney/impact/impactWood_medium_002.ogg differ
diff --git a/assets/audio/kenney/impact/impactWood_medium_002.ogg.import b/assets/audio/kenney/impact/impactWood_medium_002.ogg.import
new file mode 100644
index 0000000..674d847
--- /dev/null
+++ b/assets/audio/kenney/impact/impactWood_medium_002.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://c4uoyjr6gxttk"
+path="res://.godot/imported/impactWood_medium_002.ogg-135aefc80330374dcb84e203a2662b03.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactWood_medium_002.ogg"
+dest_files=["res://.godot/imported/impactWood_medium_002.ogg-135aefc80330374dcb84e203a2662b03.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactWood_medium_003.ogg b/assets/audio/kenney/impact/impactWood_medium_003.ogg
new file mode 100644
index 0000000..e559cb3
Binary files /dev/null and b/assets/audio/kenney/impact/impactWood_medium_003.ogg differ
diff --git a/assets/audio/kenney/impact/impactWood_medium_003.ogg.import b/assets/audio/kenney/impact/impactWood_medium_003.ogg.import
new file mode 100644
index 0000000..67a66eb
--- /dev/null
+++ b/assets/audio/kenney/impact/impactWood_medium_003.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dkqy8cdbgmei8"
+path="res://.godot/imported/impactWood_medium_003.ogg-6c2bb77432dc957c1c3b0c9c86252fb4.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactWood_medium_003.ogg"
+dest_files=["res://.godot/imported/impactWood_medium_003.ogg-6c2bb77432dc957c1c3b0c9c86252fb4.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/impact/impactWood_medium_004.ogg b/assets/audio/kenney/impact/impactWood_medium_004.ogg
new file mode 100644
index 0000000..219828a
Binary files /dev/null and b/assets/audio/kenney/impact/impactWood_medium_004.ogg differ
diff --git a/assets/audio/kenney/impact/impactWood_medium_004.ogg.import b/assets/audio/kenney/impact/impactWood_medium_004.ogg.import
new file mode 100644
index 0000000..c59b78e
--- /dev/null
+++ b/assets/audio/kenney/impact/impactWood_medium_004.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://87ol0sxolm6d"
+path="res://.godot/imported/impactWood_medium_004.ogg-d8473b2ced827a028d19ad9ff8debebd.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/impact/impactWood_medium_004.ogg"
+dest_files=["res://.godot/imported/impactWood_medium_004.ogg-d8473b2ced827a028d19ad9ff8debebd.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/interface/License.txt b/assets/audio/kenney/interface/License.txt
new file mode 100644
index 0000000..1fc5acf
--- /dev/null
+++ b/assets/audio/kenney/interface/License.txt
@@ -0,0 +1,22 @@
+
+
+ Interface Sounds (1.0)
+
+ Created/distributed by Kenney (www.kenney.nl)
+ Creation date: 11-02-2020
+
+ ------------------------------
+
+ License: (Creative Commons Zero, CC0)
+ http://creativecommons.org/publicdomain/zero/1.0/
+
+ This content is free to use in personal, educational and commercial projects.
+ Support us by crediting Kenney or www.kenney.nl (this is not mandatory)
+
+ ------------------------------
+
+ Donate: http://support.kenney.nl
+ Patreon: http://patreon.com/kenney/
+
+ Follow on Twitter for updates:
+ http://twitter.com/KenneyNL
\ No newline at end of file
diff --git a/assets/audio/kenney/interface/back_001.ogg b/assets/audio/kenney/interface/back_001.ogg
new file mode 100644
index 0000000..06c5e72
Binary files /dev/null and b/assets/audio/kenney/interface/back_001.ogg differ
diff --git a/assets/audio/kenney/interface/back_001.ogg.import b/assets/audio/kenney/interface/back_001.ogg.import
new file mode 100644
index 0000000..86b0c20
--- /dev/null
+++ b/assets/audio/kenney/interface/back_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://diurqb7h32m8g"
+path="res://.godot/imported/back_001.ogg-ca0c4aa90630edb8e9f1621ef3991521.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/interface/back_001.ogg"
+dest_files=["res://.godot/imported/back_001.ogg-ca0c4aa90630edb8e9f1621ef3991521.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/interface/click_002.ogg b/assets/audio/kenney/interface/click_002.ogg
new file mode 100644
index 0000000..4564b88
Binary files /dev/null and b/assets/audio/kenney/interface/click_002.ogg differ
diff --git a/assets/audio/kenney/interface/click_002.ogg.import b/assets/audio/kenney/interface/click_002.ogg.import
new file mode 100644
index 0000000..2265fd2
--- /dev/null
+++ b/assets/audio/kenney/interface/click_002.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://p34lwq6kopmm"
+path="res://.godot/imported/click_002.ogg-a924eb5ffa4be4f19de1663dd145ac5f.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/interface/click_002.ogg"
+dest_files=["res://.godot/imported/click_002.ogg-a924eb5ffa4be4f19de1663dd145ac5f.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/interface/close_001.ogg b/assets/audio/kenney/interface/close_001.ogg
new file mode 100644
index 0000000..b2545e7
Binary files /dev/null and b/assets/audio/kenney/interface/close_001.ogg differ
diff --git a/assets/audio/kenney/interface/close_001.ogg.import b/assets/audio/kenney/interface/close_001.ogg.import
new file mode 100644
index 0000000..786a878
--- /dev/null
+++ b/assets/audio/kenney/interface/close_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://8ykjch4tl1ci"
+path="res://.godot/imported/close_001.ogg-665f75d79cc07a189a8d0bd9ee080dfb.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/interface/close_001.ogg"
+dest_files=["res://.godot/imported/close_001.ogg-665f75d79cc07a189a8d0bd9ee080dfb.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/interface/confirmation_001.ogg b/assets/audio/kenney/interface/confirmation_001.ogg
new file mode 100644
index 0000000..78f119c
Binary files /dev/null and b/assets/audio/kenney/interface/confirmation_001.ogg differ
diff --git a/assets/audio/kenney/interface/confirmation_001.ogg.import b/assets/audio/kenney/interface/confirmation_001.ogg.import
new file mode 100644
index 0000000..429771c
--- /dev/null
+++ b/assets/audio/kenney/interface/confirmation_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://vodxek6yj726"
+path="res://.godot/imported/confirmation_001.ogg-14d71e6adfdc83b0f4744935e0b868c8.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/interface/confirmation_001.ogg"
+dest_files=["res://.godot/imported/confirmation_001.ogg-14d71e6adfdc83b0f4744935e0b868c8.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/interface/confirmation_002.ogg b/assets/audio/kenney/interface/confirmation_002.ogg
new file mode 100644
index 0000000..4e01396
Binary files /dev/null and b/assets/audio/kenney/interface/confirmation_002.ogg differ
diff --git a/assets/audio/kenney/interface/confirmation_002.ogg.import b/assets/audio/kenney/interface/confirmation_002.ogg.import
new file mode 100644
index 0000000..ddf7390
--- /dev/null
+++ b/assets/audio/kenney/interface/confirmation_002.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://beya7eg7pyt83"
+path="res://.godot/imported/confirmation_002.ogg-6272ae3cce6858edca1e241cd0c5ac93.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/interface/confirmation_002.ogg"
+dest_files=["res://.godot/imported/confirmation_002.ogg-6272ae3cce6858edca1e241cd0c5ac93.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/interface/drop_001.ogg b/assets/audio/kenney/interface/drop_001.ogg
new file mode 100644
index 0000000..091750a
Binary files /dev/null and b/assets/audio/kenney/interface/drop_001.ogg differ
diff --git a/assets/audio/kenney/interface/drop_001.ogg.import b/assets/audio/kenney/interface/drop_001.ogg.import
new file mode 100644
index 0000000..2101493
--- /dev/null
+++ b/assets/audio/kenney/interface/drop_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dk35oxg7xu202"
+path="res://.godot/imported/drop_001.ogg-c0ade90e9a242797871d8ea9e748947f.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/interface/drop_001.ogg"
+dest_files=["res://.godot/imported/drop_001.ogg-c0ade90e9a242797871d8ea9e748947f.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/interface/drop_002.ogg b/assets/audio/kenney/interface/drop_002.ogg
new file mode 100644
index 0000000..c146538
Binary files /dev/null and b/assets/audio/kenney/interface/drop_002.ogg differ
diff --git a/assets/audio/kenney/interface/drop_002.ogg.import b/assets/audio/kenney/interface/drop_002.ogg.import
new file mode 100644
index 0000000..0b9fb86
--- /dev/null
+++ b/assets/audio/kenney/interface/drop_002.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://bji078dt5jetm"
+path="res://.godot/imported/drop_002.ogg-1b495568e5649f72d32f1fab43a2d42e.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/interface/drop_002.ogg"
+dest_files=["res://.godot/imported/drop_002.ogg-1b495568e5649f72d32f1fab43a2d42e.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/interface/drop_003.ogg b/assets/audio/kenney/interface/drop_003.ogg
new file mode 100644
index 0000000..3213b02
Binary files /dev/null and b/assets/audio/kenney/interface/drop_003.ogg differ
diff --git a/assets/audio/kenney/interface/drop_003.ogg.import b/assets/audio/kenney/interface/drop_003.ogg.import
new file mode 100644
index 0000000..8ca21df
--- /dev/null
+++ b/assets/audio/kenney/interface/drop_003.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://cye0xlj6midq6"
+path="res://.godot/imported/drop_003.ogg-ab73102e81ce683214236960d9c0ba0a.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/interface/drop_003.ogg"
+dest_files=["res://.godot/imported/drop_003.ogg-ab73102e81ce683214236960d9c0ba0a.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/interface/drop_004.ogg b/assets/audio/kenney/interface/drop_004.ogg
new file mode 100644
index 0000000..d9cd368
Binary files /dev/null and b/assets/audio/kenney/interface/drop_004.ogg differ
diff --git a/assets/audio/kenney/interface/drop_004.ogg.import b/assets/audio/kenney/interface/drop_004.ogg.import
new file mode 100644
index 0000000..2b03e71
--- /dev/null
+++ b/assets/audio/kenney/interface/drop_004.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dqt4r5hwfwnsp"
+path="res://.godot/imported/drop_004.ogg-9d51e9c2de2f4819e7a6f291ff6c4c1e.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/interface/drop_004.ogg"
+dest_files=["res://.godot/imported/drop_004.ogg-9d51e9c2de2f4819e7a6f291ff6c4c1e.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/interface/error_004.ogg b/assets/audio/kenney/interface/error_004.ogg
new file mode 100644
index 0000000..cbeb4fb
Binary files /dev/null and b/assets/audio/kenney/interface/error_004.ogg differ
diff --git a/assets/audio/kenney/interface/error_004.ogg.import b/assets/audio/kenney/interface/error_004.ogg.import
new file mode 100644
index 0000000..473b907
--- /dev/null
+++ b/assets/audio/kenney/interface/error_004.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://cixtkgvy6ivvm"
+path="res://.godot/imported/error_004.ogg-e0c4107bc9fd64bc88ae45e57eb6c2bc.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/interface/error_004.ogg"
+dest_files=["res://.godot/imported/error_004.ogg-e0c4107bc9fd64bc88ae45e57eb6c2bc.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/interface/maximize_003.ogg b/assets/audio/kenney/interface/maximize_003.ogg
new file mode 100644
index 0000000..3b65187
Binary files /dev/null and b/assets/audio/kenney/interface/maximize_003.ogg differ
diff --git a/assets/audio/kenney/interface/maximize_003.ogg.import b/assets/audio/kenney/interface/maximize_003.ogg.import
new file mode 100644
index 0000000..154cf84
--- /dev/null
+++ b/assets/audio/kenney/interface/maximize_003.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dv5wlv0qbhk7o"
+path="res://.godot/imported/maximize_003.ogg-a744857cb91cd67042196532f45a6912.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/interface/maximize_003.ogg"
+dest_files=["res://.godot/imported/maximize_003.ogg-a744857cb91cd67042196532f45a6912.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/interface/open_001.ogg b/assets/audio/kenney/interface/open_001.ogg
new file mode 100644
index 0000000..699b498
Binary files /dev/null and b/assets/audio/kenney/interface/open_001.ogg differ
diff --git a/assets/audio/kenney/interface/open_001.ogg.import b/assets/audio/kenney/interface/open_001.ogg.import
new file mode 100644
index 0000000..419e4e6
--- /dev/null
+++ b/assets/audio/kenney/interface/open_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dnoj8rmpjxy6p"
+path="res://.godot/imported/open_001.ogg-df752e5194aa12a4fd33b121506e11f6.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/interface/open_001.ogg"
+dest_files=["res://.godot/imported/open_001.ogg-df752e5194aa12a4fd33b121506e11f6.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/interface/pluck_001.ogg b/assets/audio/kenney/interface/pluck_001.ogg
new file mode 100644
index 0000000..106118c
Binary files /dev/null and b/assets/audio/kenney/interface/pluck_001.ogg differ
diff --git a/assets/audio/kenney/interface/pluck_001.ogg.import b/assets/audio/kenney/interface/pluck_001.ogg.import
new file mode 100644
index 0000000..05c145c
--- /dev/null
+++ b/assets/audio/kenney/interface/pluck_001.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://cb0ttp7g7w56j"
+path="res://.godot/imported/pluck_001.ogg-de71210f09840cf82c31a37cd3ee7ad6.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/interface/pluck_001.ogg"
+dest_files=["res://.godot/imported/pluck_001.ogg-de71210f09840cf82c31a37cd3ee7ad6.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/interface/pluck_002.ogg b/assets/audio/kenney/interface/pluck_002.ogg
new file mode 100644
index 0000000..40e135d
Binary files /dev/null and b/assets/audio/kenney/interface/pluck_002.ogg differ
diff --git a/assets/audio/kenney/interface/pluck_002.ogg.import b/assets/audio/kenney/interface/pluck_002.ogg.import
new file mode 100644
index 0000000..8f62b40
--- /dev/null
+++ b/assets/audio/kenney/interface/pluck_002.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://duf3ktuoslfbx"
+path="res://.godot/imported/pluck_002.ogg-4b7cf98a327950ad654bc105a5304fcf.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/interface/pluck_002.ogg"
+dest_files=["res://.godot/imported/pluck_002.ogg-4b7cf98a327950ad654bc105a5304fcf.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/jingles/License.txt b/assets/audio/kenney/jingles/License.txt
new file mode 100644
index 0000000..4c299c2
--- /dev/null
+++ b/assets/audio/kenney/jingles/License.txt
@@ -0,0 +1,21 @@
+
+
+ Music Jingles
+
+ by Kenney Vleugels (Kenney.nl)
+
+ ------------------------------
+
+ License (Creative Commons Zero, CC0)
+ http://creativecommons.org/publicdomain/zero/1.0/
+
+ You may use these assets in personal and commercial projects.
+ Credit (Kenney or www.kenney.nl) would be nice but is not mandatory.
+
+ ------------------------------
+
+ Donate: http://support.kenney.nl
+ Request: http://request.kenney.nl
+
+ Follow on Twitter for updates:
+ @KenneyNL
\ No newline at end of file
diff --git a/assets/audio/kenney/jingles/jingles_PIZZI01.ogg b/assets/audio/kenney/jingles/jingles_PIZZI01.ogg
new file mode 100644
index 0000000..d182664
Binary files /dev/null and b/assets/audio/kenney/jingles/jingles_PIZZI01.ogg differ
diff --git a/assets/audio/kenney/jingles/jingles_PIZZI01.ogg.import b/assets/audio/kenney/jingles/jingles_PIZZI01.ogg.import
new file mode 100644
index 0000000..32805ec
--- /dev/null
+++ b/assets/audio/kenney/jingles/jingles_PIZZI01.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://bi375im7onob3"
+path="res://.godot/imported/jingles_PIZZI01.ogg-97e4a156dcd299bc5b3e8d6223816f07.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/jingles/jingles_PIZZI01.ogg"
+dest_files=["res://.godot/imported/jingles_PIZZI01.ogg-97e4a156dcd299bc5b3e8d6223816f07.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/jingles/jingles_PIZZI02.ogg b/assets/audio/kenney/jingles/jingles_PIZZI02.ogg
new file mode 100644
index 0000000..9d9d7ba
Binary files /dev/null and b/assets/audio/kenney/jingles/jingles_PIZZI02.ogg differ
diff --git a/assets/audio/kenney/jingles/jingles_PIZZI02.ogg.import b/assets/audio/kenney/jingles/jingles_PIZZI02.ogg.import
new file mode 100644
index 0000000..06367b2
--- /dev/null
+++ b/assets/audio/kenney/jingles/jingles_PIZZI02.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://deagw0or440l8"
+path="res://.godot/imported/jingles_PIZZI02.ogg-6a074bc4157586e9f190028228bf5879.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/jingles/jingles_PIZZI02.ogg"
+dest_files=["res://.godot/imported/jingles_PIZZI02.ogg-6a074bc4157586e9f190028228bf5879.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/jingles/jingles_PIZZI07.ogg b/assets/audio/kenney/jingles/jingles_PIZZI07.ogg
new file mode 100644
index 0000000..e3f2c49
Binary files /dev/null and b/assets/audio/kenney/jingles/jingles_PIZZI07.ogg differ
diff --git a/assets/audio/kenney/jingles/jingles_PIZZI07.ogg.import b/assets/audio/kenney/jingles/jingles_PIZZI07.ogg.import
new file mode 100644
index 0000000..ef480e2
--- /dev/null
+++ b/assets/audio/kenney/jingles/jingles_PIZZI07.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://6j3lu5360syo"
+path="res://.godot/imported/jingles_PIZZI07.ogg-5a6942cfaf46a03fdffab4d0b9a9b8ab.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/jingles/jingles_PIZZI07.ogg"
+dest_files=["res://.godot/imported/jingles_PIZZI07.ogg-5a6942cfaf46a03fdffab4d0b9a9b8ab.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/jingles/jingles_PIZZI10.ogg b/assets/audio/kenney/jingles/jingles_PIZZI10.ogg
new file mode 100644
index 0000000..85c1713
Binary files /dev/null and b/assets/audio/kenney/jingles/jingles_PIZZI10.ogg differ
diff --git a/assets/audio/kenney/jingles/jingles_PIZZI10.ogg.import b/assets/audio/kenney/jingles/jingles_PIZZI10.ogg.import
new file mode 100644
index 0000000..7ee6309
--- /dev/null
+++ b/assets/audio/kenney/jingles/jingles_PIZZI10.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://duv4nq2mfxbd7"
+path="res://.godot/imported/jingles_PIZZI10.ogg-2f0b2dccd45b5b0d58300f0647a611a2.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/jingles/jingles_PIZZI10.ogg"
+dest_files=["res://.godot/imported/jingles_PIZZI10.ogg-2f0b2dccd45b5b0d58300f0647a611a2.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/jingles/jingles_PIZZI12.ogg b/assets/audio/kenney/jingles/jingles_PIZZI12.ogg
new file mode 100644
index 0000000..81613d2
Binary files /dev/null and b/assets/audio/kenney/jingles/jingles_PIZZI12.ogg differ
diff --git a/assets/audio/kenney/jingles/jingles_PIZZI12.ogg.import b/assets/audio/kenney/jingles/jingles_PIZZI12.ogg.import
new file mode 100644
index 0000000..21b5712
--- /dev/null
+++ b/assets/audio/kenney/jingles/jingles_PIZZI12.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://c5dck7fceo7hy"
+path="res://.godot/imported/jingles_PIZZI12.ogg-7f58c71ad8b1fa17c7547a4307a81028.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/jingles/jingles_PIZZI12.ogg"
+dest_files=["res://.godot/imported/jingles_PIZZI12.ogg-7f58c71ad8b1fa17c7547a4307a81028.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/jingles/jingles_PIZZI14.ogg b/assets/audio/kenney/jingles/jingles_PIZZI14.ogg
new file mode 100644
index 0000000..0a2e330
Binary files /dev/null and b/assets/audio/kenney/jingles/jingles_PIZZI14.ogg differ
diff --git a/assets/audio/kenney/jingles/jingles_PIZZI14.ogg.import b/assets/audio/kenney/jingles/jingles_PIZZI14.ogg.import
new file mode 100644
index 0000000..c07bf9c
--- /dev/null
+++ b/assets/audio/kenney/jingles/jingles_PIZZI14.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://b35n3uqldean6"
+path="res://.godot/imported/jingles_PIZZI14.ogg-ec4ef0a4a75b879d186312b819cbe000.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/jingles/jingles_PIZZI14.ogg"
+dest_files=["res://.godot/imported/jingles_PIZZI14.ogg-ec4ef0a4a75b879d186312b819cbe000.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/jingles/jingles_PIZZI15.ogg b/assets/audio/kenney/jingles/jingles_PIZZI15.ogg
new file mode 100644
index 0000000..6d721f0
Binary files /dev/null and b/assets/audio/kenney/jingles/jingles_PIZZI15.ogg differ
diff --git a/assets/audio/kenney/jingles/jingles_PIZZI15.ogg.import b/assets/audio/kenney/jingles/jingles_PIZZI15.ogg.import
new file mode 100644
index 0000000..8411fa6
--- /dev/null
+++ b/assets/audio/kenney/jingles/jingles_PIZZI15.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://ciheoys2uqpgd"
+path="res://.godot/imported/jingles_PIZZI15.ogg-9b91d597f4f4d88e2fefd63cf159ba2e.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/jingles/jingles_PIZZI15.ogg"
+dest_files=["res://.godot/imported/jingles_PIZZI15.ogg-9b91d597f4f4d88e2fefd63cf159ba2e.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/jingles/jingles_PIZZI16.ogg b/assets/audio/kenney/jingles/jingles_PIZZI16.ogg
new file mode 100644
index 0000000..aceeb2b
Binary files /dev/null and b/assets/audio/kenney/jingles/jingles_PIZZI16.ogg differ
diff --git a/assets/audio/kenney/jingles/jingles_PIZZI16.ogg.import b/assets/audio/kenney/jingles/jingles_PIZZI16.ogg.import
new file mode 100644
index 0000000..faf4c13
--- /dev/null
+++ b/assets/audio/kenney/jingles/jingles_PIZZI16.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://c137v3luwbd82"
+path="res://.godot/imported/jingles_PIZZI16.ogg-051e950cbb95028398d3f10358d7d842.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/jingles/jingles_PIZZI16.ogg"
+dest_files=["res://.godot/imported/jingles_PIZZI16.ogg-051e950cbb95028398d3f10358d7d842.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/rpg/License.txt b/assets/audio/kenney/rpg/License.txt
new file mode 100644
index 0000000..2f61cec
--- /dev/null
+++ b/assets/audio/kenney/rpg/License.txt
@@ -0,0 +1,21 @@
+
+
+ RPG Audio
+
+ by Kenney Vleugels (Kenney.nl)
+
+ ------------------------------
+
+ License (Creative Commons Zero, CC0)
+ http://creativecommons.org/publicdomain/zero/1.0/
+
+ You may use these assets in personal and commercial projects.
+ Credit (Kenney or www.kenney.nl) would be nice but is not mandatory.
+
+ ------------------------------
+
+ Donate: http://support.kenney.nl
+ Request: http://request.kenney.nl
+
+ Follow on Twitter for updates:
+ @KenneyNL
\ No newline at end of file
diff --git a/assets/audio/kenney/rpg/bookPlace1.ogg b/assets/audio/kenney/rpg/bookPlace1.ogg
new file mode 100644
index 0000000..49f10a3
Binary files /dev/null and b/assets/audio/kenney/rpg/bookPlace1.ogg differ
diff --git a/assets/audio/kenney/rpg/bookPlace1.ogg.import b/assets/audio/kenney/rpg/bookPlace1.ogg.import
new file mode 100644
index 0000000..db6a23c
--- /dev/null
+++ b/assets/audio/kenney/rpg/bookPlace1.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://bly0a6xnwop6y"
+path="res://.godot/imported/bookPlace1.ogg-d1cace49d25e0cac2a115954a71fd264.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/rpg/bookPlace1.ogg"
+dest_files=["res://.godot/imported/bookPlace1.ogg-d1cace49d25e0cac2a115954a71fd264.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/rpg/bookPlace2.ogg b/assets/audio/kenney/rpg/bookPlace2.ogg
new file mode 100644
index 0000000..6636f8a
Binary files /dev/null and b/assets/audio/kenney/rpg/bookPlace2.ogg differ
diff --git a/assets/audio/kenney/rpg/bookPlace2.ogg.import b/assets/audio/kenney/rpg/bookPlace2.ogg.import
new file mode 100644
index 0000000..0fc3d09
--- /dev/null
+++ b/assets/audio/kenney/rpg/bookPlace2.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://ce5f303kx7c41"
+path="res://.godot/imported/bookPlace2.ogg-c12a71f90bcf333456d4b1189f50d540.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/rpg/bookPlace2.ogg"
+dest_files=["res://.godot/imported/bookPlace2.ogg-c12a71f90bcf333456d4b1189f50d540.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/rpg/bookPlace3.ogg b/assets/audio/kenney/rpg/bookPlace3.ogg
new file mode 100644
index 0000000..6d569d5
Binary files /dev/null and b/assets/audio/kenney/rpg/bookPlace3.ogg differ
diff --git a/assets/audio/kenney/rpg/bookPlace3.ogg.import b/assets/audio/kenney/rpg/bookPlace3.ogg.import
new file mode 100644
index 0000000..d5f99a5
--- /dev/null
+++ b/assets/audio/kenney/rpg/bookPlace3.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://cwyloi1ghdbfh"
+path="res://.godot/imported/bookPlace3.ogg-a8e975cd4034d74788f6015d57ef3dd8.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/rpg/bookPlace3.ogg"
+dest_files=["res://.godot/imported/bookPlace3.ogg-a8e975cd4034d74788f6015d57ef3dd8.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/rpg/chop.ogg b/assets/audio/kenney/rpg/chop.ogg
new file mode 100644
index 0000000..a9d991f
Binary files /dev/null and b/assets/audio/kenney/rpg/chop.ogg differ
diff --git a/assets/audio/kenney/rpg/chop.ogg.import b/assets/audio/kenney/rpg/chop.ogg.import
new file mode 100644
index 0000000..6c4b025
--- /dev/null
+++ b/assets/audio/kenney/rpg/chop.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://b6hgsx8oeuhsn"
+path="res://.godot/imported/chop.ogg-c2e4d20b5a09f76ed9e62dd7af195279.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/rpg/chop.ogg"
+dest_files=["res://.godot/imported/chop.ogg-c2e4d20b5a09f76ed9e62dd7af195279.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/rpg/cloth1.ogg b/assets/audio/kenney/rpg/cloth1.ogg
new file mode 100644
index 0000000..b76853a
Binary files /dev/null and b/assets/audio/kenney/rpg/cloth1.ogg differ
diff --git a/assets/audio/kenney/rpg/cloth1.ogg.import b/assets/audio/kenney/rpg/cloth1.ogg.import
new file mode 100644
index 0000000..d0ab0e3
--- /dev/null
+++ b/assets/audio/kenney/rpg/cloth1.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://bj2v7eciors4s"
+path="res://.godot/imported/cloth1.ogg-492ee637159799a0eb792c018bba5c45.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/rpg/cloth1.ogg"
+dest_files=["res://.godot/imported/cloth1.ogg-492ee637159799a0eb792c018bba5c45.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/rpg/cloth2.ogg b/assets/audio/kenney/rpg/cloth2.ogg
new file mode 100644
index 0000000..45e7839
Binary files /dev/null and b/assets/audio/kenney/rpg/cloth2.ogg differ
diff --git a/assets/audio/kenney/rpg/cloth2.ogg.import b/assets/audio/kenney/rpg/cloth2.ogg.import
new file mode 100644
index 0000000..bfecd8e
--- /dev/null
+++ b/assets/audio/kenney/rpg/cloth2.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://ce61lwve1l5vw"
+path="res://.godot/imported/cloth2.ogg-ae8459f49840e7c8db04826690de14ce.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/rpg/cloth2.ogg"
+dest_files=["res://.godot/imported/cloth2.ogg-ae8459f49840e7c8db04826690de14ce.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/rpg/cloth3.ogg b/assets/audio/kenney/rpg/cloth3.ogg
new file mode 100644
index 0000000..f995ff2
Binary files /dev/null and b/assets/audio/kenney/rpg/cloth3.ogg differ
diff --git a/assets/audio/kenney/rpg/cloth3.ogg.import b/assets/audio/kenney/rpg/cloth3.ogg.import
new file mode 100644
index 0000000..961ba11
--- /dev/null
+++ b/assets/audio/kenney/rpg/cloth3.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://7eqwsdecvgs1"
+path="res://.godot/imported/cloth3.ogg-f00522ed4055ac99aaa419bd983658f7.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/rpg/cloth3.ogg"
+dest_files=["res://.godot/imported/cloth3.ogg-f00522ed4055ac99aaa419bd983658f7.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/rpg/cloth4.ogg b/assets/audio/kenney/rpg/cloth4.ogg
new file mode 100644
index 0000000..a7ad4aa
Binary files /dev/null and b/assets/audio/kenney/rpg/cloth4.ogg differ
diff --git a/assets/audio/kenney/rpg/cloth4.ogg.import b/assets/audio/kenney/rpg/cloth4.ogg.import
new file mode 100644
index 0000000..85ece46
--- /dev/null
+++ b/assets/audio/kenney/rpg/cloth4.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://fqqj7d08a6ef"
+path="res://.godot/imported/cloth4.ogg-acfdcf68209359f0eeb3cbd18634612c.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/rpg/cloth4.ogg"
+dest_files=["res://.godot/imported/cloth4.ogg-acfdcf68209359f0eeb3cbd18634612c.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/rpg/clothBelt.ogg b/assets/audio/kenney/rpg/clothBelt.ogg
new file mode 100644
index 0000000..ea7d877
Binary files /dev/null and b/assets/audio/kenney/rpg/clothBelt.ogg differ
diff --git a/assets/audio/kenney/rpg/clothBelt.ogg.import b/assets/audio/kenney/rpg/clothBelt.ogg.import
new file mode 100644
index 0000000..fd0d51e
--- /dev/null
+++ b/assets/audio/kenney/rpg/clothBelt.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://ddv7mmx8rddpp"
+path="res://.godot/imported/clothBelt.ogg-72857f94b3ee95559004e1dfec5b1497.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/rpg/clothBelt.ogg"
+dest_files=["res://.godot/imported/clothBelt.ogg-72857f94b3ee95559004e1dfec5b1497.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/rpg/creak1.ogg b/assets/audio/kenney/rpg/creak1.ogg
new file mode 100644
index 0000000..4f6de6f
Binary files /dev/null and b/assets/audio/kenney/rpg/creak1.ogg differ
diff --git a/assets/audio/kenney/rpg/creak1.ogg.import b/assets/audio/kenney/rpg/creak1.ogg.import
new file mode 100644
index 0000000..e728eb8
--- /dev/null
+++ b/assets/audio/kenney/rpg/creak1.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://dmnasbvjaj28t"
+path="res://.godot/imported/creak1.ogg-494e533baf54d5e414c3daacbd157903.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/rpg/creak1.ogg"
+dest_files=["res://.godot/imported/creak1.ogg-494e533baf54d5e414c3daacbd157903.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/rpg/creak2.ogg b/assets/audio/kenney/rpg/creak2.ogg
new file mode 100644
index 0000000..bfa3045
Binary files /dev/null and b/assets/audio/kenney/rpg/creak2.ogg differ
diff --git a/assets/audio/kenney/rpg/creak2.ogg.import b/assets/audio/kenney/rpg/creak2.ogg.import
new file mode 100644
index 0000000..7c44091
--- /dev/null
+++ b/assets/audio/kenney/rpg/creak2.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://5p0aggjp73vv"
+path="res://.godot/imported/creak2.ogg-0d54c294963c6dc6e41b28828a4ffd7d.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/rpg/creak2.ogg"
+dest_files=["res://.godot/imported/creak2.ogg-0d54c294963c6dc6e41b28828a4ffd7d.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/rpg/creak3.ogg b/assets/audio/kenney/rpg/creak3.ogg
new file mode 100644
index 0000000..0673845
Binary files /dev/null and b/assets/audio/kenney/rpg/creak3.ogg differ
diff --git a/assets/audio/kenney/rpg/creak3.ogg.import b/assets/audio/kenney/rpg/creak3.ogg.import
new file mode 100644
index 0000000..10868a3
--- /dev/null
+++ b/assets/audio/kenney/rpg/creak3.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://bcqy2lnywdi2x"
+path="res://.godot/imported/creak3.ogg-5f2d6b38b16b99d9be55d3c83b06e2c7.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/rpg/creak3.ogg"
+dest_files=["res://.godot/imported/creak3.ogg-5f2d6b38b16b99d9be55d3c83b06e2c7.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/rpg/dropLeather.ogg b/assets/audio/kenney/rpg/dropLeather.ogg
new file mode 100644
index 0000000..83e3cf6
Binary files /dev/null and b/assets/audio/kenney/rpg/dropLeather.ogg differ
diff --git a/assets/audio/kenney/rpg/dropLeather.ogg.import b/assets/audio/kenney/rpg/dropLeather.ogg.import
new file mode 100644
index 0000000..2c9b687
--- /dev/null
+++ b/assets/audio/kenney/rpg/dropLeather.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://004jvtjlxqd3"
+path="res://.godot/imported/dropLeather.ogg-9bacfaf6dbc46860f9adf271f2e927c2.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/rpg/dropLeather.ogg"
+dest_files=["res://.godot/imported/dropLeather.ogg-9bacfaf6dbc46860f9adf271f2e927c2.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/rpg/handleSmallLeather.ogg b/assets/audio/kenney/rpg/handleSmallLeather.ogg
new file mode 100644
index 0000000..d98f77b
Binary files /dev/null and b/assets/audio/kenney/rpg/handleSmallLeather.ogg differ
diff --git a/assets/audio/kenney/rpg/handleSmallLeather.ogg.import b/assets/audio/kenney/rpg/handleSmallLeather.ogg.import
new file mode 100644
index 0000000..fe208db
--- /dev/null
+++ b/assets/audio/kenney/rpg/handleSmallLeather.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://b4xntokaxeh0b"
+path="res://.godot/imported/handleSmallLeather.ogg-05d894707a2c0369169ba9d43287e6d8.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/rpg/handleSmallLeather.ogg"
+dest_files=["res://.godot/imported/handleSmallLeather.ogg-05d894707a2c0369169ba9d43287e6d8.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/rpg/handleSmallLeather2.ogg b/assets/audio/kenney/rpg/handleSmallLeather2.ogg
new file mode 100644
index 0000000..80aa470
Binary files /dev/null and b/assets/audio/kenney/rpg/handleSmallLeather2.ogg differ
diff --git a/assets/audio/kenney/rpg/handleSmallLeather2.ogg.import b/assets/audio/kenney/rpg/handleSmallLeather2.ogg.import
new file mode 100644
index 0000000..1fb176a
--- /dev/null
+++ b/assets/audio/kenney/rpg/handleSmallLeather2.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://cv5v510gnorn3"
+path="res://.godot/imported/handleSmallLeather2.ogg-e5d847fa33ce621795233b66a8f480d4.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/rpg/handleSmallLeather2.ogg"
+dest_files=["res://.godot/imported/handleSmallLeather2.ogg-e5d847fa33ce621795233b66a8f480d4.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/kenney/ui/License.txt b/assets/audio/kenney/ui/License.txt
new file mode 100644
index 0000000..f1f770a
--- /dev/null
+++ b/assets/audio/kenney/ui/License.txt
@@ -0,0 +1,21 @@
+
+
+ UI SFX Set
+
+ by Kenney Vleugels (Kenney.nl)
+
+ ------------------------------
+
+ License (Creative Commons Zero, CC0)
+ http://creativecommons.org/publicdomain/zero/1.0/
+
+ You may use these assets in personal and commercial projects.
+ Credit (Kenney or www.kenney.nl) would be nice but is not mandatory.
+
+ ------------------------------
+
+ Donate: http://support.kenney.nl
+ Request: http://request.kenney.nl
+
+ Follow on Twitter for updates:
+ @KenneyNL
\ No newline at end of file
diff --git a/assets/audio/kenney/ui/rollover2.ogg b/assets/audio/kenney/ui/rollover2.ogg
new file mode 100644
index 0000000..d1964d0
Binary files /dev/null and b/assets/audio/kenney/ui/rollover2.ogg differ
diff --git a/assets/audio/kenney/ui/rollover2.ogg.import b/assets/audio/kenney/ui/rollover2.ogg.import
new file mode 100644
index 0000000..376905b
--- /dev/null
+++ b/assets/audio/kenney/ui/rollover2.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://d11npi25ahody"
+path="res://.godot/imported/rollover2.ogg-c33edb97834ad4ccbf8bb6992770f210.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/kenney/ui/rollover2.ogg"
+dest_files=["res://.godot/imported/rollover2.ogg-c33edb97834ad4ccbf8bb6992770f210.oggvorbisstr"]
+
+[params]
+
+loop=false
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/Godot_4.7_Farm_v1.0.zip b/assets/audio/music/on_the_farm.wav
similarity index 59%
rename from Godot_4.7_Farm_v1.0.zip
rename to assets/audio/music/on_the_farm.wav
index 8ae9edc..fe63fca 100644
Binary files a/Godot_4.7_Farm_v1.0.zip and b/assets/audio/music/on_the_farm.wav differ
diff --git a/assets/audio/music/on_the_farm.wav.import b/assets/audio/music/on_the_farm.wav.import
new file mode 100644
index 0000000..68148fb
--- /dev/null
+++ b/assets/audio/music/on_the_farm.wav.import
@@ -0,0 +1,24 @@
+[remap]
+
+importer="wav"
+type="AudioStreamWAV"
+uid="uid://b3n0x67ihxcqh"
+path="res://.godot/imported/on_the_farm.wav-40ddf659cec0a898c4c7dba25a18dbf3.sample"
+
+[deps]
+
+source_file="res://assets/audio/music/on_the_farm.wav"
+dest_files=["res://.godot/imported/on_the_farm.wav-40ddf659cec0a898c4c7dba25a18dbf3.sample"]
+
+[params]
+
+force/8_bit=false
+force/mono=false
+force/max_rate=false
+force/max_rate_hz=44100
+edit/trim=false
+edit/normalize=false
+edit/loop_mode=2
+edit/loop_begin=0
+edit/loop_end=-1
+compress/mode=2
diff --git a/assets/audio/music/purgatory.ogg b/assets/audio/music/purgatory.ogg
new file mode 100644
index 0000000..6d3a0a5
Binary files /dev/null and b/assets/audio/music/purgatory.ogg differ
diff --git a/assets/audio/music/purgatory.ogg.import b/assets/audio/music/purgatory.ogg.import
new file mode 100644
index 0000000..4bcf2b4
--- /dev/null
+++ b/assets/audio/music/purgatory.ogg.import
@@ -0,0 +1,19 @@
+[remap]
+
+importer="oggvorbisstr"
+type="AudioStreamOggVorbis"
+uid="uid://03qyxnkhyrvv"
+path="res://.godot/imported/purgatory.ogg-97556ec3aaf625efdad7c7267c26f6f1.oggvorbisstr"
+
+[deps]
+
+source_file="res://assets/audio/music/purgatory.ogg"
+dest_files=["res://.godot/imported/purgatory.ogg-97556ec3aaf625efdad7c7267c26f6f1.oggvorbisstr"]
+
+[params]
+
+loop=true
+loop_offset=0
+bpm=0
+beat_count=0
+bar_beats=4
diff --git a/assets/audio/synth/crow_caw_1.wav b/assets/audio/synth/crow_caw_1.wav
new file mode 100644
index 0000000..de93b2e
Binary files /dev/null and b/assets/audio/synth/crow_caw_1.wav differ
diff --git a/assets/audio/synth/crow_caw_1.wav.import b/assets/audio/synth/crow_caw_1.wav.import
new file mode 100644
index 0000000..f84a4c4
--- /dev/null
+++ b/assets/audio/synth/crow_caw_1.wav.import
@@ -0,0 +1,24 @@
+[remap]
+
+importer="wav"
+type="AudioStreamWAV"
+uid="uid://cbwhmc7grsd27"
+path="res://.godot/imported/crow_caw_1.wav-9fabe29c299b27212e939f91d8c53462.sample"
+
+[deps]
+
+source_file="res://assets/audio/synth/crow_caw_1.wav"
+dest_files=["res://.godot/imported/crow_caw_1.wav-9fabe29c299b27212e939f91d8c53462.sample"]
+
+[params]
+
+force/8_bit=false
+force/mono=false
+force/max_rate=false
+force/max_rate_hz=44100
+edit/trim=false
+edit/normalize=false
+edit/loop_mode=0
+edit/loop_begin=0
+edit/loop_end=-1
+compress/mode=2
diff --git a/assets/audio/synth/crow_caw_2.wav b/assets/audio/synth/crow_caw_2.wav
new file mode 100644
index 0000000..e1eb427
Binary files /dev/null and b/assets/audio/synth/crow_caw_2.wav differ
diff --git a/assets/audio/synth/crow_caw_2.wav.import b/assets/audio/synth/crow_caw_2.wav.import
new file mode 100644
index 0000000..1597d33
--- /dev/null
+++ b/assets/audio/synth/crow_caw_2.wav.import
@@ -0,0 +1,24 @@
+[remap]
+
+importer="wav"
+type="AudioStreamWAV"
+uid="uid://cb532g15xbau6"
+path="res://.godot/imported/crow_caw_2.wav-69c02a3a1741acb794b005fb88753ddb.sample"
+
+[deps]
+
+source_file="res://assets/audio/synth/crow_caw_2.wav"
+dest_files=["res://.godot/imported/crow_caw_2.wav-69c02a3a1741acb794b005fb88753ddb.sample"]
+
+[params]
+
+force/8_bit=false
+force/mono=false
+force/max_rate=false
+force/max_rate_hz=44100
+edit/trim=false
+edit/normalize=false
+edit/loop_mode=0
+edit/loop_begin=0
+edit/loop_end=-1
+compress/mode=2
diff --git a/assets/audio/synth/crow_squawk.wav b/assets/audio/synth/crow_squawk.wav
new file mode 100644
index 0000000..fc34baf
Binary files /dev/null and b/assets/audio/synth/crow_squawk.wav differ
diff --git a/assets/audio/synth/crow_squawk.wav.import b/assets/audio/synth/crow_squawk.wav.import
new file mode 100644
index 0000000..e744b57
--- /dev/null
+++ b/assets/audio/synth/crow_squawk.wav.import
@@ -0,0 +1,24 @@
+[remap]
+
+importer="wav"
+type="AudioStreamWAV"
+uid="uid://c8ha5rdq0mpgv"
+path="res://.godot/imported/crow_squawk.wav-6744560d178b8f2702cda5fe0bf32518.sample"
+
+[deps]
+
+source_file="res://assets/audio/synth/crow_squawk.wav"
+dest_files=["res://.godot/imported/crow_squawk.wav-6744560d178b8f2702cda5fe0bf32518.sample"]
+
+[params]
+
+force/8_bit=false
+force/mono=false
+force/max_rate=false
+force/max_rate_hz=44100
+edit/trim=false
+edit/normalize=false
+edit/loop_mode=0
+edit/loop_begin=0
+edit/loop_end=-1
+compress/mode=2
diff --git a/assets/audio/synth/day_ambience.wav b/assets/audio/synth/day_ambience.wav
new file mode 100644
index 0000000..e1ca262
Binary files /dev/null and b/assets/audio/synth/day_ambience.wav differ
diff --git a/assets/audio/synth/day_ambience.wav.import b/assets/audio/synth/day_ambience.wav.import
new file mode 100644
index 0000000..f05286c
--- /dev/null
+++ b/assets/audio/synth/day_ambience.wav.import
@@ -0,0 +1,24 @@
+[remap]
+
+importer="wav"
+type="AudioStreamWAV"
+uid="uid://clu6ctqxyj7m0"
+path="res://.godot/imported/day_ambience.wav-e937dff8639d58db8cb9c25aa6c82503.sample"
+
+[deps]
+
+source_file="res://assets/audio/synth/day_ambience.wav"
+dest_files=["res://.godot/imported/day_ambience.wav-e937dff8639d58db8cb9c25aa6c82503.sample"]
+
+[params]
+
+force/8_bit=false
+force/mono=false
+force/max_rate=false
+force/max_rate_hz=44100
+edit/trim=false
+edit/normalize=false
+edit/loop_mode=0
+edit/loop_begin=0
+edit/loop_end=-1
+compress/mode=2
diff --git a/assets/audio/synth/night_ambience.wav b/assets/audio/synth/night_ambience.wav
new file mode 100644
index 0000000..ad8c4bc
Binary files /dev/null and b/assets/audio/synth/night_ambience.wav differ
diff --git a/assets/audio/synth/night_ambience.wav.import b/assets/audio/synth/night_ambience.wav.import
new file mode 100644
index 0000000..2af91b3
--- /dev/null
+++ b/assets/audio/synth/night_ambience.wav.import
@@ -0,0 +1,24 @@
+[remap]
+
+importer="wav"
+type="AudioStreamWAV"
+uid="uid://ckdt5yqmqbxr5"
+path="res://.godot/imported/night_ambience.wav-37a6b9be44d76649be1b8ca55343d951.sample"
+
+[deps]
+
+source_file="res://assets/audio/synth/night_ambience.wav"
+dest_files=["res://.godot/imported/night_ambience.wav-37a6b9be44d76649be1b8ca55343d951.sample"]
+
+[params]
+
+force/8_bit=false
+force/mono=false
+force/max_rate=false
+force/max_rate_hz=44100
+edit/trim=false
+edit/normalize=false
+edit/loop_mode=0
+edit/loop_begin=0
+edit/loop_end=-1
+compress/mode=2
diff --git a/assets/audio/synth/pitchfork_whoosh.wav b/assets/audio/synth/pitchfork_whoosh.wav
new file mode 100644
index 0000000..34f3529
Binary files /dev/null and b/assets/audio/synth/pitchfork_whoosh.wav differ
diff --git a/assets/audio/synth/pitchfork_whoosh.wav.import b/assets/audio/synth/pitchfork_whoosh.wav.import
new file mode 100644
index 0000000..d6ad6fd
--- /dev/null
+++ b/assets/audio/synth/pitchfork_whoosh.wav.import
@@ -0,0 +1,24 @@
+[remap]
+
+importer="wav"
+type="AudioStreamWAV"
+uid="uid://d2cw8i8s1x2yj"
+path="res://.godot/imported/pitchfork_whoosh.wav-81271c77483d2c29b8628392160e5a3c.sample"
+
+[deps]
+
+source_file="res://assets/audio/synth/pitchfork_whoosh.wav"
+dest_files=["res://.godot/imported/pitchfork_whoosh.wav-81271c77483d2c29b8628392160e5a3c.sample"]
+
+[params]
+
+force/8_bit=false
+force/mono=false
+force/max_rate=false
+force/max_rate_hz=44100
+edit/trim=false
+edit/normalize=false
+edit/loop_mode=0
+edit/loop_begin=0
+edit/loop_end=-1
+compress/mode=2
diff --git a/assets/audio/synth/pumpkin_boom.wav b/assets/audio/synth/pumpkin_boom.wav
new file mode 100644
index 0000000..fd22904
Binary files /dev/null and b/assets/audio/synth/pumpkin_boom.wav differ
diff --git a/assets/audio/synth/pumpkin_boom.wav.import b/assets/audio/synth/pumpkin_boom.wav.import
new file mode 100644
index 0000000..9a7fc6a
--- /dev/null
+++ b/assets/audio/synth/pumpkin_boom.wav.import
@@ -0,0 +1,24 @@
+[remap]
+
+importer="wav"
+type="AudioStreamWAV"
+uid="uid://bssrfgywmt6fq"
+path="res://.godot/imported/pumpkin_boom.wav-424782ccfa849076312c0f1efdc8cbea.sample"
+
+[deps]
+
+source_file="res://assets/audio/synth/pumpkin_boom.wav"
+dest_files=["res://.godot/imported/pumpkin_boom.wav-424782ccfa849076312c0f1efdc8cbea.sample"]
+
+[params]
+
+force/8_bit=false
+force/mono=false
+force/max_rate=false
+force/max_rate_hz=44100
+edit/trim=false
+edit/normalize=false
+edit/loop_mode=0
+edit/loop_begin=0
+edit/loop_end=-1
+compress/mode=2
diff --git a/assets/audio/synth/truck_engine.wav b/assets/audio/synth/truck_engine.wav
new file mode 100644
index 0000000..8f2f128
Binary files /dev/null and b/assets/audio/synth/truck_engine.wav differ
diff --git a/assets/audio/synth/truck_engine.wav.import b/assets/audio/synth/truck_engine.wav.import
new file mode 100644
index 0000000..c4d94f2
--- /dev/null
+++ b/assets/audio/synth/truck_engine.wav.import
@@ -0,0 +1,24 @@
+[remap]
+
+importer="wav"
+type="AudioStreamWAV"
+uid="uid://dvjp0vql71qql"
+path="res://.godot/imported/truck_engine.wav-fc1544537e94c965be3c96ba6a9d4bb4.sample"
+
+[deps]
+
+source_file="res://assets/audio/synth/truck_engine.wav"
+dest_files=["res://.godot/imported/truck_engine.wav-fc1544537e94c965be3c96ba6a9d4bb4.sample"]
+
+[params]
+
+force/8_bit=false
+force/mono=false
+force/max_rate=false
+force/max_rate_hz=44100
+edit/trim=false
+edit/normalize=false
+edit/loop_mode=0
+edit/loop_begin=0
+edit/loop_end=-1
+compress/mode=2
diff --git a/assets/audio/synth/truck_horn.wav b/assets/audio/synth/truck_horn.wav
new file mode 100644
index 0000000..afd9f44
Binary files /dev/null and b/assets/audio/synth/truck_horn.wav differ
diff --git a/assets/audio/synth/truck_horn.wav.import b/assets/audio/synth/truck_horn.wav.import
new file mode 100644
index 0000000..3fb971f
--- /dev/null
+++ b/assets/audio/synth/truck_horn.wav.import
@@ -0,0 +1,24 @@
+[remap]
+
+importer="wav"
+type="AudioStreamWAV"
+uid="uid://u66vcuulpkf5"
+path="res://.godot/imported/truck_horn.wav-73befce90387bfa9357b075b437d8ee0.sample"
+
+[deps]
+
+source_file="res://assets/audio/synth/truck_horn.wav"
+dest_files=["res://.godot/imported/truck_horn.wav-73befce90387bfa9357b075b437d8ee0.sample"]
+
+[params]
+
+force/8_bit=false
+force/mono=false
+force/max_rate=false
+force/max_rate_hz=44100
+edit/trim=false
+edit/normalize=false
+edit/loop_mode=0
+edit/loop_begin=0
+edit/loop_end=-1
+compress/mode=2
diff --git a/assets/weapons/CornShooter.glb b/assets/weapons/CornShooter.glb
new file mode 100644
index 0000000..d865773
Binary files /dev/null and b/assets/weapons/CornShooter.glb differ
diff --git a/assets/weapons/CornShooter.glb.import b/assets/weapons/CornShooter.glb.import
new file mode 100644
index 0000000..61c5277
--- /dev/null
+++ b/assets/weapons/CornShooter.glb.import
@@ -0,0 +1,45 @@
+[remap]
+
+importer="scene"
+importer_version=1
+type="PackedScene"
+uid="uid://b73vxsrcvapx"
+path="res://.godot/imported/CornShooter.glb-e26650e915be3ea046038de904127afc.scn"
+
+[deps]
+
+source_file="res://assets/weapons/CornShooter.glb"
+dest_files=["res://.godot/imported/CornShooter.glb-e26650e915be3ea046038de904127afc.scn"]
+
+[params]
+
+nodes/root_type=""
+nodes/root_name=""
+nodes/root_script=null
+mesh_library/use_node_names_as_mesh_names=false
+array_mesh/deduplicate_surfaces=true
+nodes/apply_root_scale=true
+nodes/root_scale=1.0
+nodes/import_as_skeleton_bones=false
+nodes/use_name_suffixes=true
+nodes/use_node_type_suffixes=true
+meshes/ensure_tangents=true
+meshes/generate_lods=true
+meshes/create_shadow_meshes=true
+meshes/light_baking=1
+meshes/lightmap_texel_size=0.2
+meshes/force_disable_compression=false
+skins/use_named_skins=true
+animation/import=true
+animation/fps=30
+animation/trimming=false
+animation/remove_immutable_tracks=true
+animation/import_rest_as_RESET=false
+import_script/path=""
+materials/extract=0
+materials/extract_format=0
+materials/extract_path=""
+_subresources={}
+gltf/naming_version=2
+gltf/embedded_image_handling=1
+gltf/texture_map_mode=1
diff --git a/assets/weapons/PitchFork.glb b/assets/weapons/PitchFork.glb
new file mode 100644
index 0000000..2de575c
Binary files /dev/null and b/assets/weapons/PitchFork.glb differ
diff --git a/assets/weapons/PitchFork.glb.import b/assets/weapons/PitchFork.glb.import
new file mode 100644
index 0000000..0d23c6c
--- /dev/null
+++ b/assets/weapons/PitchFork.glb.import
@@ -0,0 +1,45 @@
+[remap]
+
+importer="scene"
+importer_version=1
+type="PackedScene"
+uid="uid://cfv8pdnn3sse3"
+path="res://.godot/imported/PitchFork.glb-f7faa0135596599bf2394b8cbeddd4ed.scn"
+
+[deps]
+
+source_file="res://assets/weapons/PitchFork.glb"
+dest_files=["res://.godot/imported/PitchFork.glb-f7faa0135596599bf2394b8cbeddd4ed.scn"]
+
+[params]
+
+nodes/root_type=""
+nodes/root_name=""
+nodes/root_script=null
+mesh_library/use_node_names_as_mesh_names=false
+array_mesh/deduplicate_surfaces=true
+nodes/apply_root_scale=true
+nodes/root_scale=1.0
+nodes/import_as_skeleton_bones=false
+nodes/use_name_suffixes=true
+nodes/use_node_type_suffixes=true
+meshes/ensure_tangents=true
+meshes/generate_lods=true
+meshes/create_shadow_meshes=true
+meshes/light_baking=1
+meshes/lightmap_texel_size=0.2
+meshes/force_disable_compression=false
+skins/use_named_skins=true
+animation/import=true
+animation/fps=30
+animation/trimming=false
+animation/remove_immutable_tracks=true
+animation/import_rest_as_RESET=false
+import_script/path=""
+materials/extract=0
+materials/extract_format=0
+materials/extract_path=""
+_subresources={}
+gltf/naming_version=2
+gltf/embedded_image_handling=1
+gltf/texture_map_mode=1
diff --git a/assets/weapons/PumpkinBomb.glb b/assets/weapons/PumpkinBomb.glb
new file mode 100644
index 0000000..f6d5a22
Binary files /dev/null and b/assets/weapons/PumpkinBomb.glb differ
diff --git a/assets/weapons/PumpkinBomb.glb.import b/assets/weapons/PumpkinBomb.glb.import
new file mode 100644
index 0000000..e898467
--- /dev/null
+++ b/assets/weapons/PumpkinBomb.glb.import
@@ -0,0 +1,45 @@
+[remap]
+
+importer="scene"
+importer_version=1
+type="PackedScene"
+uid="uid://da24y2b4153e"
+path="res://.godot/imported/PumpkinBomb.glb-a8466fca048e9c2ff93f30b0d4a144ed.scn"
+
+[deps]
+
+source_file="res://assets/weapons/PumpkinBomb.glb"
+dest_files=["res://.godot/imported/PumpkinBomb.glb-a8466fca048e9c2ff93f30b0d4a144ed.scn"]
+
+[params]
+
+nodes/root_type=""
+nodes/root_name=""
+nodes/root_script=null
+mesh_library/use_node_names_as_mesh_names=false
+array_mesh/deduplicate_surfaces=true
+nodes/apply_root_scale=true
+nodes/root_scale=1.0
+nodes/import_as_skeleton_bones=false
+nodes/use_name_suffixes=true
+nodes/use_node_type_suffixes=true
+meshes/ensure_tangents=true
+meshes/generate_lods=true
+meshes/create_shadow_meshes=true
+meshes/light_baking=1
+meshes/lightmap_texel_size=0.2
+meshes/force_disable_compression=false
+skins/use_named_skins=true
+animation/import=true
+animation/fps=30
+animation/trimming=false
+animation/remove_immutable_tracks=true
+animation/import_rest_as_RESET=false
+import_script/path=""
+materials/extract=0
+materials/extract_format=0
+materials/extract_path=""
+_subresources={}
+gltf/naming_version=2
+gltf/embedded_image_handling=1
+gltf/texture_map_mode=1
diff --git a/assets/weapons/PumpkinBomb_texture.png b/assets/weapons/PumpkinBomb_texture.png
new file mode 100644
index 0000000..4de52d3
Binary files /dev/null and b/assets/weapons/PumpkinBomb_texture.png differ
diff --git a/assets/weapons/PumpkinBomb_texture.png.import b/assets/weapons/PumpkinBomb_texture.png.import
new file mode 100644
index 0000000..1fb81b3
--- /dev/null
+++ b/assets/weapons/PumpkinBomb_texture.png.import
@@ -0,0 +1,43 @@
+[remap]
+
+importer="texture"
+type="CompressedTexture2D"
+uid="uid://dlj5cj7rqhipy"
+path="res://.godot/imported/PumpkinBomb_texture.png-50c061e72b4e1bcaa3ee520b7137056c.ctex"
+metadata={
+"vram_texture": false
+}
+generator_parameters={
+"md5": "290c6fccc94cce4ca41b7b5d4d3d92ed"
+}
+
+[deps]
+
+source_file="res://assets/weapons/PumpkinBomb_texture.png"
+dest_files=["res://.godot/imported/PumpkinBomb_texture.png-50c061e72b4e1bcaa3ee520b7137056c.ctex"]
+
+[params]
+
+compress/mode=0
+compress/high_quality=false
+compress/lossy_quality=0.7
+compress/uastc_level=0
+compress/rdo_quality_loss=0.0
+compress/hdr_compression=1
+compress/normal_map=0
+compress/channel_pack=0
+mipmaps/generate=true
+mipmaps/limit=-1
+roughness/mode=0
+roughness/src_normal=""
+process/channel_remap/red=0
+process/channel_remap/green=1
+process/channel_remap/blue=2
+process/channel_remap/alpha=3
+process/fix_alpha_border=true
+process/premult_alpha=false
+process/normal_map_invert_y=false
+process/hdr_as_srgb=false
+process/hdr_clamp_exposure=false
+process/size_limit=0
+detect_3d/compress_to=1
diff --git a/export_presets.cfg b/export_presets.cfg
new file mode 100644
index 0000000..c07e2fa
--- /dev/null
+++ b/export_presets.cfg
@@ -0,0 +1,57 @@
+[preset.0]
+
+name="Linux"
+platform="Linux"
+runnable=true
+dedicated_server=false
+custom_features=""
+export_filter="all_resources"
+include_filter=""
+exclude_filter="game/tests/*, game/tools/*, benchmarks/*, prototype/tests/*, prototype/tools/*"
+export_path="build/linux/HarvestSeason.x86_64"
+patches=PackedStringArray()
+encryption_include_filters=""
+encryption_exclude_filters=""
+seed=0
+encrypt_pck=false
+encrypt_directory=false
+script_export_mode=2
+
+[preset.0.options]
+
+custom_template/debug=""
+custom_template/release=""
+debug/export_console_wrapper=1
+binary_format/embed_pck=true
+binary_format/architecture="x86_64"
+
+[preset.1]
+
+name="Windows"
+platform="Windows Desktop"
+runnable=true
+dedicated_server=false
+custom_features=""
+export_filter="all_resources"
+include_filter=""
+exclude_filter="game/tests/*, game/tools/*, benchmarks/*, prototype/tests/*, prototype/tools/*"
+export_path="build/windows/HarvestSeason.exe"
+patches=PackedStringArray()
+encryption_include_filters=""
+encryption_exclude_filters=""
+seed=0
+encrypt_pck=false
+encrypt_directory=false
+script_export_mode=2
+
+[preset.1.options]
+
+custom_template/debug=""
+custom_template/release=""
+debug/export_console_wrapper=1
+binary_format/embed_pck=true
+binary_format/architecture="x86_64"
+application/modify_resources=true
+application/icon=""
+application/product_name="Harvest Season"
+application/file_description="Harvest Season"
diff --git a/first-game-plan.md b/first-game-plan.md
index 5afef4d..8f51a9f 100644
--- a/first-game-plan.md
+++ b/first-game-plan.md
@@ -18,7 +18,7 @@ Inspected 2026-10-03.
| `prototype/` | Tested combat stack: `PlayerInput` (mouse/gamepad aim), `WeaponController`, `ProjectileSystem` (pooled swept bullets), `HordeSystem` (pooled ground birds, one-target flow field, circle-vs-footprint collision, melee), `RoundController`, HUD, 107 headless tests, benchmarks | Source of combat and enemy systems |
| Farm pack (ithappy) | Static, unanimated animals (chicken, pig, sheep, cow, goat, horse), coop, fences, stone fences, hay, firewood, dry wood, barrels, boxes, bags, trucks, tractor | Pen, animals, gathering nodes, supply piles |
| KayKit | Rig_Medium and Rig_Large animation sets (general, movement, melee, tools) | Ground-enemy animation |
-| Audio | **None in the project** | Asset gap: needed from Step 4, required by Step 11 |
+| Audio | **None in the project** (Step 11 added Kenney CC0 packs and synthesized sounds) | Asset gap: needed from Step 4, required by Step 11 |
What's missing compared with `first-game.md`:
@@ -221,6 +221,12 @@ alerts can refer to them later.
### Step 3 — Make one farm asset stealable
+**Status: done (2026-10-03).** Deviations from the tasks below:
+- All 30 crop units are stealable, not a single one, since the mechanism is the same.
+- The flow fields are built once at load. Sliced rebuilds move to Step 6, the first time occupancy changes.
+- The sunrise retreat and the end-of-dawn rules (D4, D6) are already in, in their simple form.
+- 3.7 is the full port of the prototype's aim and gun (Step 4.2), at a 1.8 m combat height.
+
**Goal:** the full theft-and-recovery loop with one crop plot and one enemy, during normal play.
3.1 Fork `HordeSystem` into `EnemySystem`.
@@ -278,6 +284,24 @@ dropped, recovered, or lost) and every state is easy to read on screen.
### Step 4 — The scarecrow's defensive tools
+**Status: done (2026-10-03), apart from the look.** Notes against the tasks below:
+- **4.1 / 4.2 visuals deferred by request:** the reskin and the seed-shooter look come later.
+ Aiming, the gun, and shooting were already ported in Step 3.
+- **Fear input:** fear counts a press from its input event or from the action turning pressed
+ since the last tick, so a tap between two ticks still registers.
+- **Exit gate:** the gate is a human playtest. Supporting evidence from
+ `game/tools/soak_night.gd` (four 150 s nights with a scripted scarecrow):
+
+ | Scarecrow | Thieves at once | Crops lost | Crops recovered | Fear used |
+ |---|---|---|---|---|
+ | Idle | 1 | 20 | 0 | 0 |
+ | Guarding | 1 | 0 | 0 | 0 |
+ | Guarding | 2 | 8 | 7 | 9 |
+ | Guarding | 3 | 12 | 11 | 7 |
+
+ Thieves only fight on contact, so across these runs the scarecrow took one hit. Its health
+ matters once fence breakers arrive (Step 9).
+
**Goal:** protecting crops with the scarecrow alone is fun.
4.1 Scarecrow identity and controls.
@@ -337,6 +361,18 @@ uses both shooting (to intercept) and fear (for breathing room), and losing feel
### Step 5 — Gathering and a small resource economy
+**Status: done (2026-10-03).** Notes against the tasks below:
+- **Gather points:** 4 per material, made of the zones' existing props. Charges come back fully
+ overnight, at the end of the dawn grace, so the morning retry snapshot includes the regrowth.
+- **Full yields only:** a gather needs room for its whole yield, so no charge is half wasted.
+- **Focus:** when two points are in reach, a point with charges left wins over a used-up one.
+- **5.3 measured** (`soak_night.gd --mode=gather`): everything (18 wood, 18 scrap, 20 straw)
+ is gathered and stored in about 106 s of the 180 s day, with 4 trips. Step 12 checks whether
+ that covers a bad night's repairs.
+- **Exit gate:** gather → store → spend is covered by `test_economy`. The spends are patching
+ (straw) and Straw Stuffing (+2 max HP), and both help against the next attack. The fuller
+ "spending decision" arrives with building in Step 6.
+
**Goal:** the player gathers three materials and spends them on a useful preparation choice.
5.1 `ResourceStore` in `FarmState`: wood, scrap, and straw. Storage uses a pouch plus the shed:
@@ -377,6 +413,29 @@ next attack.
### Step 6 — Construction and repairs
+**Status: done (2026-10-03).** Notes against the tasks below:
+- **Instant building, by day:** no build channel. Dismantling is cancel (RMB / B) over a
+ structure in build mode, refunding 50% into the shed.
+- **Gates:** they swing open as the scarecrow nears and have no collision for it. For enemies
+ they are barrier cells.
+- **Crop route targets the rows:** the thieves' route now targets the crop rows rather than the
+ whole crop-field zone, so a fence ring really encloses the crops.
+- **Flow fields:** Dial's algorithm with 256 circular buckets, needed because barrier costs go
+ far beyond the old 8-bucket queue. Slices of 2,000 cells: about 40 ms in total over 18 ticks
+ per rebuild, at most 2.5 ms in one tick. There are 2 goal fields today; Step 8 adds the pen
+ and the shed.
+- **Exit gate:** `test_structures` A/B night (2 thieves at a time, scarecrow away):
+
+ | Layout | Crops lost |
+ |---|---|
+ | Open field | 9 |
+ | Fence ring | 7 (3 fences broken) |
+ | Ring + 4 automated defenses | 3 |
+
+- **Saves (for Step 11):** JSON must use full float precision (`JSON.stringify(d, "", true,
+ true)`).
+- **Flying rule:** written into `RULES.md` now, enforced from Step 9.
+
**Goal:** the player's defense layout visibly changes how an attack turns out.
6.1 `BuildMode`, working with both mouse and gamepad:
@@ -440,6 +499,22 @@ attack.
### Step 7 — Connect one complete day and night (milestone M3)
+**Status: done (2026-10-03).** Notes against the tasks below:
+- **Night plans are data:** `NightPlan` resources in `game/resources/nights/`, with groups of
+ {time, count, spacing, gap, target}. Night 1, "Crop thieves", sends 9 thieves through 4 gaps.
+ Every night uses it until Step 10.
+- **Rim light:** done as a faint night glow in the thief shader. The lighting also uses the
+ Environment's brightness and saturation adjustments, which leave the HUD alone.
+- **Dusk:** a banner, the HUD line, and pulsing rings with "Thieves tonight" labels and red edge
+ arrows at tonight's gaps, which stay up for the first 12 s of the night. The sound hook waits
+ for the audio pass in Step 12.
+- **Debug readout:** `CampaignDebug` is hidden behind F1, and Enter no longer begins the day
+ (the review's button does).
+- **7.8:** played as scripted cycles (`soak_night.gd --mode=cycle`), 3–4 cycles per variant, plus
+ `test_cycle`. Results and tuning notes are in `game/PLAYTEST.md`. With the scarecrow guarding or
+ a few automated defenses, night 1 loses nothing; undefended it loses 9 a night; materials pile
+ up. The human playtest checklist is in the same file.
+
**Goal:** one complete cycle that carries over into the next.
7.1 Hook the Step 1 state machine up to real content: phase timers from `GameConfig`, and
@@ -482,6 +557,44 @@ losses preserved.
### Step 8 — All three farm targets
+**Status: done (2026-10-03), apart from the human playtest for the exit gate.** Notes against the
+tasks below:
+- **8.1:** `LootSystem` keeps every stealable item in one id space: crop units, then animals, then
+ 6 sacks for supply bundles. A bundle is up to `supply_bundle` (5) units of the material the shed
+ holds most of, taken when the sack is filled, so it never exceeds the stock.
+- **8.2:**
+ - The pen's 8 animals (4 chickens, 2 pigs, 2 sheep) were already placed in Step 2.
+ - **The breach is the pen's gate:** its swung-open panel prop is gone, and a normal gate structure
+ stands in the opening from the start (`GameConfig.start_structures`). Animal thieves have to
+ break it.
+ - While the pen is open, one animal wanders out every 10 s, at night only.
+ - Loose animals head for the nearest gap.
+ - Followers walk the scarecrow's trail, which takes them through gates. Back in the pen they
+ stay calm for 30 s.
+- **8.3:** sacks drop on death or fear; touching one puts its contents back in the shed.
+ `ShedStock` grows and shrinks piles of logs, crates, and hay. A pile's props all collide at load,
+ so navigation never changes; hidden ones stop colliding for the scarecrow.
+- **8.4:**
+ - Plan groups have `target` (crops, animals, supplies, any); a thief whose category is empty falls
+ back by `target_weights`.
+ - Each shed pile has its own flow field, because a single shed field led thieves to the nearest
+ pile, where they couldn't see the one they wanted.
+ - Six fields now rebuild in about 120 ms over 49 ticks, at most 2.8 ms in one tick.
+- **8.5:**
+ - `AssetHud` (top center) flashes red or green.
+ - Carried loot and animals are outlined in their category's color (crops gold, animals pink,
+ supplies blue), and badges are filled in it.
+ - Edge arrows are ringed in it, and the dusk warning and beacons name each gap's target.
+ - Toasts and the morning review cover every category; the review and a toast say when the pen
+ is open.
+- **8.6:** the D2 open item is decided: spent supplies don't strip the farm, only a shed emptied
+ by thieves does (`FarmState.shed_raided`). `FarmState` is now version 2, with per-animal lost
+ ids.
+- **Night 1's plan** now threatens all three: 11 thieves. At 60 s an animal thief and a crop
+ thief arrive on opposite sides of the farm.
+- **Exit gate:** scripted cycles are in `game/PLAYTEST.md`. Whether two simultaneous threats force
+ a choice needs the human playtest: the scripted guard aims perfectly and loses nothing.
+
**Goal:** the player has to choose between valuable targets.
8.1 Split loot into categories: CROP (one unit), ANIMAL (one entity), SUPPLY (a bundle of K
@@ -522,6 +635,33 @@ flow fields for the pen and shed goals.
### Step 9 — The first enemy roster
+**Status: done (2026-10-03), apart from the human playtest for the exit gate.** Notes against the
+tasks below:
+- **9.1:** `GameConfig.enemy_types` holds one row per type: speed, acceleration, HP, flying,
+ targets, steal time, carry speed, structure damage, damage and hit interval, aggression, hit
+ radius, and aggro range. The old single-thief settings are gone.
+- **9.2:**
+ - **Crops are the crows' alone.** Ground thieves take animals and supplies only, so a fence
+ around the crops no longer does anything.
+ - **Crows** steer straight with separation from other crows, cruise at 3.2 m (visual only), and
+ land on the crop. They arrive from and leave toward the crow approach markers.
+ - **Ground enemies** are drawn by a fixed pool of KayKit characters: 14 thieves and 6 breakers.
+ A corpse is taken over at once if the pool is full.
+ - **Fence breakers** target barriers within 6 m of the crop field, the pen, or the shed, through
+ a breaker flow field. "Fights the scarecrow" became: turns on it within 4 m or when shot, and
+ hunts it along a field toward it (rebuilt in slices only while something hunts) once nothing
+ is left to break.
+- **9.3:** `AlertManager` replaces the Step 3–8 threat arrows.
+ - Kinds in priority order: escape, breach, theft, loose or dropped, incoming.
+ - Alerts are grouped by kind, type, loot, and zone.
+ - Escapes escalate by distance to the exit (the escape field on foot, the fence for crows).
+ - At most 5 show. Labels stack and keep clear of the HUD panels.
+- **9.4:** six debug scenarios in `game/resources/scenarios/`, cycled with F2: each type alone,
+ two pairs, and all three. T / G / H spawn one of each.
+- **Night 1** (until Step 10): 10 crows, 4 thieves, and a fence breaker.
+- **Exit gate:** scripted cycles and A/B nights are in `game/PLAYTEST.md`. Whether each enemy's
+ best response feels different to people is the human playtest's question.
+
**Goal:** three enemies that each need a different response.
9.1 Enemy type table in `GameConfig`: speed, HP, flying, targets, steal time, carry speed,
@@ -555,6 +695,29 @@ priorities.
### Step 10 — The five-night progression
+**Status: done (2026-10-03), apart from the human playtest for the exit gate.** Notes against the
+tasks below:
+- **10.1:** the existing `NightPlan` resource is the NightDefinition. It gained `dusk_hint` and a
+ `night_length` override; the last night uses 180 s. Target bias is the group's `target` (or
+ "any", by `target_weights`). `NightPlan.problems()` validates a plan against the farm.
+- **10.2:** five plans, `night_1..5.tres`, one main test each, as in the table. Night 5's three
+ waves are spelled out in its dusk hint, and every group appears in the dusk warning, so nothing
+ arrives unannounced.
+- **10.3:**
+ - **Eight upgrades** in four tracks:
+ - Weapon: rapid fire, heavy seeds.
+ - Fear: wide, quick.
+ - Scarecrow: straw stuffing.
+ - Defenses: reinforced fences, long-range defenses, sticky tar.
+ - **Buying:** once each, from a menu at the workbench (`UpgradePanel`).
+ - **Prices:** priced so that one run can't buy them all. Measured: the scripted scarecrow
+ affords 6 of 8 alongside its build plan, held back by scrap.
+- **10.4:** `test_nights` plays all five nights back to back. It checks each night's arrivals
+ against its plan, that each morning is its night's snapshot, and that the farm carries over to
+ the farmers' return.
+- **Exit gate:** scripted five-night runs are in `game/PLAYTEST.md`. Whether the decisions
+ between nights feel useful is the human playtest's question.
+
**Goal:** five distinct nights played back to back, with preparation choices between them.
10.1 `NightDefinition` resources (`game/resources/nights/night_1..5.tres`): spawn groups (type,
@@ -593,6 +756,41 @@ them.
### Step 11 — The complete campaign experience
+**Status: done (2026-10-03), apart from the hallway test for the exit gate.** Notes against the
+tasks below:
+- **11.1:** `game/scenes/main.tscn` is the main scene: the farm under the menus. The title
+ screen shows over the paused farm. Pause stops the whole tree, so the tick freezes. Labels:
+ "Save & quit to menu" and "Quit the game", because the only save point is the morning (11.2).
+- **11.2:** `SaveGame` writes the morning to `user://savegame.json`. FarmState is now version 3:
+ the nightly record counts more (11.4), and `SaveGame.migrate` upgrades version 2. There is no
+ mid-day save: quitting keeps the morning, and the pause menu says so.
+- **11.3:** `Tutorial`: nine contextual tips on night 1. Hide them with a new `hide_tips` action
+ (Backspace / Back) or in Settings.
+- **11.4:** the results are the top half of the morning screen rather than a screen of their
+ own: one click from dawn to the day. Every purchase now goes through `FarmState.pay`, so
+ spending is counted.
+- **11.5:** `EndPanel`'s failure mode.
+- **11.6:** `FarmersReturn`. Deviation: the existing trucks are semi-trailers parked out of
+ bounds, so the farmers come home in the ithappy station wagon (`car_002`, roof rack and all).
+ It drives in at GapDriveway and parks east of the house; the farmers walk to the north porch.
+ Tinted mannequins, straw hats from primitives, `Waving` and the new `Cheering` clip.
+- **11.7:** `Assessment`: the weights and tiers are in `GameConfig`. Supplies are scored by
+ theft, since spending them is fine.
+- **11.8:** `GameSettings` / `SettingsMenu`. There's no mouse sensitivity because mouse aim is
+ the cursor itself. Instead there are move and aim stick dead zones, and a tips toggle.
+- **11.9:** Kenney CC0 packs (impact, interface, RPG, UI, digital, music jingles), approved by
+ the user. Ambience, crows, and the car are synthesized by `game/tools/synth_audio.gd`. Animal
+ sounds and music tracks aren't covered: there's nothing suitable in the packs, and music was
+ optional. `FarmAudio` routes everything through the Master, Music, SFX, and Ambience buses.
+- **UI theme:** `UiTheme` is the project's default theme (asset table: UI theme). There's no
+ sourced font yet.
+- **Tests:** `test_save` (save/load field for field, bad and old versions, autosave, retry,
+ settings) and `test_flow` (the whole game through `main.tscn`: menus, pause, settings, restart,
+ save & quit, continue, failure, the ending, tips, sounds).
+- **Exit gate:** the hallway test is open (checklist in `game/PLAYTEST.md`).
+
+The tasks as planned:
+
**Goal:** a new player can start, understand the game, quit and resume, and reach an ending
without help.
@@ -642,6 +840,21 @@ a stats summary.
**Exit gate:** in a hallway test, an unfamiliar player starts the game, understands it, quits and
resumes, and reaches an ending without help.
+### After Step 11 — requests from the user (2026-10-03)
+
+- **No arrival markers:** the dusk rings, their labels, and the edge arrows toward tonight's gaps
+ are gone. The phase HUD still lists where enemies come from.
+- **Five times the enemies, more often:** `GameConfig.wave_count_scale` 5 and
+ `wave_spacing_scale` 0.4 scale every plan's groups. `enemy_capacity` is 160, and the character
+ pool is 48 thieves and 20 breakers. The 30-night campaign is still to come.
+- **Gathering outside the fence:** the scarecrow roams out to the old farm's outer fences. Four
+ outside areas yield 3 per charge (`game/LAYOUT.md`).
+- **Co-op for two** over GD-Sync: LAN, LAN by address, or online with API keys; tags, a partner
+ panel and arrow, voice chat, and the fall rule (out until morning; both down is Game Over).
+ This moves multiplayer (section 5) into scope, for two players. Everything is in
+ `game/COOP.md`.
+- **Music:** "On the Farm" (title, morning, day) and "Purgatory" (night).
+
### Step 12 — Balance and polish the full run
**Goal:** the five-night run is reliable, understandable, and enjoyable.
@@ -679,7 +892,8 @@ finish, and the 12.3 answers are recorded in `game/PLAYTEST.md`.
## 5. Out of scope for version 1
From `first-game.md`: farming simulation, hunger and thirst, power networks, automation,
-procedural maps, multiplayer, and large technology trees. Also excluded: processing chains
+procedural maps, multiplayer (except the co-op for two added after Step 11), and large technology
+trees. Also excluded: processing chains
(Step 5).
## 6. Risks to watch
diff --git a/game/COOP.md b/game/COOP.md
new file mode 100644
index 0000000..3de2850
--- /dev/null
+++ b/game/COOP.md
@@ -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 |
diff --git a/game/LAYOUT.md b/game/LAYOUT.md
index 1ae6299..bdb0b36 100644
--- a/game/LAYOUT.md
+++ b/game/LAYOUT.md
@@ -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.
diff --git a/game/PLAYTEST.md b/game/PLAYTEST.md
new file mode 100644
index 0000000..dc00715
--- /dev/null
+++ b/game/PLAYTEST.md
@@ -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?
diff --git a/game/RULES.md b/game/RULES.md
index 8bf0296..ebb2033 100644
--- a/game/RULES.md
+++ b/game/RULES.md
@@ -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.
diff --git a/game/resources/audio_buses.tres b/game/resources/audio_buses.tres
new file mode 100644
index 0000000..d5456da
--- /dev/null
+++ b/game/resources/audio_buses.tres
@@ -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"
diff --git a/game/resources/breaker_animations.res b/game/resources/breaker_animations.res
new file mode 100644
index 0000000..74b13fc
Binary files /dev/null and b/game/resources/breaker_animations.res differ
diff --git a/game/resources/enemy_overlay.gdshader b/game/resources/enemy_overlay.gdshader
new file mode 100644
index 0000000..b7b1814
--- /dev/null
+++ b/game/resources/enemy_overlay.gdshader
@@ -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;
+}
diff --git a/game/resources/enemy_overlay.gdshader.uid b/game/resources/enemy_overlay.gdshader.uid
new file mode 100644
index 0000000..dd62e8f
--- /dev/null
+++ b/game/resources/enemy_overlay.gdshader.uid
@@ -0,0 +1 @@
+uid://cr0wjm6153fqy
diff --git a/game/resources/fear_burst.gdshader b/game/resources/fear_burst.gdshader
new file mode 100644
index 0000000..5c1cb58
--- /dev/null
+++ b/game/resources/fear_burst.gdshader
@@ -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;
+}
diff --git a/game/resources/fear_burst.gdshader.uid b/game/resources/fear_burst.gdshader.uid
new file mode 100644
index 0000000..1ad68c9
--- /dev/null
+++ b/game/resources/fear_burst.gdshader.uid
@@ -0,0 +1 @@
+uid://cph3bo6e0l8gl
diff --git a/game/resources/game_config.tres b/game/resources/game_config.tres
index 78691ea..d1b5fb3 100644
--- a/game/resources/game_config.tres
+++ b/game/resources/game_config.tres
@@ -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
diff --git a/game/resources/hp_bar.gdshader b/game/resources/hp_bar.gdshader
new file mode 100644
index 0000000..2369ff3
--- /dev/null
+++ b/game/resources/hp_bar.gdshader
@@ -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;
+}
diff --git a/game/resources/hp_bar.gdshader.uid b/game/resources/hp_bar.gdshader.uid
new file mode 100644
index 0000000..36d1a1e
--- /dev/null
+++ b/game/resources/hp_bar.gdshader.uid
@@ -0,0 +1 @@
+uid://cigmrijnscla7
diff --git a/game/resources/loot_icon.gdshader b/game/resources/loot_icon.gdshader
new file mode 100644
index 0000000..907986f
--- /dev/null
+++ b/game/resources/loot_icon.gdshader
@@ -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;
+}
diff --git a/game/resources/loot_icon.gdshader.uid b/game/resources/loot_icon.gdshader.uid
new file mode 100644
index 0000000..865075a
--- /dev/null
+++ b/game/resources/loot_icon.gdshader.uid
@@ -0,0 +1 @@
+uid://cickuixgqv8ka
diff --git a/game/resources/nights/night_1.tres b/game/resources/nights/night_1.tres
new file mode 100644
index 0000000..e0c2a94
--- /dev/null
+++ b/game/resources/nights/night_1.tres
@@ -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"
+}])
diff --git a/game/resources/nights/night_2.tres b/game/resources/nights/night_2.tres
new file mode 100644
index 0000000..d49e49b
--- /dev/null
+++ b/game/resources/nights/night_2.tres
@@ -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"
+}])
diff --git a/game/resources/nights/night_3.tres b/game/resources/nights/night_3.tres
new file mode 100644
index 0000000..d1bc246
--- /dev/null
+++ b/game/resources/nights/night_3.tres
@@ -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"
+}])
diff --git a/game/resources/nights/night_4.tres b/game/resources/nights/night_4.tres
new file mode 100644
index 0000000..662d7d9
--- /dev/null
+++ b/game/resources/nights/night_4.tres
@@ -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"
+}])
diff --git a/game/resources/nights/night_5.tres b/game/resources/nights/night_5.tres
new file mode 100644
index 0000000..da8ff9e
--- /dev/null
+++ b/game/resources/nights/night_5.tres
@@ -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"
+}])
diff --git a/game/resources/player_animations.res b/game/resources/player_animations.res
index ca42314..ed223f3 100644
Binary files a/game/resources/player_animations.res and b/game/resources/player_animations.res differ
diff --git a/game/resources/scenarios/all_three.tres b/game/resources/scenarios/all_three.tres
new file mode 100644
index 0000000..5163ac2
--- /dev/null
+++ b/game/resources/scenarios/all_three.tres
@@ -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"
+}])
diff --git a/game/resources/scenarios/breakers.tres b/game/resources/scenarios/breakers.tres
new file mode 100644
index 0000000..cc9851e
--- /dev/null
+++ b/game/resources/scenarios/breakers.tres
@@ -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"
+}])
diff --git a/game/resources/scenarios/crows.tres b/game/resources/scenarios/crows.tres
new file mode 100644
index 0000000..7bd53ef
--- /dev/null
+++ b/game/resources/scenarios/crows.tres
@@ -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"
+}])
diff --git a/game/resources/scenarios/crows_thieves.tres b/game/resources/scenarios/crows_thieves.tres
new file mode 100644
index 0000000..bbd4999
--- /dev/null
+++ b/game/resources/scenarios/crows_thieves.tres
@@ -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"
+}])
diff --git a/game/resources/scenarios/thieves.tres b/game/resources/scenarios/thieves.tres
new file mode 100644
index 0000000..7dc995f
--- /dev/null
+++ b/game/resources/scenarios/thieves.tres
@@ -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"
+}])
diff --git a/game/resources/scenarios/thieves_breakers.tres b/game/resources/scenarios/thieves_breakers.tres
new file mode 100644
index 0000000..d4d6bad
--- /dev/null
+++ b/game/resources/scenarios/thieves_breakers.tres
@@ -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"
+}])
diff --git a/game/resources/steal_ring.gdshader b/game/resources/steal_ring.gdshader
new file mode 100644
index 0000000..17ccd65
--- /dev/null
+++ b/game/resources/steal_ring.gdshader
@@ -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;
+}
diff --git a/game/resources/steal_ring.gdshader.uid b/game/resources/steal_ring.gdshader.uid
new file mode 100644
index 0000000..e4d1c49
--- /dev/null
+++ b/game/resources/steal_ring.gdshader.uid
@@ -0,0 +1 @@
+uid://bvuoqfvggy7iy
diff --git a/game/resources/thief.gdshader b/game/resources/thief.gdshader
new file mode 100644
index 0000000..1e5feb2
--- /dev/null
+++ b/game/resources/thief.gdshader
@@ -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;
+}
diff --git a/game/resources/thief.gdshader.uid b/game/resources/thief.gdshader.uid
new file mode 100644
index 0000000..8229db5
--- /dev/null
+++ b/game/resources/thief.gdshader.uid
@@ -0,0 +1 @@
+uid://5vlqyyk1u75v
diff --git a/game/resources/ui_theme.tres b/game/resources/ui_theme.tres
new file mode 100644
index 0000000..48a1161
--- /dev/null
+++ b/game/resources/ui_theme.tres
@@ -0,0 +1,580 @@
+[gd_resource type="Theme" format=3 uid="uid://k2xq4hqpv3xe"]
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_lp2ro"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0.14, 0.15, 0.13, 1)
+border_width_left = 2
+border_width_top = 2
+border_width_right = 2
+border_width_bottom = 2
+border_color = Color(0.28, 0.28, 0.25, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_cb5cy"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0, 0, 0, 0)
+draw_center = false
+border_width_left = 4
+border_width_top = 4
+border_width_right = 4
+border_width_bottom = 4
+border_color = Color(0.95, 0.82, 0.45, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+expand_margin_left = 3.0
+expand_margin_top = 3.0
+expand_margin_right = 3.0
+expand_margin_bottom = 3.0
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_lx6lh"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0.3, 0.35, 0.24, 1)
+border_width_left = 2
+border_width_top = 2
+border_width_right = 2
+border_width_bottom = 2
+border_color = Color(0.95, 0.82, 0.45, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_hvl4h"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0.2, 0.24, 0.18, 1)
+border_width_left = 2
+border_width_top = 2
+border_width_right = 2
+border_width_bottom = 2
+border_color = Color(0.45, 0.42, 0.3, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_ukm2w"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0.15, 0.19, 0.13, 1)
+border_width_left = 2
+border_width_top = 2
+border_width_right = 2
+border_width_bottom = 2
+border_color = Color(0.95, 0.82, 0.45, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="Image" id="Image_lp2ro"]
+data = {
+"data": PackedByteArray(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
+"format": "RGBA8",
+"height": 30,
+"mipmaps": false,
+"width": 30
+}
+
+[sub_resource type="ImageTexture" id="ImageTexture_3nop5"]
+image = SubResource("Image_lp2ro")
+
+[sub_resource type="Image" id="Image_cb5cy"]
+data = {
+"data": PackedByteArray(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
+"format": "RGBA8",
+"height": 30,
+"mipmaps": false,
+"width": 30
+}
+
+[sub_resource type="ImageTexture" id="ImageTexture_yain7"]
+image = SubResource("Image_cb5cy")
+
+[sub_resource type="Image" id="Image_lx6lh"]
+data = {
+"data": PackedByteArray(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
+"format": "RGBA8",
+"height": 30,
+"mipmaps": false,
+"width": 30
+}
+
+[sub_resource type="ImageTexture" id="ImageTexture_ybvsy"]
+image = SubResource("Image_lx6lh")
+
+[sub_resource type="Image" id="Image_hvl4h"]
+data = {
+"data": PackedByteArray(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
+"format": "RGBA8",
+"height": 30,
+"mipmaps": false,
+"width": 30
+}
+
+[sub_resource type="ImageTexture" id="ImageTexture_rl28s"]
+image = SubResource("Image_hvl4h")
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_da138"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0, 0, 0, 0)
+draw_center = false
+border_width_left = 3
+border_width_top = 3
+border_width_right = 3
+border_width_bottom = 3
+border_color = Color(0.95, 0.82, 0.45, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_jjtsc"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(1, 1, 1, 0.05)
+border_color = Color(0, 0, 0, 0)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_0cj1e"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(1, 1, 1, 0.05)
+border_color = Color(0, 0, 0, 0)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxEmpty" id="StyleBoxEmpty_i1onf"]
+
+[sub_resource type="Image" id="Image_ukm2w"]
+data = {
+"data": PackedByteArray(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 30, 25, 12, 255, 30, 25, 12, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 242, 209, 114, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
+"format": "RGBA8",
+"height": 30,
+"mipmaps": false,
+"width": 30
+}
+
+[sub_resource type="ImageTexture" id="ImageTexture_6p25f"]
+image = SubResource("Image_ukm2w")
+
+[sub_resource type="Image" id="Image_hx7kx"]
+data = {
+"data": PackedByteArray(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 30, 25, 12, 255, 30, 25, 12, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 114, 107, 81, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
+"format": "RGBA8",
+"height": 30,
+"mipmaps": false,
+"width": 30
+}
+
+[sub_resource type="ImageTexture" id="ImageTexture_yt3a7"]
+image = SubResource("Image_hx7kx")
+
+[sub_resource type="Image" id="Image_3nop5"]
+data = {
+"data": PackedByteArray(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 198, 188, 153, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
+"format": "RGBA8",
+"height": 30,
+"mipmaps": false,
+"width": 30
+}
+
+[sub_resource type="ImageTexture" id="ImageTexture_1xurq"]
+image = SubResource("Image_3nop5")
+
+[sub_resource type="Image" id="Image_4e5wc"]
+data = {
+"data": PackedByteArray(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 35, 40, 30, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 102, 102, 91, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
+"format": "RGBA8",
+"height": 30,
+"mipmaps": false,
+"width": 30
+}
+
+[sub_resource type="ImageTexture" id="ImageTexture_q4gji"]
+image = SubResource("Image_4e5wc")
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_o86wr"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0, 0, 0, 0)
+draw_center = false
+border_width_left = 3
+border_width_top = 3
+border_width_right = 3
+border_width_bottom = 3
+border_color = Color(0.95, 0.82, 0.45, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_b3hvf"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(1, 1, 1, 0.05)
+border_color = Color(0, 0, 0, 0)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_0kjmo"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(1, 1, 1, 0.05)
+border_color = Color(0, 0, 0, 0)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxEmpty" id="StyleBoxEmpty_u64ej"]
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_slfdx"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0, 0, 0, 0)
+draw_center = false
+border_width_left = 3
+border_width_top = 3
+border_width_right = 3
+border_width_bottom = 3
+border_color = Color(0.95, 0.82, 0.45, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+expand_margin_left = 4.0
+expand_margin_top = 4.0
+expand_margin_right = 4.0
+expand_margin_bottom = 4.0
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_8yu3x"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0.55, 0.78, 0.4, 1)
+border_color = Color(0, 0, 0, 0)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_ats34"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0.7, 0.9, 0.5, 1)
+border_color = Color(0, 0, 0, 0)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_nphkm"]
+content_margin_left = 16.0
+content_margin_top = 4.0
+content_margin_right = 16.0
+content_margin_bottom = 4.0
+bg_color = Color(0.22, 0.24, 0.2, 1)
+border_color = Color(0, 0, 0, 0)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_3jn1p"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0.14, 0.15, 0.13, 1)
+border_width_left = 2
+border_width_top = 2
+border_width_right = 2
+border_width_bottom = 2
+border_color = Color(0.28, 0.28, 0.25, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_8nyvl"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0, 0, 0, 0)
+draw_center = false
+border_width_left = 4
+border_width_top = 4
+border_width_right = 4
+border_width_bottom = 4
+border_color = Color(0.95, 0.82, 0.45, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+expand_margin_left = 3.0
+expand_margin_top = 3.0
+expand_margin_right = 3.0
+expand_margin_bottom = 3.0
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_4w6hl"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0.3, 0.35, 0.24, 1)
+border_width_left = 2
+border_width_top = 2
+border_width_right = 2
+border_width_bottom = 2
+border_color = Color(0.95, 0.82, 0.45, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_yfab0"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0.2, 0.24, 0.18, 1)
+border_width_left = 2
+border_width_top = 2
+border_width_right = 2
+border_width_bottom = 2
+border_color = Color(0.45, 0.42, 0.3, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_m46qi"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0.15, 0.19, 0.13, 1)
+border_width_left = 2
+border_width_top = 2
+border_width_right = 2
+border_width_bottom = 2
+border_color = Color(0.95, 0.82, 0.45, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_6b2nu"]
+bg_color = Color(0.1, 0.12, 0.1, 1)
+border_width_left = 2
+border_width_top = 2
+border_width_right = 2
+border_width_bottom = 2
+border_color = Color(0.55, 0.5, 0.35, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_m45q2"]
+bg_color = Color(0.1, 0.12, 0.1, 1)
+border_width_left = 2
+border_width_top = 2
+border_width_right = 2
+border_width_bottom = 2
+border_color = Color(0.55, 0.5, 0.35, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_mqj73"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0.12, 0.14, 0.11, 1)
+border_width_left = 2
+border_width_top = 2
+border_width_right = 2
+border_width_bottom = 2
+border_color = Color(0.35, 0.33, 0.25, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_u8cet"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0, 0, 0, 0)
+draw_center = false
+border_width_left = 3
+border_width_top = 3
+border_width_right = 3
+border_width_bottom = 3
+border_color = Color(0.95, 0.82, 0.45, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_28ifq"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0.24, 0.28, 0.2, 1)
+border_width_left = 2
+border_width_top = 2
+border_width_right = 2
+border_width_bottom = 2
+border_color = Color(0.95, 0.82, 0.45, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_iubca"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0.3, 0.35, 0.24, 1)
+border_width_left = 2
+border_width_top = 2
+border_width_right = 2
+border_width_bottom = 2
+border_color = Color(0.95, 0.82, 0.45, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_mbola"]
+content_margin_left = 16.0
+content_margin_top = 8.0
+content_margin_right = 16.0
+content_margin_bottom = 8.0
+bg_color = Color(0.16, 0.19, 0.14, 1)
+border_width_left = 2
+border_width_top = 2
+border_width_right = 2
+border_width_bottom = 2
+border_color = Color(0.35, 0.33, 0.25, 1)
+corner_radius_top_left = 6
+corner_radius_top_right = 6
+corner_radius_bottom_right = 6
+corner_radius_bottom_left = 6
+
+[resource]
+default_font_size = 22
+Button/colors/font_color = Color(0.95, 0.93, 0.85, 1)
+Button/colors/font_disabled_color = Color(0.5, 0.5, 0.45, 1)
+Button/colors/font_focus_color = Color(1, 0.95, 0.7, 1)
+Button/colors/font_hover_color = Color(1, 0.95, 0.7, 1)
+Button/colors/font_pressed_color = Color(0.95, 0.82, 0.45, 1)
+Button/styles/disabled = SubResource("StyleBoxFlat_lp2ro")
+Button/styles/focus = SubResource("StyleBoxFlat_cb5cy")
+Button/styles/hover = SubResource("StyleBoxFlat_lx6lh")
+Button/styles/normal = SubResource("StyleBoxFlat_hvl4h")
+Button/styles/pressed = SubResource("StyleBoxFlat_ukm2w")
+CheckBox/colors/font_color = Color(0.95, 0.93, 0.85, 1)
+CheckBox/colors/font_focus_color = Color(1, 0.95, 0.7, 1)
+CheckBox/colors/font_hover_color = Color(1, 0.95, 0.7, 1)
+CheckBox/colors/font_pressed_color = Color(0.95, 0.93, 0.85, 1)
+CheckBox/constants/h_separation = 12
+CheckBox/icons/checked = SubResource("ImageTexture_3nop5")
+CheckBox/icons/checked_disabled = SubResource("ImageTexture_yain7")
+CheckBox/icons/unchecked = SubResource("ImageTexture_ybvsy")
+CheckBox/icons/unchecked_disabled = SubResource("ImageTexture_rl28s")
+CheckBox/styles/focus = SubResource("StyleBoxFlat_da138")
+CheckBox/styles/hover = SubResource("StyleBoxFlat_jjtsc")
+CheckBox/styles/hover_pressed = SubResource("StyleBoxFlat_0cj1e")
+CheckBox/styles/normal = SubResource("StyleBoxEmpty_i1onf")
+CheckBox/styles/pressed = SubResource("StyleBoxEmpty_i1onf")
+CheckButton/colors/font_color = Color(0.95, 0.93, 0.85, 1)
+CheckButton/colors/font_focus_color = Color(1, 0.95, 0.7, 1)
+CheckButton/colors/font_hover_color = Color(1, 0.95, 0.7, 1)
+CheckButton/colors/font_pressed_color = Color(0.95, 0.93, 0.85, 1)
+CheckButton/constants/h_separation = 12
+CheckButton/icons/checked = SubResource("ImageTexture_6p25f")
+CheckButton/icons/checked_disabled = SubResource("ImageTexture_yt3a7")
+CheckButton/icons/unchecked = SubResource("ImageTexture_1xurq")
+CheckButton/icons/unchecked_disabled = SubResource("ImageTexture_q4gji")
+CheckButton/styles/focus = SubResource("StyleBoxFlat_o86wr")
+CheckButton/styles/hover = SubResource("StyleBoxFlat_b3hvf")
+CheckButton/styles/hover_pressed = SubResource("StyleBoxFlat_0kjmo")
+CheckButton/styles/normal = SubResource("StyleBoxEmpty_u64ej")
+CheckButton/styles/pressed = SubResource("StyleBoxEmpty_u64ej")
+HSlider/styles/focus = SubResource("StyleBoxFlat_slfdx")
+HSlider/styles/grabber_area = SubResource("StyleBoxFlat_8yu3x")
+HSlider/styles/grabber_area_highlight = SubResource("StyleBoxFlat_ats34")
+HSlider/styles/slider = SubResource("StyleBoxFlat_nphkm")
+OptionButton/colors/font_color = Color(0.95, 0.93, 0.85, 1)
+OptionButton/colors/font_disabled_color = Color(0.5, 0.5, 0.45, 1)
+OptionButton/colors/font_focus_color = Color(1, 0.95, 0.7, 1)
+OptionButton/colors/font_hover_color = Color(1, 0.95, 0.7, 1)
+OptionButton/colors/font_pressed_color = Color(0.95, 0.82, 0.45, 1)
+OptionButton/styles/disabled = SubResource("StyleBoxFlat_3jn1p")
+OptionButton/styles/focus = SubResource("StyleBoxFlat_8nyvl")
+OptionButton/styles/hover = SubResource("StyleBoxFlat_4w6hl")
+OptionButton/styles/normal = SubResource("StyleBoxFlat_yfab0")
+OptionButton/styles/pressed = SubResource("StyleBoxFlat_m46qi")
+Panel/styles/panel = SubResource("StyleBoxFlat_6b2nu")
+PanelContainer/styles/panel = SubResource("StyleBoxFlat_m45q2")
+TabContainer/colors/font_hovered_color = Color(1, 0.95, 0.7, 1)
+TabContainer/colors/font_selected_color = Color(0.95, 0.82, 0.45, 1)
+TabContainer/colors/font_unselected_color = Color(0.95, 0.93, 0.85, 1)
+TabContainer/styles/panel = SubResource("StyleBoxFlat_mqj73")
+TabContainer/styles/tab_focus = SubResource("StyleBoxFlat_u8cet")
+TabContainer/styles/tab_hovered = SubResource("StyleBoxFlat_28ifq")
+TabContainer/styles/tab_selected = SubResource("StyleBoxFlat_iubca")
+TabContainer/styles/tab_unselected = SubResource("StyleBoxFlat_mbola")
diff --git a/game/scenes/farm.tscn b/game/scenes/farm.tscn
index 61d8066..756789e 100644
--- a/game/scenes/farm.tscn
+++ b/game/scenes/farm.tscn
@@ -4,7 +4,6 @@
[ext_resource type="PackedScene" uid="uid://jrpjchi0u7h1" path="res://assets/farm/ithappy/farm/prefabs/assets/ground/ground_004.tscn" id="2_aqlkk"]
[ext_resource type="Script" uid="uid://bdlmtj20npler" path="res://game/scripts/follow_camera.gd" id="2_camera"]
[ext_resource type="Texture2D" uid="uid://bq421knnjuapb" path="res://assets/farm/ithappy/farm/textures/Skybox_3.png" id="3_sky"]
-[ext_resource type="PackedScene" uid="uid://hnyfs6uqvejm" path="res://assets/farm/ithappy/farm/prefabs/assets/ground/ground_010.tscn" id="3_t8vhl"]
[ext_resource type="PackedScene" uid="uid://wbiymevvh11y" path="res://assets/farm/ithappy/farm/prefabs/assets/ground/ground_008.tscn" id="4_wbrnf"]
[ext_resource type="PackedScene" uid="uid://bf3e5b3p5iko5" path="res://assets/farm/ithappy/farm/prefabs/assets/ground/ground_011.tscn" id="5_rhwtn"]
[ext_resource type="PackedScene" uid="uid://rg2gblm7uljg" path="res://assets/farm/ithappy/farm/prefabs/assets/ground/ground_017.tscn" id="6_3bdhk"]
@@ -31,13 +30,9 @@
[ext_resource type="PackedScene" uid="uid://t0vsfoagibp7" path="res://assets/farm/ithappy/farm/prefabs/assets/tree/fir_tree_002.tscn" id="25_axy3h"]
[ext_resource type="PackedScene" uid="uid://b5qsaxd63wx80" path="res://assets/farm/ithappy/farm/prefabs/assets/plant/plant_007.tscn" id="26_ydg3k"]
[ext_resource type="PackedScene" uid="uid://b0x1d6k745djv" path="res://assets/farm/ithappy/farm/prefabs/assets/plant/plant_008.tscn" id="27_hirfa"]
-[ext_resource type="PackedScene" uid="uid://43cd6lkj4xrm" path="res://assets/farm/ithappy/farm/prefabs/assets/plant/plant_004.tscn" id="28_bi5en"]
[ext_resource type="PackedScene" uid="uid://detjnm1cm0s28" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/fence_002.tscn" id="28_oc1g0"]
-[ext_resource type="PackedScene" uid="uid://1p6k2a6oiqne" path="res://assets/farm/ithappy/farm/prefabs/assets/plant/plant_005.tscn" id="29_aut3c"]
[ext_resource type="PackedScene" uid="uid://diltek1802a3d" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/fence_004.tscn" id="30_50kde"]
-[ext_resource type="PackedScene" uid="uid://bggbu54nwq0bm" path="res://assets/farm/ithappy/farm/prefabs/assets/plant/plant_009.tscn" id="30_x016k"]
[ext_resource type="PackedScene" uid="uid://dk00oyv7occ3t" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/fence_005.tscn" id="31_fk54y"]
-[ext_resource type="PackedScene" uid="uid://qfw7xi5gawgq" path="res://assets/farm/ithappy/farm/prefabs/assets/plant/plant_006.tscn" id="31_i5oqq"]
[ext_resource type="PackedScene" uid="uid://ef3pluccqsj4" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/fence_006.tscn" id="32_ec1uo"]
[ext_resource type="PackedScene" uid="uid://bhko6le6hyqdh" path="res://assets/farm/ithappy/farm/prefabs/assets/tower/tower_017.tscn" id="32_mcuoy"]
[ext_resource type="PackedScene" uid="uid://djjak33vjenrq" path="res://assets/farm/ithappy/farm/prefabs/assets/tower/tower_006.tscn" id="33_6imja"]
@@ -66,11 +61,24 @@
[ext_resource type="PackedScene" uid="uid://cnbrd60dxlvir" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/firewood_007.tscn" id="62_ibwhs"]
[ext_resource type="PackedScene" uid="uid://bmvokusoktgrl" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/barrel_009.tscn" id="63_ocduh"]
[ext_resource type="PackedScene" uid="uid://bm13bxk1epllr" path="res://assets/farm/ithappy/farm/prefabs/assets/box/box_005.tscn" id="67_1l04x"]
-[ext_resource type="Script" path="res://game/scripts/campaign_controller.gd" id="100_campaign"]
-[ext_resource type="Script" path="res://game/scripts/campaign_debug.gd" id="101_campaign_debug"]
-[ext_resource type="Script" path="res://game/scripts/farm_zones.gd" id="200_farm_zones"]
-[ext_resource type="Script" path="res://game/scripts/farm_zone.gd" id="201_farm_zone"]
-[ext_resource type="Script" path="res://game/scripts/crop_unit.gd" id="202_crop_unit"]
+[ext_resource type="Script" uid="uid://dh1gl5p44sjb1" path="res://game/scripts/campaign_controller.gd" id="100_campaign"]
+[ext_resource type="Script" uid="uid://bvvdfx5idf2u5" path="res://game/scripts/campaign_debug.gd" id="101_campaign_debug"]
+[ext_resource type="Script" uid="uid://c6auf64ahke4k" path="res://game/scripts/farm_sim.gd" id="102_farm_sim"]
+[ext_resource type="Script" uid="uid://clqvqr3bnsp5k" path="res://game/scripts/alert_manager.gd" id="103_threats"]
+[ext_resource type="Script" uid="uid://f647f4bijmdy" path="res://game/scripts/toast_feed.gd" id="104_toasts"]
+[ext_resource type="Script" uid="uid://e768baxfmoit" path="res://game/scripts/scarecrow_hud.gd" id="105_scarecrow_hud"]
+[ext_resource type="Script" uid="uid://b6pkgit825mrl" path="res://game/scripts/end_panel.gd" id="106_end_panel"]
+[ext_resource type="Script" uid="uid://dc3i7w50plvjs" path="res://game/scripts/resource_hud.gd" id="107_resource_hud"]
+[ext_resource type="Script" uid="uid://cj88bbt6nct61" path="res://game/scripts/gather_node.gd" id="108_gather"]
+[ext_resource type="Script" uid="uid://dr1dglq0p05hu" path="res://game/scripts/workbench.gd" id="109_workbench"]
+[ext_resource type="Script" uid="uid://kmuyj86rfjj2" path="res://game/scripts/build_hud.gd" id="110_build_hud"]
+[ext_resource type="Script" uid="uid://bp7dq566avk2v" path="res://game/scripts/phase_hud.gd" id="111_phase_hud"]
+[ext_resource type="Script" uid="uid://cwll33writ0hq" path="res://game/scripts/review_panel.gd" id="112_review"]
+[ext_resource type="Script" uid="uid://cdhho7exq5x3s" path="res://game/scripts/asset_hud.gd" id="113_asset_hud"]
+[ext_resource type="Script" uid="uid://cq4ipv3nc7ual" path="res://game/scripts/upgrade_panel.gd" id="114_upgrades"]
+[ext_resource type="Script" uid="uid://bpl66stkcn1rr" path="res://game/scripts/farm_zones.gd" id="200_farm_zones"]
+[ext_resource type="Script" uid="uid://celghhlevq85l" path="res://game/scripts/farm_zone.gd" id="201_farm_zone"]
+[ext_resource type="Script" uid="uid://d0bha7ghc1lfc" path="res://game/scripts/crop_unit.gd" id="202_crop_unit"]
[ext_resource type="PackedScene" uid="uid://te14rbc18m2d" path="res://assets/farm/ithappy/farm/prefabs/assets/box/box_004.tscn" id="203_box_004"]
[ext_resource type="PackedScene" uid="uid://cv2j3lopav0e0" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/bag_001.tscn" id="204_bag_001"]
[ext_resource type="PackedScene" uid="uid://d111wl4dghphq" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/bag_003.tscn" id="205_bag_003"]
@@ -84,7 +92,6 @@
[ext_resource type="PackedScene" uid="uid://ceco5h6fe6hyu" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/table_002.tscn" id="213_table_002"]
[ext_resource type="PackedScene" uid="uid://c5dpfl620ystw" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/bucket_001.tscn" id="214_bucket_001"]
[ext_resource type="PackedScene" uid="uid://dm7inst25lj00" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/fence_024.tscn" id="215_fence_024"]
-[ext_resource type="PackedScene" uid="uid://cl44abqxswc6l" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/fence_018.tscn" id="216_fence_018"]
[ext_resource type="PackedScene" uid="uid://dw1k3ilpn8nll" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/coop_002.tscn" id="217_coop_002"]
[ext_resource type="PackedScene" uid="uid://cr17qkqcl5n5k" path="res://assets/farm/ithappy/farm/prefabs/assets/animal/chicken_001.tscn" id="218_chicken_001"]
[ext_resource type="PackedScene" uid="uid://b1awnl6wg6nur" path="res://assets/farm/ithappy/farm/prefabs/assets/animal/chicken_003.tscn" id="219_chicken_003"]
@@ -102,9 +109,9 @@
[ext_resource type="PackedScene" uid="uid://cw02nvouivbcr" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/cart_003.tscn" id="231_cart_003"]
[ext_resource type="PackedScene" uid="uid://bwwacrifny7im" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/dray_001.tscn" id="232_dray_001"]
[ext_resource type="PackedScene" uid="uid://chk3qbbrouuhw" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/barrel_005.tscn" id="233_barrel_005"]
-[ext_resource type="Script" path="res://game/scripts/farm_marker.gd" id="234_farm_marker"]
+[ext_resource type="Script" uid="uid://dewrnp06jkx2y" path="res://game/scripts/farm_marker.gd" id="234_farm_marker"]
[ext_resource type="PackedScene" uid="uid://dge2nlq7ko5pj" path="res://assets/farm/ithappy/farm/prefabs/assets/prop/pointer_002.tscn" id="235_pointer_002"]
-[ext_resource type="Script" path="res://game/scripts/zone_banner.gd" id="236_zone_banner"]
+[ext_resource type="Script" uid="uid://dbfcgsdrh5v60" path="res://game/scripts/zone_banner.gd" id="236_zone_banner"]
[sub_resource type="PanoramaSkyMaterial" id="PanoramaSkyMaterial_farm"]
panorama = ExtResource("3_sky")
@@ -129,10 +136,10 @@ size = Vector2(120, 120)
size = Vector3(120, 1, 120)
[sub_resource type="BoxShape3D" id="BoxShape3D_bounds_ns"]
-size = Vector3(60.4, 3, 0.2)
+size = Vector3(82.4, 3, 0.2)
[sub_resource type="BoxShape3D" id="BoxShape3D_bounds_we"]
-size = Vector3(0.2, 3, 60.4)
+size = Vector3(0.2, 3, 106.6)
[node name="Farm" type="Node3D" unique_id=1715863860]
@@ -160,15 +167,15 @@ shape = SubResource("Box_ground")
[node name="ground_004_005" parent="Level" unique_id=261290431 instance=ExtResource("2_aqlkk")]
transform = Transform3D(1.4, 0, 0, 0, 1, 0, 0, 0, 1.4, 20.554321, -1.1, -31.602497)
-[node name="ground_010_001" parent="Level" unique_id=404466587 instance=ExtResource("3_t8vhl")]
-transform = Transform3D(0.45, 0, 0, 0, 1, 0, 0, 0, 0.8, 28.294678, 0.20026417, -4.000801)
-
[node name="ground_008_004" parent="Level" unique_id=975238962 instance=ExtResource("4_wbrnf")]
transform = Transform3D(-0.45, 0, 3.115315e-07, 0, 1, 0, -1.7523647e-07, 0, -0.8, -7.1738434, 0.20026417, 30.275806)
[node name="ground_011_003" parent="Level" unique_id=524529247 instance=ExtResource("5_rhwtn")]
transform = Transform3D(0.45, 0, 0, 0, 0.9, 0, 0, 0, 0.8, 28.010208, 0.20026417, 29.138395)
+[node name="ground_011_004" parent="Level" unique_id=563707019 instance=ExtResource("5_rhwtn")]
+transform = Transform3D(0.45, 0, 0, 0, 0.9, 0, 0, 0, 0.8, 27.488281, 0.20026417, -3.2764406)
+
[node name="ground_017_014" parent="Level" unique_id=726155084 instance=ExtResource("6_3bdhk")]
transform = Transform3D(-0.43464974, 0, -1.1494302, 0, 1, 0, 1.1494302, 0, -0.43464974, 29.382858, -1.1757813, -0.07070279)
@@ -346,9 +353,6 @@ transform = Transform3D(1.9470717e-07, 0, -0.99999994, 0, 1, 0, 0.99999994, 0, 1
[node name="tractor_004_002" parent="Level" unique_id=501002737 instance=ExtResource("40_ckas0")]
transform = Transform3D(0.9348669, 0, 0.3549982, 0, 1, 0, -0.3549982, 0, 0.9348669, 29.917847, 0.33919105, -24.772142)
-[node name="car_003_001" parent="Level" unique_id=1328810145 instance=ExtResource("41_fwpte")]
-transform = Transform3D(-1, 0, -3.8941437e-07, 0, 1, 0, 3.8941437e-07, 0, -1, 52.368347, 0.48251343, -14.380997)
-
[node name="truck_003_005" parent="Level" unique_id=444048277 instance=ExtResource("42_dbth4")]
transform = Transform3D(0.999992, 0, -0.0039759804, 0, 1, 0, 0.0039759804, 0, 0.999992, -31.17688, 0.42419434, -30.661972)
@@ -984,35 +988,34 @@ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 3, 0, -13)
[node name="Camera" type="Camera3D" parent="." unique_id=863952848 node_paths=PackedStringArray("target")]
physics_interpolation_mode = 2
-transform = Transform3D(0.70710677, -0.5416752, 0.45451948, 0, 0.64278764, 0.76604444, -0.70710677, -0.5416752, 0.45451948, 16.31182, 13.256711, 7.2723117)
+transform = Transform3D(0.70710677, -0.5416752, 0.45451948, 0, 0.64278764, 0.76604444, -0.70710677, -0.5416752, 0.45451948, 10.272312, 13.256711, -5.7276883)
current = true
fov = 40.0
script = ExtResource("2_camera")
target = NodePath("../Player")
-[node name="Campaign" type="Node" parent="."]
+[node name="Campaign" type="Node" parent="." unique_id=1700964328]
script = ExtResource("100_campaign")
-[node name="CampaignDebug" type="CanvasLayer" parent="." node_paths=PackedStringArray("campaign")]
+[node name="CampaignDebug" type="CanvasLayer" parent="." unique_id=1369688369 node_paths=PackedStringArray("campaign", "sim")]
script = ExtResource("101_campaign_debug")
campaign = NodePath("../Campaign")
+sim = NodePath("../FarmSim")
-[node name="Zones" type="Node3D" parent="."]
+[node name="Zones" type="Node3D" parent="." unique_id=2101147225]
script = ExtResource("200_farm_zones")
-playable = Rect2(-13, -45, 60, 60)
-[node name="CropField" type="Node3D" parent="Zones"]
+[node name="CropField" type="Node3D" parent="Zones" unique_id=1332218493]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 30, 0, -3.6)
script = ExtResource("201_farm_zone")
-kind = 0
display_name = "Crop Field"
size = Vector2(32, 30)
tint = Color(0.95, 0.8, 0.2, 1)
-[node name="Plot1" type="Node3D" parent="Zones/CropField"]
+[node name="Plot1" type="Node3D" parent="Zones/CropField" unique_id=846071431]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -7.345706, 0, -8.45)
-[node name="Unit01" type="Node3D" parent="Zones/CropField/Plot1"]
+[node name="Unit01" type="Node3D" parent="Zones/CropField/Plot1" unique_id=438446798]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -6.07034, 0, 0.084016)
script = ExtResource("202_crop_unit")
unit_id = 1
@@ -1054,7 +1057,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_115" parent="Zones/CropField/Plot1/Unit01" unique_id=1206525691 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.08931, 0.535209, 3.400703)
-[node name="Unit02" type="Node3D" parent="Zones/CropField/Plot1"]
+[node name="Unit02" type="Node3D" parent="Zones/CropField/Plot1" unique_id=1695647054]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2.884898, 0, 0.177054)
script = ExtResource("202_crop_unit")
unit_id = 2
@@ -1093,7 +1096,7 @@ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.097429, 0.288354, 2.487404
[node name="plant_008_095" parent="Zones/CropField/Plot1/Unit02" unique_id=1718469635 instance=ExtResource("27_hirfa")]
transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828, 0.08119, 0.288354, 3.020717)
-[node name="Unit03" type="Node3D" parent="Zones/CropField/Plot1"]
+[node name="Unit03" type="Node3D" parent="Zones/CropField/Plot1" unique_id=683350275]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.07034, 0, 0.084016)
script = ExtResource("202_crop_unit")
unit_id = 3
@@ -1135,7 +1138,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_135" parent="Zones/CropField/Plot1/Unit03" unique_id=1938535413 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.08931, 0.288354, 3.400703)
-[node name="Unit04" type="Node3D" parent="Zones/CropField/Plot1"]
+[node name="Unit04" type="Node3D" parent="Zones/CropField/Plot1" unique_id=899956326]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 3.115102, 0, 0.177054)
script = ExtResource("202_crop_unit")
unit_id = 4
@@ -1174,7 +1177,7 @@ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.097429, 0.288354, 2.487404
[node name="plant_008_075" parent="Zones/CropField/Plot1/Unit04" unique_id=1834675376 instance=ExtResource("27_hirfa")]
transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828, 0.08119, 0.288354, 3.020717)
-[node name="Unit05" type="Node3D" parent="Zones/CropField/Plot1"]
+[node name="Unit05" type="Node3D" parent="Zones/CropField/Plot1" unique_id=1973523503]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 5.92966, 0, 0.084016)
script = ExtResource("202_crop_unit")
unit_id = 5
@@ -1216,10 +1219,10 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_155" parent="Zones/CropField/Plot1/Unit05" unique_id=1101294147 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.08931, 0.288354, 3.400703)
-[node name="Plot2" type="Node3D" parent="Zones/CropField"]
+[node name="Plot2" type="Node3D" parent="Zones/CropField" unique_id=935980584]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 7.691314, 0, -8.45)
-[node name="Unit06" type="Node3D" parent="Zones/CropField/Plot2"]
+[node name="Unit06" type="Node3D" parent="Zones/CropField/Plot2" unique_id=1908616481]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -5.921918, 0, 0.177054)
script = ExtResource("202_crop_unit")
unit_id = 6
@@ -1258,7 +1261,7 @@ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.097429, 0.288354, 2.487404
[node name="plant_008_055" parent="Zones/CropField/Plot2/Unit06" unique_id=855411460 instance=ExtResource("27_hirfa")]
transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828, 0.08119, 0.288354, 3.020717)
-[node name="Unit07" type="Node3D" parent="Zones/CropField/Plot2"]
+[node name="Unit07" type="Node3D" parent="Zones/CropField/Plot2" unique_id=2121819161]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -3.10736, 0, 0.084016)
script = ExtResource("202_crop_unit")
unit_id = 7
@@ -1300,7 +1303,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_175" parent="Zones/CropField/Plot2/Unit07" unique_id=554231931 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.08931, 0.288354, 3.400703)
-[node name="Unit08" type="Node3D" parent="Zones/CropField/Plot2"]
+[node name="Unit08" type="Node3D" parent="Zones/CropField/Plot2" unique_id=2058676943]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.078079, 0, 0.177054)
script = ExtResource("202_crop_unit")
unit_id = 8
@@ -1339,7 +1342,7 @@ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.097432, 0.288354, 2.487404
[node name="plant_008_035" parent="Zones/CropField/Plot2/Unit08" unique_id=163411748 instance=ExtResource("27_hirfa")]
transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828, 0.081194, 0.288354, 3.020717)
-[node name="Unit09" type="Node3D" parent="Zones/CropField/Plot2"]
+[node name="Unit09" type="Node3D" parent="Zones/CropField/Plot2" unique_id=1515144739]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2.89264, 0, 0.084016)
script = ExtResource("202_crop_unit")
unit_id = 9
@@ -1381,7 +1384,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_195" parent="Zones/CropField/Plot2/Unit09" unique_id=693535929 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.08931, 0.288354, 3.400703)
-[node name="Unit10" type="Node3D" parent="Zones/CropField/Plot2"]
+[node name="Unit10" type="Node3D" parent="Zones/CropField/Plot2" unique_id=2127309879]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 6.078079, 0, 0.177054)
script = ExtResource("202_crop_unit")
unit_id = 10
@@ -1420,10 +1423,10 @@ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.097432, 0.288354, 2.487404
[node name="plant_008_015" parent="Zones/CropField/Plot2/Unit10" unique_id=1499305029 instance=ExtResource("27_hirfa")]
transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828, 0.081194, 0.288354, 3.020717)
-[node name="Plot3" type="Node3D" parent="Zones/CropField"]
+[node name="Plot3" type="Node3D" parent="Zones/CropField" unique_id=230755483]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -7.346084, 0, 0.55)
-[node name="Unit11" type="Node3D" parent="Zones/CropField/Plot3"]
+[node name="Unit11" type="Node3D" parent="Zones/CropField/Plot3" unique_id=1470093137]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -6.078081, 0, -0.049657)
script = ExtResource("202_crop_unit")
unit_id = 11
@@ -1462,7 +1465,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_108" parent="Zones/CropField/Plot3/Unit11" unique_id=2011530485 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.081191, 0.535209, 3.091548)
-[node name="Unit12" type="Node3D" parent="Zones/CropField/Plot3"]
+[node name="Unit12" type="Node3D" parent="Zones/CropField/Plot3" unique_id=1722790726]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2.892639, 0, 0.04338)
script = ExtResource("202_crop_unit")
unit_id = 12
@@ -1504,7 +1507,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_088" parent="Zones/CropField/Plot3/Unit12" unique_id=37602738 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.089309, 0.288354, 3.400703)
-[node name="Unit13" type="Node3D" parent="Zones/CropField/Plot3"]
+[node name="Unit13" type="Node3D" parent="Zones/CropField/Plot3" unique_id=567390927]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.078081, 0, -0.049657)
script = ExtResource("202_crop_unit")
unit_id = 13
@@ -1543,7 +1546,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_128" parent="Zones/CropField/Plot3/Unit13" unique_id=1609296466 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.081191, 0.288354, 3.091548)
-[node name="Unit14" type="Node3D" parent="Zones/CropField/Plot3"]
+[node name="Unit14" type="Node3D" parent="Zones/CropField/Plot3" unique_id=691278757]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 3.107361, 0, 0.04338)
script = ExtResource("202_crop_unit")
unit_id = 14
@@ -1585,7 +1588,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_068" parent="Zones/CropField/Plot3/Unit14" unique_id=167402520 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.089309, 0.288354, 3.400703)
-[node name="Unit15" type="Node3D" parent="Zones/CropField/Plot3"]
+[node name="Unit15" type="Node3D" parent="Zones/CropField/Plot3" unique_id=1377259880]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 5.921919, 0, -0.049657)
script = ExtResource("202_crop_unit")
unit_id = 15
@@ -1624,10 +1627,10 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_148" parent="Zones/CropField/Plot3/Unit15" unique_id=1501033159 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.081191, 0.288354, 3.091548)
-[node name="Plot4" type="Node3D" parent="Zones/CropField"]
+[node name="Plot4" type="Node3D" parent="Zones/CropField" unique_id=129578352]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 7.690935, 0, 0.55)
-[node name="Unit16" type="Node3D" parent="Zones/CropField/Plot4"]
+[node name="Unit16" type="Node3D" parent="Zones/CropField/Plot4" unique_id=1810458941]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -5.929659, 0, 0.04338)
script = ExtResource("202_crop_unit")
unit_id = 16
@@ -1669,7 +1672,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_048" parent="Zones/CropField/Plot4/Unit16" unique_id=141077577 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.089309, 0.288354, 3.400703)
-[node name="Unit17" type="Node3D" parent="Zones/CropField/Plot4"]
+[node name="Unit17" type="Node3D" parent="Zones/CropField/Plot4" unique_id=1997234670]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -3.1151, 0, -0.049657)
script = ExtResource("202_crop_unit")
unit_id = 17
@@ -1708,7 +1711,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_168" parent="Zones/CropField/Plot4/Unit17" unique_id=2113174336 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.081191, 0.288354, 3.091548)
-[node name="Unit18" type="Node3D" parent="Zones/CropField/Plot4"]
+[node name="Unit18" type="Node3D" parent="Zones/CropField/Plot4" unique_id=1419972502]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.070338, 0, 0.04338)
script = ExtResource("202_crop_unit")
unit_id = 18
@@ -1750,7 +1753,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_028" parent="Zones/CropField/Plot4/Unit18" unique_id=2055108374 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.089313, 0.288354, 3.400703)
-[node name="Unit19" type="Node3D" parent="Zones/CropField/Plot4"]
+[node name="Unit19" type="Node3D" parent="Zones/CropField/Plot4" unique_id=1396612137]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2.8849, 0, -0.049657)
script = ExtResource("202_crop_unit")
unit_id = 19
@@ -1789,7 +1792,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_188" parent="Zones/CropField/Plot4/Unit19" unique_id=2099121335 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.081191, 0.288354, 3.091548)
-[node name="Unit20" type="Node3D" parent="Zones/CropField/Plot4"]
+[node name="Unit20" type="Node3D" parent="Zones/CropField/Plot4" unique_id=300550596]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 6.070338, 0, 0.04338)
script = ExtResource("202_crop_unit")
unit_id = 20
@@ -1831,10 +1834,10 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_008" parent="Zones/CropField/Plot4/Unit20" unique_id=1753225118 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.089313, 0.288354, 3.400703)
-[node name="Plot5" type="Node3D" parent="Zones/CropField"]
+[node name="Plot5" type="Node3D" parent="Zones/CropField" unique_id=1290402936]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -7.351865, 0, 9.5)
-[node name="Unit21" type="Node3D" parent="Zones/CropField/Plot5"]
+[node name="Unit21" type="Node3D" parent="Zones/CropField/Plot5" unique_id=29823990]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -6.064181, 0, -0.127795)
script = ExtResource("202_crop_unit")
unit_id = 21
@@ -1876,7 +1879,7 @@ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.08931, 0.535209, 2.776858)
[node name="plant_008_121" parent="Zones/CropField/Plot5/Unit21" unique_id=779125598 instance=ExtResource("27_hirfa")]
transform = Transform3D(-0.328259, 0, 0.944588, 0, 1, 0, -0.944588, 0, -0.328259, 0.08931, 0.288354, 3.46159)
-[node name="Unit22" type="Node3D" parent="Zones/CropField/Plot5"]
+[node name="Unit22" type="Node3D" parent="Zones/CropField/Plot5" unique_id=1659890964]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2.894977, 0, -0.040293)
script = ExtResource("202_crop_unit")
unit_id = 22
@@ -1915,7 +1918,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_081" parent="Zones/CropField/Plot5/Unit22" unique_id=178797609 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.08119, 0.288354, 3.091548)
-[node name="Unit23" type="Node3D" parent="Zones/CropField/Plot5"]
+[node name="Unit23" type="Node3D" parent="Zones/CropField/Plot5" unique_id=1411976054]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.064181, 0, -0.127795)
script = ExtResource("202_crop_unit")
unit_id = 23
@@ -1957,7 +1960,7 @@ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.08931, 0.288354, 2.776858)
[node name="plant_008_142" parent="Zones/CropField/Plot5/Unit23" unique_id=743162416 instance=ExtResource("27_hirfa")]
transform = Transform3D(-0.328259, 0, 0.944588, 0, 1, 0, -0.944588, 0, -0.328259, 0.08931, 0.288354, 3.46159)
-[node name="Unit24" type="Node3D" parent="Zones/CropField/Plot5"]
+[node name="Unit24" type="Node3D" parent="Zones/CropField/Plot5" unique_id=1118002809]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 3.105023, 0, -0.040293)
script = ExtResource("202_crop_unit")
unit_id = 24
@@ -1996,7 +1999,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_061" parent="Zones/CropField/Plot5/Unit24" unique_id=1829629933 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.08119, 0.288354, 3.091548)
-[node name="Unit25" type="Node3D" parent="Zones/CropField/Plot5"]
+[node name="Unit25" type="Node3D" parent="Zones/CropField/Plot5" unique_id=1125647660]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 5.935819, 0, -0.127795)
script = ExtResource("202_crop_unit")
unit_id = 25
@@ -2038,10 +2041,10 @@ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.08931, 0.288354, 2.776858)
[node name="plant_008_163" parent="Zones/CropField/Plot5/Unit25" unique_id=134116940 instance=ExtResource("27_hirfa")]
transform = Transform3D(-0.328259, 0, 0.944588, 0, 1, 0, -0.944588, 0, -0.328259, 0.08931, 0.288354, 3.46159)
-[node name="Plot6" type="Node3D" parent="Zones/CropField"]
+[node name="Plot6" type="Node3D" parent="Zones/CropField" unique_id=159261907]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 7.681912, 0, 9.5)
-[node name="Unit26" type="Node3D" parent="Zones/CropField/Plot6"]
+[node name="Unit26" type="Node3D" parent="Zones/CropField/Plot6" unique_id=1625043588]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -5.928755, 0, -0.040293)
script = ExtResource("202_crop_unit")
unit_id = 26
@@ -2080,7 +2083,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_041" parent="Zones/CropField/Plot6/Unit26" unique_id=2134067814 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.08119, 0.288354, 3.091548)
-[node name="Unit27" type="Node3D" parent="Zones/CropField/Plot6"]
+[node name="Unit27" type="Node3D" parent="Zones/CropField/Plot6" unique_id=1810938346]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -3.097958, 0, -0.127795)
script = ExtResource("202_crop_unit")
unit_id = 27
@@ -2122,7 +2125,7 @@ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.08931, 0.288354, 2.776858)
[node name="plant_008_184" parent="Zones/CropField/Plot6/Unit27" unique_id=826706703 instance=ExtResource("27_hirfa")]
transform = Transform3D(-0.328259, 0, 0.944588, 0, 1, 0, -0.944588, 0, -0.328259, 0.08931, 0.288354, 3.46159)
-[node name="Unit28" type="Node3D" parent="Zones/CropField/Plot6"]
+[node name="Unit28" type="Node3D" parent="Zones/CropField/Plot6" unique_id=358730520]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.071241, 0, -0.040293)
script = ExtResource("202_crop_unit")
unit_id = 28
@@ -2161,7 +2164,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_021" parent="Zones/CropField/Plot6/Unit28" unique_id=1550087423 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.081194, 0.288354, 3.091548)
-[node name="Unit29" type="Node3D" parent="Zones/CropField/Plot6"]
+[node name="Unit29" type="Node3D" parent="Zones/CropField/Plot6" unique_id=959546619]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2.902042, 0, -0.127795)
script = ExtResource("202_crop_unit")
unit_id = 29
@@ -2203,7 +2206,7 @@ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.08931, 0.288354, 2.776858)
[node name="plant_008_205" parent="Zones/CropField/Plot6/Unit29" unique_id=1796951931 instance=ExtResource("27_hirfa")]
transform = Transform3D(-0.328259, 0, 0.944588, 0, 1, 0, -0.944588, 0, -0.328259, 0.08931, 0.288354, 3.46159)
-[node name="Unit30" type="Node3D" parent="Zones/CropField/Plot6"]
+[node name="Unit30" type="Node3D" parent="Zones/CropField/Plot6" unique_id=1953668199]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 6.071241, 0, -0.040293)
script = ExtResource("202_crop_unit")
unit_id = 30
@@ -2242,7 +2245,7 @@ transform = Transform3D(0.261828, 0, 0.965115, 0, 1, 0, -0.965115, 0, 0.261828,
[node name="plant_007_001" parent="Zones/CropField/Plot6/Unit30" unique_id=422270990 instance=ExtResource("26_ydg3k")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.081194, 0.288354, 3.091548)
-[node name="SupplyShed" type="Node3D" parent="Zones"]
+[node name="SupplyShed" type="Node3D" parent="Zones" unique_id=224907067]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, -19)
script = ExtResource("201_farm_zone")
kind = 2
@@ -2250,40 +2253,40 @@ display_name = "Supply Shed"
size = Vector2(14, 10)
tint = Color(0.9, 0.3, 0.25, 1)
-[node name="box_004_1" parent="Zones/SupplyShed" instance=ExtResource("203_box_004")]
+[node name="box_004_1" parent="Zones/SupplyShed" unique_id=1112942794 instance=ExtResource("203_box_004")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 0.5, 0.6)
-[node name="box_004_2" parent="Zones/SupplyShed" instance=ExtResource("203_box_004")]
+[node name="box_004_2" parent="Zones/SupplyShed" unique_id=1865373081 instance=ExtResource("203_box_004")]
transform = Transform3D(0.978148, 0, 0.207912, 0, 1, 0, -0.207912, 0, 0.978148, -5.15, 0.5, 0.8)
-[node name="box_004_3" parent="Zones/SupplyShed" instance=ExtResource("203_box_004")]
+[node name="box_004_3" parent="Zones/SupplyShed" unique_id=1948098606 instance=ExtResource("203_box_004")]
transform = Transform3D(0.766044, 0, 0.642788, 0, 1, 0, -0.642788, 0, 0.766044, -4.5, 1.5, 0.7)
-[node name="bag_001_1" parent="Zones/SupplyShed" instance=ExtResource("204_bag_001")]
+[node name="bag_001_1" parent="Zones/SupplyShed" unique_id=190773379 instance=ExtResource("204_bag_001")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -3, 0, 2)
-[node name="bag_003_1" parent="Zones/SupplyShed" instance=ExtResource("205_bag_003")]
+[node name="bag_003_1" parent="Zones/SupplyShed" unique_id=1571516706 instance=ExtResource("205_bag_003")]
transform = Transform3D(0.642788, 0, 0.766044, 0, 1, 0, -0.766044, 0, 0.642788, -3.7, 0, 2.5)
-[node name="case_001_1" parent="Zones/SupplyShed" instance=ExtResource("206_case_001")]
+[node name="case_001_1" parent="Zones/SupplyShed" unique_id=253384907 instance=ExtResource("206_case_001")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -5.6, 0, 2.8)
-[node name="firewood_010_1" parent="Zones/SupplyShed" instance=ExtResource("207_firewood_010")]
+[node name="firewood_010_1" parent="Zones/SupplyShed" unique_id=258407514 instance=ExtResource("207_firewood_010")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 3.2, 0, 0.6)
-[node name="firewood_010_2" parent="Zones/SupplyShed" instance=ExtResource("207_firewood_010")]
+[node name="firewood_010_2" parent="Zones/SupplyShed" unique_id=955421319 instance=ExtResource("207_firewood_010")]
transform = Transform3D(0.990268, 0, 0.139173, 0, 1, 0, -0.139173, 0, 0.990268, 3.2, 0.35, 0.6)
-[node name="hay_001_1" parent="Zones/SupplyShed" instance=ExtResource("208_hay_001")]
+[node name="hay_001_1" parent="Zones/SupplyShed" unique_id=2114770263 instance=ExtResource("208_hay_001")]
transform = Transform3D(0.939693, 0, 0.34202, 0, 1, 0, -0.34202, 0, 0.939693, 4.9, 0, 1)
-[node name="barrel_001_1" parent="Zones/SupplyShed" instance=ExtResource("209_barrel_001")]
+[node name="barrel_001_1" parent="Zones/SupplyShed" unique_id=1428572823 instance=ExtResource("209_barrel_001")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2.8, 0, 2.4)
-[node name="barrel_010_1" parent="Zones/SupplyShed" instance=ExtResource("210_barrel_010")]
+[node name="barrel_010_1" parent="Zones/SupplyShed" unique_id=306653999 instance=ExtResource("210_barrel_010")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 3.7, 0, 2.9)
-[node name="WorkArea" type="Node3D" parent="Zones"]
+[node name="WorkArea" type="Node3D" parent="Zones" unique_id=1622333960]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 11, 0, -19.5)
script = ExtResource("201_farm_zone")
kind = 3
@@ -2291,19 +2294,22 @@ display_name = "Work Area"
size = Vector2(6, 9)
tint = Color(0.6, 0.4, 0.85, 1)
-[node name="table_001_1" parent="Zones/WorkArea" instance=ExtResource("211_table_001")]
+[node name="Workbench" type="Node3D" parent="Zones/WorkArea" unique_id=1153768229]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -2.5)
+script = ExtResource("109_workbench")
-[node name="chair_001_1" parent="Zones/WorkArea" instance=ExtResource("212_chair_001")]
+[node name="table_001_1" parent="Zones/WorkArea/Workbench" unique_id=994088681 instance=ExtResource("211_table_001")]
+
+[node name="chair_001_1" parent="Zones/WorkArea" unique_id=1265146992 instance=ExtResource("212_chair_001")]
transform = Transform3D(-1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, -1.6)
-[node name="table_002_1" parent="Zones/WorkArea" instance=ExtResource("213_table_002")]
+[node name="table_002_1" parent="Zones/WorkArea" unique_id=1315992584 instance=ExtResource("213_table_002")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 1.8, 0, 1.3)
-[node name="bucket_001_1" parent="Zones/WorkArea" instance=ExtResource("214_bucket_001")]
+[node name="bucket_001_1" parent="Zones/WorkArea" unique_id=1895776257 instance=ExtResource("214_bucket_001")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1.3, 0, -2.8)
-[node name="AnimalPen" type="Node3D" parent="Zones"]
+[node name="AnimalPen" type="Node3D" parent="Zones" unique_id=1301701174]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -3, 0, -6)
script = ExtResource("201_farm_zone")
kind = 1
@@ -2311,109 +2317,106 @@ display_name = "Animal Pen"
size = Vector2(14, 10)
tint = Color(0.85, 0.55, 0.3, 1)
-[node name="fence_024_1" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_1" parent="Zones/AnimalPen" unique_id=1446580389 instance=ExtResource("215_fence_024")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -6, 0, -5)
-[node name="fence_024_2" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_2" parent="Zones/AnimalPen" unique_id=1858327670 instance=ExtResource("215_fence_024")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -6, 0, 5)
-[node name="fence_024_3" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_3" parent="Zones/AnimalPen" unique_id=1072155173 instance=ExtResource("215_fence_024")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 0, -5)
-[node name="fence_024_4" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_4" parent="Zones/AnimalPen" unique_id=2082000001 instance=ExtResource("215_fence_024")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 0, 5)
-[node name="fence_024_5" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_5" parent="Zones/AnimalPen" unique_id=1226141495 instance=ExtResource("215_fence_024")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0, -5)
-[node name="fence_024_6" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_6" parent="Zones/AnimalPen" unique_id=1100914280 instance=ExtResource("215_fence_024")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0, 5)
-[node name="fence_024_7" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_7" parent="Zones/AnimalPen" unique_id=13821588 instance=ExtResource("215_fence_024")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -5)
-[node name="fence_024_8" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_8" parent="Zones/AnimalPen" unique_id=1576318148 instance=ExtResource("215_fence_024")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 5)
-[node name="fence_024_9" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_9" parent="Zones/AnimalPen" unique_id=625414246 instance=ExtResource("215_fence_024")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0, -5)
-[node name="fence_024_10" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_10" parent="Zones/AnimalPen" unique_id=638219621 instance=ExtResource("215_fence_024")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0, 5)
-[node name="fence_024_11" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_11" parent="Zones/AnimalPen" unique_id=1078283597 instance=ExtResource("215_fence_024")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 0, -5)
-[node name="fence_024_12" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_12" parent="Zones/AnimalPen" unique_id=961024064 instance=ExtResource("215_fence_024")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 0, 5)
-[node name="fence_024_13" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_13" parent="Zones/AnimalPen" unique_id=796402607 instance=ExtResource("215_fence_024")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 6, 0, -5)
-[node name="fence_024_14" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_14" parent="Zones/AnimalPen" unique_id=2086364847 instance=ExtResource("215_fence_024")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 6, 0, 5)
-[node name="fence_024_15" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_15" parent="Zones/AnimalPen" unique_id=2064386247 instance=ExtResource("215_fence_024")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -7, 0, -4)
-[node name="fence_024_16" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_16" parent="Zones/AnimalPen" unique_id=349303733 instance=ExtResource("215_fence_024")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 7, 0, -4)
-[node name="fence_024_17" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_17" parent="Zones/AnimalPen" unique_id=164449478 instance=ExtResource("215_fence_024")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -7, 0, -2)
-[node name="fence_024_18" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_18" parent="Zones/AnimalPen" unique_id=1944845284 instance=ExtResource("215_fence_024")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 7, 0, -2)
-[node name="fence_024_19" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_19" parent="Zones/AnimalPen" unique_id=909623837 instance=ExtResource("215_fence_024")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -7, 0, 0)
-[node name="fence_024_20" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_20" parent="Zones/AnimalPen" unique_id=631815421 instance=ExtResource("215_fence_024")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -7, 0, 2)
-[node name="fence_024_21" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_21" parent="Zones/AnimalPen" unique_id=709037316 instance=ExtResource("215_fence_024")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 7, 0, 2)
-[node name="fence_024_22" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_22" parent="Zones/AnimalPen" unique_id=1495963615 instance=ExtResource("215_fence_024")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -7, 0, 4)
-[node name="fence_024_23" parent="Zones/AnimalPen" instance=ExtResource("215_fence_024")]
+[node name="fence_024_23" parent="Zones/AnimalPen" unique_id=753148669 instance=ExtResource("215_fence_024")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 7, 0, 4)
-[node name="fence_018_1" parent="Zones/AnimalPen" instance=ExtResource("216_fence_018")]
-transform = Transform3D(0.843391, 0, 0.5373, 0, 1, 0, -0.5373, 0, 0.843391, 7, 0, -1)
-
-[node name="coop_002_1" parent="Zones/AnimalPen" instance=ExtResource("217_coop_002")]
+[node name="coop_002_1" parent="Zones/AnimalPen" unique_id=1811355265 instance=ExtResource("217_coop_002")]
transform = Transform3D(-1, 0, 0, 0, 1, 0, 0, 0, -1, -5.3, 0, -3.4)
-[node name="bucket_001_1" parent="Zones/AnimalPen" instance=ExtResource("214_bucket_001")]
+[node name="bucket_001_1" parent="Zones/AnimalPen" unique_id=469656349 instance=ExtResource("214_bucket_001")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 5.6, 0, -3.8)
-[node name="chicken_001_1" parent="Zones/AnimalPen" instance=ExtResource("218_chicken_001")]
+[node name="chicken_001_1" parent="Zones/AnimalPen" unique_id=1659396666 instance=ExtResource("218_chicken_001")]
transform = Transform3D(0.866025, 0, 0.5, 0, 1, 0, -0.5, 0, 0.866025, -3.4, 0, -2.6)
-[node name="chicken_003_1" parent="Zones/AnimalPen" instance=ExtResource("219_chicken_003")]
+[node name="chicken_003_1" parent="Zones/AnimalPen" unique_id=1833058849 instance=ExtResource("219_chicken_003")]
transform = Transform3D(0.5, 0, -0.866025, 0, 1, 0, 0.866025, 0, 0.5, -4.3, 0, -1.2)
-[node name="chicken_001_2" parent="Zones/AnimalPen" instance=ExtResource("218_chicken_001")]
+[node name="chicken_001_2" parent="Zones/AnimalPen" unique_id=2108487036 instance=ExtResource("218_chicken_001")]
transform = Transform3D(-0.866025, 0, 0.5, 0, 1, 0, -0.5, 0, -0.866025, -2.4, 0, -3.7)
-[node name="chicken_003_2" parent="Zones/AnimalPen" instance=ExtResource("219_chicken_003")]
+[node name="chicken_003_2" parent="Zones/AnimalPen" unique_id=1156792561 instance=ExtResource("219_chicken_003")]
transform = Transform3D(-0.087156, 0, 0.996195, 0, 1, 0, -0.996195, 0, -0.087156, -5.2, 0, 0)
-[node name="pig_001_1" parent="Zones/AnimalPen" instance=ExtResource("220_pig_001")]
+[node name="pig_001_1" parent="Zones/AnimalPen" unique_id=2083549518 instance=ExtResource("220_pig_001")]
transform = Transform3D(0.34202, 0, 0.939693, 0, 1, 0, -0.939693, 0, 0.34202, 1.4, 0, -3.4)
-[node name="pig_002_1" parent="Zones/AnimalPen" instance=ExtResource("221_pig_002")]
+[node name="pig_002_1" parent="Zones/AnimalPen" unique_id=334475536 instance=ExtResource("221_pig_002")]
transform = Transform3D(-0.5, 0, -0.866025, 0, 1, 0, 0.866025, 0, -0.5, 4, 0, -1.4)
-[node name="sheep_001_1" parent="Zones/AnimalPen" instance=ExtResource("222_sheep_001")]
+[node name="sheep_001_1" parent="Zones/AnimalPen" unique_id=1531276024 instance=ExtResource("222_sheep_001")]
transform = Transform3D(0.939693, 0, 0.34202, 0, 1, 0, -0.34202, 0, 0.939693, -0.2, 0, 2.6)
-[node name="sheep_002_1" parent="Zones/AnimalPen" instance=ExtResource("223_sheep_002")]
+[node name="sheep_002_1" parent="Zones/AnimalPen" unique_id=872389713 instance=ExtResource("223_sheep_002")]
transform = Transform3D(-0.939693, 0, -0.34202, 0, 1, 0, 0.34202, 0, -0.939693, 4.2, 0, 3)
-[node name="Wood" type="Node3D" parent="Zones"]
+[node name="Wood" type="Node3D" parent="Zones" unique_id=971465957]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 42, 0, -28)
script = ExtResource("201_farm_zone")
kind = 4
@@ -2421,28 +2424,50 @@ display_name = "Woodlot"
size = Vector2(9, 14)
tint = Color(0.45, 0.7, 0.3, 1)
-[node name="dry_wood_008_1" parent="Zones/Wood" instance=ExtResource("224_dry_wood_008")]
+[node name="DeadTree" type="Node3D" parent="Zones/Wood" unique_id=422609298]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -1.6, 0, 1.2)
+script = ExtResource("108_gather")
+reach = 1.9
+clip = &"Chopping"
-[node name="dry_wood_011_1" parent="Zones/Wood" instance=ExtResource("225_dry_wood_011")]
-transform = Transform3D(0.766044, 0, 0.642788, 0, 1, 0, -0.642788, 0, 0.766044, 2.6, 0, 3.8)
+[node name="dry_wood_008_1" parent="Zones/Wood/DeadTree" unique_id=100253733 instance=ExtResource("224_dry_wood_008")]
-[node name="dry_wood_004_1" parent="Zones/Wood" instance=ExtResource("226_dry_wood_004")]
-transform = Transform3D(0.866025, 0, -0.5, 0, 1, 0, 0.5, 0, 0.866025, 2.4, 0, -5.4)
+[node name="Snag" type="Node3D" parent="Zones/Wood" unique_id=482679739]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2.6, 0, 3.8)
+script = ExtResource("108_gather")
+reach = 1.9
+clip = &"Chopping"
-[node name="dry_wood_001_1" parent="Zones/Wood" instance=ExtResource("227_dry_wood_001")]
+[node name="dry_wood_011_1" parent="Zones/Wood/Snag" unique_id=727967448 instance=ExtResource("225_dry_wood_011")]
+transform = Transform3D(0.766044, 0, 0.642788, 0, 1, 0, -0.642788, 0, 0.766044, 0, 0, 0)
+
+[node name="Deadfall" type="Node3D" parent="Zones/Wood" unique_id=946840482]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2.4, 0, -5.4)
+script = ExtResource("108_gather")
+max_charges = 3
+reach = 2.6
+clip = &"Chopping"
+
+[node name="dry_wood_004_1" parent="Zones/Wood/Deadfall" unique_id=1521850624 instance=ExtResource("226_dry_wood_004")]
+transform = Transform3D(0.866025, 0, -0.5, 0, 1, 0, 0.5, 0, 0.866025, 0, 0, 0)
+
+[node name="dry_wood_001_1" parent="Zones/Wood" unique_id=2086357088 instance=ExtResource("227_dry_wood_001")]
transform = Transform3D(0.34202, 0, 0.939693, 0, 1, 0, -0.939693, 0, 0.34202, -2.2, 0, -5.6)
-[node name="firewood_013_1" parent="Zones/Wood" instance=ExtResource("228_firewood_013")]
+[node name="LogPile" type="Node3D" parent="Zones/Wood" unique_id=721885307]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.6, 0, 3.4)
+script = ExtResource("108_gather")
+reach = 1.7
-[node name="firewood_010_1" parent="Zones/Wood" instance=ExtResource("207_firewood_010")]
+[node name="firewood_013_1" parent="Zones/Wood/LogPile" unique_id=2072175599 instance=ExtResource("228_firewood_013")]
+
+[node name="firewood_010_1" parent="Zones/Wood" unique_id=1569528285 instance=ExtResource("207_firewood_010")]
transform = Transform3D(0.939693, 0, 0.34202, 0, 1, 0, -0.34202, 0, 0.939693, -2.4, 0, -1.8)
-[node name="firewood_010_2" parent="Zones/Wood" instance=ExtResource("207_firewood_010")]
+[node name="firewood_010_2" parent="Zones/Wood" unique_id=270901432 instance=ExtResource("207_firewood_010")]
transform = Transform3D(0.866025, 0, -0.5, 0, 1, 0, 0.5, 0, 0.866025, 1, 0, 1.2)
-[node name="Scrap" type="Node3D" parent="Zones"]
+[node name="Scrap" type="Node3D" parent="Zones" unique_id=1744086940]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 31, 0, -38.5)
script = ExtResource("201_farm_zone")
kind = 5
@@ -2450,31 +2475,58 @@ display_name = "Scrap Heap"
size = Vector2(11, 11)
tint = Color(0.55, 0.65, 0.8, 1)
-[node name="car_001_1" parent="Zones/Scrap" instance=ExtResource("229_car_001")]
-transform = Transform3D(0.258819, 0, 0.965926, 0, 1, 0, -0.965926, 0, 0.258819, -2.6, 0, -2.1)
+[node name="Wreck" type="Node3D" parent="Zones/Scrap" unique_id=1452606636]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2.6, 0, -2.1)
+script = ExtResource("108_gather")
+material = "scrap"
+max_charges = 3
+reach = 2.8
+clip = &"Hammering"
-[node name="lawn_mower_001_1" parent="Zones/Scrap" instance=ExtResource("230_lawn_mower_001")]
-transform = Transform3D(0.766044, 0, -0.642788, 0, 1, 0, 0.642788, 0, 0.766044, 1.2, 0, 2.5)
+[node name="car_001_1" parent="Zones/Scrap/Wreck" unique_id=541636159 instance=ExtResource("229_car_001")]
+transform = Transform3D(0.258819, 0, 0.965926, 0, 1, 0, -0.965926, 0, 0.258819, 0, 0, 0)
-[node name="cart_003_1" parent="Zones/Scrap" instance=ExtResource("231_cart_003")]
+[node name="Mower" type="Node3D" parent="Zones/Scrap" unique_id=179874598]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1.2, 0, 2.5)
+script = ExtResource("108_gather")
+material = "scrap"
+reach = 1.7
+
+[node name="lawn_mower_001_1" parent="Zones/Scrap/Mower" unique_id=668863717 instance=ExtResource("230_lawn_mower_001")]
+transform = Transform3D(0.766044, 0, -0.642788, 0, 1, 0, 0.642788, 0, 0.766044, 0, 0, 0)
+
+[node name="cart_003_1" parent="Zones/Scrap" unique_id=177558842 instance=ExtResource("231_cart_003")]
transform = Transform3D(-0.5, 0, 0.866025, 0, 1, 0, -0.866025, 0, -0.5, -0.4, 0, 3.5)
-[node name="dray_001_1" parent="Zones/Scrap" instance=ExtResource("232_dray_001")]
-transform = Transform3D(0.984808, 0, 0.173648, 0, 1, 0, -0.173648, 0, 0.984808, 3, 0, -0.9)
+[node name="Wagon" type="Node3D" parent="Zones/Scrap" unique_id=1010270729]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 3, 0, -0.9)
+script = ExtResource("108_gather")
+material = "scrap"
+reach = 2.6
+clip = &"Hammering"
-[node name="barrel_005_1" parent="Zones/Scrap" instance=ExtResource("233_barrel_005")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4.2, 0, 2.1)
+[node name="dray_001_1" parent="Zones/Scrap/Wagon" unique_id=2075460044 instance=ExtResource("232_dray_001")]
+transform = Transform3D(0.984808, 0, 0.173648, 0, 1, 0, -0.173648, 0, 0.984808, 0, 0, 0)
-[node name="barrel_010_1" parent="Zones/Scrap" instance=ExtResource("210_barrel_010")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -3.4, 0, 2.8)
+[node name="OldBarrels" type="Node3D" parent="Zones/Scrap" unique_id=1935107100]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -3.8, 0, 2.45)
+script = ExtResource("108_gather")
+material = "scrap"
+reach = 1.9
-[node name="barrel_001_1" parent="Zones/Scrap" instance=ExtResource("209_barrel_001")]
+[node name="barrel_005_1" parent="Zones/Scrap/OldBarrels" unique_id=348306933 instance=ExtResource("233_barrel_005")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.4, 0, -0.35)
+
+[node name="barrel_010_1" parent="Zones/Scrap/OldBarrels" unique_id=298148691 instance=ExtResource("210_barrel_010")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.4, 0, 0.35)
+
+[node name="barrel_001_1" parent="Zones/Scrap" unique_id=1179019893 instance=ExtResource("209_barrel_001")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1.6, 0, -3.8)
-[node name="case_001_1" parent="Zones/Scrap" instance=ExtResource("206_case_001")]
+[node name="case_001_1" parent="Zones/Scrap" unique_id=1030509790 instance=ExtResource("206_case_001")]
transform = Transform3D(0.866025, 0, 0.5, 0, 1, 0, -0.5, 0, 0.866025, -1, 0, -4.3)
-[node name="Straw" type="Node3D" parent="Zones"]
+[node name="Straw" type="Node3D" parent="Zones" unique_id=374842873]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 18, 0, -39.5)
script = ExtResource("201_farm_zone")
kind = 6
@@ -2482,447 +2534,607 @@ display_name = "Haystacks"
size = Vector2(8, 9)
tint = Color(1, 0.95, 0.5, 1)
-[node name="hay_002_262" parent="Zones/Straw" unique_id=1884353408 instance=ExtResource("57_u2sqs")]
+[node name="Haystack" type="Node3D" parent="Zones/Straw" unique_id=611054724]
+script = ExtResource("108_gather")
+material = "straw"
+max_charges = 4
+reach = 3
+
+[node name="hay_002_262" parent="Zones/Straw/Haystack" unique_id=1884353408 instance=ExtResource("57_u2sqs")]
transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, -1.40509, -0.027496, 1.26233)
-[node name="hay_002_263" parent="Zones/Straw" unique_id=11950323 instance=ExtResource("57_u2sqs")]
+[node name="hay_002_263" parent="Zones/Straw/Haystack" unique_id=11950323 instance=ExtResource("57_u2sqs")]
transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, -0.148148, -0.027496, 1.26233)
-[node name="hay_002_264" parent="Zones/Straw" unique_id=566957480 instance=ExtResource("57_u2sqs")]
+[node name="hay_002_264" parent="Zones/Straw/Haystack" unique_id=566957480 instance=ExtResource("57_u2sqs")]
transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, 1.092255, -0.027496, 1.26233)
-[node name="hay_002_265" parent="Zones/Straw" unique_id=1139079336 instance=ExtResource("57_u2sqs")]
+[node name="hay_002_265" parent="Zones/Straw/Haystack" unique_id=1139079336 instance=ExtResource("57_u2sqs")]
transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, -1.40509, -0.027496, -1.279768)
-[node name="hay_002_266" parent="Zones/Straw" unique_id=1416074219 instance=ExtResource("57_u2sqs")]
+[node name="hay_002_266" parent="Zones/Straw/Haystack" unique_id=1416074219 instance=ExtResource("57_u2sqs")]
transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, -0.148148, -0.027496, -1.279768)
-[node name="hay_002_267" parent="Zones/Straw" unique_id=326184429 instance=ExtResource("57_u2sqs")]
+[node name="hay_002_267" parent="Zones/Straw/Haystack" unique_id=326184429 instance=ExtResource("57_u2sqs")]
transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, 1.092255, -0.027496, -1.279768)
-[node name="hay_002_268" parent="Zones/Straw" unique_id=1696929929 instance=ExtResource("57_u2sqs")]
+[node name="hay_002_268" parent="Zones/Straw/Haystack" unique_id=1696929929 instance=ExtResource("57_u2sqs")]
transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, -1.40509, 0.930816, 1.26233)
-[node name="hay_002_269" parent="Zones/Straw" unique_id=1044273134 instance=ExtResource("57_u2sqs")]
+[node name="hay_002_269" parent="Zones/Straw/Haystack" unique_id=1044273134 instance=ExtResource("57_u2sqs")]
transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, -1.40509, 0.930816, -1.279768)
-[node name="hay_002_270" parent="Zones/Straw" unique_id=1044398015 instance=ExtResource("57_u2sqs")]
+[node name="hay_002_270" parent="Zones/Straw/Haystack" unique_id=1044398015 instance=ExtResource("57_u2sqs")]
transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, -1.40509, 0.930816, 1.26233)
-[node name="hay_002_271" parent="Zones/Straw" unique_id=1326779889 instance=ExtResource("57_u2sqs")]
+[node name="hay_002_271" parent="Zones/Straw/Haystack" unique_id=1326779889 instance=ExtResource("57_u2sqs")]
transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, -1.40509, 0.930816, -1.279768)
-[node name="hay_002_272" parent="Zones/Straw" unique_id=679926451 instance=ExtResource("57_u2sqs")]
+[node name="hay_002_272" parent="Zones/Straw/Haystack" unique_id=679926451 instance=ExtResource("57_u2sqs")]
transform = Transform3D(-0.215817, 0, -0.976434, 0, 1, 0, 0.976434, 0, -0.215817, -0.029877, 0.930816, -0.071577)
-[node name="hay_002_273" parent="Zones/Straw" unique_id=556781931 instance=ExtResource("57_u2sqs")]
+[node name="hay_002_273" parent="Zones/Straw/Haystack" unique_id=556781931 instance=ExtResource("57_u2sqs")]
transform = Transform3D(0.413577, 0, -0.910469, 0, 1, 0, 0.910469, 0, 0.413577, 2.715729, -0.027496, -1.772405)
-[node name="hay_001_1" parent="Zones/Straw" instance=ExtResource("208_hay_001")]
+[node name="BaleA" type="Node3D" parent="Zones/Straw" unique_id=1509328548]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2.8, 0, 3.1)
+script = ExtResource("108_gather")
+material = "straw"
+reach = 1.9
-[node name="hay_001_2" parent="Zones/Straw" instance=ExtResource("208_hay_001")]
-transform = Transform3D(0.866025, 0, 0.5, 0, 1, 0, -0.5, 0, 0.866025, 3, 0, 2.7)
+[node name="hay_001_1" parent="Zones/Straw/BaleA" unique_id=894641795 instance=ExtResource("208_hay_001")]
-[node name="hay_001_3" parent="Zones/Straw" instance=ExtResource("208_hay_001")]
-transform = Transform3D(0.965926, 0, -0.258819, 0, 1, 0, 0.258819, 0, 0.965926, -2.4, 0, -3.1)
+[node name="BaleB" type="Node3D" parent="Zones/Straw" unique_id=331032365]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 3, 0, 2.7)
+script = ExtResource("108_gather")
+material = "straw"
+reach = 1.9
-[node name="Perimeter" type="Node3D" parent="Zones"]
+[node name="hay_001_2" parent="Zones/Straw/BaleB" unique_id=1901914839 instance=ExtResource("208_hay_001")]
+transform = Transform3D(0.866025, 0, 0.5, 0, 1, 0, -0.5, 0, 0.866025, 0, 0, 0)
-[node name="Fence" type="Node3D" parent="Zones/Perimeter"]
+[node name="BaleC" type="Node3D" parent="Zones/Straw" unique_id=476642620]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2.4, 0, -3.1)
+script = ExtResource("108_gather")
+material = "straw"
+reach = 1.9
-[node name="fence_005_001" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="hay_001_3" parent="Zones/Straw/BaleC" unique_id=1302102301 instance=ExtResource("208_hay_001")]
+transform = Transform3D(0.965926, 0, -0.258819, 0, 1, 0, 0.258819, 0, 0.965926, 0, 0, 0)
+
+[node name="NorthGrove" type="Node3D" parent="Zones" unique_id=1119171604]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 12, 0, -52)
+script = ExtResource("201_farm_zone")
+kind = 4
+display_name = "North Grove (outside the fence)"
+size = Vector2(16, 12)
+tint = Color(0.45, 0.7, 0.3, 1)
+outside = true
+
+[node name="GroveDeadTree" type="Node3D" parent="Zones/NorthGrove" unique_id=1245870363]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.5, 0, 2.5)
+script = ExtResource("108_gather")
+max_charges = 3
+yield_amount = 3
+reach = 1.9
+clip = &"Chopping"
+
+[node name="dry_wood_008_g1" parent="Zones/NorthGrove/GroveDeadTree" unique_id=1037626263 instance=ExtResource("224_dry_wood_008")]
+
+[node name="GroveSnag" type="Node3D" parent="Zones/NorthGrove" unique_id=929462372]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4.5, 0, -1.5)
+script = ExtResource("108_gather")
+max_charges = 3
+yield_amount = 3
+reach = 1.9
+clip = &"Chopping"
+
+[node name="dry_wood_011_g1" parent="Zones/NorthGrove/GroveSnag" unique_id=1592828303 instance=ExtResource("225_dry_wood_011")]
+transform = Transform3D(0.766044, 0, 0.642788, 0, 1, 0, -0.642788, 0, 0.766044, 0, 0, 0)
+
+[node name="GroveDeadfall" type="Node3D" parent="Zones/NorthGrove" unique_id=170944657]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.5, 0, -4)
+script = ExtResource("108_gather")
+max_charges = 3
+yield_amount = 3
+reach = 2.6
+clip = &"Chopping"
+
+[node name="dry_wood_004_g1" parent="Zones/NorthGrove/GroveDeadfall" unique_id=437184072 instance=ExtResource("226_dry_wood_004")]
+transform = Transform3D(0.866025, 0, -0.5, 0, 1, 0, 0.5, 0, 0.866025, 0, 0, 0)
+
+[node name="GroveLogs" type="Node3D" parent="Zones/NorthGrove" unique_id=1598217066]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2.5, 0, 3.5)
+script = ExtResource("108_gather")
+max_charges = 3
+yield_amount = 3
+reach = 1.7
+
+[node name="firewood_013_g1" parent="Zones/NorthGrove/GroveLogs" unique_id=897246555 instance=ExtResource("228_firewood_013")]
+
+[node name="OldHangar" type="Node3D" parent="Zones" unique_id=404706321]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 38, 0, -53)
+script = ExtResource("201_farm_zone")
+kind = 5
+display_name = "Old Hangar (outside the fence)"
+size = Vector2(18, 13)
+tint = Color(0.55, 0.65, 0.8, 1)
+outside = true
+
+[node name="HangarWreck" type="Node3D" parent="Zones/OldHangar" unique_id=337623953]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -6, 0, -2)
+script = ExtResource("108_gather")
+material = "scrap"
+max_charges = 4
+yield_amount = 3
+reach = 2.8
+clip = &"Hammering"
+
+[node name="car_001_g1" parent="Zones/OldHangar/HangarWreck" unique_id=146255292 instance=ExtResource("229_car_001")]
+transform = Transform3D(0.34202, 0, -0.939693, 0, 1, 0, 0.939693, 0, 0.34202, 0, 0, 0)
+
+[node name="HangarBarrels" type="Node3D" parent="Zones/OldHangar" unique_id=1539598738]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 6.5, 0, 1.5)
+script = ExtResource("108_gather")
+material = "scrap"
+max_charges = 3
+yield_amount = 3
+reach = 1.9
+
+[node name="barrel_001_g1" parent="Zones/OldHangar/HangarBarrels" unique_id=2086631899 instance=ExtResource("209_barrel_001")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.5, 0, 0)
+
+[node name="barrel_010_g1" parent="Zones/OldHangar/HangarBarrels" unique_id=1073778171 instance=ExtResource("210_barrel_010")]
+transform = Transform3D(0.866025, 0, 0.5, 0, 1, 0, -0.5, 0, 0.866025, 0.6, 0, 0.4)
+
+[node name="barrel_005_g1" parent="Zones/OldHangar/HangarBarrels" unique_id=106496079 instance=ExtResource("233_barrel_005")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.1, 0, -0.7)
+
+[node name="HangarCart" type="Node3D" parent="Zones/OldHangar" unique_id=841352646]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 7, 0, -4.5)
+script = ExtResource("108_gather")
+material = "scrap"
+max_charges = 3
+yield_amount = 3
+reach = 2.2
+clip = &"Hammering"
+
+[node name="cart_003_g1" parent="Zones/OldHangar/HangarCart" unique_id=880647819 instance=ExtResource("231_cart_003")]
+transform = Transform3D(0.939693, 0, 0.34202, 0, 1, 0, -0.34202, 0, 0.939693, 0, 0, 0)
+
+[node name="EastRoad" type="Node3D" parent="Zones" unique_id=526193588]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 51.5, 0, -15)
+script = ExtResource("201_farm_zone")
+kind = 5
+display_name = "East Road (outside the fence)"
+size = Vector2(6, 14)
+tint = Color(0.55, 0.65, 0.8, 1)
+outside = true
+
+[node name="RoadsideCar" type="Node3D" parent="Zones/EastRoad" unique_id=1986628569]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.87, 0, 0.62)
+script = ExtResource("108_gather")
+material = "scrap"
+max_charges = 4
+yield_amount = 3
+reach = 3
+clip = &"Hammering"
+
+[node name="car_003_001" parent="Zones/EastRoad/RoadsideCar" unique_id=1328810145 instance=ExtResource("41_fwpte")]
+transform = Transform3D(-1, 0, -3.8941437e-07, 0, 1, 0, 3.8941437e-07, 0, -1, -0.0017, 0.48251343, -0.001)
+
+[node name="RoadsideBarrels" type="Node3D" parent="Zones/EastRoad" unique_id=1131456836]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.5, 0, -5.5)
+script = ExtResource("108_gather")
+material = "scrap"
+max_charges = 3
+yield_amount = 3
+reach = 1.9
+
+[node name="barrel_001_g2" parent="Zones/EastRoad/RoadsideBarrels" unique_id=708384703 instance=ExtResource("209_barrel_001")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.4, 0, 0.2)
+
+[node name="barrel_005_g2" parent="Zones/EastRoad/RoadsideBarrels" unique_id=1841311248 instance=ExtResource("233_barrel_005")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.5, 0, -0.3)
+
+[node name="SouthFields" type="Node3D" parent="Zones" unique_id=2081155831]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 9.5, 0, 31)
+script = ExtResource("201_farm_zone")
+kind = 6
+display_name = "South Fields (outside the fence)"
+size = Vector2(66, 30)
+tint = Color(1, 0.95, 0.5, 1)
+outside = true
+
+[node name="FieldStackWest" type="Node3D" parent="Zones/SouthFields" unique_id=1757202658]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -19.5, 0.08, -6)
+script = ExtResource("108_gather")
+material = "straw"
+max_charges = 4
+yield_amount = 3
+reach = 2.6
+
+[node name="hay_002_s0" parent="Zones/SouthFields/FieldStackWest" unique_id=1500024712 instance=ExtResource("57_u2sqs")]
+transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, -0.65, -0.027496, 0.63)
+
+[node name="hay_002_s1" parent="Zones/SouthFields/FieldStackWest" unique_id=300369972 instance=ExtResource("57_u2sqs")]
+transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, 0.6, -0.027496, 0.63)
+
+[node name="hay_002_s2" parent="Zones/SouthFields/FieldStackWest" unique_id=939483186 instance=ExtResource("57_u2sqs")]
+transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, -0.65, -0.027496, -0.64)
+
+[node name="hay_002_s3" parent="Zones/SouthFields/FieldStackWest" unique_id=1173688203 instance=ExtResource("57_u2sqs")]
+transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, 0.6, -0.027496, -0.64)
+
+[node name="FieldBaleWest" type="Node3D" parent="Zones/SouthFields" unique_id=214188758]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -15.5, 0.08, 7)
+script = ExtResource("108_gather")
+material = "straw"
+max_charges = 3
+yield_amount = 3
+reach = 1.9
+
+[node name="hay_001_s1" parent="Zones/SouthFields/FieldBaleWest" unique_id=1602922239 instance=ExtResource("208_hay_001")]
+transform = Transform3D(0.906308, 0, 0.422618, 0, 1, 0, -0.422618, 0, 0.906308, 0, 0, 0)
+
+[node name="FieldBaleEast" type="Node3D" parent="Zones/SouthFields" unique_id=900608230]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 14.5, 0.08, -4)
+script = ExtResource("108_gather")
+material = "straw"
+max_charges = 3
+yield_amount = 3
+reach = 1.9
+
+[node name="hay_001_s2" parent="Zones/SouthFields/FieldBaleEast" unique_id=1659027828 instance=ExtResource("208_hay_001")]
+transform = Transform3D(0.965926, 0, -0.258819, 0, 1, 0, 0.258819, 0, 0.965926, 0, 0, 0)
+
+[node name="FieldStackEast" type="Node3D" parent="Zones/SouthFields" unique_id=1758123327]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 25.5, 0.08, 6)
+script = ExtResource("108_gather")
+material = "straw"
+max_charges = 4
+yield_amount = 3
+reach = 2.6
+
+[node name="hay_002_t0" parent="Zones/SouthFields/FieldStackEast" unique_id=979361292 instance=ExtResource("57_u2sqs")]
+transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, -0.65, -0.027496, 0.63)
+
+[node name="hay_002_t1" parent="Zones/SouthFields/FieldStackEast" unique_id=809052879 instance=ExtResource("57_u2sqs")]
+transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, 0.6, -0.027496, 0.63)
+
+[node name="hay_002_t2" parent="Zones/SouthFields/FieldStackEast" unique_id=1780694829 instance=ExtResource("57_u2sqs")]
+transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, -0.65, -0.027496, -0.64)
+
+[node name="hay_002_t3" parent="Zones/SouthFields/FieldStackEast" unique_id=907401534 instance=ExtResource("57_u2sqs")]
+transform = Transform3D(0, 0, -1, 0, 1, 0, 1, 0, 0, 0.6, -0.027496, -0.64)
+
+[node name="Perimeter" type="Node3D" parent="Zones" unique_id=1350785421]
+
+[node name="Fence" type="Node3D" parent="Zones/Perimeter" unique_id=1649402522]
+
+[node name="fence_005_001" parent="Zones/Perimeter/Fence" unique_id=1161032349 instance=ExtResource("31_fk54y")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -11.931818, 0, -45)
-[node name="fence_005_002" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_002" parent="Zones/Perimeter/Fence" unique_id=574423392 instance=ExtResource("31_fk54y")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -9.795455, 0, -45)
-[node name="fence_005_003" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_003" parent="Zones/Perimeter/Fence" unique_id=1323172307 instance=ExtResource("31_fk54y")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -7.659091, 0, -45)
-[node name="fence_005_004" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_004" parent="Zones/Perimeter/Fence" unique_id=1253282150 instance=ExtResource("31_fk54y")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -5.522727, 0, -45)
-[node name="fence_005_005" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_005" parent="Zones/Perimeter/Fence" unique_id=1107021584 instance=ExtResource("31_fk54y")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -3.386364, 0, -45)
-[node name="fence_005_006" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_006" parent="Zones/Perimeter/Fence" unique_id=2038155224 instance=ExtResource("31_fk54y")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -1.25, 0, -45)
-[node name="fence_005_007" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.886364, 0, -45)
-
-[node name="fence_005_008" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 3.022727, 0, -45)
-
-[node name="fence_005_009" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 5.159091, 0, -45)
-
-[node name="fence_005_010" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 7.295455, 0, -45)
-
-[node name="fence_005_011" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 9.431818, 0, -45)
-
-[node name="fence_005_012" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_012" parent="Zones/Perimeter/Fence" unique_id=1670421591 instance=ExtResource("31_fk54y")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 14.616667, 0, -45)
-[node name="fence_005_013" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_007" parent="Zones/Perimeter/Fence" unique_id=1667945338 instance=ExtResource("31_fk54y")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.886364, 0, -45)
+
+[node name="fence_005_008" parent="Zones/Perimeter/Fence" unique_id=917492665 instance=ExtResource("31_fk54y")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 3.022727, 0, -45)
+
+[node name="fence_005_009" parent="Zones/Perimeter/Fence" unique_id=1564701813 instance=ExtResource("31_fk54y")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 5.159091, 0, -45)
+
+[node name="fence_005_010" parent="Zones/Perimeter/Fence" unique_id=972636099 instance=ExtResource("31_fk54y")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 7.295455, 0, -45)
+
+[node name="fence_005_011" parent="Zones/Perimeter/Fence" unique_id=1728646292 instance=ExtResource("31_fk54y")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 9.431818, 0, -45)
+
+[node name="fence_005_013" parent="Zones/Perimeter/Fence" unique_id=2107662877 instance=ExtResource("31_fk54y")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 16.85, 0, -45)
-[node name="fence_005_014" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 19.083333, 0, -45)
+[node name="fence_005_014" parent="Zones/Perimeter/Fence" unique_id=2071231555 instance=ExtResource("31_fk54y")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 19.083332, 0, -45)
-[node name="fence_005_015" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 21.316667, 0, -45)
+[node name="fence_005_015" parent="Zones/Perimeter/Fence" unique_id=554635897 instance=ExtResource("31_fk54y")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 21.316668, 0, -45)
-[node name="fence_005_016" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_016" parent="Zones/Perimeter/Fence" unique_id=1569373557 instance=ExtResource("31_fk54y")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 23.55, 0, -45)
-[node name="fence_005_017" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_017" parent="Zones/Perimeter/Fence" unique_id=1105495615 instance=ExtResource("31_fk54y")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 25.783333, 0, -45)
-[node name="fence_005_018" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 28.016667, 0, -45)
+[node name="fence_005_018" parent="Zones/Perimeter/Fence" unique_id=1650184652 instance=ExtResource("31_fk54y")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 28.016666, 0, -45)
-[node name="fence_005_019" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_019" parent="Zones/Perimeter/Fence" unique_id=2056048852 instance=ExtResource("31_fk54y")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 30.25, 0, -45)
-[node name="fence_005_020" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 32.483333, 0, -45)
+[node name="fence_005_020" parent="Zones/Perimeter/Fence" unique_id=1654433955 instance=ExtResource("31_fk54y")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 32.483334, 0, -45)
-[node name="fence_005_021" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_021" parent="Zones/Perimeter/Fence" unique_id=1694962134 instance=ExtResource("31_fk54y")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 34.716667, 0, -45)
-[node name="fence_005_022" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_022" parent="Zones/Perimeter/Fence" unique_id=626027329 instance=ExtResource("31_fk54y")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 36.95, 0, -45)
-[node name="fence_005_023" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 39.183333, 0, -45)
+[node name="fence_005_023" parent="Zones/Perimeter/Fence" unique_id=585996230 instance=ExtResource("31_fk54y")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 39.183334, 0, -45)
-[node name="fence_005_024" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 41.416667, 0, -45)
+[node name="fence_005_024" parent="Zones/Perimeter/Fence" unique_id=1556329756 instance=ExtResource("31_fk54y")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 41.416668, 0, -45)
-[node name="fence_005_025" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_025" parent="Zones/Perimeter/Fence" unique_id=396279007 instance=ExtResource("31_fk54y")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 43.65, 0, -45)
-[node name="fence_005_026" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 45.883333, 0, -45)
+[node name="fence_005_026" parent="Zones/Perimeter/Fence" unique_id=1176074545 instance=ExtResource("31_fk54y")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 45.88333, 0, -45)
-[node name="fence_005_027" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -12.0625, 0, 15)
-
-[node name="fence_005_028" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -10.1875, 0, 15)
-
-[node name="fence_005_029" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -8.3125, 0, 15)
-
-[node name="fence_005_030" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -6.4375, 0, 15)
-
-[node name="fence_005_031" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -1.357143, 0, 15)
-
-[node name="fence_005_032" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.928571, 0, 15)
-
-[node name="fence_005_033" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 3.214286, 0, 15)
-
-[node name="fence_005_034" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 5.5, 0, 15)
-
-[node name="fence_005_035" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 7.785714, 0, 15)
-
-[node name="fence_005_036" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 10.071429, 0, 15)
-
-[node name="fence_005_037" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 12.357143, 0, 15)
-
-[node name="fence_005_038" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 14.642857, 0, 15)
-
-[node name="fence_005_039" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 16.928571, 0, 15)
-
-[node name="fence_005_040" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 19.214286, 0, 15)
-
-[node name="fence_005_041" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 21.5, 0, 15)
-
-[node name="fence_005_042" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 23.785714, 0, 15)
-
-[node name="fence_005_043" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 26.071429, 0, 15)
-
-[node name="fence_005_044" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 28.357143, 0, 15)
-
-[node name="fence_005_045" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 33.535714, 0, 15)
-
-[node name="fence_005_046" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 35.607143, 0, 15)
-
-[node name="fence_005_047" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 37.678571, 0, 15)
-
-[node name="fence_005_048" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 39.75, 0, 15)
-
-[node name="fence_005_049" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 41.821429, 0, 15)
-
-[node name="fence_005_050" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 43.892857, 0, 15)
-
-[node name="fence_005_051" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 45.964286, 0, 15)
-
-[node name="fence_005_052" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -43.897059)
-
-[node name="fence_005_053" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -41.691176)
-
-[node name="fence_005_054" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -39.485294)
-
-[node name="fence_005_055" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -37.279412)
-
-[node name="fence_005_056" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -35.073529)
-
-[node name="fence_005_057" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -32.867647)
-
-[node name="fence_005_058" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -30.661765)
-
-[node name="fence_005_059" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -28.455882)
-
-[node name="fence_005_060" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -26.25)
-
-[node name="fence_005_061" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -24.044118)
-
-[node name="fence_005_062" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -21.838235)
-
-[node name="fence_005_063" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -19.632353)
-
-[node name="fence_005_064" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -17.426471)
-
-[node name="fence_005_065" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -15.220588)
-
-[node name="fence_005_066" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -13.014706)
-
-[node name="fence_005_067" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -10.808824)
-
-[node name="fence_005_068" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -8.602941)
-
-[node name="fence_005_069" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -3.416667)
-
-[node name="fence_005_070" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -1.25)
-
-[node name="fence_005_071" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, 0.916667)
-
-[node name="fence_005_072" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, 3.083333)
-
-[node name="fence_005_073" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, 5.25)
-
-[node name="fence_005_074" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, 7.416667)
-
-[node name="fence_005_075" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, 9.583333)
-
-[node name="fence_005_076" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, 11.75)
-
-[node name="fence_005_077" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
-transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, 13.916667)
-
-[node name="fence_005_078" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_078" parent="Zones/Perimeter/Fence" unique_id=771420219 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -44.125)
-[node name="fence_005_079" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_079" parent="Zones/Perimeter/Fence" unique_id=2032935496 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -42.375)
-[node name="fence_005_080" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_080" parent="Zones/Perimeter/Fence" unique_id=1118160237 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -36.40625)
-[node name="fence_005_081" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_081" parent="Zones/Perimeter/Fence" unique_id=815021849 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -34.21875)
-[node name="fence_005_082" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_052" parent="Zones/Perimeter/Fence" unique_id=1732787875 instance=ExtResource("31_fk54y")]
+transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -43.89706)
+
+[node name="fence_005_053" parent="Zones/Perimeter/Fence" unique_id=1104058453 instance=ExtResource("31_fk54y")]
+transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, -13, 0, -41.691177)
+
+[node name="fence_005_082" parent="Zones/Perimeter/Fence" unique_id=83855487 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -32.03125)
-[node name="fence_005_083" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_083" parent="Zones/Perimeter/Fence" unique_id=1343890373 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -29.84375)
-[node name="fence_005_084" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_084" parent="Zones/Perimeter/Fence" unique_id=569298234 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -27.65625)
-[node name="fence_005_085" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_085" parent="Zones/Perimeter/Fence" unique_id=1367850141 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -25.46875)
-[node name="fence_005_086" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_086" parent="Zones/Perimeter/Fence" unique_id=34524124 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -23.28125)
-[node name="fence_005_087" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_087" parent="Zones/Perimeter/Fence" unique_id=1613104355 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -21.09375)
-[node name="fence_005_088" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_088" parent="Zones/Perimeter/Fence" unique_id=1153010813 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -15.857143)
-[node name="fence_005_089" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_089" parent="Zones/Perimeter/Fence" unique_id=1567556162 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -13.571429)
-[node name="fence_005_090" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_090" parent="Zones/Perimeter/Fence" unique_id=4032246 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -11.285714)
-[node name="fence_005_091" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_091" parent="Zones/Perimeter/Fence" unique_id=123612668 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -9)
-[node name="fence_005_092" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_092" parent="Zones/Perimeter/Fence" unique_id=167933495 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -6.714286)
-[node name="fence_005_093" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_093" parent="Zones/Perimeter/Fence" unique_id=1701987526 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -4.428571)
-[node name="fence_005_094" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_094" parent="Zones/Perimeter/Fence" unique_id=452730294 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, -2.142857)
-[node name="fence_005_095" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_095" parent="Zones/Perimeter/Fence" unique_id=1241503916 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, 0.142857)
-[node name="fence_005_096" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_096" parent="Zones/Perimeter/Fence" unique_id=1941336920 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, 2.428571)
-[node name="fence_005_097" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_097" parent="Zones/Perimeter/Fence" unique_id=1436507905 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, 4.714286)
-[node name="fence_005_098" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_098" parent="Zones/Perimeter/Fence" unique_id=2105926581 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, 7)
-[node name="fence_005_099" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_099" parent="Zones/Perimeter/Fence" unique_id=873724244 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, 9.285714)
-[node name="fence_005_100" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_100" parent="Zones/Perimeter/Fence" unique_id=1031857301 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, 11.571429)
-[node name="fence_005_101" parent="Zones/Perimeter/Fence" instance=ExtResource("31_fk54y")]
+[node name="fence_005_101" parent="Zones/Perimeter/Fence" unique_id=764491698 instance=ExtResource("31_fk54y")]
transform = Transform3D(0, 0, 1, 0, 1, 0, -1, 0, 0, 47, 0, 13.857143)
-[node name="GapNorth" type="Marker3D" parent="Zones/Perimeter"]
+[node name="GapNorth" type="Marker3D" parent="Zones/Perimeter" unique_id=109510600]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 12, 0, -48)
script = ExtResource("234_farm_marker")
-kind = 0
-[node name="SignNorth" parent="Zones/Perimeter" instance=ExtResource("235_pointer_002")]
+[node name="SignNorth" parent="Zones/Perimeter" unique_id=1199229245 instance=ExtResource("235_pointer_002")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 14.2, 1, -43.8)
-[node name="GapDriveway" type="Marker3D" parent="Zones/Perimeter"]
+[node name="GapDriveway" type="Marker3D" parent="Zones/Perimeter" unique_id=985619263]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 50, 0, -39.5)
script = ExtResource("234_farm_marker")
-kind = 0
-[node name="SignDriveway" parent="Zones/Perimeter" instance=ExtResource("235_pointer_002")]
+[node name="SignDriveway" parent="Zones/Perimeter" unique_id=1001663022 instance=ExtResource("235_pointer_002")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 45.6, 1, -36.2)
-[node name="GapEast" type="Marker3D" parent="Zones/Perimeter"]
+[node name="GapEast" type="Marker3D" parent="Zones/Perimeter" unique_id=375797560]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 50, 0, -18.5)
script = ExtResource("234_farm_marker")
-kind = 0
-[node name="SignEast" parent="Zones/Perimeter" instance=ExtResource("235_pointer_002")]
+[node name="SignEast" parent="Zones/Perimeter" unique_id=1316868575 instance=ExtResource("235_pointer_002")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 45.8, 1, -21)
-[node name="GapSouthEast" type="Marker3D" parent="Zones/Perimeter"]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 31, 0, 18)
-script = ExtResource("234_farm_marker")
-kind = 0
-
-[node name="SignSouthEast" parent="Zones/Perimeter" instance=ExtResource("235_pointer_002")]
+[node name="SignSouthEast" parent="Zones/Perimeter" unique_id=2121204080 instance=ExtResource("235_pointer_002")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 33.2, 1, 13.8)
-[node name="GapSouthWest" type="Marker3D" parent="Zones/Perimeter"]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 0, 18)
-script = ExtResource("234_farm_marker")
-kind = 0
-
-[node name="SignSouthWest" parent="Zones/Perimeter" instance=ExtResource("235_pointer_002")]
+[node name="SignSouthWest" parent="Zones/Perimeter" unique_id=148049561 instance=ExtResource("235_pointer_002")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -1.8, 1, 13.8)
-[node name="GapWest" type="Marker3D" parent="Zones/Perimeter"]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -16, 0, -6)
-script = ExtResource("234_farm_marker")
-kind = 0
-
-[node name="SignWest" parent="Zones/Perimeter" instance=ExtResource("235_pointer_002")]
+[node name="SignWest" parent="Zones/Perimeter" unique_id=476824738 instance=ExtResource("235_pointer_002")]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -11.8, 1, -3.6)
-[node name="CrowNorth" type="Marker3D" parent="Zones/Perimeter"]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 17, 0, -53)
-script = ExtResource("234_farm_marker")
-kind = 1
-
-[node name="CrowEast" type="Marker3D" parent="Zones/Perimeter"]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 55, 0, -5)
-script = ExtResource("234_farm_marker")
-kind = 1
-
-[node name="CrowSouth" type="Marker3D" parent="Zones/Perimeter"]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 17, 0, 23)
-script = ExtResource("234_farm_marker")
-kind = 1
-
-[node name="CrowWest" type="Marker3D" parent="Zones/Perimeter"]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -21, 0, -15)
-script = ExtResource("234_farm_marker")
-kind = 1
-
-[node name="PlayerBounds" type="StaticBody3D" parent="Zones/Perimeter"]
+[node name="PlayerBounds" type="StaticBody3D" parent="Zones/Perimeter" unique_id=821846216]
collision_layer = 4
collision_mask = 0
-[node name="North" type="CollisionShape3D" parent="Zones/Perimeter/PlayerBounds"]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 17, 1.5, -45)
+[node name="North" type="CollisionShape3D" parent="Zones/Perimeter/PlayerBounds" unique_id=1954546835]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 13.6, 1.5, -59.6)
shape = SubResource("BoxShape3D_bounds_ns")
-[node name="South" type="CollisionShape3D" parent="Zones/Perimeter/PlayerBounds"]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 17, 1.5, 15)
+[node name="South" type="CollisionShape3D" parent="Zones/Perimeter/PlayerBounds" unique_id=1419002204]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 13.6, 1.5, 47)
shape = SubResource("BoxShape3D_bounds_ns")
-[node name="West" type="CollisionShape3D" parent="Zones/Perimeter/PlayerBounds"]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -13, 1.5, -15)
+[node name="West" type="CollisionShape3D" parent="Zones/Perimeter/PlayerBounds" unique_id=1522510694]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -27.6, 1.5, -6.3)
shape = SubResource("BoxShape3D_bounds_we")
-[node name="East" type="CollisionShape3D" parent="Zones/Perimeter/PlayerBounds"]
-transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 47, 1.5, -15)
+[node name="East" type="CollisionShape3D" parent="Zones/Perimeter/PlayerBounds" unique_id=720523922]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 54.8, 1.5, -6.3)
shape = SubResource("BoxShape3D_bounds_we")
-[node name="ZoneBanner" type="CanvasLayer" parent="." node_paths=PackedStringArray("zones", "target")]
+[node name="ZoneBanner" type="CanvasLayer" parent="." unique_id=940903714 node_paths=PackedStringArray("zones", "target")]
script = ExtResource("236_zone_banner")
zones = NodePath("../Zones")
target = NodePath("../Player")
+
+[node name="Hud" type="CanvasLayer" parent="." unique_id=666315498]
+
+[node name="Alerts" type="Control" parent="Hud" unique_id=110836126]
+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("103_threats")
+
+[node name="ToastFeed" type="VBoxContainer" parent="Hud" unique_id=1261899939]
+anchors_preset = 10
+anchor_right = 1.0
+offset_top = 152.0
+grow_horizontal = 2
+mouse_filter = 2
+script = ExtResource("104_toasts")
+
+[node name="ScarecrowHud" type="Control" parent="Hud" unique_id=1120148247]
+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("105_scarecrow_hud")
+
+[node name="EndPanel" type="CenterContainer" parent="Hud" unique_id=62343155]
+anchors_preset = 15
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 2
+grow_vertical = 2
+mouse_filter = 2
+script = ExtResource("106_end_panel")
+
+[node name="ResourceHud" type="Control" parent="Hud" unique_id=223271798]
+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("107_resource_hud")
+
+[node name="BuildHud" type="Control" parent="Hud" unique_id=2004685226]
+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("110_build_hud")
+
+[node name="PhaseHud" type="Control" parent="Hud" unique_id=1095005378]
+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("111_phase_hud")
+
+[node name="AssetHud" type="Control" parent="Hud" unique_id=302543386]
+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("113_asset_hud")
+
+[node name="ReviewPanel" type="CenterContainer" parent="Hud" unique_id=953437021]
+anchors_preset = 15
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 2
+grow_vertical = 2
+mouse_filter = 2
+script = ExtResource("112_review")
+
+[node name="UpgradePanel" type="CenterContainer" parent="Hud" unique_id=1781909006]
+anchors_preset = 15
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 2
+grow_vertical = 2
+mouse_filter = 2
+script = ExtResource("114_upgrades")
+
+[node name="FarmSim" type="Node" parent="." unique_id=117307361 node_paths=PackedStringArray("campaign", "zones", "player", "camera", "toasts", "alerts", "hud", "end_panel", "resource_hud", "build_hud", "phase_hud", "asset_hud", "review_panel", "upgrade_panel", "sun", "world_environment")]
+script = ExtResource("102_farm_sim")
+campaign = NodePath("../Campaign")
+zones = NodePath("../Zones")
+player = NodePath("../Player")
+camera = NodePath("../Camera")
+toasts = NodePath("../Hud/ToastFeed")
+alerts = NodePath("../Hud/Alerts")
+hud = NodePath("../Hud/ScarecrowHud")
+end_panel = NodePath("../Hud/EndPanel")
+resource_hud = NodePath("../Hud/ResourceHud")
+build_hud = NodePath("../Hud/BuildHud")
+phase_hud = NodePath("../Hud/PhaseHud")
+asset_hud = NodePath("../Hud/AssetHud")
+review_panel = NodePath("../Hud/ReviewPanel")
+upgrade_panel = NodePath("../Hud/UpgradePanel")
+sun = NodePath("../Sun")
+world_environment = NodePath("../WorldEnvironment")
diff --git a/game/scenes/main.tscn b/game/scenes/main.tscn
new file mode 100644
index 0000000..6f900cc
--- /dev/null
+++ b/game/scenes/main.tscn
@@ -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")
diff --git a/game/scripts/action_edges.gd b/game/scripts/action_edges.gd
new file mode 100644
index 0000000..900451b
--- /dev/null
+++ b/game/scripts/action_edges.gd
@@ -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)
diff --git a/game/scripts/action_edges.gd.uid b/game/scripts/action_edges.gd.uid
new file mode 100644
index 0000000..6ea1118
--- /dev/null
+++ b/game/scripts/action_edges.gd.uid
@@ -0,0 +1 @@
+uid://cx3ym8d1fbxy1
diff --git a/game/scripts/alert_manager.gd b/game/scripts/alert_manager.gd
new file mode 100644
index 0000000..f9daccb
--- /dev/null
+++ b/game/scripts/alert_manager.gd
@@ -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
diff --git a/game/scripts/alert_manager.gd.uid b/game/scripts/alert_manager.gd.uid
new file mode 100644
index 0000000..b011c04
--- /dev/null
+++ b/game/scripts/alert_manager.gd.uid
@@ -0,0 +1 @@
+uid://clqvqr3bnsp5k
diff --git a/game/scripts/animal_system.gd b/game/scripts/animal_system.gd
new file mode 100644
index 0000000..1ec2af1
--- /dev/null
+++ b/game/scripts/animal_system.gd
@@ -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
diff --git a/game/scripts/animal_system.gd.uid b/game/scripts/animal_system.gd.uid
new file mode 100644
index 0000000..2ae3764
--- /dev/null
+++ b/game/scripts/animal_system.gd.uid
@@ -0,0 +1 @@
+uid://cip8klystkp4v
diff --git a/game/scripts/assessment.gd b/game/scripts/assessment.gd
new file mode 100644
index 0000000..96e5dc1
--- /dev/null
+++ b/game/scripts/assessment.gd
@@ -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"
diff --git a/game/scripts/assessment.gd.uid b/game/scripts/assessment.gd.uid
new file mode 100644
index 0000000..5c0d403
--- /dev/null
+++ b/game/scripts/assessment.gd.uid
@@ -0,0 +1 @@
+uid://cnn7o882bgewn
diff --git a/game/scripts/asset_hud.gd b/game/scripts/asset_hud.gd
new file mode 100644
index 0000000..9320f33
--- /dev/null
+++ b/game/scripts/asset_hud.gd
@@ -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])
diff --git a/game/scripts/asset_hud.gd.uid b/game/scripts/asset_hud.gd.uid
new file mode 100644
index 0000000..1e1bb3a
--- /dev/null
+++ b/game/scripts/asset_hud.gd.uid
@@ -0,0 +1 @@
+uid://cdhho7exq5x3s
diff --git a/game/scripts/avatar.gd b/game/scripts/avatar.gd
new file mode 100644
index 0000000..2827d97
--- /dev/null
+++ b/game/scripts/avatar.gd
@@ -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]
diff --git a/game/scripts/avatar.gd.uid b/game/scripts/avatar.gd.uid
new file mode 100644
index 0000000..948d29f
--- /dev/null
+++ b/game/scripts/avatar.gd.uid
@@ -0,0 +1 @@
+uid://r1m82ruktoay
diff --git a/game/scripts/build_hud.gd b/game/scripts/build_hud.gd
new file mode 100644
index 0000000..67938c3
--- /dev/null
+++ b/game/scripts/build_hud.gd
@@ -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
diff --git a/game/scripts/build_hud.gd.uid b/game/scripts/build_hud.gd.uid
new file mode 100644
index 0000000..f7a9a32
--- /dev/null
+++ b/game/scripts/build_hud.gd.uid
@@ -0,0 +1 @@
+uid://kmuyj86rfjj2
diff --git a/game/scripts/build_mode.gd b/game/scripts/build_mode.gd
new file mode 100644
index 0000000..4043862
--- /dev/null
+++ b/game/scripts/build_mode.gd
@@ -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
diff --git a/game/scripts/build_mode.gd.uid b/game/scripts/build_mode.gd.uid
new file mode 100644
index 0000000..0c5388c
--- /dev/null
+++ b/game/scripts/build_mode.gd.uid
@@ -0,0 +1 @@
+uid://btsyw0fbbdpeh
diff --git a/game/scripts/campaign_controller.gd b/game/scripts/campaign_controller.gd
index d4732db..5dc0fc8 100644
--- a/game/scripts/campaign_controller.gd
+++ b/game/scripts/campaign_controller.gd
@@ -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)
diff --git a/game/scripts/campaign_debug.gd b/game/scripts/campaign_debug.gd
index 71b6d90..e8f981c 100644
--- a/game/scripts/campaign_debug.gd
+++ b/game/scripts/campaign_debug.gd
@@ -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)
diff --git a/game/scripts/confirm_box.gd b/game/scripts/confirm_box.gd
new file mode 100644
index 0000000..feadb95
--- /dev/null
+++ b/game/scripts/confirm_box.gd
@@ -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()
diff --git a/game/scripts/confirm_box.gd.uid b/game/scripts/confirm_box.gd.uid
new file mode 100644
index 0000000..b792192
--- /dev/null
+++ b/game/scripts/confirm_box.gd.uid
@@ -0,0 +1 @@
+uid://rusd2ksjv11
diff --git a/game/scripts/coop_hud.gd b/game/scripts/coop_hud.gd
new file mode 100644
index 0000000..d0ec3ea
--- /dev/null
+++ b/game/scripts/coop_hud.gd
@@ -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
diff --git a/game/scripts/coop_hud.gd.uid b/game/scripts/coop_hud.gd.uid
new file mode 100644
index 0000000..70ebf0e
--- /dev/null
+++ b/game/scripts/coop_hud.gd.uid
@@ -0,0 +1 @@
+uid://dn5wrd05u30o3
diff --git a/game/scripts/coop_link.gd b/game/scripts/coop_link.gd
new file mode 100644
index 0000000..9095c38
--- /dev/null
+++ b/game/scripts/coop_link.gd
@@ -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
diff --git a/game/scripts/coop_link.gd.uid b/game/scripts/coop_link.gd.uid
new file mode 100644
index 0000000..f261b1c
--- /dev/null
+++ b/game/scripts/coop_link.gd.uid
@@ -0,0 +1 @@
+uid://cguqgjquppxln
diff --git a/game/scripts/coop_lobby.gd b/game/scripts/coop_lobby.gd
new file mode 100644
index 0000000..0ff3c99
--- /dev/null
+++ b/game/scripts/coop_lobby.gd
@@ -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)
diff --git a/game/scripts/coop_lobby.gd.uid b/game/scripts/coop_lobby.gd.uid
new file mode 100644
index 0000000..250d934
--- /dev/null
+++ b/game/scripts/coop_lobby.gd.uid
@@ -0,0 +1 @@
+uid://yhd32jflx2xj
diff --git a/game/scripts/coop_menu.gd b/game/scripts/coop_menu.gd
new file mode 100644
index 0000000..a86a9bc
--- /dev/null
+++ b/game/scripts/coop_menu.gd
@@ -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()
diff --git a/game/scripts/coop_menu.gd.uid b/game/scripts/coop_menu.gd.uid
new file mode 100644
index 0000000..9e7fa71
--- /dev/null
+++ b/game/scripts/coop_menu.gd.uid
@@ -0,0 +1 @@
+uid://bwf7mnsom2ekv
diff --git a/game/scripts/coop_session.gd b/game/scripts/coop_session.gd
new file mode 100644
index 0000000..f7edf43
--- /dev/null
+++ b/game/scripts/coop_session.gd
@@ -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
diff --git a/game/scripts/coop_session.gd.uid b/game/scripts/coop_session.gd.uid
new file mode 100644
index 0000000..b6d3c2d
--- /dev/null
+++ b/game/scripts/coop_session.gd.uid
@@ -0,0 +1 @@
+uid://yyjmd3opd2bd
diff --git a/game/scripts/coop_voice.gd b/game/scripts/coop_voice.gd
new file mode 100644
index 0000000..1c14f72
--- /dev/null
+++ b/game/scripts/coop_voice.gd
@@ -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)
diff --git a/game/scripts/coop_voice.gd.uid b/game/scripts/coop_voice.gd.uid
new file mode 100644
index 0000000..29d97f5
--- /dev/null
+++ b/game/scripts/coop_voice.gd.uid
@@ -0,0 +1 @@
+uid://bbj7krc3xfv1h
diff --git a/game/scripts/day_night.gd b/game/scripts/day_night.gd
new file mode 100644
index 0000000..a89ff1f
--- /dev/null
+++ b/game/scripts/day_night.gd
@@ -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
diff --git a/game/scripts/day_night.gd.uid b/game/scripts/day_night.gd.uid
new file mode 100644
index 0000000..d660788
--- /dev/null
+++ b/game/scripts/day_night.gd.uid
@@ -0,0 +1 @@
+uid://c7fee6n0qdqwn
diff --git a/game/scripts/end_panel.gd b/game/scripts/end_panel.gd
new file mode 100644
index 0000000..d499926
--- /dev/null
+++ b/game/scripts/end_panel.gd
@@ -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
diff --git a/game/scripts/end_panel.gd.uid b/game/scripts/end_panel.gd.uid
new file mode 100644
index 0000000..1ab43e9
--- /dev/null
+++ b/game/scripts/end_panel.gd.uid
@@ -0,0 +1 @@
+uid://b6pkgit825mrl
diff --git a/game/scripts/enemy_characters.gd b/game/scripts/enemy_characters.gd
new file mode 100644
index 0000000..c43f83b
--- /dev/null
+++ b/game/scripts/enemy_characters.gd
@@ -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)
diff --git a/game/scripts/enemy_characters.gd.uid b/game/scripts/enemy_characters.gd.uid
new file mode 100644
index 0000000..b7b62af
--- /dev/null
+++ b/game/scripts/enemy_characters.gd.uid
@@ -0,0 +1 @@
+uid://bq245wu5ed25i
diff --git a/game/scripts/enemy_system.gd b/game/scripts/enemy_system.gd
new file mode 100644
index 0000000..c655489
--- /dev/null
+++ b/game/scripts/enemy_system.gd
@@ -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
diff --git a/game/scripts/enemy_system.gd.uid b/game/scripts/enemy_system.gd.uid
new file mode 100644
index 0000000..a9ca89f
--- /dev/null
+++ b/game/scripts/enemy_system.gd.uid
@@ -0,0 +1 @@
+uid://qpvv6poddjes
diff --git a/game/scripts/farm_audio.gd b/game/scripts/farm_audio.gd
new file mode 100644
index 0000000..ee02616
--- /dev/null
+++ b/game/scripts/farm_audio.gd
@@ -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
diff --git a/game/scripts/farm_audio.gd.uid b/game/scripts/farm_audio.gd.uid
new file mode 100644
index 0000000..bd7d47d
--- /dev/null
+++ b/game/scripts/farm_audio.gd.uid
@@ -0,0 +1 @@
+uid://bod5ytvc2vhfs
diff --git a/game/scripts/farm_marker.gd b/game/scripts/farm_marker.gd
index ff0ee9c..7443443 100644
--- a/game/scripts/farm_marker.gd
+++ b/game/scripts/farm_marker.gd
@@ -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.
diff --git a/game/scripts/farm_navigation.gd b/game/scripts/farm_navigation.gd
index db87a3a..29a564b 100644
--- a/game/scripts/farm_navigation.gd
+++ b/game/scripts/farm_navigation.gd
@@ -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
diff --git a/game/scripts/farm_projectiles.gd b/game/scripts/farm_projectiles.gd
new file mode 100644
index 0000000..4756e97
--- /dev/null
+++ b/game/scripts/farm_projectiles.gd
@@ -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
diff --git a/game/scripts/farm_projectiles.gd.uid b/game/scripts/farm_projectiles.gd.uid
new file mode 100644
index 0000000..c5ec5a4
--- /dev/null
+++ b/game/scripts/farm_projectiles.gd.uid
@@ -0,0 +1 @@
+uid://bjfvqmqtt45ww
diff --git a/game/scripts/farm_sim.gd b/game/scripts/farm_sim.gd
new file mode 100644
index 0000000..75962d2
--- /dev/null
+++ b/game/scripts/farm_sim.gd
@@ -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)
diff --git a/game/scripts/farm_sim.gd.uid b/game/scripts/farm_sim.gd.uid
new file mode 100644
index 0000000..714a9af
--- /dev/null
+++ b/game/scripts/farm_sim.gd.uid
@@ -0,0 +1 @@
+uid://c6auf64ahke4k
diff --git a/game/scripts/farm_state.gd b/game/scripts/farm_state.gd
index 9d69d68..f470609 100644
--- a/game/scripts/farm_state.gd
+++ b/game/scripts/farm_state.gd
@@ -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
diff --git a/game/scripts/farm_zone.gd b/game/scripts/farm_zone.gd
index 43e8bf8..e3ceb34 100644
--- a/game/scripts/farm_zone.gd
+++ b/game/scripts/farm_zone.gd
@@ -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
diff --git a/game/scripts/farm_zones.gd b/game/scripts/farm_zones.gd
index 8c321a1..7ef650f 100644
--- a/game/scripts/farm_zones.gd
+++ b/game/scripts/farm_zones.gd
@@ -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)
diff --git a/game/scripts/farmers_return.gd b/game/scripts/farmers_return.gd
new file mode 100644
index 0000000..31f46d2
--- /dev/null
+++ b/game/scripts/farmers_return.gd
@@ -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()
diff --git a/game/scripts/farmers_return.gd.uid b/game/scripts/farmers_return.gd.uid
new file mode 100644
index 0000000..0f1791c
--- /dev/null
+++ b/game/scripts/farmers_return.gd.uid
@@ -0,0 +1 @@
+uid://00yqn4v1vtyl
diff --git a/game/scripts/game_config.gd b/game/scripts/game_config.gd
index 940a219..ce280c5 100644
--- a/game/scripts/game_config.gd
+++ b/game/scripts/game_config.gd
@@ -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.
diff --git a/game/scripts/game_settings.gd b/game/scripts/game_settings.gd
new file mode 100644
index 0000000..a908b4c
--- /dev/null
+++ b/game/scripts/game_settings.gd
@@ -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
diff --git a/game/scripts/game_settings.gd.uid b/game/scripts/game_settings.gd.uid
new file mode 100644
index 0000000..c759a94
--- /dev/null
+++ b/game/scripts/game_settings.gd.uid
@@ -0,0 +1 @@
+uid://bunyhk45ja6cu
diff --git a/game/scripts/gather_node.gd b/game/scripts/gather_node.gd
new file mode 100644
index 0000000..9c291de
--- /dev/null
+++ b/game/scripts/gather_node.gd
@@ -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
diff --git a/game/scripts/gather_node.gd.uid b/game/scripts/gather_node.gd.uid
new file mode 100644
index 0000000..ffb8c34
--- /dev/null
+++ b/game/scripts/gather_node.gd.uid
@@ -0,0 +1 @@
+uid://cj88bbt6nct61
diff --git a/game/scripts/gdsync_link.gd b/game/scripts/gdsync_link.gd
new file mode 100644
index 0000000..5385da0
--- /dev/null
+++ b/game/scripts/gdsync_link.gd
@@ -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)
diff --git a/game/scripts/gdsync_link.gd.uid b/game/scripts/gdsync_link.gd.uid
new file mode 100644
index 0000000..da96033
--- /dev/null
+++ b/game/scripts/gdsync_link.gd.uid
@@ -0,0 +1 @@
+uid://c1sifg7g5bbsn
diff --git a/game/scripts/interactions.gd b/game/scripts/interactions.gd
new file mode 100644
index 0000000..4d857f5
--- /dev/null
+++ b/game/scripts/interactions.gd
@@ -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
diff --git a/game/scripts/interactions.gd.uid b/game/scripts/interactions.gd.uid
new file mode 100644
index 0000000..19f9337
--- /dev/null
+++ b/game/scripts/interactions.gd.uid
@@ -0,0 +1 @@
+uid://clbenujyc2nyp
diff --git a/game/scripts/loot_system.gd b/game/scripts/loot_system.gd
new file mode 100644
index 0000000..a0b853e
--- /dev/null
+++ b/game/scripts/loot_system.gd
@@ -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
diff --git a/game/scripts/loot_system.gd.uid b/game/scripts/loot_system.gd.uid
new file mode 100644
index 0000000..8585535
--- /dev/null
+++ b/game/scripts/loot_system.gd.uid
@@ -0,0 +1 @@
+uid://gakx27ujp4gh
diff --git a/game/scripts/main.gd b/game/scripts/main.gd
new file mode 100644
index 0000000..3895592
--- /dev/null
+++ b/game/scripts/main.gd
@@ -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()
diff --git a/game/scripts/main.gd.uid b/game/scripts/main.gd.uid
new file mode 100644
index 0000000..2f4de87
--- /dev/null
+++ b/game/scripts/main.gd.uid
@@ -0,0 +1 @@
+uid://cknwtl25dvosc
diff --git a/game/scripts/main_menu.gd b/game/scripts/main_menu.gd
new file mode 100644
index 0000000..cfc4765
--- /dev/null
+++ b/game/scripts/main_menu.gd
@@ -0,0 +1,113 @@
+class_name MainMenu
+extends Control
+## The title screen over the farm (Main slowly circles a camera around it): the title, then
+## Continue (with which morning it resumes at, or why the save can't be continued), New
+## vacation, Play with a friend (co-op, CoopMenu), Settings, and Quit, and a notice line (e.g.
+## why a co-op game ended). Mouse, keyboard, and gamepad work through focus.
+
+signal continue_requested
+signal new_requested
+signal settings_requested
+signal coop_requested
+signal quit_requested
+
+var continue_button: Button
+var new_button: Button
+var settings_button: Button
+var coop_button: Button
+var notice: Label
+var quit_button: Button
+var save_note: Label
+
+
+func _ready() -> void:
+ set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
+ var shade := ColorRect.new() # darkens the left side behind the buttons
+ shade.color = Color(0.03, 0.04, 0.03, 0.62)
+ shade.mouse_filter = Control.MOUSE_FILTER_IGNORE
+ add_child(shade)
+ shade.set_anchors_and_offsets_preset(Control.PRESET_LEFT_WIDE)
+ shade.offset_right = 700.0
+ var box := VBoxContainer.new()
+ box.position = Vector2(110.0, 150.0)
+ box.add_theme_constant_override("separation", 16)
+ add_child(box)
+ var title := Label.new()
+ title.text = "Harvest Season"
+ title.add_theme_font_size_override("font_size", 92)
+ title.add_theme_color_override("font_color", UiTheme.GOLD)
+ title.add_theme_color_override("font_outline_color", Color(0.15, 0.1, 0.05))
+ title.add_theme_constant_override("outline_size", 14)
+ box.add_child(title)
+ var sub := Label.new()
+ sub.text = "The farmers are away. You're the scarecrow."
+ sub.add_theme_font_size_override("font_size", 28)
+ sub.add_theme_color_override("font_color", UiTheme.TEXT)
+ box.add_child(sub)
+ var gap := Control.new()
+ gap.custom_minimum_size = Vector2(0.0, 50.0)
+ box.add_child(gap)
+ continue_button = _button(box, "Continue")
+ continue_button.pressed.connect(func() -> void: continue_requested.emit())
+ save_note = Label.new()
+ save_note.add_theme_font_size_override("font_size", 19)
+ save_note.add_theme_color_override("font_color", Color(0.75, 0.77, 0.7))
+ box.add_child(save_note)
+ new_button = _button(box, "New vacation")
+ new_button.pressed.connect(func() -> void: new_requested.emit())
+ coop_button = _button(box, "Play with a friend")
+ coop_button.pressed.connect(func() -> void: coop_requested.emit())
+ settings_button = _button(box, "Settings")
+ settings_button.pressed.connect(func() -> void: settings_requested.emit())
+ quit_button = _button(box, "Quit")
+ quit_button.pressed.connect(func() -> void: quit_requested.emit())
+ notice = Label.new()
+ notice.add_theme_font_size_override("font_size", 22)
+ notice.add_theme_color_override("font_color", Color(1.0, 0.75, 0.5))
+ box.add_child(notice)
+ var credits := Label.new()
+ credits.text = "Art: KayKit and ithappy · Sounds: Kenney (CC0) · Music: \"On the Farm\"; DavidKBD, Purgatory · Co-op: GD-Sync · Made with Godot"
+ credits.add_theme_font_size_override("font_size", 16)
+ credits.add_theme_color_override("font_color", Color(0.6, 0.62, 0.56))
+ add_child(credits)
+ credits.set_anchors_and_offsets_preset(Control.PRESET_BOTTOM_LEFT)
+ credits.offset_top = -60.0
+ credits.offset_left = 110.0
+ visible = false
+
+
+## Shows the menu for the save as read (SaveGame.read): Continue says where it resumes, or is
+## off with the reason.
+func open(saved: SaveGame.Loaded, nights: int) -> void:
+ visible = true
+ var ok := saved != null and saved.status == SaveGame.Status.OK
+ continue_button.disabled = not ok
+ continue_button.focus_mode = Control.FOCUS_ALL if ok else Control.FOCUS_NONE
+ if ok:
+ save_note.text = "Morning of day %d of %d%s" % [saved.state.night, nights,
+ (" · saved " + saved.saved_at.replace("T", " ").left(16)) if saved.saved_at != "" else ""]
+ else:
+ save_note.text = saved.message if saved != null else "No saved vacation"
+ _focus_first.call_deferred()
+
+
+func close() -> void:
+ visible = false
+
+
+## Continue when it can be used, else New vacation (checked when it runs: open() may have been
+## called again since).
+func _focus_first() -> void:
+ if visible:
+ (new_button if continue_button.disabled else continue_button).grab_focus()
+
+
+func _button(parent: Control, text: String) -> Button:
+ var b := Button.new()
+ b.text = text
+ b.alignment = HORIZONTAL_ALIGNMENT_LEFT
+ b.custom_minimum_size = Vector2(380.0, 62.0)
+ b.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN
+ b.add_theme_font_size_override("font_size", 28)
+ parent.add_child(b)
+ return b
diff --git a/game/scripts/main_menu.gd.uid b/game/scripts/main_menu.gd.uid
new file mode 100644
index 0000000..12f9287
--- /dev/null
+++ b/game/scripts/main_menu.gd.uid
@@ -0,0 +1 @@
+uid://cw4ypb8hbwkef
diff --git a/game/scripts/night_plan.gd b/game/scripts/night_plan.gd
new file mode 100644
index 0000000..2522504
--- /dev/null
+++ b/game/scripts/night_plan.gd
@@ -0,0 +1,86 @@
+class_name NightPlan
+extends Resource
+## One night (the plan's NightDefinition): its title, the hint shown at dusk, an optional length,
+## and groups of enemies, each arriving at a time into the night. Where is not planned: every
+## enemy arrives at its own random point along the farm's edge (WaveDirector).
+## game/resources/nights/night_1..5.tres are the vacation's nights; game/resources/scenarios/
+## holds debug plans.
+## time seconds after nightfall when the group's first enemy arrives
+## count how many arrive
+## every seconds between them
+## type enemy type: "thief", "crow", or "breaker"
+## target what they're after: "crops", "animals", "supplies", or "any" (GameConfig.target_weights)
+## The plans are the nights' designs; GameConfig.wave_count_scale and wave_spacing_scale scale
+## every group when the night is played (count_scale x the enemies, spacing_scale x the time
+## between them), so the whole vacation's pressure is tuned in one place. A plan can set its own
+## scales instead (night 1 plays as designed, at 1 and 1).
+
+@export var title: String = ""
+## What the HUD tells the player at dusk about tonight.
+@export_multiline var dusk_hint: String = ""
+## Seconds the night lasts; 0 uses GameConfig.night_length.
+@export var night_length: float = 0.0
+## This night's own scales; 0 uses GameConfig.wave_count_scale / wave_spacing_scale.
+@export var count_scale: float = 0.0
+@export var spacing_scale: float = 0.0
+@export var groups: Array[Dictionary] = []
+
+
+## The scales this night is played at: its own, or the config's.
+func count_scale_in(config: GameConfig) -> float:
+ return count_scale if count_scale > 0.0 else config.wave_count_scale
+
+
+func spacing_scale_in(config: GameConfig) -> float:
+ return spacing_scale if spacing_scale > 0.0 else config.wave_spacing_scale
+
+
+## A group's enemies and the seconds between them, scaled.
+static func scaled_count(g: Dictionary, count_scale: float = 1.0) -> int:
+ return maxi(roundi(int(g.get("count", 1)) * count_scale), 1)
+
+
+static func scaled_every(g: Dictionary, spacing_scale: float = 1.0) -> float:
+ return float(g.get("every", 2.0)) * spacing_scale
+
+
+func total(count_scale: float = 1.0) -> int:
+ var n := 0
+ for g in groups:
+ n += scaled_count(g, count_scale)
+ return n
+
+
+## What's wrong with the plan (empty when it's fine): unknown enemy types, a target the type
+## doesn't take, or arrivals outside the night (as scaled).
+func problems(length: float, count_scale: float = 1.0, spacing_scale: float = 1.0) -> PackedStringArray:
+ var out := PackedStringArray()
+ if groups.is_empty():
+ out.append("no groups")
+ for k in groups.size():
+ var g: Dictionary = groups[k]
+ var where := "group %d" % (k + 1)
+ var type := String(g.get("type", ""))
+ var t := EnemySystem.TYPE_NAMES.find(type)
+ if t < 0:
+ out.append("%s: unknown enemy type '%s'" % [where, type])
+ continue
+ var target := String(g.get("target", "any"))
+ var allowed := {"crow": ["crops", "any"], "thief": ["animals", "supplies", "any"], "breaker": ["any"]}
+ if not (allowed[type] as Array).has(target):
+ out.append("%s: a %s doesn't go for '%s'" % [where, type, target])
+ if int(g.get("count", 0)) < 1 or float(g.get("every", 0.0)) <= 0.0:
+ out.append("%s: count and spacing must be positive" % where)
+ var last := float(g.get("time", 0.0)) + (scaled_count(g, count_scale) - 1) * scaled_every(g, spacing_scale)
+ if float(g.get("time", -1.0)) < 0.0 or last >= length:
+ out.append("%s: arrivals (%.0f..%.0f s) outside the %.0f s night" % [where, float(g.get("time", 0.0)), last, length])
+ return out
+
+
+## How many of each enemy type (EnemySystem type id -> count), scaled.
+func type_counts(count_scale: float = 1.0) -> Dictionary:
+ var out := {}
+ for g in groups:
+ var t := maxi(EnemySystem.TYPE_NAMES.find(String(g.get("type", "thief"))), 0)
+ out[t] = int(out.get(t, 0)) + scaled_count(g, count_scale)
+ return out
diff --git a/game/scripts/night_plan.gd.uid b/game/scripts/night_plan.gd.uid
new file mode 100644
index 0000000..1a31dd7
--- /dev/null
+++ b/game/scripts/night_plan.gd.uid
@@ -0,0 +1 @@
+uid://bx3jd1naaa7iu
diff --git a/game/scripts/pause_menu.gd b/game/scripts/pause_menu.gd
new file mode 100644
index 0000000..7da50e4
--- /dev/null
+++ b/game/scripts/pause_menu.gd
@@ -0,0 +1,98 @@
+class_name PauseMenu
+extends CenterContainer
+## Escape / Start during play (Main pauses the tree): where you are, then Resume, Restart the
+## night, Settings, Save & quit to the menu, and Quit the game, with a reminder of what Continue
+## picks up (the vacation is saved every morning).
+
+signal resume_requested
+signal restart_requested
+signal settings_requested
+signal menu_requested
+signal quit_requested
+
+var resume_button: Button
+var restart_button: Button
+var settings_button: Button
+var menu_button: Button
+var quit_button: Button
+var _where: Label
+var _note: Label
+
+
+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, 32)
+ panel.add_child(margin)
+ var box := VBoxContainer.new()
+ box.add_theme_constant_override("separation", 14)
+ margin.add_child(box)
+ var title := Label.new()
+ title.text = "Paused"
+ title.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
+ title.add_theme_font_size_override("font_size", 48)
+ title.add_theme_color_override("font_color", UiTheme.GOLD)
+ box.add_child(title)
+ _where = Label.new()
+ _where.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
+ _where.add_theme_font_size_override("font_size", 22)
+ box.add_child(_where)
+ resume_button = _button(box, "Resume")
+ resume_button.pressed.connect(func() -> void: resume_requested.emit())
+ restart_button = _button(box, "Restart the night")
+ restart_button.pressed.connect(func() -> void: restart_requested.emit())
+ settings_button = _button(box, "Settings")
+ settings_button.pressed.connect(func() -> void: settings_requested.emit())
+ menu_button = _button(box, "Save & quit to menu")
+ menu_button.pressed.connect(func() -> void: menu_requested.emit())
+ quit_button = _button(box, "Quit the game")
+ quit_button.pressed.connect(func() -> void: quit_requested.emit())
+ _note = Label.new()
+ _note.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
+ _note.custom_minimum_size = Vector2(520.0, 0.0)
+ _note.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
+ _note.add_theme_font_size_override("font_size", 18)
+ _note.add_theme_color_override("font_color", Color(0.72, 0.74, 0.68))
+ box.add_child(_note)
+ visible = false
+ mouse_filter = Control.MOUSE_FILTER_IGNORE
+
+
+## coop: 0 solo, 1 hosting a co-op game, 2 a partner in one (the farm doesn't stop for menus).
+func open(campaign: CampaignController, coop: int = 0) -> void:
+ var s := campaign.state
+ var phase: String = CampaignController.Phase.keys()[s.phase]
+ _where.text = "Night %d of %d · %s" % [s.night, campaign.config.campaign_nights, phase.replace("_", " ").capitalize()]
+ var over := campaign.outcome == CampaignController.Outcome.VACATION_COMPLETE
+ restart_button.disabled = over or coop == 2
+ menu_button.text = "Leave the game" if coop == 2 else "Save & quit to menu"
+ _note.text = "The vacation is finished." if over else \
+ "The vacation is saved every morning: Continue picks up at the morning of day %d." % s.night
+ if coop == 1:
+ _note.text += " Co-op: the farm keeps going while you're in this menu, and quitting ends the game for your friend."
+ elif coop == 2:
+ _note.text = "Co-op: the farm keeps going while you're in this menu. Only the host can restart the night; the host's game is saved."
+ visible = true
+ mouse_filter = Control.MOUSE_FILTER_STOP
+ resume_button.grab_focus.call_deferred()
+
+
+func _draw() -> void:
+ draw_rect(Rect2(Vector2.ZERO, size), Color(0.0, 0.0, 0.0, 0.4)) # dims what's behind
+
+
+func close() -> void:
+ visible = false
+ mouse_filter = Control.MOUSE_FILTER_IGNORE
+
+
+func _button(parent: Control, text: String) -> Button:
+ var b := Button.new()
+ b.text = text
+ b.custom_minimum_size = Vector2(420.0, 56.0)
+ b.add_theme_font_size_override("font_size", 24)
+ parent.add_child(b)
+ return b
diff --git a/game/scripts/pause_menu.gd.uid b/game/scripts/pause_menu.gd.uid
new file mode 100644
index 0000000..e375cdd
--- /dev/null
+++ b/game/scripts/pause_menu.gd.uid
@@ -0,0 +1 @@
+uid://f0v40qt4cy1s
diff --git a/game/scripts/phase_hud.gd b/game/scripts/phase_hud.gd
new file mode 100644
index 0000000..f89fc74
--- /dev/null
+++ b/game/scripts/phase_hud.gd
@@ -0,0 +1,195 @@
+class_name PhaseHud
+extends Control
+## Top-left phase indicator: a dial whose ring fills over the current phase with a sun (day), a
+## setting sun (dusk), a moon (night), or a rising sun (dawn) in it; "Night N of M"; the phase
+## and its time left; and a hint line (what tonight brings at dusk, thieves on the farm at night, the
+## early-night key when allowed). Each phase also announces itself with a banner that fades;
+## from dusk into the night, tonight's dusk hint (NightPlan.dusk_hint) shows under it.
+
+const DIAL_CENTER := Vector2(62.0, 64.0)
+const DIAL_RADIUS := 34.0
+const BANNER_TIME := 3.0
+
+var campaign: CampaignController
+var waves: WaveDirector
+var enemies: EnemySystem
+
+var _title: Label
+var _sub: Label
+var _hint: Label
+var _banner: Label
+var _banner_left: float = 0.0
+var _dusk_hint: Label
+
+
+func setup(p_campaign: CampaignController, p_waves: WaveDirector, p_enemies: EnemySystem) -> void:
+ campaign = p_campaign
+ waves = p_waves
+ enemies = p_enemies
+ campaign.phase_changed.connect(_on_phase_changed)
+ _on_phase_changed(campaign.state.phase, campaign.state.phase)
+
+
+func _ready() -> void:
+ set_anchors_preset(Control.PRESET_FULL_RECT)
+ mouse_filter = Control.MOUSE_FILTER_IGNORE
+ _title = _label(28, Vector2(112.0, 26.0))
+ _sub = _label(22, Vector2(112.0, 62.0))
+ _hint = _label(19, Vector2(112.0, 92.0))
+ _banner = Label.new()
+ _banner.set_anchors_preset(Control.PRESET_TOP_WIDE)
+ _banner.offset_top = 250.0
+ _banner.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
+ _banner.add_theme_font_size_override("font_size", 52)
+ _banner.add_theme_color_override("font_outline_color", Color.BLACK)
+ _banner.add_theme_constant_override("outline_size", 12)
+ _banner.mouse_filter = Control.MOUSE_FILTER_IGNORE
+ _banner.modulate.a = 0.0
+ add_child(_banner)
+ _dusk_hint = Label.new()
+ _dusk_hint.set_anchors_preset(Control.PRESET_CENTER_TOP)
+ _dusk_hint.offset_top = 330.0
+ _dusk_hint.offset_left = -520.0
+ _dusk_hint.offset_right = 520.0
+ _dusk_hint.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
+ _dusk_hint.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
+ _dusk_hint.add_theme_font_size_override("font_size", 26)
+ _dusk_hint.add_theme_color_override("font_color", Color(1.0, 0.88, 0.7))
+ _dusk_hint.add_theme_color_override("font_outline_color", Color.BLACK)
+ _dusk_hint.add_theme_constant_override("outline_size", 8)
+ _dusk_hint.mouse_filter = Control.MOUSE_FILTER_IGNORE
+ _dusk_hint.visible = false
+ add_child(_dusk_hint)
+
+
+## "Night 1 of 5 · Day · 2:34 left", as the HUD shows it (also used by tests).
+func describe() -> String:
+ return "%s · %s" % [_title.text, _sub.text]
+
+
+func _process(delta: float) -> void:
+ if campaign == null:
+ return
+ var s := campaign.state
+ var cfg := campaign.config
+ _title.text = "Night %d of %d" % [s.night, cfg.campaign_nights]
+ var left := _clock(s.phase_time_left)
+ var hint := ""
+ match s.phase:
+ CampaignController.Phase.MORNING:
+ _sub.text = "Morning"
+ CampaignController.Phase.DAY:
+ _sub.text = "Day · %s left" % left
+ if campaign.can_start_night_early():
+ hint = "[N] start the night early"
+ CampaignController.Phase.DUSK:
+ _sub.text = "Dusk · nightfall in %s" % left
+ hint = "\n".join(waves.tonight_warning()) if waves != null else ""
+ CampaignController.Phase.NIGHT:
+ _sub.text = "Night · sunrise in %s" % left
+ hint = on_the_farm(enemies)
+ CampaignController.Phase.DAWN:
+ _sub.text = "Dawn · the thieves are fleeing (%s)" % left
+ CampaignController.Phase.FARMERS_RETURN:
+ _sub.text = "The farmers are back"
+ CampaignController.Phase.GAME_OVER:
+ _sub.text = "Game over"
+ _hint.text = hint
+ var plan := waves.tonight() if waves != null else null
+ _dusk_hint.visible = plan != null and plan.dusk_hint != "" and waves.warning_active()
+ if _dusk_hint.visible:
+ _dusk_hint.text = plan.dusk_hint
+ _banner_left = maxf(_banner_left - delta, 0.0)
+ _banner.modulate.a = clampf(_banner_left / 0.8, 0.0, 1.0)
+ queue_redraw()
+
+
+func _draw() -> void:
+ if campaign == null:
+ return
+ var s := campaign.state
+ var length := campaign.phase_length(s.phase)
+ var frac := 1.0 - s.phase_time_left / length if is_finite(length) and length > 0.0 else 0.0
+ var phase := s.phase
+ var night := phase == CampaignController.Phase.NIGHT
+ var hint_size := _hint.get_minimum_size() if _hint.text != "" else Vector2.ZERO
+ var box := Vector2(maxf(430.0, 112.0 + hint_size.x + 18.0), maxf(104.0, 92.0 + hint_size.y - 14.0 + 22.0))
+ draw_rect(Rect2(Vector2(14.0, 14.0), box), Color(0.0, 0.0, 0.0, 0.42))
+ draw_circle(DIAL_CENTER, DIAL_RADIUS, Color(0.08, 0.1, 0.18, 0.95) if night else Color(0.25, 0.45, 0.7, 0.95))
+ var ring := Color(0.6, 0.7, 1.0) if night else Color(1.0, 0.85, 0.4)
+ draw_arc(DIAL_CENTER, DIAL_RADIUS - 4.0, -PI * 0.5, -PI * 0.5 + TAU * frac, 48, ring, 5.0)
+ match phase:
+ CampaignController.Phase.NIGHT:
+ draw_circle(DIAL_CENTER, 15.0, Color(0.93, 0.95, 1.0))
+ draw_circle(DIAL_CENTER + Vector2(7.0, -5.0), 13.0, Color(0.08, 0.1, 0.18))
+ CampaignController.Phase.DUSK, CampaignController.Phase.DAWN:
+ var c := DIAL_CENTER + Vector2(0.0, 8.0)
+ draw_circle(c, 15.0, Color(1.0, 0.55, 0.3) if phase == CampaignController.Phase.DUSK else Color(1.0, 0.72, 0.6))
+ draw_rect(Rect2(c + Vector2(-20.0, 4.0), Vector2(40.0, 16.0)), Color(0.12, 0.2, 0.12))
+ _:
+ draw_circle(DIAL_CENTER, 15.0, Color(1.0, 0.88, 0.35))
+
+
+func _on_phase_changed(phase: CampaignController.Phase, _previous: CampaignController.Phase) -> void:
+ var s := campaign.state
+ var text := ""
+ match phase:
+ CampaignController.Phase.DAY:
+ text = "Day %d: gather and build" % s.night
+ CampaignController.Phase.DUSK:
+ text = "Dusk: %s" % _tonight_title("the thieves come at nightfall")
+ CampaignController.Phase.NIGHT:
+ text = "Night %d: %s" % [s.night, _tonight_title("")] if _tonight_title("") != "" else "Night %d" % s.night
+ CampaignController.Phase.DAWN:
+ text = "Sunrise"
+ if text != "":
+ _banner.text = text
+ _banner_left = BANNER_TIME
+
+
+func _tonight_title(fallback: String) -> String:
+ var plan := waves.tonight() if waves != null else null
+ return plan.title if plan != null and plan.title != "" else fallback
+
+
+static func _clock(seconds: float) -> String:
+ var t := ceili(seconds)
+ return "%d:%02d" % [floori(t / 60.0), t % 60]
+
+
+## "3 crows, 2 thieves, and a fence breaker on the farm" (or "" when nobody is).
+static func on_the_farm(es: EnemySystem) -> String:
+ if es == null:
+ return ""
+ var counts := PackedInt32Array()
+ counts.resize(EnemySystem.TYPE_NAMES.size())
+ for d in es.active_count:
+ if es.alive[d] == 1:
+ counts[es.type[d]] += 1
+ var parts := PackedStringArray()
+ for t in [EnemySystem.TYPE_CROW, EnemySystem.TYPE_THIEF, EnemySystem.TYPE_BREAKER]:
+ if counts[t] == 1:
+ parts.append("a " + EnemySystem.NAMES[t])
+ elif counts[t] > 1:
+ parts.append("%d %s" % [counts[t], EnemySystem.PLURALS[t]])
+ if parts.is_empty():
+ return "Nobody on the farm"
+ var text := join_words(parts) + " on the farm"
+ return text[0].to_upper() + text.substr(1)
+
+
+static func join_words(words: PackedStringArray) -> String:
+ if words.size() <= 1:
+ return "".join(words)
+ return ", ".join(words.slice(0, words.size() - 1)) + " and " + words[words.size() - 1]
+
+
+func _label(font_size: int, at: Vector2) -> Label:
+ var l := Label.new()
+ l.position = at
+ 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
diff --git a/game/scripts/phase_hud.gd.uid b/game/scripts/phase_hud.gd.uid
new file mode 100644
index 0000000..0f2ef34
--- /dev/null
+++ b/game/scripts/phase_hud.gd.uid
@@ -0,0 +1 @@
+uid://bp7dq566avk2v
diff --git a/game/scripts/player_character.gd b/game/scripts/player_character.gd
index 71b91b2..7452eae 100644
--- a/game/scripts/player_character.gd
+++ b/game/scripts/player_character.gd
@@ -1,13 +1,28 @@
class_name PlayerCharacter
extends CharacterBody3D
-## The farmer: camera-relative movement on the move_* actions (WASD / arrows / left stick) with
-## gravity. The model turns toward the direction of travel and crossfades idle / walk / run.
-## The walk clip plays for partial stick deflection; full keyboard input runs.
+## The scarecrow's body: camera-relative movement on the move_* actions (WASD / arrows / left
+## stick) with gravity. The model turns toward the direction of travel and crossfades idle /
+## walk / run; the walk clip plays for partial stick deflection, full keyboard input runs.
+## While shooting (face_aim) the model turns toward the aim instead. During a channel
+## (start_channel: patching up, gathering) it is rooted and loops the channel's clip; once fallen
+## (die) it plays the death clip and takes no input until revived. set_flash() tints the model
+## for hit feedback.
+## Sprint (the workbench's Sprint upgrade): holding sprint (Shift / L3) while moving runs at
+## GameConfig.sprint_speed_mult times run_speed, the run clip sped up to match, for up to
+## sprint_time seconds; once it ends (time's up, let go, or stopped) it takes sprint_cooldown
+## seconds to come back. FarmSim sets config and campaign; without them, or without the upgrade,
+## there's no sprint.
+## Co-op: the other machine's scarecrow is remote_driven: it eases toward the position and facing
+## it was last sent (net_position, net_yaw) and animates by net_speed (like input strength: 1 at
+## run speed, more while sprinting) instead of reading the input. Each scarecrow sprints on the
+## machine that plays it. set_tint() and set_tag() tell the two scarecrows apart.
@export var run_speed := 5.0
@export var acceleration := 30.0
## How quickly the model turns to face the movement direction (higher = snappier).
@export var turn_speed := 12.0
+## How quickly the model turns toward the aim while shooting.
+@export var aim_turn_speed := 30.0
## Input strength (0..1) above which the run clip plays instead of the walk clip.
@export_range(0.0, 1.0) var run_threshold := 0.6
@@ -15,29 +30,201 @@ extends CharacterBody3D
@export var idle_animation: StringName = &"Idle_A"
@export var walk_animation: StringName = &"Walking_A"
@export var run_animation: StringName = &"Running_A"
+@export var channel_animation: StringName = &"Use_Item"
+@export var death_animation: StringName = &"Death_A"
@export var blend_time := 0.2
@onready var model: Node3D = $Model
@onready var animation_player: AnimationPlayer = $Model/AnimationPlayer
+var alive := true
+## Standing still for a channel: no movement input, the channel clip loops.
+var rooted := false
+var channel_clip: StringName = &"Use_Item"
+
+## Off while a co-op menu is up (the farm doesn't pause): no movement input.
+var input_enabled := true
+## Co-op: moved by the network (see above).
+var remote_driven := false
+var net_position := Vector3.ZERO
+var net_yaw: float = 0.0
+var net_speed: float = 0.0
+
+## Set by FarmSim: the sprint's tuning, and the farm state that says whether it's unlocked.
+var config: GameConfig
+var campaign: CampaignController
+## Sprinting now, seconds of it left, and seconds until the next one (0 = ready).
+var sprinting := false
+var sprint_left: float = 0.0
+var sprint_recharge: float = 0.0
+
+var _aim := Vector2.ZERO
+var _aim_hold: float = 0.0
+var _flash_mat: ShaderMaterial
+var _tag: Label3D
+
+
+func _ready() -> void:
+ _flash_mat = ShaderMaterial.new()
+ _flash_mat.shader = load("res://prototype/resources/hit_flash.gdshader") as Shader
+ for mi in model.find_children("*", "MeshInstance3D", true, false):
+ (mi as MeshInstance3D).material_overlay = _flash_mat
+
func _physics_process(delta: float) -> void:
- var move := _move_direction()
- var horizontal := Vector3(velocity.x, 0.0, velocity.z).move_toward(move * run_speed, acceleration * delta)
+ if remote_driven:
+ _follow_net(delta)
+ return
+ var move := _move_direction() if alive and not rooted else Vector3.ZERO
+ step_sprint(delta, can_sprint() and input_enabled and Input.is_action_pressed("sprint"), move.length_squared() > 1e-4)
+ var horizontal := Vector3(velocity.x, 0.0, velocity.z).move_toward(move * run_speed * speed_factor(), acceleration * delta)
velocity.x = horizontal.x
velocity.z = horizontal.z
if not is_on_floor():
velocity += get_gravity() * delta
move_and_slide()
-
- if move.length_squared() > 1e-4:
+ if not alive:
+ return
+ if _aim_hold > 0.0:
+ _aim_hold -= delta
+ var aim_yaw := atan2(-_aim.x, -_aim.y)
+ model.rotation.y = lerp_angle(model.rotation.y, aim_yaw, 1.0 - exp(-aim_turn_speed * delta))
+ elif move.length_squared() > 1e-4:
var yaw := atan2(-move.x, -move.z)
model.rotation.y = lerp_angle(model.rotation.y, yaw, 1.0 - exp(-turn_speed * delta))
- _update_animation(move.length())
+ _update_animation(move.length() * speed_factor())
+
+
+func _follow_net(delta: float) -> void:
+ velocity = Vector3.ZERO
+ if global_position.distance_to(net_position) > 6.0:
+ global_position = net_position # too far behind (a join, a respawn): jump
+ else:
+ global_position = global_position.lerp(net_position, 1.0 - exp(-14.0 * delta))
+ if not alive:
+ return
+ model.rotation.y = lerp_angle(model.rotation.y, net_yaw, 1.0 - exp(-20.0 * delta))
+ _update_animation(net_speed)
+
+
+## Starts following the network from where it is (no glide in from the old spot).
+func snap_to_net(at: Vector3, yaw: float) -> void:
+ net_position = at
+ net_yaw = yaw
+ global_position = at
+ model.rotation.y = yaw
+
+
+## Movement strength for the network: 0 standing .. 1 at run speed (more while sprinting).
+func move_strength() -> float:
+ return clampf(Vector2(velocity.x, velocity.z).length() / run_speed, 0.0, 2.0)
+
+
+## Whether the Sprint upgrade is owned.
+func can_sprint() -> bool:
+ return config != null and campaign != null and Upgrades.owned(campaign.state, "sprint")
+
+
+## Speed relative to run_speed: sprint_speed_mult while sprinting.
+func speed_factor() -> float:
+ return config.sprint_speed_mult if sprinting else 1.0
+
+
+## One tick of the sprint: starts one while held and moving (when unlocked and recharged); ends
+## it when its time is up, it's let go, or the scarecrow stops; then counts the recharge down.
+func step_sprint(dt: float, held: bool, moving: bool) -> void:
+ if sprinting:
+ sprint_left -= dt
+ if sprint_left <= 0.0 or not held or not moving or not alive or not can_sprint():
+ _end_sprint()
+ return
+ sprint_recharge = maxf(sprint_recharge - dt, 0.0)
+ if held and moving and alive and sprint_recharge == 0.0 and can_sprint():
+ sprinting = true
+ sprint_left = config.sprint_time
+
+
+## Ready to sprint again at once (a new morning).
+func reset_sprint() -> void:
+ sprinting = false
+ sprint_left = 0.0
+ sprint_recharge = 0.0
+
+
+func _end_sprint() -> void:
+ sprinting = false
+ sprint_left = 0.0
+ sprint_recharge = config.sprint_cooldown if config != null else 0.0
+
+
+## Tints the model (co-op: player 2's scarecrow is blue).
+func set_tint(color: Color) -> void:
+ 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 = color
+ m.material_override = tinted
+
+
+## A name tag over the head ("" hides it).
+func set_tag(text: String, color: Color) -> void:
+ if _tag == null:
+ _tag = Label3D.new()
+ _tag.billboard = BaseMaterial3D.BILLBOARD_ENABLED
+ _tag.no_depth_test = true
+ _tag.shaded = false
+ _tag.font_size = 44
+ _tag.outline_size = 12
+ _tag.pixel_size = 0.009
+ _tag.position = Vector3(0.0, 2.75, 0.0)
+ add_child(_tag)
+ _tag.text = text
+ _tag.modulate = color
+ _tag.visible = text != ""
+
+
+## Faces the (unit, XZ) aim direction instead of the travel direction for the next hold seconds.
+func face_aim(aim: Vector2, hold: float) -> void:
+ _aim = aim
+ _aim_hold = maxf(_aim_hold, hold)
+
+
+func start_channel(clip: StringName) -> void:
+ rooted = true
+ channel_clip = clip
+
+
+func stop_channel() -> void:
+ rooted = false
+
+
+func die() -> void:
+ alive = false
+ rooted = false
+ reset_sprint()
+ animation_player.speed_scale = 1.0
+ animation_player.play(death_animation, 0.15)
+
+
+func revive() -> void:
+ alive = true
+ rooted = false
+ _aim_hold = 0.0
+ reset_sprint()
+ animation_player.play(idle_animation, 0.1)
+
+
+## Hit tint over the model, 0 (none) .. 1 (solid red).
+func set_flash(amount: float) -> void:
+ _flash_mat.set_shader_parameter("flash", amount)
## Input rotated by the active camera's yaw, so "forward" is always up the screen.
func _move_direction() -> Vector3:
+ if not input_enabled:
+ return Vector3.ZERO
var input := Input.get_vector("move_left", "move_right", "move_forward", "move_back")
var camera := get_viewport().get_camera_3d()
var yaw := camera.global_rotation.y if camera != null else 0.0
@@ -45,10 +232,18 @@ func _move_direction() -> Vector3:
func _update_animation(strength: float) -> void:
+ if rooted:
+ animation_player.speed_scale = 1.0
+ # Some channel clips don't loop; replay them for as long as the channel lasts.
+ if animation_player.current_animation != channel_clip or not animation_player.is_playing():
+ animation_player.play(channel_clip, blend_time)
+ return
var clip := idle_animation
if strength > run_threshold:
clip = run_animation
elif strength > 0.0:
clip = walk_animation
+ # A sprint (strength above 1) plays the run clip faster.
+ animation_player.speed_scale = maxf(strength, 1.0) if clip == run_animation else 1.0
if animation_player.current_animation != clip:
animation_player.play(clip, blend_time)
diff --git a/game/scripts/pumpkin_bombs.gd b/game/scripts/pumpkin_bombs.gd
new file mode 100644
index 0000000..61a804d
--- /dev/null
+++ b/game/scripts/pumpkin_bombs.gd
@@ -0,0 +1,141 @@
+class_name PumpkinBombs
+extends Node3D
+## Pumpkin bombs in flight, for both scarecrows (ScarecrowCombat throws them): each flies in an
+## arc from the thrower's hand to its target, spinning, at GameConfig.bomb_speed, and bursts on
+## landing: every enemy within its radius (plus the enemy's hit radius) takes its damage, crows
+## included. Walls don't stop the blast; structures, animals, and the scarecrows aren't hurt.
+## A burst flashes an orange ring on the ground (the fear burst's shader) over the blast radius.
+## Co-op: on the partner's machine (replica) bombs are only drawn, from the host's throws; the
+## host's bursts do the damage.
+
+signal thrown(from: Vector3, to: Vector3)
+signal burst(at: Vector3, hits: int)
+
+const MAX_FLYING := 12
+const BURST_TIME := 0.5
+## Seconds of flight at the shortest and longest.
+const MIN_FLIGHT := 0.35
+const MAX_FLIGHT := 1.1
+
+var replica := false
+var bursts: int = 0
+var enemies_hit: int = 0
+
+var _cfg: GameConfig
+var _enemies: EnemySystem
+var _flying: Array[Dictionary] = [] # {from, to, t, time, damage, radius, mesh}
+var _idle: Array[MeshInstance3D] = []
+var _rings: Array[Dictionary] = [] # {mesh, t}
+
+
+func setup(cfg: GameConfig, enemies: EnemySystem) -> void:
+ _cfg = cfg
+ _enemies = enemies
+
+
+## Throws one from from (the hand) to to (on the ground). Returns false if too many are flying.
+func throw(from: Vector3, to: Vector3, damage: int, radius: float) -> bool:
+ if _flying.size() >= MAX_FLYING:
+ return false
+ var span := Vector2(to.x - from.x, to.z - from.z).length()
+ var mi: MeshInstance3D = _idle.pop_back() if not _idle.is_empty() else _new_mesh()
+ mi.visible = true
+ mi.global_position = from
+ mi.reset_physics_interpolation()
+ _flying.append({"from": from, "to": Vector3(to.x, 0.2, to.z), "t": 0.0, "damage": damage, "radius": radius,
+ "time": clampf(span / _cfg.bomb_speed, MIN_FLIGHT, MAX_FLIGHT), "peak": 1.0 + span * 0.22, "mesh": mi})
+ thrown.emit(from, to)
+ return true
+
+
+func flying() -> int:
+ return _flying.size()
+
+
+## Every bomb in flight lands now, without bursting (a new morning).
+func clear() -> void:
+ for f in _flying:
+ _park(f["mesh"])
+ _flying.clear()
+
+
+## Physics tick: flights move on; landed ones burst.
+func step(dt: float) -> void:
+ var i := 0
+ while i < _flying.size():
+ var f := _flying[i]
+ f["t"] = float(f["t"]) + dt
+ var u := minf(float(f["t"]) / float(f["time"]), 1.0)
+ var mi := f["mesh"] as MeshInstance3D
+ var at := (f["from"] as Vector3).lerp(f["to"], u)
+ at.y += float(f["peak"]) * 4.0 * u * (1.0 - u)
+ mi.global_position = at
+ mi.rotation = Vector3(u * TAU * 1.5, 0.0, u * PI)
+ if u < 1.0:
+ i += 1
+ continue
+ _burst(f["to"], int(f["damage"]), float(f["radius"]))
+ _park(mi)
+ _flying.remove_at(i)
+
+
+func _burst(at: Vector3, damage: int, radius: float) -> void:
+ bursts += 1
+ var n := 0
+ if not replica:
+ var es := _enemies
+ for d in es.active_count:
+ if es.alive[d] == 0:
+ continue
+ var reach := radius + es.t_hit_radius[es.type[d]]
+ if Vector2(es.pos_x[d] - at.x, es.pos_z[d] - at.z).length_squared() <= reach * reach:
+ es.apply_hit(d, damage)
+ n += 1
+ enemies_hit += n
+ _flash(at, radius)
+ burst.emit(at, n)
+
+
+func _new_mesh() -> MeshInstance3D:
+ var mi := MeshInstance3D.new()
+ mi.mesh = WeaponModels.mesh_of(2)
+ mi.scale = Vector3.ONE * WeaponModels.BOMB_SCALE
+ mi.top_level = true
+ add_child(mi)
+ return mi
+
+
+func _park(mi: MeshInstance3D) -> void:
+ mi.visible = false
+ _idle.append(mi)
+
+
+func _flash(at: Vector3, radius: float) -> void:
+ var plane := PlaneMesh.new()
+ plane.size = Vector2.ONE * radius * 2.0
+ var mat := ShaderMaterial.new()
+ mat.shader = load("res://game/resources/fear_burst.gdshader") as Shader
+ mat.set_shader_parameter("color", Color(1.0, 0.55, 0.12))
+ var mi := MeshInstance3D.new()
+ mi.mesh = plane
+ mi.material_override = mat
+ mi.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
+ mi.top_level = true
+ mi.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
+ add_child(mi)
+ mi.global_position = Vector3(at.x, 0.3, at.z)
+ _rings.append({"mesh": mi, "t": 0.0})
+
+
+func _process(delta: float) -> void:
+ var i := 0
+ while i < _rings.size():
+ var r := _rings[i]
+ r["t"] = float(r["t"]) + delta / BURST_TIME
+ var mi := r["mesh"] as MeshInstance3D
+ (mi.material_override as ShaderMaterial).set_shader_parameter("t", minf(float(r["t"]), 1.0))
+ if float(r["t"]) >= 1.0:
+ mi.queue_free()
+ _rings.remove_at(i)
+ continue
+ i += 1
diff --git a/game/scripts/pumpkin_bombs.gd.uid b/game/scripts/pumpkin_bombs.gd.uid
new file mode 100644
index 0000000..2fccca6
--- /dev/null
+++ b/game/scripts/pumpkin_bombs.gd.uid
@@ -0,0 +1 @@
+uid://bsvpn6aieq3fw
diff --git a/game/scripts/remote_controls.gd b/game/scripts/remote_controls.gd
new file mode 100644
index 0000000..d16f6f7
--- /dev/null
+++ b/game/scripts/remote_controls.gd
@@ -0,0 +1,86 @@
+class_name RemoteControls
+extends RefCounted
+## What a scarecrow played on another machine wants this tick, as the host sees it (co-op,
+## CoopSession). The partner's game sends its input every frame: which actions are held, a
+## running press count per action (so a press is never lost with a dropped packet: the host
+## counts the new ones), its aim (and the ground point a pumpkin bomb would land on), the weapon
+## in hand, and whether it is building or has the upgrade menu open. The
+## kit classes (Scarecrow, Interactions, ScarecrowCombat) read this instead of the local Input
+## when their remote is set.
+
+const ACTIONS: Array[StringName] = [&"fire", &"fear", &"patch", &"interact"]
+
+var aim := Vector2(0.0, -1.0)
+var aim_point := Vector3.ZERO
+var ground_point := Vector3.ZERO
+## ScarecrowCombat.Device of the partner's aim, and its ScarecrowCombat.Weapon (-1: none said).
+var device: int = 0
+var weapon: int = -1
+var build_active := false
+var ui_open := false
+
+var _held := 0
+var _presses := PackedInt32Array([0, 0, 0, 0])
+var _seen := PackedInt32Array([0, 0, 0, 0])
+
+
+func held(action: StringName) -> bool:
+ var i := ACTIONS.find(action)
+ return i >= 0 and (_held & (1 << i)) != 0
+
+
+## Whether the action was pressed since the last time this was asked (one press each time).
+func take(action: StringName) -> bool:
+ var i := ACTIONS.find(action)
+ if i < 0 or _seen[i] >= _presses[i]:
+ return false
+ _seen[i] += 1
+ return true
+
+
+## The partner's input record (CoopSession): {"held": bits, "presses": counts, "aim": Vector2,
+## "aim_point": Vector3, "ground": Vector3, "device", "weapon", "build", "ui"}.
+func apply(rec: Dictionary) -> void:
+ _held = int(rec.get("held", 0))
+ var p: Variant = rec.get("presses", [])
+ var counts: Array = Array(p) if p is PackedInt32Array else (p if p is Array else [])
+ for i in mini(ACTIONS.size(), counts.size()):
+ _presses[i] = maxi(_presses[i], int(counts[i]))
+ aim = rec.get("aim", aim)
+ aim_point = rec.get("aim_point", aim_point)
+ ground_point = rec.get("ground", ground_point)
+ device = int(rec.get("device", device))
+ weapon = int(rec.get("weapon", weapon))
+ build_active = bool(rec.get("build", false))
+ ui_open = bool(rec.get("ui", false))
+
+
+## Forget held actions (the partner left, or a new morning).
+func release() -> void:
+ _held = 0
+ _seen = _presses.duplicate()
+
+
+## The local side: an input record for the actions held now and every press so far.
+class Sender:
+ var presses := PackedInt32Array([0, 0, 0, 0])
+ var _was := PackedInt32Array([0, 0, 0, 0])
+
+ ## Counts presses from input events (taps between two frames still count).
+ func note(event: InputEvent) -> void:
+ for i in RemoteControls.ACTIONS.size():
+ if event.is_action_pressed(RemoteControls.ACTIONS[i], false):
+ presses[i] += 1
+ _was[i] = 1
+
+ func record(aim: Vector2, aim_point: Vector3, device: int, build: bool, ui: bool) -> Dictionary:
+ var bits := 0
+ for i in RemoteControls.ACTIONS.size():
+ var down := Input.is_action_pressed(RemoteControls.ACTIONS[i])
+ if down:
+ bits |= 1 << i
+ if _was[i] == 0: # pressed without an event (simulated input)
+ presses[i] += 1
+ _was[i] = 1 if down else 0
+ return {"held": bits, "presses": presses.duplicate(), "aim": aim, "aim_point": aim_point, "device": device,
+ "build": build, "ui": ui}
diff --git a/game/scripts/remote_controls.gd.uid b/game/scripts/remote_controls.gd.uid
new file mode 100644
index 0000000..0eda22c
--- /dev/null
+++ b/game/scripts/remote_controls.gd.uid
@@ -0,0 +1 @@
+uid://ub7soqkr43sf
diff --git a/game/scripts/resource_hud.gd b/game/scripts/resource_hud.gd
new file mode 100644
index 0000000..539efea
--- /dev/null
+++ b/game/scripts/resource_hud.gd
@@ -0,0 +1,76 @@
+class_name ResourceHud
+extends Control
+## Top-right materials readout: what the supply shed holds, and what the scarecrow carries in
+## its pouch (with its capacity). A line flashes when its numbers change.
+
+var campaign: CampaignController
+
+## Set by FarmSim: shows how many structures stand.
+var structures: StructureSystem
+
+var _shed: RichTextLabel
+var _pouch: RichTextLabel
+var _built: RichTextLabel
+var _last_shed := ""
+var _last_pouch := ""
+var _flash_shed: float = 0.0
+var _flash_pouch: float = 0.0
+
+
+func setup(p_campaign: CampaignController) -> void:
+ campaign = p_campaign
+
+
+func _ready() -> void:
+ set_anchors_preset(Control.PRESET_FULL_RECT)
+ mouse_filter = Control.MOUSE_FILTER_IGNORE
+ _shed = _line(20.0)
+ _pouch = _line(52.0)
+ _built = _line(84.0)
+
+
+func _process(delta: float) -> void:
+ if campaign == null:
+ return
+ var r := campaign.state.resources
+ var shed := "Shed %s" % _amounts(r.shed)
+ var pouch := "Pouch %d/%d %s" % [r.pouch_total(), r.pouch_capacity, _amounts(r.pouch) if r.pouch_total() > 0 else "empty"]
+ if shed != _last_shed:
+ _last_shed = shed
+ _shed.text = shed
+ _flash_shed = 1.0
+ if pouch != _last_pouch:
+ _last_pouch = pouch
+ _pouch.text = pouch
+ _flash_pouch = 1.0
+ _flash_shed = maxf(_flash_shed - delta * 2.0, 0.0)
+ _flash_pouch = maxf(_flash_pouch - delta * 2.0, 0.0)
+ if structures != null:
+ _built.text = "Built %d structures [B] build" % structures.count()
+ _shed.modulate = Color.WHITE.lerp(Color(1.0, 1.0, 0.55), _flash_shed)
+ _pouch.modulate = Color.WHITE.lerp(Color(1.0, 1.0, 0.55), _flash_pouch)
+
+
+func _amounts(d: Dictionary) -> String:
+ var parts: Array[String] = []
+ for m in ResourceStore.MATERIALS:
+ parts.append("[color=#%s]%s %d[/color]" % [GatherNode.COLORS[m].to_html(false), m.capitalize(), int(d[m])])
+ return " ".join(parts)
+
+
+func _line(y: float) -> RichTextLabel:
+ var l := RichTextLabel.new()
+ l.bbcode_enabled = true
+ l.fit_content = true
+ l.scroll_active = false
+ l.autowrap_mode = TextServer.AUTOWRAP_OFF
+ l.mouse_filter = Control.MOUSE_FILTER_IGNORE
+ l.add_theme_font_size_override("normal_font_size", 22)
+ l.add_theme_color_override("font_outline_color", Color.BLACK)
+ l.add_theme_constant_override("outline_size", 6)
+ l.set_anchors_preset(Control.PRESET_TOP_RIGHT)
+ l.offset_left = -520.0
+ l.offset_right = -24.0
+ l.offset_top = y
+ add_child(l)
+ return l
diff --git a/game/scripts/resource_hud.gd.uid b/game/scripts/resource_hud.gd.uid
new file mode 100644
index 0000000..d54d8cf
--- /dev/null
+++ b/game/scripts/resource_hud.gd.uid
@@ -0,0 +1 @@
+uid://dc3i7w50plvjs
diff --git a/game/scripts/resource_store.gd b/game/scripts/resource_store.gd
new file mode 100644
index 0000000..3844546
--- /dev/null
+++ b/game/scripts/resource_store.gd
@@ -0,0 +1,124 @@
+class_name ResourceStore
+extends RefCounted
+## The farm's construction materials (wood, scrap, straw): stock stored in the supply shed, and
+## what the scarecrow carries in its pouch (pouch_capacity units across all materials). The
+## pouch empties into the shed when the scarecrow walks in. Costs are paid all-or-nothing, from
+## the pouch first and then the shed. Only shed stock can be stolen.
+
+const MATERIALS: Array[String] = ["wood", "scrap", "straw"]
+
+var shed := {"wood": 0, "scrap": 0, "straw": 0}
+var pouch := {"wood": 0, "scrap": 0, "straw": 0}
+var pouch_capacity: int = 15
+
+
+func pouch_total() -> int:
+ var n := 0
+ for m in MATERIALS:
+ n += int(pouch[m])
+ return n
+
+
+func shed_total() -> int:
+ var n := 0
+ for m in MATERIALS:
+ n += int(shed[m])
+ return n
+
+
+## The material the shed holds most of (ties in MATERIALS order), or "" when it's empty.
+func most_stocked() -> String:
+ var best := ""
+ var most := 0
+ for m in MATERIALS:
+ if int(shed[m]) > most:
+ most = int(shed[m])
+ best = m
+ return best
+
+
+func pouch_room() -> int:
+ return maxi(pouch_capacity - pouch_total(), 0)
+
+
+## Puts up to amount into the pouch, as much as fits. Returns how much went in.
+func add_to_pouch(material: String, amount: int) -> int:
+ var added := mini(maxi(amount, 0), pouch_room())
+ pouch[material] = int(pouch[material]) + added
+ return added
+
+
+## Moves the whole pouch into the shed. Returns what moved (material -> amount, only non-zero).
+func deposit() -> Dictionary:
+ var moved := {}
+ for m in MATERIALS:
+ var n := int(pouch[m])
+ if n > 0:
+ shed[m] = int(shed[m]) + n
+ pouch[m] = 0
+ moved[m] = n
+ return moved
+
+
+func available(material: String) -> int:
+ return int(shed[material]) + int(pouch[material])
+
+
+## What a cost still lacks (material -> amount short; empty when affordable).
+func missing(cost: Dictionary) -> Dictionary:
+ var short := {}
+ for m in cost:
+ var need := int(cost[m]) - available(String(m))
+ if need > 0:
+ short[m] = need
+ return short
+
+
+func can_afford(cost: Dictionary) -> bool:
+ return missing(cost).is_empty()
+
+
+## Pays a cost from the pouch first, then the shed. Pays nothing and returns false if short.
+func pay(cost: Dictionary) -> bool:
+ if not can_afford(cost):
+ return false
+ for m in cost:
+ var need := int(cost[m])
+ var from_pouch := mini(need, int(pouch[m]))
+ pouch[m] = int(pouch[m]) - from_pouch
+ shed[m] = int(shed[m]) - (need - from_pouch)
+ return true
+
+
+func to_dict() -> Dictionary:
+ return {"shed": shed.duplicate(), "pouch": pouch.duplicate(), "pouch_capacity": pouch_capacity}
+
+
+## Returns null for unknown materials, missing entries, negative amounts, or an overfull pouch.
+static func from_dict(d: Variant) -> ResourceStore:
+ if not d is Dictionary:
+ return null
+ var dd := d as Dictionary
+ if not (dd.get("shed") is Dictionary and dd.get("pouch") is Dictionary and dd.has("pouch_capacity")):
+ return null
+ var r := ResourceStore.new()
+ r.pouch_capacity = int(dd["pouch_capacity"])
+ for part in ["shed", "pouch"]:
+ var src: Dictionary = dd[part]
+ if src.size() != MATERIALS.size():
+ return null
+ for m in MATERIALS:
+ if not src.has(m) or int(src[m]) < 0:
+ return null
+ var into: Dictionary = r.shed if part == "shed" else r.pouch
+ into[m] = int(src[m])
+ return r if r.pouch_capacity >= 1 and r.pouch_total() <= r.pouch_capacity else null
+
+
+## "6 wood, 2 straw" for a material -> amount dictionary (in MATERIALS order).
+static func describe(amounts: Dictionary) -> String:
+ var parts: Array[String] = []
+ for m in MATERIALS:
+ if int(amounts.get(m, 0)) > 0:
+ parts.append("%d %s" % [int(amounts[m]), m])
+ return ", ".join(parts)
diff --git a/game/scripts/resource_store.gd.uid b/game/scripts/resource_store.gd.uid
new file mode 100644
index 0000000..36920c9
--- /dev/null
+++ b/game/scripts/resource_store.gd.uid
@@ -0,0 +1 @@
+uid://cwji8ltvlipll
diff --git a/game/scripts/review_panel.gd b/game/scripts/review_panel.gd
new file mode 100644
index 0000000..3d53a67
--- /dev/null
+++ b/game/scripts/review_panel.gd
@@ -0,0 +1,223 @@
+class_name ReviewPanel
+extends CenterContainer
+## The morning screen (the untimed MORNING phase), between one night and the next day:
+## * Last night's results (from the night's log entry): per category what was taken,
+## recovered, and lost; enemies defeated by type and how many got away with loot; damage
+## (the scarecrow's, structures hit, broken, and repaired); materials gathered and spent
+## over the day and night.
+## * This morning: what's left (crops, animals, supplies, the scarecrow's health), what needs
+## repair (damaged structures keep their health bars on the farm), the pen's gate, the
+## materials on hand, and tonight's plan.
+## "Start the day" (focused, so Enter / A work) ends it. The first morning explains the vacation
+## instead of results.
+
+const CATEGORIES := ["Crops", "Animals", "Supplies"]
+const GOLD := Color(0.95, 0.82, 0.45)
+const GREY := Color(0.7, 0.72, 0.68)
+const RED := Color(1.0, 0.5, 0.42)
+
+var campaign: CampaignController
+var structures: StructureSystem
+## Set by FarmSim: whether the pen is open, and tonight's plan.
+var animals: AnimalSystem
+var waves: WaveDirector
+
+var _title: Label
+var _last_head: Label
+var _grid: GridContainer
+var _cells := {} # "Crops/taken" -> Label
+var _results: Label
+var _rule: HSeparator
+var _morning_head: Label
+var _body: Label
+var _start: Button
+
+
+func setup(p_campaign: CampaignController, p_structures: StructureSystem) -> void:
+ campaign = p_campaign
+ structures = p_structures
+ campaign.phase_changed.connect(func(_p: CampaignController.Phase, _prev: CampaignController.Phase) -> void: refresh())
+ refresh()
+
+
+func _ready() -> void:
+ set_anchors_preset(Control.PRESET_FULL_RECT)
+ var panel := PanelContainer.new()
+ panel.add_theme_stylebox_override("panel", backing())
+ 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", 12)
+ margin.add_child(box)
+ _title = _label(box, 38)
+ _last_head = _label(box, 26, GOLD)
+ _grid = GridContainer.new()
+ _grid.columns = 4
+ _grid.add_theme_constant_override("h_separation", 48)
+ _grid.add_theme_constant_override("v_separation", 2)
+ box.add_child(_grid)
+ for head in ["", "Taken", "Recovered", "Lost"]:
+ _label(_grid, 20, GREY).text = head
+ for cat: String in CATEGORIES:
+ _label(_grid, 22).text = cat
+ for col in ["taken", "recovered", "lost"]:
+ var l := _label(_grid, 22)
+ l.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
+ _cells["%s/%s" % [cat, col]] = l
+ _results = _label(box, 21)
+ _results.custom_minimum_size = Vector2(760.0, 0.0)
+ _results.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
+ _rule = HSeparator.new()
+ box.add_child(_rule)
+ _morning_head = _label(box, 26, GOLD)
+ _morning_head.text = "This morning"
+ _body = _label(box, 21)
+ _body.custom_minimum_size = Vector2(760.0, 0.0)
+ _body.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
+ _start = Button.new()
+ _start.text = "Start the day"
+ _start.custom_minimum_size = Vector2(260.0, 56.0)
+ _start.add_theme_font_size_override("font_size", 24)
+ _start.size_flags_horizontal = Control.SIZE_SHRINK_CENTER
+ _start.pressed.connect(func() -> void: campaign.begin_day())
+ box.add_child(_start)
+ visible = false
+
+
+## The dark, nearly opaque panel behind the morning screen, the menus, and the end screens.
+static func backing() -> StyleBoxFlat:
+ var bg := StyleBoxFlat.new()
+ bg.bg_color = Color(0.1, 0.12, 0.1)
+ bg.border_color = Color(0.55, 0.5, 0.35)
+ bg.set_border_width_all(2)
+ bg.set_corner_radius_all(6)
+ return bg
+
+
+func refresh() -> void:
+ if campaign == null:
+ return
+ visible = campaign.state.phase == CampaignController.Phase.MORNING
+ mouse_filter = Control.MOUSE_FILTER_STOP if visible else Control.MOUSE_FILTER_IGNORE
+ if not visible:
+ return
+ var s := campaign.state
+ var nights := campaign.config.campaign_nights
+ var first := s.night_log.is_empty()
+ for n: Control in [_last_head, _grid, _results, _rule, _morning_head]:
+ n.visible = not first
+ var lines: Array[String] = []
+ if first:
+ _title.text = "The farmers are away"
+ lines.append("Keep the farm safe for %d nights until they come home: the crops, the animals in the pen, and the supplies in the shed." % nights)
+ lines.append("By day, gather wood, scrap, and straw (hold E), store them at the barn, and build defenses (B). There's more to gather off the farm, to the north, east, and south.")
+ lines.append("At night, stab thieves with your pitchfork (left mouse), scare them off (Q), and pick up anything they drop. A dropped animal runs off: walk up to it and lead it back to the pen. The workbench sells a corn shooter and pumpkin bombs (switch weapons with Tab or 1-3).")
+ else:
+ var e: Dictionary = s.night_log[s.night_log.size() - 1]
+ _title.text = "Morning of day %d of %d" % [s.night, nights]
+ var plan := waves.plan_for(int(e["night"])) if waves != null else null
+ _last_head.text = "Night %d: %s" % [e["night"], plan.title] if plan != null and plan.title != "" else "Night %d" % e["night"]
+ _fill_grid(e)
+ _results.text = "\n".join(result_lines(e, s))
+ lines.append("Left: %d of %d crops, %d of %d animals, %d supplies. Scarecrow: %d of %d HP." % [s.crops, s.crops_total,
+ s.animals, s.animals_total, s.supplies, s.scarecrow_hp, s.scarecrow_max_hp])
+ lines.append(_damage_line())
+ if animals != null and animals.pen_open and s.animals > 0:
+ lines.append("The pen is open: put a gate in its opening (B) before nightfall, or animals will wander out.")
+ var r := s.resources
+ lines.append("In the shed: %s. In the pouch: %s." % [_or_none(ResourceStore.describe(r.shed)), _or_none(ResourceStore.describe(r.pouch))])
+ var plan := waves.tonight() if waves != null else null
+ if plan != null and plan.title != "":
+ lines.append("Tonight: %s. Upgrades at the work area: %d of %d done." % [plan.title, _upgrades_done(), Upgrades.ORDER.size()])
+ _body.text = "\n".join(lines)
+ _start.grab_focus.call_deferred()
+
+
+## The results table as text, one row per category ("Crops 4 3 1"), for tests.
+func grid_text() -> String:
+ var rows: Array[String] = []
+ for cat: String in CATEGORIES:
+ rows.append("%s %s %s %s" % [cat, _cells[cat + "/taken"].text, _cells[cat + "/recovered"].text, _cells[cat + "/lost"].text])
+ return "\n".join(rows)
+
+
+## Per category: (taken, recovered, lost) in a night's log entry. Animals taken include those
+## that wandered out of an open pen.
+static func category_counts(e: Dictionary) -> Dictionary:
+ return {
+ "Crops": [int(e["crops_stolen"]), int(e["crops_recovered"]), int(e["crops_lost"])],
+ "Animals": [int(e["animals_stolen"]) + int(e["animals_strayed"]), int(e["animals_recovered"]), int(e["animals_lost"])],
+ "Supplies": [int(e["supplies_stolen"]), int(e["supplies_recovered"]), int(e["supplies_lost"])],
+ }
+
+
+## Enemies, damage, and materials of a night's log entry.
+static func result_lines(e: Dictionary, s: FarmState) -> Array[String]:
+ var out: Array[String] = []
+ var enemies := "Enemies defeated: %s." % Assessment.enemies_line(e)
+ if int(e["escaped"]) > 0:
+ enemies = enemies.trim_suffix(".") + "; %d got away with loot." % int(e["escaped"])
+ out.append(enemies)
+ var damage := PackedStringArray()
+ damage.append("the scarecrow took %d" % int(e["scarecrow_damage"]) if int(e["scarecrow_damage"]) > 0 else "the scarecrow wasn't hurt")
+ if int(e["patches"]) > 0:
+ damage.append("patched up %d %s" % [int(e["patches"]), "time" if int(e["patches"]) == 1 else "times"])
+ if int(e["structures_damaged"]) > 0:
+ damage.append("structures took %d damage" % int(e["structures_damaged"]))
+ if int(e["structures_destroyed"]) > 0:
+ damage.append("%d broken" % int(e["structures_destroyed"]))
+ if int(e["repairs"]) > 0:
+ damage.append("%d repaired" % int(e["repairs"]))
+ out.append("Damage: %s." % ", ".join(damage))
+ out.append("Materials: gathered %s; spent %s." % [Assessment.materials_line(e, "gathered_"), Assessment.materials_line(e, "spent_")])
+ if s != null and int(e["structures_built"]) + int(e["upgrades_bought"]) > 0:
+ out.append("Built %d, upgrades bought %d." % [int(e["structures_built"]), int(e["upgrades_bought"])])
+ return out
+
+
+func _fill_grid(e: Dictionary) -> void:
+ var counts := category_counts(e)
+ for cat: String in CATEGORIES:
+ var c: Array = counts[cat]
+ for k in 3:
+ var l: Label = _cells["%s/%s" % [cat, ["taken", "recovered", "lost"][k]]]
+ l.text = str(c[k])
+ l.add_theme_color_override("font_color", RED if k == 2 and int(c[k]) > 0 else Color(0.92, 0.92, 0.88))
+
+
+func _damage_line() -> String:
+ if structures == null or structures.count() == 0:
+ return "Nothing built yet."
+ var damaged := {}
+ for e in campaign.state.structures:
+ if int(e["hp"]) < structures.max_hp(e["type"]):
+ damaged[e["type"]] = int(damaged.get(e["type"], 0)) + 1
+ if damaged.is_empty():
+ return "No repairs needed."
+ var parts: Array[String] = []
+ for t in damaged:
+ parts.append("%d %s%s" % [damaged[t], StructureSystem.NAMES[t].to_lower(), "s" if int(damaged[t]) > 1 else ""])
+ return "Needs repair (marked with health bars): %s." % ", ".join(parts)
+
+
+func _upgrades_done() -> int:
+ var n := 0
+ for id in Upgrades.ORDER:
+ if Upgrades.owned(campaign.state, id):
+ n += 1
+ return n
+
+
+func _label(parent: Node, font_size: int, color: Color = Color(0.92, 0.92, 0.88)) -> Label:
+ var l := Label.new()
+ l.add_theme_font_size_override("font_size", font_size)
+ l.add_theme_color_override("font_color", color)
+ parent.add_child(l)
+ return l
+
+
+static func _or_none(text: String) -> String:
+ return text if text != "" else "nothing"
diff --git a/game/scripts/review_panel.gd.uid b/game/scripts/review_panel.gd.uid
new file mode 100644
index 0000000..ad8aded
--- /dev/null
+++ b/game/scripts/review_panel.gd.uid
@@ -0,0 +1 @@
+uid://cwll33writ0hq
diff --git a/game/scripts/save_game.gd b/game/scripts/save_game.gd
new file mode 100644
index 0000000..3b34ae1
--- /dev/null
+++ b/game/scripts/save_game.gd
@@ -0,0 +1,108 @@
+class_name SaveGame
+extends RefCounted
+## The vacation's save file: the farm state of the latest morning as JSON (full float precision)
+## at user://savegame.json. CampaignController writes it every MORNING when its save_path is set
+## (Main sets it; tests and the farm scene on its own don't), so Continue always resumes at that
+## morning, and a Game Over leaves the failed night's morning there to retry. Finishing the
+## vacation deletes it.
+##
+## Reading it back never crashes and never loads something broken: a missing file, unreadable
+## JSON, a state that FarmState.from_dict rejects or that isn't a morning, and a save from a newer
+## version are reported (Loaded.status) and not loaded. A save from an older version is upgraded
+## first (migrate) when there's a known way forward, and reported as OLD when there isn't.
+
+enum Status { OK, MISSING, CORRUPT, OLD, NEWER }
+
+const PATH := "user://savegame.json"
+const GAME := "harvest-season"
+
+
+class Loaded:
+ var status: Status = Status.MISSING
+ ## The saved farm state (status OK only).
+ var state: FarmState
+ ## For the player: why it can't be continued ("" when it can).
+ var message := ""
+ var saved_at := ""
+ ## The version the file was written with (-1 if unknown).
+ var version: int = -1
+
+
+## Writes a FarmState.to_dict() atomically: to path.tmp, then renamed over path.
+static func write(state: Dictionary, path: String = PATH) -> Error:
+ var data := {"game": GAME, "version": FarmState.VERSION, "saved_at": Time.get_datetime_string_from_system(false, true),
+ "state": state}
+ var tmp := path + ".tmp"
+ var f := FileAccess.open(tmp, FileAccess.WRITE)
+ if f == null:
+ return FileAccess.get_open_error()
+ f.store_string(JSON.stringify(data, "\t", true, true))
+ f.close()
+ return DirAccess.rename_absolute(ProjectSettings.globalize_path(tmp), ProjectSettings.globalize_path(path))
+
+
+static func read(path: String = PATH) -> Loaded:
+ var out := Loaded.new()
+ if not FileAccess.file_exists(path):
+ out.message = "No saved vacation"
+ return out
+ var json := JSON.new()
+ var parsed: Variant = json.data if json.parse(FileAccess.get_file_as_string(path)) == OK else null
+ if not parsed is Dictionary or String((parsed as Dictionary).get("game", "")) != GAME \
+ or not (parsed as Dictionary).get("state") is Dictionary:
+ return _fail(out, Status.CORRUPT, "The saved vacation is damaged and can't be continued")
+ out.saved_at = String(parsed.get("saved_at", ""))
+ var d: Dictionary = parsed["state"]
+ out.version = int(d.get("version", -1))
+ if out.version > FarmState.VERSION:
+ return _fail(out, Status.NEWER, "The saved vacation is from a newer version of the game")
+ if out.version < FarmState.VERSION:
+ d = migrate(d)
+ if d.is_empty():
+ return _fail(out, Status.OLD, "The saved vacation is from an older version and can't be continued")
+ var s := FarmState.from_dict(d)
+ if s == null or s.phase != CampaignController.Phase.MORNING:
+ return _fail(out, Status.CORRUPT, "The saved vacation is damaged and can't be continued")
+ out.status = Status.OK
+ out.state = s
+ return out
+
+
+## Upgrades a FarmState dictionary from an older VERSION, one version at a time. Returns {} when
+## there's no way forward (version 1 predates saving to disk).
+static func migrate(d: Dictionary) -> Dictionary:
+ var out := d.duplicate(true)
+ while int(out.get("version", -1)) < FarmState.VERSION:
+ match int(out.get("version", -1)):
+ 2:
+ # Version 3 counts more per night: kills, damage, building, and materials.
+ for entry: Variant in out.get("night_log", []):
+ if entry is Dictionary:
+ for key in FarmState.LOG_KEYS:
+ if not (entry as Dictionary).has(key):
+ entry[key] = 0
+ out["version"] = 3
+ 3:
+ # Version 4 adds co-op: a second scarecrow's health.
+ out["coop"] = false
+ out["partner_max_hp"] = int(out.get("scarecrow_max_hp", 10))
+ out["partner_hp"] = int(out.get("scarecrow_max_hp", 10))
+ out["version"] = 4
+ _:
+ return {}
+ return out
+
+
+static func exists(path: String = PATH) -> bool:
+ return FileAccess.file_exists(path)
+
+
+static func delete(path: String = PATH) -> void:
+ if FileAccess.file_exists(path):
+ DirAccess.remove_absolute(ProjectSettings.globalize_path(path))
+
+
+static func _fail(out: Loaded, status: Status, message: String) -> Loaded:
+ out.status = status
+ out.message = message
+ return out
diff --git a/game/scripts/save_game.gd.uid b/game/scripts/save_game.gd.uid
new file mode 100644
index 0000000..ed53499
--- /dev/null
+++ b/game/scripts/save_game.gd.uid
@@ -0,0 +1 @@
+uid://b85t5jrscqbpo
diff --git a/game/scripts/scarecrow.gd b/game/scripts/scarecrow.gd
new file mode 100644
index 0000000..3434429
--- /dev/null
+++ b/game/scripts/scarecrow.gd
@@ -0,0 +1,302 @@
+class_name Scarecrow
+extends Node3D
+## The scarecrow's defensive kit apart from the gun (ScarecrowCombat):
+## * Health lives in FarmState and carries over between nights (D7). try_damage() is the only
+## way to hurt the scarecrow: after an accepted hit it is invulnerable for
+## invulnerability_time, so several hits on one tick cost one hit's damage. Hits blink the
+## model red, tint the screen (ScarecrowHud), and interrupt patching.
+## * Fear (fear action): every thief within fear_radius flees for fear_duration; carriers
+## drop their crop (D5) and thieves mid-steal lose their progress. Then fear_cooldown
+## seconds until the next one. A ring under the scarecrow shows that fear is ready.
+## * Patch up (hold patch): stand still, unable to shoot, for patch_time, then +patch_heal HP
+## for costs["patch"] (straw, paid when the patch completes). Releasing early, taking a hit,
+## or using fear cancels it. Not available at full health, while gathering, or without the
+## straw (patch_denied says what's missing).
+## * Defeat: at 0 HP the scarecrow falls (death clip) and stops acting; the campaign turns it
+## into Game Over on the same tick (in co-op only once both have fallen: until then it's out
+## until the morning). Every new morning, also after a retry, revives it with fear ready.
+## In co-op there are two kits: slot 0 (player 1) uses FarmState.scarecrow_hp, slot 1 (player 2)
+## partner_hp. A kit whose remote is set (the partner's, on the host) reads RemoteControls
+## instead of the local input.
+
+signal damaged(hp: int)
+signal fear_used(position: Vector3, scared: int)
+signal fear_ready
+signal patched(hp: int)
+signal patch_cancelled
+signal patch_denied(missing: Dictionary)
+
+const BURST_TIME := 0.45
+
+var config: GameConfig
+var campaign: CampaignController
+var player: PlayerCharacter
+var enemies: EnemySystem
+var behavior: ThiefBehavior
+## Set by FarmSim: patching doesn't start while a gather channel runs.
+var interactions: Interactions
+## 0 = player 1, 1 = player 2 (whose health in FarmState), and the partner's input (co-op host).
+var slot: int = 0
+var remote: RemoteControls
+
+var alive := true
+var invulnerable_left: float = 0.0
+## Seconds until fear can be used again (0 = ready).
+var fear_left: float = 0.0
+var patching := false
+var patch_elapsed: float = 0.0
+var accepted_hits: int = 0
+var rejected_hits: int = 0
+
+var _burst: MeshInstance3D
+var _burst_mat: ShaderMaterial
+var _burst_t: float = -1.0
+var _ready_ring: MeshInstance3D
+var _ready_mat: StandardMaterial3D
+var _patch_ring: MeshInstance3D
+var _patch_mat: ShaderMaterial
+var _time: float = 0.0
+var _fear_requested := false
+var _patch_denied := false
+var _fear_was_held := false
+
+
+func setup(cfg: GameConfig, p_campaign: CampaignController, p_player: PlayerCharacter,
+ p_enemies: EnemySystem, p_behavior: ThiefBehavior) -> void:
+ config = cfg
+ campaign = p_campaign
+ player = p_player
+ enemies = p_enemies
+ behavior = p_behavior
+ campaign.campaign_ended.connect(_on_campaign_ended)
+ _build_effects()
+
+
+func hp() -> int:
+ return campaign.state.scarecrow_hp if slot == 0 else campaign.state.partner_hp
+
+
+func max_hp() -> int:
+ return campaign.state.scarecrow_max_hp if slot == 0 else campaign.state.partner_max_hp
+
+
+func _set_hp(value: int) -> void:
+ if slot == 0:
+ campaign.state.scarecrow_hp = clampi(value, 0, campaign.state.scarecrow_max_hp)
+ else:
+ campaign.state.partner_hp = clampi(value, 0, campaign.state.partner_max_hp)
+
+
+func can_shoot() -> bool:
+ return alive and not patching
+
+
+## Share of the fear cooldown that has passed: 1 when fear is ready.
+func fear_charge() -> float:
+ var cd := fear_cooldown()
+ return 1.0 - fear_left / cd if cd > 0.0 else 1.0
+
+
+## Fear's reach and recharge time, with upgrades.
+func fear_radius() -> float:
+ return Upgrades.value(config, campaign.state, "fear_radius")
+
+
+func fear_cooldown() -> float:
+ return Upgrades.value(config, campaign.state, "fear_cooldown")
+
+
+## One physics tick: timers, then the fear and patch inputs.
+func step(dt: float) -> void:
+ invulnerable_left = maxf(invulnerable_left - dt, 0.0)
+ if fear_left > 0.0:
+ fear_left = maxf(fear_left - dt, 0.0)
+ if fear_left == 0.0:
+ fear_ready.emit()
+ # A fear press counts from its input event (so even a tap between two ticks registers) or
+ # from the action turning pressed since the last tick (simulated input).
+ var held := remote.held(&"fear") if remote != null else Input.is_action_pressed("fear")
+ var pressed := _fear_requested or (held and not _fear_was_held)
+ if remote != null:
+ pressed = remote.take(&"fear")
+ _fear_requested = false
+ _fear_was_held = held
+ if not alive:
+ return
+ if pressed:
+ use_fear()
+ step_patch(dt, remote.held(&"patch") if remote != null else Input.is_action_pressed("patch"))
+
+
+func _unhandled_input(event: InputEvent) -> void:
+ if remote == null and event.is_action_pressed("fear", false):
+ _fear_requested = true
+
+
+## Advances the patch channel while held (keeps channeling, one patch after another, for as
+## long as it is held and the scarecrow isn't at full health); releasing cancels.
+func step_patch(dt: float, held: bool) -> void:
+ if not held or not alive:
+ cancel_patch()
+ _patch_denied = false
+ return
+ var s := campaign.state
+ var cost: Dictionary = config.costs.get("patch", {})
+ if not patching:
+ if hp() >= max_hp() or (interactions != null and interactions.channeling()):
+ return
+ if not s.resources.can_afford(cost):
+ if not _patch_denied: # once per press
+ _patch_denied = true
+ patch_denied.emit(s.resources.missing(cost))
+ return
+ patching = true
+ patch_elapsed = 0.0
+ player.start_channel(player.channel_animation)
+ patch_elapsed += dt
+ if patch_elapsed >= config.patch_time:
+ _end_patch()
+ if s.pay(cost):
+ _set_hp(hp() + config.patch_heal)
+ s.record_event("patches")
+ patched.emit(hp())
+
+
+func cancel_patch() -> void:
+ if patching:
+ _end_patch()
+ patch_cancelled.emit()
+
+
+## The only way to hurt the scarecrow. Returns true if the hit was accepted.
+func try_damage(amount: int = 1) -> bool:
+ if not alive:
+ return false
+ if invulnerable_left > 0.0:
+ rejected_hits += 1
+ return false
+ invulnerable_left = config.invulnerability_time
+ accepted_hits += 1
+ var s := campaign.state
+ s.record_event("scarecrow_damage", mini(amount, hp()))
+ _set_hp(hp() - amount)
+ cancel_patch()
+ damaged.emit(hp())
+ if hp() <= 0:
+ _die()
+ return true
+
+
+## Fear burst at the scarecrow. Returns how many thieves fled, or -1 if it isn't ready.
+func use_fear() -> int:
+ if not alive or fear_left > 0.0:
+ return -1
+ cancel_patch()
+ fear_left = fear_cooldown()
+ var p := player.global_position
+ var n := behavior.scare(enemies, Vector2(p.x, p.z), fear_radius())
+ play_burst()
+ fear_used.emit(p, n)
+ return n
+
+
+## The fear ring spreading from the scarecrow (also on the co-op partner's machine).
+func play_burst() -> void:
+ var p := player.global_position
+ _burst.scale = Vector3.ONE * fear_radius() / config.fear_radius
+ _burst_t = 0.0
+ _burst.global_position = Vector3(p.x, p.y + 0.3, p.z)
+
+
+func reset_for_morning() -> void:
+ alive = true
+ invulnerable_left = 0.0
+ fear_left = 0.0
+ _end_patch()
+ player.revive()
+ player.set_flash(0.0)
+
+
+func _die() -> void:
+ if not alive:
+ return
+ alive = false
+ _end_patch()
+ player.die()
+
+
+func _end_patch() -> void:
+ patching = false
+ patch_elapsed = 0.0
+ if player != null:
+ player.stop_channel()
+
+
+func _on_campaign_ended(outcome: CampaignController.Outcome) -> void:
+ if outcome == CampaignController.Outcome.GAME_OVER_SCARECROW:
+ _die()
+
+
+func _process(delta: float) -> void:
+ if player == null:
+ return
+ _time += delta
+ var flash := 0.0
+ if alive and invulnerable_left > 0.0:
+ flash = 0.65 if fmod(invulnerable_left, 0.2) > 0.1 else 0.15
+ player.set_flash(flash)
+ var at := player.get_global_transform_interpolated().origin
+ if _burst_t >= 0.0:
+ _burst_t += delta / BURST_TIME
+ _burst.visible = _burst_t < 1.0
+ _burst_mat.set_shader_parameter("t", clampf(_burst_t, 0.0, 1.0))
+ if _burst_t >= 1.0:
+ _burst_t = -1.0
+ _ready_ring.visible = alive and fear_left == 0.0
+ if _ready_ring.visible:
+ _ready_ring.global_position = at + Vector3(0.0, 0.12, 0.0)
+ _ready_mat.albedo_color.a = 0.45 + 0.25 * sin(_time * 4.0)
+ _patch_ring.visible = patching
+ if patching:
+ _patch_ring.global_position = at + Vector3(0.0, 2.75, 0.0)
+ _patch_mat.set_shader_parameter("progress", patch_elapsed / config.patch_time)
+
+
+func _build_effects() -> void:
+ var plane := PlaneMesh.new()
+ plane.size = Vector2.ONE * config.fear_radius * 2.0
+ _burst_mat = ShaderMaterial.new()
+ _burst_mat.shader = load("res://game/resources/fear_burst.gdshader") as Shader
+ _burst = _effect(plane, _burst_mat)
+
+ var torus := TorusMesh.new()
+ torus.inner_radius = 0.55
+ torus.outer_radius = 0.68
+ torus.rings = 32
+ torus.ring_segments = 4
+ _ready_mat = StandardMaterial3D.new()
+ _ready_mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
+ _ready_mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
+ _ready_mat.albedo_color = Color(0.6, 0.9, 1.0, 0.6)
+ _ready_mat.no_depth_test = true
+ _ready_ring = _effect(torus, _ready_mat)
+ _ready_ring.scale = Vector3(1.0, 0.12, 1.0)
+
+ var quad := QuadMesh.new()
+ quad.size = Vector2(0.9, 0.9)
+ _patch_mat = ShaderMaterial.new()
+ _patch_mat.shader = load("res://game/resources/steal_ring.gdshader") as Shader
+ _patch_mat.set_shader_parameter("fill_color", Color(0.45, 1.0, 0.4))
+ _patch_ring = _effect(quad, _patch_mat)
+
+
+func _effect(mesh: Mesh, mat: Material) -> MeshInstance3D:
+ var mi := MeshInstance3D.new()
+ mi.mesh = mesh
+ mi.material_override = mat
+ mi.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
+ mi.top_level = true
+ mi.visible = false
+ mi.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
+ add_child(mi)
+ return mi
diff --git a/game/scripts/scarecrow.gd.uid b/game/scripts/scarecrow.gd.uid
new file mode 100644
index 0000000..8938d44
--- /dev/null
+++ b/game/scripts/scarecrow.gd.uid
@@ -0,0 +1 @@
+uid://bskggq8mxtab3
diff --git a/game/scripts/scarecrow_combat.gd b/game/scripts/scarecrow_combat.gd
new file mode 100644
index 0000000..94d3e34
--- /dev/null
+++ b/game/scripts/scarecrow_combat.gd
@@ -0,0 +1,433 @@
+class_name ScarecrowCombat
+extends Node3D
+## The scarecrow's weapons, ported from the prototype's PlayerInput + WeaponController (Step 4
+## finished the kit; the weapons came after Step 11):
+## * Three weapons (Weapon): the pitchfork, every scarecrow's from the start; the corn shooter
+## and pumpkin bombs, bought at the workbench (Upgrades "corn_shooter", "pumpkin_bomb").
+## weapon_next (Tab / d-pad down) cycles through the ones owned, weapon_1..3 (1-3) pick one,
+## both only outside build mode (where those keys pick structures) and with no menu open.
+## One no longer owned (a retry from before it was bought) goes back to the pitchfork.
+## * Aim with the mouse (the cursor projected onto the combat-height plane through the follow
+## camera, corrected for the gun's side offset so shots pass through the cursor; bombs land
+## on the ground point under the cursor) or the right stick (camera-relative, radial dead
+## zone, last aim kept). The active device switches only on deliberate input: mouse travel
+## past a threshold or a click, stick deflection past the dead zone or the trigger.
+## * Attack with the fire action, needing a fresh press after every reset; holding it repeats:
+## pitchfork a stab every pitchfork_interval: the nearest pitchfork_targets enemies
+## within pitchfork_reach and pitchfork_arc of the aim, with a clear line,
+## take pitchfork_damage
+## corn shooter kernels at fire_rate through FarmProjectiles, shot_damage each (rapid fire
+## and heavy seeds)
+## pumpkin bomb one every bomb_cooldown, thrown at the aim point (bomb_min_range ..
+## bomb_range away; GAMEPAD_THROW ahead with the stick), bursting where it
+## lands (PumpkinBombs)
+## * The weapon in hand on the scarecrow's model (WeaponModels), and an aim marker (with bombs:
+## on the ground where one would land, ringed by its blast).
+## While attacking, the model faces the aim.
+## Co-op: the partner's weapons on the host read its RemoteControls (aim, fire, and its pick of
+## weapon come from the partner's game); on the partner's machine its own only aims and shows the
+## attack motions (replica: the host attacks), and only the local player's aim marker shows.
+
+enum Device { MOUSE, GAMEPAD }
+enum Weapon { PITCHFORK, CORN_SHOOTER, PUMPKIN_BOMB }
+
+## A corn shot left the gun (for its sound).
+signal fired
+## A pitchfork stab (how many it hit), and each enemy it struck (for the sounds).
+signal stabbed(hits: int)
+signal struck(at: Vector3, enemy_type: int)
+## A pumpkin bomb thrown (where it will land).
+signal threw(at: Vector3)
+## Any attack (co-op: the partner's machine shows its motion), and a change of weapon.
+signal attacked(weapon: Weapon)
+signal switched(weapon: Weapon)
+
+## Lateral offset of the gun from the scarecrow's center line (the prototype's value).
+const SIDE_OFFSET := 0.35
+## Upgrade ids that unlock the weapons (the pitchfork needs none), and what they're called.
+const WEAPON_IDS: Array[String] = ["pitchfork", "corn_shooter", "pumpkin_bomb"]
+const WEAPON_NAMES: Array[String] = ["Pitchfork", "Corn shooter", "Pumpkin bombs"]
+const SWITCH_ACTIONS: Array[StringName] = [&"weapon_next", &"weapon_1", &"weapon_2", &"weapon_3"]
+## How far ahead a bomb lands when aiming with the stick, and how high it leaves the hand.
+const GAMEPAD_THROW := 7.0
+const THROW_HEIGHT := 1.6
+const WORLD_LAYER := 1
+
+var device: Device = Device.MOUSE
+var weapon: Weapon = Weapon.PITCHFORK
+## Last valid horizontal aim direction (unit, XZ).
+var aim := Vector2(0.0, -1.0)
+## World point the mouse aims at (combat-height plane), and the ground point under the cursor;
+## valid in MOUSE mode.
+var aim_point := Vector3.ZERO
+var ground_point := Vector3.ZERO
+var shots_fired: int = 0
+var stabs: int = 0
+var bombs_thrown: int = 0
+## Seconds until the next pumpkin bomb is in hand (0 = ready).
+var bomb_left: float = 0.0
+var remote: RemoteControls
+var replica := false
+var show_marker := true
+## Set by FarmSim: the enemies the pitchfork stabs, and the pumpkin bombs in flight.
+var enemies: EnemySystem
+var bombs: PumpkinBombs
+var models: WeaponModels
+
+var _cfg: GameConfig
+## Set by FarmSim: the upgrades (the weapons, fire rate, shot damage).
+var campaign: CampaignController
+var _player: PlayerCharacter
+var _camera: Camera3D
+var _shots: FarmProjectiles
+var _marker: MeshInstance3D
+var _blast: MeshInstance3D
+## Ticks until each weapon can attack again (the pumpkin bomb's recharge is bomb_left), kept
+## through switches so swapping weapons can't skip a wait.
+var _cooldown := PackedInt32Array([0, 0, 0])
+var _needs_release := true
+var _mouse_travel: float = 0.0
+var _edges := ActionEdges.new()
+var _ray := PhysicsRayQueryParameters3D.new()
+
+
+func setup(cfg: GameConfig, player: PlayerCharacter, camera: Camera3D, shots: FarmProjectiles) -> void:
+ _cfg = cfg
+ _player = player
+ _camera = camera
+ _shots = shots
+ _ray.collision_mask = WORLD_LAYER
+ _ray.collide_with_areas = false
+ _ray.exclude = [player.get_rid()]
+ models = WeaponModels.new()
+ models.setup(player.model, Vector3(SIDE_OFFSET, cfg.combat_height, -cfg.muzzle_distance))
+ _build_marker()
+
+
+## Requires a fresh fire press, so a held button can't fire into a new morning or a retry.
+func reset() -> void:
+ _cooldown.fill(0)
+ _needs_release = true
+
+
+## A new morning (also after a retry): a pumpkin bomb back in hand.
+func ready_for_morning() -> void:
+ reset()
+ bomb_left = 0.0
+
+
+## Whether this scarecrow has the weapon: the pitchfork always, the others once bought.
+func owns(w: int) -> bool:
+ if w == Weapon.PITCHFORK:
+ return true
+ return w > 0 and w < WEAPON_IDS.size() and campaign != null and Upgrades.owned(campaign.state, WEAPON_IDS[w])
+
+
+## Takes the weapon in hand if it's owned. Returns whether it's in hand now.
+func equip(w: int) -> bool:
+ if not owns(w):
+ return false
+ if w != weapon:
+ show_weapon(w)
+ switched.emit(weapon)
+ return true
+
+
+## The next weapon owned after the one in hand.
+func cycle() -> void:
+ for k in range(1, WEAPON_IDS.size()):
+ if equip((weapon + k) % WEAPON_IDS.size()):
+ return
+
+
+## Shows the weapon in hand without the ownership check (co-op: the other scarecrow's, as its
+## machine says).
+func show_weapon(w: int) -> void:
+ var next := clampi(w, 0, WEAPON_IDS.size() - 1) as Weapon
+ if next == weapon and models.weapon == next:
+ return # (a snapshot saying so again mustn't cut an attack's motion short)
+ weapon = next
+ models.show_weapon(weapon)
+
+
+func _input(event: InputEvent) -> void:
+ if remote != null:
+ return
+ _edges.note(event, SWITCH_ACTIONS)
+ if event is InputEventMouseMotion:
+ if device == Device.GAMEPAD:
+ _mouse_travel += (event as InputEventMouseMotion).relative.length()
+ if _mouse_travel >= _cfg.mouse_switch_threshold:
+ device = Device.MOUSE
+ elif event is InputEventMouseButton and (event as InputEventMouseButton).pressed:
+ device = Device.MOUSE
+ elif event is InputEventJoypadButton and (event as InputEventJoypadButton).pressed and event.is_action("fire"):
+ _to_gamepad()
+ elif event is InputEventJoypadMotion:
+ var jm := event as InputEventJoypadMotion
+ if jm.axis == JOY_AXIS_TRIGGER_RIGHT and jm.axis_value > 0.5:
+ _to_gamepad()
+
+
+## Every tick, attacking or not (building, patching): the bomb's recharge, and the pick of
+## weapon (the switch actions count only when can_switch: outside build mode, no menu open; the
+## partner's pick comes from its game).
+func tick(dt: float, can_switch: bool) -> void:
+ bomb_left = maxf(bomb_left - dt, 0.0)
+ models.set_bomb_charge(1.0 - bomb_left / _cfg.bomb_cooldown if _cfg.bomb_cooldown > 0.0 else 1.0)
+ if not owns(weapon):
+ equip(Weapon.PITCHFORK)
+ if remote != null:
+ if remote.weapon >= 0:
+ equip(remote.weapon)
+ return
+ var p := {}
+ for a in SWITCH_ACTIONS:
+ p[a] = _edges.pressed(a)
+ if not can_switch:
+ return
+ if p[&"weapon_next"]:
+ cycle()
+ for k in WEAPON_IDS.size():
+ if p[SWITCH_ACTIONS[k + 1]]:
+ equip(k)
+
+
+## One physics tick while the scarecrow can attack: update the aim, then attack with the weapon
+## in hand if fire is held and it's ready.
+func step(_dt: float) -> void:
+ _update_aim()
+ var held := remote.held(&"fire") if remote != null else Input.is_action_pressed("fire")
+ for i in _cooldown.size():
+ _cooldown[i] = maxi(_cooldown[i] - 1, 0)
+ if replica:
+ if held:
+ _player.face_aim(aim, 0.35)
+ _show_attack()
+ return
+ if _needs_release:
+ if held:
+ return
+ _needs_release = false
+ if not held:
+ return
+ _player.face_aim(aim, 0.35)
+ attack()
+
+
+## The weapon in hand attacks along the aim, if it's ready. Returns whether it did.
+func attack() -> bool:
+ if _cooldown[weapon] > 0:
+ return false
+ match weapon:
+ Weapon.CORN_SHOOTER:
+ _cooldown[weapon] = interval_ticks()
+ _shoot()
+ Weapon.PUMPKIN_BOMB:
+ if bomb_left > 0.0 or not _throw():
+ return false
+ _:
+ _cooldown[weapon] = stab_ticks()
+ _stab()
+ attacked.emit(weapon)
+ return true
+
+
+## A scripted attack (the soak's scarecrow, tests): aims at target and attacks if ready.
+func attack_toward(target: Vector2) -> bool:
+ var p := Vector2(_player.global_position.x, _player.global_position.z)
+ var to := target - p
+ if to.length() > 1e-3:
+ aim = PlayerInput.muzzle_corrected_aim(to, to.normalized()) if weapon == Weapon.CORN_SHOOTER else to.normalized()
+ aim_point = Vector3(target.x, _cfg.combat_height, target.y)
+ ground_point = Vector3(target.x, 0.0, target.y)
+ device = Device.MOUSE
+ _player.face_aim(aim, 0.35)
+ return attack()
+
+
+## Attacks so far, with any weapon.
+func attacks() -> int:
+ return stabs + shots_fired + bombs_thrown
+
+
+## Ticks between shots, and a shot's damage, with upgrades.
+func interval_ticks() -> int:
+ var state := campaign.state if campaign != null else null
+ return maxi(1, roundi(Engine.physics_ticks_per_second / Upgrades.value(_cfg, state, "fire_rate")))
+
+
+func shot_damage() -> int:
+ return roundi(Upgrades.value(_cfg, campaign.state if campaign != null else null, "shot_damage"))
+
+
+## Ticks between pitchfork stabs.
+func stab_ticks() -> int:
+ return maxi(1, roundi(_cfg.pitchfork_interval * Engine.physics_ticks_per_second))
+
+
+## Where a bomb thrown now lands: the ground point aimed at (GAMEPAD_THROW ahead with the stick),
+## bomb_min_range .. bomb_range from the scarecrow.
+func throw_target() -> Vector3:
+ var p := Vector2(_player.global_position.x, _player.global_position.z)
+ var want := Vector2(ground_point.x, ground_point.z) - p if device == Device.MOUSE else aim * GAMEPAD_THROW
+ var dir := want.normalized() if want.length() > 1e-3 else aim
+ var at := p + dir * clampf(want.length(), _cfg.bomb_min_range, _cfg.bomb_range)
+ return Vector3(at.x, 0.0, at.y)
+
+
+func _shoot() -> void:
+ var origin := Vector3(_player.global_position.x, _cfg.combat_height, _player.global_position.z)
+ var dir := Vector3(aim.x, 0.0, aim.y)
+ var right := Vector3(-aim.y, 0.0, aim.x)
+ var muzzle := origin + dir * _cfg.muzzle_distance + right * SIDE_OFFSET
+ shots_fired += 1
+ _shots.fire(origin, muzzle, dir, shot_damage())
+ models.attack(Weapon.CORN_SHOOTER)
+ fired.emit()
+
+
+## The nearest few enemies in reach, in the arc, and in the clear take a stab.
+func _stab() -> int:
+ stabs += 1
+ models.attack(Weapon.PITCHFORK)
+ var hits := 0
+ if enemies != null:
+ var es := enemies
+ var p := Vector2(_player.global_position.x, _player.global_position.z)
+ var cos_half := cos(deg_to_rad(_cfg.pitchfork_arc) * 0.5)
+ var found: Array = [] # [distance, slot]
+ for d in es.active_count:
+ if es.alive[d] == 0:
+ continue
+ var e := Vector2(es.pos_x[d], es.pos_z[d])
+ var dist := e.distance_to(p)
+ if dist > _cfg.pitchfork_reach + es.t_hit_radius[es.type[d]]:
+ continue
+ if dist > 0.3 and (e - p).dot(aim) < cos_half * dist:
+ continue
+ if _clear_line(p, e):
+ found.append([dist, d])
+ found.sort_custom(func(a: Array, b: Array) -> bool: return a[0] < b[0])
+ for k in mini(found.size(), _cfg.pitchfork_targets):
+ var d: int = found[k][1]
+ var at := Vector3(es.pos_x[d], _cfg.combat_height, es.pos_z[d])
+ var type := es.type[d]
+ if es.apply_hit(d, _cfg.pitchfork_damage):
+ hits += 1
+ struck.emit(at, type)
+ stabbed.emit(hits)
+ return hits
+
+
+func _throw() -> bool:
+ if bombs == null:
+ return false
+ var p := _player.global_position
+ var hand := Vector3(p.x - aim.y * 0.4, THROW_HEIGHT, p.z + aim.x * 0.4)
+ var to := throw_target()
+ if not bombs.throw(hand, to, _cfg.bomb_damage, _cfg.bomb_radius):
+ return false
+ bomb_left = _cfg.bomb_cooldown
+ models.set_bomb_charge(0.0)
+ bombs_thrown += 1
+ threw.emit(to)
+ return true
+
+
+## The partner's machine: the attack motion on the weapon's own cadence (the host attacks).
+func _show_attack() -> void:
+ if weapon == Weapon.PUMPKIN_BOMB or _cooldown[weapon] > 0:
+ return # the host's throw shows the bomb, and empties the hand
+ _cooldown[weapon] = interval_ticks() if weapon == Weapon.CORN_SHOOTER else stab_ticks()
+ models.attack(weapon)
+
+
+func _clear_line(a: Vector2, b: Vector2) -> bool:
+ if not is_inside_tree():
+ return true
+ _ray.from = Vector3(a.x, _cfg.combat_height, a.y)
+ _ray.to = Vector3(b.x, _cfg.combat_height, b.y)
+ return get_world_3d().direct_space_state.intersect_ray(_ray).is_empty()
+
+
+func _update_aim() -> void:
+ if remote != null:
+ aim = remote.aim
+ aim_point = remote.aim_point
+ ground_point = remote.ground_point
+ device = remote.device as Device
+ return
+ var b := _camera.global_transform.basis
+ var fwd := Vector3(-b.z.x, 0.0, -b.z.z).normalized()
+ var right := Vector3(b.x.x, 0.0, b.x.z).normalized()
+ var stick := Input.get_vector("aim_left", "aim_right", "aim_down", "aim_up", _cfg.aim_dead_zone)
+ if stick != Vector2.ZERO:
+ _to_gamepad()
+ var w := right * stick.x + fwd * stick.y
+ aim = Vector2(w.x, w.z).normalized()
+ elif device == Device.MOUSE:
+ aim_point = _cursor_on_plane(_cfg.combat_height)
+ ground_point = _cursor_on_plane(0.0)
+ var p := _player.global_position
+ aim = PlayerInput.muzzle_corrected_aim(Vector2(aim_point.x - p.x, aim_point.z - p.z), aim)
+
+
+func _cursor_on_plane(height: float) -> Vector3:
+ var screen := _camera.get_viewport().get_mouse_position()
+ var o := _camera.project_ray_origin(screen)
+ var d := _camera.project_ray_normal(screen)
+ if absf(d.y) < 1e-5:
+ return Vector3(o.x, height, o.z)
+ return o + d * ((height - o.y) / d.y)
+
+
+func _to_gamepad() -> void:
+ device = Device.GAMEPAD
+ _mouse_travel = 0.0
+
+
+func _process(_delta: float) -> void:
+ if _player == null:
+ return
+ var bomb := weapon == Weapon.PUMPKIN_BOMB
+ _marker.visible = show_marker
+ _blast.visible = show_marker and bomb
+ if bomb:
+ var at := throw_target()
+ _marker.global_position = Vector3(at.x, 0.12, at.z)
+ _blast.global_position = Vector3(at.x, 0.1, at.z)
+ elif device == Device.MOUSE:
+ _marker.global_position = Vector3(aim_point.x, _cfg.combat_height, aim_point.z)
+ else:
+ var p := _player.get_global_transform_interpolated().origin
+ _marker.global_position = Vector3(p.x + aim.x * 3.0, _cfg.combat_height, p.z + aim.y * 3.0)
+
+
+func _build_marker() -> void:
+ _marker = _ring(0.2, 0.3, Color(1.0, 0.85, 0.25))
+ _marker.name = "AimMarker"
+ _blast = _ring(_cfg.bomb_radius - 0.08, _cfg.bomb_radius, Color(1.0, 0.55, 0.12, 0.8))
+ _blast.name = "BlastMarker"
+
+
+func _ring(inner: float, outer: float, color: Color) -> MeshInstance3D:
+ var torus := TorusMesh.new()
+ torus.inner_radius = inner
+ torus.outer_radius = outer
+ torus.rings = 48
+ torus.ring_segments = 6
+ var mat := StandardMaterial3D.new()
+ mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
+ mat.albedo_color = color
+ mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA if color.a < 1.0 else BaseMaterial3D.TRANSPARENCY_DISABLED
+ mat.no_depth_test = true
+ mat.render_priority = 1
+ var mi := MeshInstance3D.new()
+ mi.mesh = torus
+ mi.material_override = mat
+ mi.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
+ mi.top_level = true
+ mi.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
+ add_child(mi)
+ return mi
diff --git a/game/scripts/scarecrow_combat.gd.uid b/game/scripts/scarecrow_combat.gd.uid
new file mode 100644
index 0000000..a0e83d6
--- /dev/null
+++ b/game/scripts/scarecrow_combat.gd.uid
@@ -0,0 +1 @@
+uid://bumgf758vykhm
diff --git a/game/scripts/scarecrow_hud.gd b/game/scripts/scarecrow_hud.gd
new file mode 100644
index 0000000..8001c65
--- /dev/null
+++ b/game/scripts/scarecrow_hud.gd
@@ -0,0 +1,205 @@
+class_name ScarecrowHud
+extends Control
+## Bottom-left status for the scarecrow: health as pips, the fear ability as a circle that
+## sweeps full while it cools down and flashes when it is ready again, the patch hint with its
+## progress, and once the Sprint upgrade is bought a sprint line (ready, seconds left, or
+## recharging); plus a red screen tint when the scarecrow is hit. Bottom-right, the weapons:
+## the three by number, the one in hand marked, the ones not bought yet greyed out (from the
+## workbench), the pumpkin bomb's recharge, and how to switch.
+
+const PIP := Vector2(22.0, 16.0)
+const PIP_GAP := 5.0
+const FEAR_RADIUS := 26.0
+## Extra height of the panel for the sprint line.
+const SPRINT_ROW := 30.0
+## The weapon panel, from the bottom-right corner, and its rows.
+const WEAPONS := Rect2(-340.0, -176.0, 304.0, 150.0)
+const WEAPON_ROW := 30.0
+
+var kit: Scarecrow
+## This machine's scarecrow's weapons.
+var combat: ScarecrowCombat
+var campaign: CampaignController
+## The health line's name ("Scarecrow"; in co-op "P1 Scarecrow" / "P2 Scarecrow").
+var label := "Scarecrow"
+
+var _tint: ColorRect
+var _hp_label: Label
+var _fear_label: Label
+var _patch_label: Label
+var _sprint_label: Label
+var _weapon_title: Label
+var _weapon_rows: Array[Label] = []
+var _weapon_hint: Label
+var _hit: float = 0.0
+var _ready_flash: float = 0.0
+
+
+func setup(p_kit: Scarecrow, p_campaign: CampaignController, p_combat: ScarecrowCombat = null) -> void:
+ campaign = p_campaign
+ retarget(p_kit, p_combat)
+
+
+## Shows another kit (co-op: the partner's game shows player 2's).
+func retarget(p_kit: Scarecrow, p_combat: ScarecrowCombat = null) -> void:
+ combat = p_combat
+ if kit != null:
+ kit.damaged.disconnect(_on_damaged)
+ kit.fear_ready.disconnect(_on_fear_ready)
+ kit = p_kit
+ kit.damaged.connect(_on_damaged)
+ kit.fear_ready.connect(_on_fear_ready)
+
+
+func _on_damaged(_hp: int) -> void:
+ _hit = 1.0
+
+
+func _on_fear_ready() -> void:
+ _ready_flash = 1.0
+
+
+func _ready() -> void:
+ set_anchors_preset(Control.PRESET_FULL_RECT)
+ mouse_filter = Control.MOUSE_FILTER_IGNORE
+ _tint = ColorRect.new()
+ _tint.set_anchors_preset(Control.PRESET_FULL_RECT)
+ _tint.color = Color(0.85, 0.05, 0.0, 0.0)
+ _tint.mouse_filter = Control.MOUSE_FILTER_IGNORE
+ add_child(_tint)
+ _hp_label = _label(22)
+ _fear_label = _label(20)
+ _patch_label = _label(20)
+ _sprint_label = _label(20)
+ _weapon_title = _label(18)
+ _weapon_title.text = "Weapon"
+ for i in ScarecrowCombat.WEAPON_NAMES.size():
+ _weapon_rows.append(_label(20))
+ _weapon_hint = _label(16)
+ _weapon_hint.text = "Switch: Tab / 1-3 / d-pad down"
+
+
+func _process(delta: float) -> void:
+ _hit = maxf(_hit - delta * 2.5, 0.0)
+ _ready_flash = maxf(_ready_flash - delta * 2.0, 0.0)
+ _tint.color.a = 0.22 * _hit
+ if kit == null:
+ return
+ var base := _base()
+ var s := campaign.state
+ _hp_label.text = "%s %d/%d" % [label, kit.hp(), kit.max_hp()]
+ _hp_label.position = base + Vector2(0.0, -34.0)
+ if not kit.alive:
+ _fear_label.text = "Fear"
+ elif kit.fear_left == 0.0:
+ _fear_label.text = "Fear Q / LB"
+ else:
+ _fear_label.text = "Fear %.0f s" % ceilf(kit.fear_left)
+ _fear_label.position = base + Vector2(FEAR_RADIUS * 2.0 + 14.0, 34.0)
+ if not kit.alive:
+ _patch_label.text = "Patch"
+ elif kit.patching:
+ _patch_label.text = "Patching up..."
+ elif kit.hp() >= kit.max_hp():
+ _patch_label.text = "Patch (full health)"
+ else:
+ _patch_label.text = "Patch hold F / Y (%s)" % ResourceStore.describe(kit.config.costs.get("patch", {}))
+ _patch_label.position = base + Vector2(FEAR_RADIUS * 2.0 + 14.0, 62.0)
+ var body := kit.player
+ _sprint_label.visible = _sprint_shown()
+ if _sprint_label.visible:
+ if not kit.alive:
+ _sprint_label.text = "Sprint"
+ elif body.sprinting:
+ _sprint_label.text = "Sprinting %.1f s" % body.sprint_left
+ elif body.sprint_recharge > 0.0:
+ _sprint_label.text = "Sprint %.0f s" % ceilf(body.sprint_recharge)
+ else:
+ _sprint_label.text = "Sprint hold Shift / L3"
+ _sprint_label.position = base + Vector2(0.0, 100.0)
+ _update_weapons()
+ queue_redraw()
+
+
+func _update_weapons() -> void:
+ var shown := combat != null
+ _weapon_title.visible = shown
+ _weapon_hint.visible = shown
+ for l in _weapon_rows:
+ l.visible = shown
+ if not shown:
+ return
+ var at := _weapons_rect().position
+ _weapon_title.position = at + Vector2(12.0, 6.0)
+ for i in _weapon_rows.size():
+ var l := _weapon_rows[i]
+ var text := "%d %s" % [i + 1, ScarecrowCombat.WEAPON_NAMES[i]]
+ var color := Color(0.95, 0.95, 0.95)
+ if not combat.owns(i):
+ text += " (workbench)"
+ color = Color(0.55, 0.55, 0.55)
+ elif i == ScarecrowCombat.Weapon.PUMPKIN_BOMB and combat.bomb_left > 0.0:
+ text += " %.0f s" % ceilf(combat.bomb_left)
+ if i == combat.weapon:
+ color = Color(1.0, 0.85, 0.3)
+ l.text = text
+ l.add_theme_color_override("font_color", color)
+ l.position = at + Vector2(30.0, 30.0 + i * WEAPON_ROW)
+ _weapon_hint.position = at + Vector2(12.0, 30.0 + _weapon_rows.size() * WEAPON_ROW + 2.0)
+
+
+func _weapons_rect() -> Rect2:
+ return Rect2(size + WEAPONS.position, WEAPONS.size)
+
+
+func _draw() -> void:
+ if kit == null:
+ return
+ var base := _base()
+ var s := campaign.state
+ var height := 146.0 + (SPRINT_ROW if _sprint_shown() else 0.0)
+ draw_rect(Rect2(base - Vector2(14.0, 46.0), Vector2(340.0, height)), Color(0.0, 0.0, 0.0, 0.42))
+ var frac := float(kit.hp()) / float(maxi(kit.max_hp(), 1))
+ var full := Color(0.45, 0.9, 0.35) if frac > 0.5 else (Color(1.0, 0.8, 0.2) if frac > 0.25 else Color(1.0, 0.3, 0.2))
+ full = full.lerp(Color.WHITE, _hit * 0.6)
+ for i in kit.max_hp():
+ var r := Rect2(base + Vector2(i * (PIP.x + PIP_GAP), 0.0), PIP)
+ draw_rect(r, full if i < kit.hp() else Color(0.15, 0.15, 0.15, 0.8))
+ draw_rect(r, Color(0.0, 0.0, 0.0, 0.9), false, 2.0)
+ # Fear: dark disc, a sweep that fills while cooling down, bright when ready.
+ var c := base + Vector2(FEAR_RADIUS, 32.0 + FEAR_RADIUS)
+ var ready := kit.fear_left == 0.0 and kit.alive
+ draw_circle(c, FEAR_RADIUS, Color(0.08, 0.1, 0.14, 0.9))
+ if ready:
+ draw_circle(c, FEAR_RADIUS - 5.0, Color(0.55, 0.85, 1.0).lerp(Color.WHITE, _ready_flash))
+ else:
+ draw_arc(c, FEAR_RADIUS - 8.0, -PI * 0.5, -PI * 0.5 + TAU * kit.fear_charge(), 48, Color(0.4, 0.6, 0.75), 9.0)
+ draw_arc(c, FEAR_RADIUS + 3.0 + _ready_flash * 10.0, 0.0, TAU, 48, Color(1.0, 1.0, 1.0, 0.25 + 0.75 * _ready_flash), 2.5)
+ if combat != null:
+ var w := _weapons_rect()
+ draw_rect(w, Color(0.0, 0.0, 0.0, 0.42))
+ var row := Rect2(w.position + Vector2(6.0, 32.0 + combat.weapon * WEAPON_ROW), Vector2(w.size.x - 12.0, WEAPON_ROW - 2.0))
+ draw_rect(row, Color(1.0, 0.85, 0.3, 0.18))
+ draw_rect(Rect2(row.position, Vector2(4.0, row.size.y)), Color(1.0, 0.85, 0.3))
+ if kit.patching:
+ var bar := Rect2(base + Vector2(FEAR_RADIUS * 2.0 + 14.0, 92.0), Vector2(210.0, 8.0))
+ draw_rect(bar, Color(0.1, 0.1, 0.1, 0.9))
+ draw_rect(Rect2(bar.position, Vector2(bar.size.x * kit.patch_elapsed / kit.config.patch_time, bar.size.y)), Color(0.45, 1.0, 0.4))
+
+
+func _base() -> Vector2:
+ return Vector2(36.0, size.y - 126.0 - (SPRINT_ROW if _sprint_shown() else 0.0))
+
+
+func _sprint_shown() -> bool:
+ return kit != null and kit.player != null and kit.player.can_sprint()
+
+
+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
diff --git a/game/scripts/scarecrow_hud.gd.uid b/game/scripts/scarecrow_hud.gd.uid
new file mode 100644
index 0000000..64bda45
--- /dev/null
+++ b/game/scripts/scarecrow_hud.gd.uid
@@ -0,0 +1 @@
+uid://e768baxfmoit
diff --git a/game/scripts/settings_menu.gd b/game/scripts/settings_menu.gd
new file mode 100644
index 0000000..976cdd9
--- /dev/null
+++ b/game/scripts/settings_menu.gd
@@ -0,0 +1,304 @@
+class_name SettingsMenu
+extends CenterContainer
+## Settings, from the main menu or the pause menu (Main): one scrolling column so the
+## keyboard and gamepad can reach everything in order.
+## Audio a volume slider per bus (GameSettings.BUSES)
+## Controls move / aim stick dead zones, then every binding (read from the InputMap, so
+## it always shows what the game really uses; remapping isn't offered)
+## Display fullscreen, VSync, 3D resolution scale
+## Gameplay tips on the first day and night
+## Co-op your name (the lobby and your name tag), and your microphone for voice chat
+## Every change is applied and saved at once (changed); Back or Escape / B closes it.
+
+signal changed
+signal closed
+
+## (label, actions) shown in the bindings list.
+const BINDINGS := [
+ ["Move", []],
+ ["Aim", []],
+ ["Shoot", ["fire"]],
+ ["Fear", ["fear"]],
+ ["Patch up (hold)", ["patch"]],
+ ["Gather / repair / workbench", ["interact"]],
+ ["Build mode", ["build_mode"]],
+ ["Pick a buildable", ["build_1", "build_2", "build_3", "build_4", "build_next"]],
+ ["Rotate", ["rotate_left", "rotate_right"]],
+ ["Dismantle / leave build mode", ["cancel"]],
+ ["Pause", ["pause"]],
+ ["Hide tips", ["hide_tips"]],
+ ["Microphone on / off (co-op)", ["toggle_mic"]],
+]
+const PAD_BUTTONS := {
+ JOY_BUTTON_A: "A", JOY_BUTTON_B: "B", JOY_BUTTON_X: "X", JOY_BUTTON_Y: "Y", JOY_BUTTON_BACK: "Back",
+ JOY_BUTTON_START: "Start", JOY_BUTTON_LEFT_SHOULDER: "LB", JOY_BUTTON_RIGHT_SHOULDER: "RB",
+ JOY_BUTTON_DPAD_UP: "D-pad up", JOY_BUTTON_DPAD_DOWN: "D-pad down", JOY_BUTTON_DPAD_LEFT: "D-pad left",
+ JOY_BUTTON_DPAD_RIGHT: "D-pad right", JOY_BUTTON_LEFT_STICK: "L3", JOY_BUTTON_RIGHT_STICK: "R3",
+}
+
+var settings: GameSettings
+var is_open := false
+var back_button: Button
+## Controls by setting, for tests: "volume/Master", "move_dead_zone", "aim_dead_zone",
+## "fullscreen", "vsync", "resolution_scale", "show_tips".
+var controls := {}
+
+var _box: VBoxContainer
+var _scroll: ScrollContainer
+var _values := {} # setting -> value Label
+var _loading := false
+
+
+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, 28)
+ panel.add_child(margin)
+ var outer := VBoxContainer.new()
+ outer.add_theme_constant_override("separation", 14)
+ margin.add_child(outer)
+ var title := Label.new()
+ title.text = "Settings"
+ title.add_theme_font_size_override("font_size", 44)
+ title.add_theme_color_override("font_color", UiTheme.GOLD)
+ outer.add_child(title)
+ _scroll = ScrollContainer.new()
+ _scroll.custom_minimum_size = Vector2(980.0, 640.0)
+ _scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
+ _scroll.follow_focus = true
+ outer.add_child(_scroll)
+ _box = VBoxContainer.new()
+ _box.size_flags_horizontal = Control.SIZE_EXPAND_FILL
+ _box.add_theme_constant_override("separation", 10)
+ _scroll.add_child(_box)
+ _head("Audio")
+ for bus in GameSettings.BUSES:
+ _slider("volume/" + bus, GameSettings.BUS_NAMES[bus], 0.0, 1.0, 0.05)
+ _head("Controls")
+ _slider("move_dead_zone", "Move stick dead zone", 0.05, 0.9, 0.05)
+ _slider("aim_dead_zone", "Aim stick dead zone", 0.05, 0.9, 0.05)
+ _note("Mouse aim follows the cursor directly, so it has no sensitivity to set.")
+ _bindings()
+ _head("Display")
+ _check("fullscreen", "Fullscreen")
+ _check("vsync", "VSync")
+ _slider("resolution_scale", "3D resolution scale", 0.5, 1.0, 0.05)
+ _head("Gameplay")
+ _check("show_tips", "Tips on the first day and night")
+ _head("Co-op")
+ _text("player_name", "Your name")
+ _check("microphone", "Send my microphone in voice chat")
+ var row := HBoxContainer.new()
+ row.add_theme_constant_override("separation", 20)
+ outer.add_child(row)
+ back_button = Button.new()
+ back_button.text = "Back"
+ back_button.custom_minimum_size = Vector2(220.0, 54.0)
+ back_button.pressed.connect(close)
+ row.add_child(back_button)
+ var reset := Button.new()
+ reset.text = "Reset to defaults"
+ reset.custom_minimum_size = Vector2(280.0, 54.0)
+ reset.pressed.connect(func() -> void:
+ var fresh := GameSettings.new()
+ for key in ["volume", "move_dead_zone", "aim_dead_zone", "fullscreen", "vsync", "resolution_scale", "show_tips"]:
+ settings.set(key, fresh.get(key))
+ _load()
+ changed.emit())
+ row.add_child(reset)
+ visible = false
+ mouse_filter = Control.MOUSE_FILTER_IGNORE
+
+
+func open(p_settings: GameSettings) -> void:
+ settings = p_settings
+ _load()
+ is_open = true
+ visible = true
+ mouse_filter = Control.MOUSE_FILTER_STOP
+ _scroll.scroll_vertical = 0
+ (controls["volume/Master"] as Control).grab_focus.call_deferred()
+
+
+func _draw() -> void:
+ draw_rect(Rect2(Vector2.ZERO, size), Color(0.0, 0.0, 0.0, 0.4)) # dims what's behind
+
+
+func close() -> void:
+ if not is_open:
+ return
+ is_open = false
+ visible = false
+ mouse_filter = Control.MOUSE_FILTER_IGNORE
+ closed.emit()
+
+
+## "W, A, S, D, Up, Left, Down, Right" and "Left stick" for an action list.
+static func describe_keys(actions: Array) -> String:
+ var out := PackedStringArray()
+ for a: String in actions:
+ if not InputMap.has_action(a):
+ continue
+ for e in InputMap.action_get_events(a):
+ var text := ""
+ if e is InputEventKey:
+ var k := e as InputEventKey
+ text = OS.get_keycode_string(k.physical_keycode if k.physical_keycode != KEY_NONE else k.keycode)
+ elif e is InputEventMouseButton:
+ text = {MOUSE_BUTTON_LEFT: "Left mouse", MOUSE_BUTTON_RIGHT: "Right mouse", MOUSE_BUTTON_MIDDLE: "Middle mouse"}.get(
+ (e as InputEventMouseButton).button_index, "Mouse")
+ if text != "" and not out.has(text):
+ out.append(text)
+ return ", ".join(out)
+
+
+static func describe_pad(actions: Array) -> String:
+ var out := PackedStringArray()
+ for a: String in actions:
+ if not InputMap.has_action(a):
+ continue
+ for e in InputMap.action_get_events(a):
+ var text := ""
+ if e is InputEventJoypadButton:
+ text = PAD_BUTTONS.get((e as InputEventJoypadButton).button_index, "Button %d" % (e as InputEventJoypadButton).button_index)
+ elif e is InputEventJoypadMotion:
+ var m := e as InputEventJoypadMotion
+ text = {JOY_AXIS_LEFT_X: "Left stick", JOY_AXIS_LEFT_Y: "Left stick", JOY_AXIS_RIGHT_X: "Right stick",
+ JOY_AXIS_RIGHT_Y: "Right stick", JOY_AXIS_TRIGGER_LEFT: "LT", JOY_AXIS_TRIGGER_RIGHT: "RT"}.get(m.axis, "Axis")
+ if text != "" and not out.has(text):
+ out.append(text)
+ return ", ".join(out)
+
+
+func _load() -> void:
+ _loading = true
+ for key: String in controls:
+ var c: Control = controls[key]
+ var v: Variant = settings.volume[key.trim_prefix("volume/")] if key.begins_with("volume/") else settings.get(key)
+ if c is HSlider:
+ (c as HSlider).value = float(v)
+ _show_value(key, float(v))
+ elif c is CheckBox:
+ (c as CheckBox).button_pressed = bool(v)
+ elif c is LineEdit:
+ (c as LineEdit).text = String(v)
+ _loading = false
+
+
+func _apply_value(key: String, v: Variant) -> void:
+ if _loading or settings == null:
+ return
+ if key.begins_with("volume/"):
+ settings.volume[key.trim_prefix("volume/")] = float(v)
+ else:
+ settings.set(key, v)
+ if v is float:
+ _show_value(key, v)
+ changed.emit()
+
+
+func _show_value(key: String, v: float) -> void:
+ if _values.has(key):
+ (_values[key] as Label).text = "%d%%" % roundi(v * 100.0)
+
+
+func _head(text: String) -> void:
+ var l := Label.new()
+ l.text = text
+ l.add_theme_font_size_override("font_size", 28)
+ l.add_theme_color_override("font_color", UiTheme.GOLD)
+ _box.add_child(l)
+
+
+func _note(text: String) -> void:
+ var l := Label.new()
+ l.text = text
+ l.add_theme_font_size_override("font_size", 18)
+ l.add_theme_color_override("font_color", Color(0.72, 0.74, 0.68))
+ _box.add_child(l)
+
+
+func _slider(key: String, label: String, lo: float, hi: float, step: float) -> void:
+ var row := HBoxContainer.new()
+ row.add_theme_constant_override("separation", 18)
+ _box.add_child(row)
+ var l := Label.new()
+ l.text = label
+ l.custom_minimum_size = Vector2(340.0, 0.0)
+ row.add_child(l)
+ var s := HSlider.new()
+ s.min_value = lo
+ s.max_value = hi
+ s.step = step
+ s.custom_minimum_size = Vector2(440.0, 32.0)
+ s.size_flags_vertical = Control.SIZE_SHRINK_CENTER
+ s.value_changed.connect(func(v: float) -> void: _apply_value(key, v))
+ row.add_child(s)
+ var value := Label.new()
+ value.custom_minimum_size = Vector2(80.0, 0.0)
+ row.add_child(value)
+ controls[key] = s
+ _values[key] = value
+
+
+func _text(key: String, label: String) -> void:
+ var row := HBoxContainer.new()
+ row.add_theme_constant_override("separation", 18)
+ _box.add_child(row)
+ var l := Label.new()
+ l.text = label
+ l.custom_minimum_size = Vector2(340.0, 0.0)
+ row.add_child(l)
+ var e := LineEdit.new()
+ e.max_length = 20
+ e.custom_minimum_size = Vector2(440.0, 40.0)
+ e.placeholder_text = "Shown over your scarecrow in co-op"
+ e.text_changed.connect(func(t: String) -> void: _apply_value(key, t.strip_edges()))
+ row.add_child(e)
+ controls[key] = e
+
+
+func _check(key: String, label: String) -> void:
+ var c := CheckBox.new()
+ c.text = label
+ c.toggled.connect(func(on: bool) -> void: _apply_value(key, on))
+ _box.add_child(c)
+ controls[key] = c
+
+
+func _bindings() -> void:
+ var grid := GridContainer.new()
+ grid.columns = 3
+ grid.add_theme_constant_override("h_separation", 30)
+ grid.add_theme_constant_override("v_separation", 4)
+ _box.add_child(grid)
+ for head in ["Action", "Keyboard / mouse", "Gamepad"]:
+ var l := Label.new()
+ l.text = head
+ l.add_theme_font_size_override("font_size", 18)
+ l.add_theme_color_override("font_color", Color(0.72, 0.74, 0.68))
+ grid.add_child(l)
+ for row: Array in BINDINGS:
+ var keys := describe_keys(row[1])
+ var pad := describe_pad(row[1])
+ match row[0]:
+ "Move":
+ keys = "W A S D, arrow keys"
+ pad = describe_pad(["move_left", "move_right", "move_forward", "move_back"])
+ "Aim":
+ keys = "Mouse cursor"
+ pad = describe_pad(["aim_left", "aim_right", "aim_up", "aim_down"])
+ for text in [row[0], keys, pad]:
+ var l := Label.new()
+ l.text = text
+ l.add_theme_font_size_override("font_size", 19)
+ grid.add_child(l)
+
+
+func _unhandled_input(event: InputEvent) -> void:
+ if is_open and event.is_action_pressed("ui_cancel"):
+ close()
+ get_viewport().set_input_as_handled()
diff --git a/game/scripts/settings_menu.gd.uid b/game/scripts/settings_menu.gd.uid
new file mode 100644
index 0000000..f05b6bc
--- /dev/null
+++ b/game/scripts/settings_menu.gd.uid
@@ -0,0 +1 @@
+uid://cvfknxxm526j2
diff --git a/game/scripts/shed_stock.gd b/game/scripts/shed_stock.gd
new file mode 100644
index 0000000..57c21d4
--- /dev/null
+++ b/game/scripts/shed_stock.gd
@@ -0,0 +1,145 @@
+class_name ShedStock
+extends Node3D
+## The supply shed's stock piles, which grow and shrink with what the shed holds: logs for wood,
+## crates for scrap, hay bales for straw. Each pile is a list of props (some already in the scene,
+## the rest added here); a pile shows one prop per `per` units, up to all of them. Every prop has
+## collision, and all of them are in place when the farm's navigation is built, so a pile's
+## footprint never changes for enemies; a hidden prop only stops colliding for the scarecrow and
+## shots. Each pile has a spot in front of it where supply thieves stand to fill their sacks, and a
+## label with the amount while the scarecrow is nearby.
+
+const PREF := "res://assets/farm/ithappy/farm/prefabs/assets/"
+const LABEL_RANGE := 9.0
+## material -> adopt (scene props under the shed zone, in fill order), extra ([prefab, world
+## position, yaw in degrees, scale]), per (units per prop), front (thieves' spot), label (world).
+const PILES := {
+ "wood": {
+ "adopt": ["firewood_010_1", "firewood_010_2"],
+ "extra": [
+ ["prop/firewood_010", Vector3(4.2, 0.0, -19.0), -4.0, 1.0],
+ ["prop/firewood_010", Vector3(4.2, 0.35, -19.0), 5.0, 1.0],
+ ["prop/firewood_010", Vector3(4.2, 0.7, -18.45), 3.0, 1.0],
+ ["prop/firewood_010", Vector3(4.2, 0.7, -19.0), -2.0, 1.0],
+ ["prop/firewood_010", Vector3(4.2, 1.05, -18.7), 6.0, 1.0],
+ ],
+ "per": 4,
+ "front": Vector2(2.6, -18.6),
+ "label": Vector3(4.2, 2.2, -18.7),
+ },
+ "scrap": {
+ "adopt": ["box_004_1", "box_004_2", "case_001_1", "box_004_3"],
+ "extra": [
+ ["box/box_004", Vector3(-2.0, 0.5, -20.3), 4.0, 1.0],
+ ["box/box_004", Vector3(-3.1, 0.5, -20.4), -6.0, 1.0],
+ ["prop/barrel_010", Vector3(-4.3, 0.0, -20.3), 0.0, 1.0],
+ ["box/box_004", Vector3(-2.55, 1.5, -20.35), 12.0, 1.0],
+ ["prop/barrel_001", Vector3(-5.4, 0.0, -20.2), 0.0, 1.0],
+ ["box/box_004", Vector3(-3.1, 2.5, -20.35), -15.0, 1.0],
+ ],
+ "per": 3,
+ "front": Vector2(-3.0, -15.1),
+ "label": Vector3(-3.4, 2.8, -18.6),
+ },
+ "straw": {
+ "adopt": ["hay_001_1"],
+ "extra": [
+ ["prop/hay_001", Vector3(7.3, 0.0, -18.9), 15.0, 0.55],
+ ["prop/hay_001", Vector3(7.3, 0.0, -17.7), -10.0, 0.55],
+ ["prop/hay_001", Vector3(6.3, 0.0, -20.1), 30.0, 0.55],
+ ["prop/hay_001", Vector3(5.9, 1.9, -18.0), 0.0, 0.55],
+ ["prop/hay_001", Vector3(5.1, 0.0, -20.1), -25.0, 0.55],
+ ],
+ "per": 4,
+ "front": Vector2(6.75, -16.25),
+ "label": Vector3(6.2, 3.2, -18.4),
+ },
+}
+
+var campaign: CampaignController
+var player: Node3D
+## material -> Array[Node3D], in fill order.
+var slots := {}
+var shown := {}
+
+var _labels := {}
+var _bodies := {} # material -> Array (per slot: Array[CollisionObject3D])
+var _last := {}
+
+
+## Before the navigation is built: adopts the scene's piles and adds the extra props (every prop
+## present and colliding).
+func setup(p_campaign: CampaignController, shed_zone: Node3D, p_player: Node3D) -> void:
+ campaign = p_campaign
+ player = p_player
+ for m: String in PILES:
+ var pile: Dictionary = PILES[m]
+ var list: Array[Node3D] = []
+ for prop_name: String in pile["adopt"]:
+ var n := shed_zone.get_node_or_null(prop_name) as Node3D
+ if n != null:
+ list.append(n)
+ for e: Array in pile["extra"]:
+ var n := (load(PREF + String(e[0]) + ".tscn") as PackedScene).instantiate() as Node3D
+ n.name = "Stock_%s_%d" % [m, list.size()]
+ shed_zone.add_child(n)
+ n.global_transform = Transform3D(Basis(Vector3.UP, deg_to_rad(float(e[2]))).scaled(Vector3.ONE * float(e[3])), e[1])
+ list.append(n)
+ slots[m] = list
+ var bodies: Array = []
+ for n in list:
+ bodies.append(n.find_children("*", "CollisionObject3D", true, false))
+ _bodies[m] = bodies
+ var l := Label3D.new()
+ l.billboard = BaseMaterial3D.BILLBOARD_ENABLED
+ l.no_depth_test = true
+ l.shaded = false
+ l.font_size = 44
+ l.outline_size = 10
+ l.pixel_size = 0.0075
+ l.modulate = GatherNode.COLORS[m]
+ l.visible = false
+ add_child(l)
+ l.global_position = pile["label"]
+ _labels[m] = l
+
+
+## Where supply thieves stand to take this material.
+func spot(material: String) -> Vector2:
+ return PILES[material]["front"] if PILES.has(material) else Vector2.ZERO
+
+
+## Props a pile shows for an amount.
+static func props_for(material: String, amount: int, slot_count: int) -> int:
+ return clampi(ceili(amount / float(PILES[material]["per"])), 0, slot_count)
+
+
+## Shows each pile for the shed's stock (after the navigation is built; then on every change).
+func refresh() -> void:
+ var shed := campaign.state.resources.shed
+ for m: String in slots:
+ var list: Array = slots[m]
+ var n := props_for(m, int(shed[m]), list.size())
+ shown[m] = n
+ _last[m] = int(shed[m])
+ for i in list.size():
+ var on := i < n
+ (list[i] as Node3D).visible = on
+ for body: CollisionObject3D in _bodies[m][i]:
+ body.collision_layer = 1 if on else 0
+
+
+func _process(_delta: float) -> void:
+ if campaign == null:
+ return
+ var shed := campaign.state.resources.shed
+ for m: String in slots:
+ if int(shed[m]) != int(_last.get(m, -1)):
+ refresh()
+ break
+ var near := player != null
+ for m: String in _labels:
+ var l := _labels[m] as Label3D
+ var at: Vector3 = PILES[m]["label"]
+ l.visible = near and Vector2(player.global_position.x - at.x, player.global_position.z - at.z).length() < LABEL_RANGE
+ if l.visible:
+ l.text = "%s %d" % [m.capitalize(), int(shed[m])]
diff --git a/game/scripts/shed_stock.gd.uid b/game/scripts/shed_stock.gd.uid
new file mode 100644
index 0000000..25bcd86
--- /dev/null
+++ b/game/scripts/shed_stock.gd.uid
@@ -0,0 +1 @@
+uid://c8v027vvws1b3
diff --git a/game/scripts/structure_system.gd b/game/scripts/structure_system.gd
new file mode 100644
index 0000000..0a52b34
--- /dev/null
+++ b/game/scripts/structure_system.gd
@@ -0,0 +1,642 @@
+class_name StructureSystem
+extends Node3D
+## Player-built defenses. The records live in FarmState.structures; this system validates and
+## places them, builds their views, keeps the navigation's structure layer in sync, and runs them:
+## fence 2 m segment that ground enemies can't walk through.
+## gate a fence segment the scarecrow walks through (it swings open as the
+## scarecrow nears; it has no collision for the scarecrow) but enemies can't.
+## slowing_trap 1.5 m patch: a ground enemy stepping on it moves at trap_slow_factor speed
+## for trap_slow_time, using up one of its trap_triggers. Doesn't block.
+## automated_defense 1 m post that shoots the nearest enemy within turret_range with a clear
+## line, from the shared shot pool, every turret_fire_interval (leading the
+## target). Flying enemies are hit too (Step 9); fences, gates, and traps
+## don't affect them.
+## Barriers (everything but traps) are high-cost cells for enemy navigation; an enemy whose route
+## runs into one hits it (damage) until it breaks, then carries on. Damaged structures show an HP
+## bar, a red tint, and wobble on each hit; a broken one leaves debris and emits destroyed
+## ("breach"). Positions snap to a 0.5 m grid, rotations to 45 degree steps (fences run 2 m along
+## the grid, 1.5 x 1.5 m on the diagonal, so chains line up either way).
+
+signal layout_changed
+signal built(id: int, type: String)
+signal destroyed(id: int, type: String, position: Vector3)
+## Damaged but still standing; repaired fully; an automated defense shot; a trap slowed someone.
+signal hurt(id: int, position: Vector3)
+signal repaired(id: int)
+signal turret_fired(position: Vector3)
+signal trap_sprung(position: Vector3)
+
+const PREF := "res://assets/farm/ithappy/farm/prefabs/assets/"
+const ORDER: Array[String] = ["fence", "gate", "slowing_trap", "automated_defense"]
+const NAMES := {
+ "fence": "Fence",
+ "gate": "Gate",
+ "slowing_trap": "Slowing trap",
+ "automated_defense": "Automated defense",
+}
+const GRID := 0.5
+const FENCE_LENGTH := 2.0
+const DIAGONAL_FENCE_LENGTH := 2.1213 # 1.5 * sqrt(2)
+const FENCE_THICKNESS := 0.2
+## Clear space kept around each gap in the remaining perimeter fence (the scarecrow's ways out to
+## the gathering areas) and in front of the barn doors.
+const GAP_CLEAR := 2.5
+const DOOR_RECT := Rect2(-0.8, -21.2, 3.6, 3.4)
+const WOBBLE_TIME := 0.35
+
+var campaign: CampaignController
+var config: GameConfig
+var nav: FarmNavigation
+var zones: FarmZones
+var enemies: EnemySystem
+var projectiles: FarmProjectiles
+var player: PlayerCharacter
+## Co-op: player 2's scarecrow (gates open for it too, and nothing is built onto it).
+var partner: Node3D
+
+var _views := {} # id -> Node3D
+var _bars := {} # id -> MeshInstance3D
+var _bodies := {} # id -> Array[RID] (physics bodies to leave out of placement queries)
+var _tints := {} # id -> StandardMaterial3D
+var _wobble := {} # id -> seconds left
+var _turret_cd := {} # id -> seconds left
+var _heads := {} # id -> Node3D (turret head)
+var _gate_open := {} # id -> 0..1
+var _crop_rects: Array[Rect2] = []
+var _gap_points := PackedVector2Array()
+var _query := PhysicsShapeQueryParameters3D.new()
+var _query_box := BoxShape3D.new()
+var _bar_shader: Shader
+
+
+func setup(p_campaign: CampaignController, p_nav: FarmNavigation, p_zones: FarmZones, p_enemies: EnemySystem,
+ p_projectiles: FarmProjectiles, p_player: PlayerCharacter) -> void:
+ campaign = p_campaign
+ config = p_campaign.config
+ nav = p_nav
+ zones = p_zones
+ enemies = p_enemies
+ projectiles = p_projectiles
+ player = p_player
+ nav.set_barrier_cost(roundi(config.barrier_detour / nav.cell_size * FarmNavigation.COST_ORTH))
+ _bar_shader = load("res://game/resources/hp_bar.gdshader") as Shader
+ for u in zones.crop_units():
+ var lo := Vector2(INF, INF)
+ var hi := Vector2(-INF, -INF)
+ for plant in u.get_children():
+ var p := Vector2((plant as Node3D).global_position.x, (plant as Node3D).global_position.z)
+ lo = lo.min(p)
+ hi = hi.max(p)
+ _crop_rects.append(Rect2(lo, hi - lo).grow(0.5))
+ var map := zones.playable
+ for m in zones.gaps():
+ var g := Vector2(m.global_position.x, m.global_position.z)
+ _gap_points.append(Vector2(clampf(g.x, map.position.x, map.end.x), clampf(g.y, map.position.y, map.end.y)))
+ _query.shape = _query_box
+ _query.collision_mask = 1
+ _query.collide_with_areas = false
+ sync_from_state()
+
+
+## Full health of a structure type, with upgrades (reinforced fences and gates).
+func max_hp(type: String) -> int:
+ var hp := config.structure_hp(type)
+ if type == "fence" or type == "gate":
+ hp = roundi(hp * Upgrades.value(config, campaign.state, "barrier_hp"))
+ return hp
+
+
+## The automated defense's range and the traps' slow time, with upgrades.
+func turret_range() -> float:
+ return Upgrades.value(config, campaign.state, "turret_range")
+
+
+func trap_slow_time() -> float:
+ return Upgrades.value(config, campaign.state, "trap_slow_time")
+
+
+func blocks(type: String) -> bool:
+ return type != "slowing_trap"
+
+
+func count() -> int:
+ return campaign.state.structures.size()
+
+
+## Snaps a world point onto the build grid.
+static func snap(p: Vector2) -> Vector2:
+ return Vector2(roundf(p.x / GRID) * GRID, roundf(p.y / GRID) * GRID)
+
+
+## Oriented footprint {"center", "half", "angle"} (angle: the long axis from +X toward +Z).
+func footprint(type: String, x: float, z: float, rot: int) -> Dictionary:
+ var half := Vector2(0.75, 0.75) if type == "slowing_trap" else Vector2(0.5, 0.5)
+ var angle := 0.0
+ if type == "fence" or type == "gate":
+ half = Vector2((DIAGONAL_FENCE_LENGTH if rot % 2 == 1 else FENCE_LENGTH) * 0.5, FENCE_THICKNESS * 0.5)
+ angle = rot * PI / 4.0
+ return {"center": Vector2(x, z), "half": half, "angle": angle}
+
+
+## Closed outline (5 points) of a footprint, optionally shrunk along its length / width.
+static func corners(fp: Dictionary, shrink_long: float = 0.0, shrink_wide: float = 0.0) -> PackedVector2Array:
+ var c: Vector2 = fp["center"]
+ var h: Vector2 = fp["half"] - Vector2(shrink_long, shrink_wide)
+ var u := Vector2(cos(fp["angle"]), sin(fp["angle"]))
+ var v := Vector2(-u.y, u.x)
+ var pts := PackedVector2Array([c + u * h.x + v * h.y, c - u * h.x + v * h.y, c - u * h.x - v * h.y, c + u * h.x - v * h.y])
+ pts.append(pts[0])
+ return pts
+
+
+## Why a structure can't go here ("" if it can). Space first, then daytime, then the cost.
+func validate(type: String, x: float, z: float, rot: int, scarecrow: Vector2) -> String:
+ var fp := footprint(type, x, z, rot)
+ var outline := corners(fp)
+ var inside := zones.playable.grow(-0.3)
+ for i in 4:
+ if not inside.has_point(outline[i]):
+ return "Build inside the farm"
+ for g in _gap_points:
+ if _distance_to_outline(g, outline) < GAP_CLEAR:
+ return "Keep the gap clear"
+ if _overlaps_rect(outline, DOOR_RECT):
+ return "Keep the barn doors clear"
+ for r in _crop_rects:
+ if _overlaps_rect(outline, r):
+ return "Not on the crops"
+ var tight := corners(fp, 0.2, 0.02)
+ for e in campaign.state.structures:
+ if _overlap(tight, corners(footprint(e["type"], e["x"], e["z"], e["rot"]), 0.2, 0.02)):
+ return "Something is built here already"
+ if _world_blocked(fp):
+ return "Blocked"
+ if _distance_to_outline(scarecrow, outline) < 0.45 and blocks(type) and type != "gate":
+ return "The scarecrow is in the way"
+ if partner != null and blocks(type) and type != "gate" \
+ and _distance_to_outline(Vector2(partner.global_position.x, partner.global_position.z), outline) < 0.45:
+ return "The other scarecrow is in the way"
+ for d in enemies.active_count:
+ if enemies.alive[d] == 1 and _distance_to_outline(Vector2(enemies.pos_x[d], enemies.pos_z[d]), outline) < config.enemy_radius:
+ return "An enemy is in the way"
+ if scarecrow.distance_to(Vector2(x, z)) > config.build_range:
+ return "Too far from the scarecrow"
+ if not campaign.is_daytime():
+ return "Building is for daytime"
+ var cost: Dictionary = config.costs.get(type, {})
+ if not campaign.state.resources.can_afford(cost):
+ return "Not enough: need %s more" % ResourceStore.describe(campaign.state.resources.missing(cost))
+ return ""
+
+
+## Builds after validate() passed: pays, records, shows, and updates navigation. Returns the id.
+func place(type: String, x: float, z: float, rot: int) -> int:
+ var s := campaign.state
+ if not s.pay(config.costs.get(type, {})):
+ return -1
+ var id := s.next_structure_id
+ s.next_structure_id += 1
+ s.structures.append({"id": id, "type": type, "x": x, "z": z, "rot": rot, "hp": max_hp(type)})
+ s.record_event("structures_built")
+ _add_view(s.structures[s.structures.size() - 1])
+ _update_nav()
+ built.emit(id, type)
+ return id
+
+
+## Takes a structure down, refunding dismantle_refund of its cost into the shed. Returns the
+## refund.
+func dismantle(id: int) -> Dictionary:
+ var e := campaign.state.structure(id)
+ if e.is_empty():
+ return {}
+ var refund := {}
+ var cost: Dictionary = config.costs.get(e["type"], {})
+ for m in cost:
+ var back := floori(int(cost[m]) * config.dismantle_refund)
+ if back > 0:
+ refund[m] = back
+ campaign.state.resources.shed[m] = int(campaign.state.resources.shed[m]) + back
+ _remove(id)
+ return refund
+
+
+## Damages a structure; at 0 HP it breaks (debris, destroyed). Returns true if it broke.
+func damage(id: int, amount: int) -> bool:
+ var e := campaign.state.structure(id)
+ if e.is_empty():
+ return false
+ campaign.state.record_event("structures_damaged", mini(amount, int(e["hp"])))
+ e["hp"] = maxi(int(e["hp"]) - amount, 0)
+ _wobble[id] = WOBBLE_TIME
+ if int(e["hp"]) > 0:
+ hurt.emit(id, Vector3(e["x"], 0.0, e["z"]))
+ return false
+ campaign.state.record_event("structures_destroyed")
+ var at := Vector3(e["x"], 0.0, e["z"])
+ var type: String = e["type"]
+ _debris(at)
+ _remove(id)
+ destroyed.emit(id, type, at)
+ return true
+
+
+## Co-op partner: the broken bits where a structure fell on the host.
+func show_debris(at: Vector3) -> void:
+ _debris(at)
+
+
+## What a full repair costs now (empty if nothing is missing).
+func repair_cost(id: int) -> Dictionary:
+ var e := campaign.state.structure(id)
+ if e.is_empty():
+ return {}
+ var top := max_hp(e["type"])
+ var missing := top - int(e["hp"])
+ if missing <= 0:
+ return {}
+ var out := {}
+ var cost: Dictionary = config.costs.get(e["type"], {})
+ for m in cost:
+ out[m] = ceili(int(cost[m]) * missing / float(top))
+ return out
+
+
+## Pays and repairs fully. Returns false if there was nothing to repair or it couldn't be paid.
+func repair(id: int) -> bool:
+ var cost := repair_cost(id)
+ if cost.is_empty() or not campaign.state.pay(cost):
+ return false
+ var e := campaign.state.structure(id)
+ e["hp"] = max_hp(e["type"])
+ campaign.state.record_event("repairs")
+ repaired.emit(id)
+ return true
+
+
+## The structure whose footprint is within reach of p, preferring damaged ones, or -1.
+func structure_near(p: Vector2, reach: float, damaged_only: bool = false) -> int:
+ var best := -1
+ var best_d := INF
+ for e in campaign.state.structures:
+ if damaged_only and int(e["hp"]) >= max_hp(e["type"]):
+ continue
+ var d := _distance_to_outline(p, corners(footprint(e["type"], e["x"], e["z"], e["rot"])))
+ if d <= reach and d < best_d:
+ best = int(e["id"])
+ best_d = d
+ return best
+
+
+## A ground enemy at (x, z) steps on a slowing trap with triggers left: uses one up. Returns true
+## if the enemy is slowed.
+func try_trap(x: float, z: float) -> bool:
+ for e in campaign.state.structures:
+ if e["type"] != "slowing_trap" or int(e["hp"]) <= 0:
+ continue
+ if absf(x - float(e["x"])) <= 0.75 and absf(z - float(e["z"])) <= 0.75:
+ e["hp"] = int(e["hp"]) - 1
+ trap_sprung.emit(Vector3(e["x"], 0.0, e["z"]))
+ return true
+ return false
+
+
+## Physics tick: the automated defenses shoot.
+func step(dt: float) -> void:
+ for e in campaign.state.structures:
+ if e["type"] != "automated_defense":
+ continue
+ var id: int = e["id"]
+ var cd := maxf(float(_turret_cd.get(id, 0.0)) - dt, 0.0)
+ if cd > 0.0:
+ _turret_cd[id] = cd
+ continue
+ var from := Vector2(e["x"], e["z"])
+ var target := -1
+ var best := turret_range()
+ for d in enemies.active_count:
+ if enemies.alive[d] == 0:
+ continue
+ var p := Vector2(enemies.pos_x[d], enemies.pos_z[d])
+ var dist := p.distance_to(from)
+ if dist < best and nav.line_clear(from.x, from.y, p.x, p.y, true):
+ best = dist
+ target = d
+ if target < 0:
+ _turret_cd[id] = 0.0
+ continue
+ var lead := best / config.projectile_speed
+ var aim := Vector2(enemies.pos_x[target] + enemies.vel_x[target] * lead, enemies.pos_z[target] + enemies.vel_z[target] * lead) - from
+ var dir := Vector3(aim.x, 0.0, aim.y).normalized()
+ var origin := Vector3(from.x, config.combat_height, from.y)
+ projectiles.fire(origin, origin + dir * 0.6, dir)
+ turret_fired.emit(origin)
+ _turret_cd[id] = config.turret_fire_interval
+ var head: Node3D = _heads.get(id)
+ if head != null:
+ head.rotation.y = atan2(-dir.x, -dir.z)
+
+
+## Rebuilds every view and the navigation layer from the farm state (new vacation, retry).
+func sync_from_state() -> void:
+ for id in _views.keys():
+ (_views[id] as Node3D).queue_free()
+ _views.clear()
+ _bars.clear()
+ _bodies.clear()
+ _tints.clear()
+ _wobble.clear()
+ _heads.clear()
+ _turret_cd.clear()
+ _gate_open.clear()
+ for e in campaign.state.structures:
+ _add_view(e)
+ _update_nav()
+
+
+## A display-only copy of a structure (no collision), for the build preview.
+func make_ghost(type: String, rot: int) -> Node3D:
+ var root := _build_view(type, rot)
+ _strip_collision(root)
+ return root
+
+
+func body_rids() -> Array[RID]:
+ var out: Array[RID] = []
+ for id in _bodies:
+ out.append_array(_bodies[id])
+ return out
+
+
+func _process(delta: float) -> void:
+ var near := player.global_position if player != null else Vector3(INF, 0.0, INF)
+ var near2 := partner.global_position if partner != null else Vector3(INF, 0.0, INF)
+ for e in campaign.state.structures:
+ var id: int = e["id"]
+ var view: Node3D = _views.get(id)
+ if view == null:
+ continue
+ var top := max_hp(e["type"])
+ var frac := float(e["hp"]) / float(top)
+ var bar: MeshInstance3D = _bars.get(id)
+ if bar != null:
+ bar.visible = frac < 1.0
+ (bar.material_override as ShaderMaterial).set_shader_parameter("fill", frac)
+ var tint: StandardMaterial3D = _tints.get(id)
+ if tint != null:
+ tint.albedo_color.a = (1.0 - frac) * 0.45 if e["type"] != "slowing_trap" else 0.0
+ var w := maxf(float(_wobble.get(id, 0.0)) - delta, 0.0)
+ _wobble[id] = w
+ view.rotation.z = sin(w * 60.0) * 0.08 * (w / WOBBLE_TIME)
+ if e["type"] == "slowing_trap":
+ view.get_node("Tar").visible = int(e["hp"]) > 0
+ elif e["type"] == "gate":
+ var dist := minf(Vector2(near.x - float(e["x"]), near.z - float(e["z"])).length(),
+ Vector2(near2.x - float(e["x"]), near2.z - float(e["z"])).length())
+ var target := 1.0 if dist < 2.2 else 0.0
+ var o := move_toward(float(_gate_open.get(id, 0.0)), target, delta * 3.0)
+ _gate_open[id] = o
+ var panel := view.get_node("Panel") as Node3D
+ panel.rotation.y = deg_to_rad(32.5 + 100.0 * o)
+
+
+func _remove(id: int) -> void:
+ var s := campaign.state
+ for i in s.structures.size():
+ if int(s.structures[i]["id"]) == id:
+ s.structures.remove_at(i)
+ break
+ var view: Node3D = _views.get(id)
+ if view != null:
+ view.queue_free()
+ for d in [_views, _bars, _bodies, _tints, _wobble, _heads, _turret_cd, _gate_open]:
+ (d as Dictionary).erase(id)
+ _update_nav()
+
+
+func _update_nav() -> void:
+ var entries: Array = []
+ for e in campaign.state.structures:
+ if blocks(e["type"]):
+ entries.append({"id": e["id"], "outline": corners(footprint(e["type"], e["x"], e["z"], e["rot"]))})
+ nav.set_structures(entries)
+ layout_changed.emit()
+
+
+func _add_view(e: Dictionary) -> void:
+ var id: int = e["id"]
+ var view := _build_view(e["type"], e["rot"])
+ view.name = "%s_%d" % [e["type"], id]
+ add_child(view)
+ _views[id] = view
+ view.global_position = Vector3(e["x"], _ground_y(Vector2(e["x"], e["z"])), e["z"])
+ var rids: Array[RID] = []
+ for body in view.find_children("*", "StaticBody3D", true, false):
+ rids.append((body as StaticBody3D).get_rid())
+ _bodies[id] = rids
+ var tint := StandardMaterial3D.new()
+ tint.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
+ tint.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
+ tint.albedo_color = Color(0.9, 0.1, 0.05, 0.0)
+ for mi in view.find_children("*", "MeshInstance3D", true, false):
+ (mi as MeshInstance3D).material_overlay = tint
+ _tints[id] = tint
+ var quad := QuadMesh.new()
+ quad.size = Vector2(1.1, 0.14)
+ var mat := ShaderMaterial.new()
+ mat.shader = _bar_shader
+ var bar := MeshInstance3D.new()
+ bar.mesh = quad
+ bar.material_override = mat
+ bar.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
+ bar.top_level = true
+ bar.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
+ bar.visible = false
+ view.add_child(bar)
+ bar.global_position = view.global_position + Vector3(0.0, 2.3, 0.0)
+ _bars[id] = bar
+ if e["type"] == "automated_defense":
+ _heads[id] = view.get_node("Head")
+
+
+## The visual (and, for barriers other than gates, collision) of a structure, centered on its
+## footprint and rotated to it.
+func _build_view(type: String, rot: int) -> Node3D:
+ var root := Node3D.new()
+ root.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
+ var fp := footprint(type, 0.0, 0.0, rot)
+ root.rotation.y = -float(fp["angle"])
+ match type:
+ "fence":
+ var fence := _instance("prop/fence_026.tscn")
+ fence.scale.x = float(fp["half"].x) * 2.0 / 2.08
+ fence.position.x = -0.05 * fence.scale.x
+ root.add_child(fence)
+ "gate":
+ var panel := _instance("prop/fence_018.tscn")
+ panel.name = "Panel"
+ panel.position = Vector3(-0.865, 0.0, 0.0)
+ panel.rotation.y = deg_to_rad(32.5)
+ _strip_collision(panel) # the scarecrow walks through; enemies are kept out by navigation
+ root.add_child(panel)
+ for end in [-1.0, 1.0]:
+ var post := _instance("prop/fence_027.tscn")
+ post.position = Vector3(end * 0.95, 0.0, 0.0)
+ root.add_child(post)
+ "slowing_trap":
+ var tar := MeshInstance3D.new()
+ tar.name = "Tar"
+ var box := BoxMesh.new()
+ box.size = Vector3(1.4, 0.06, 1.4)
+ var mat := StandardMaterial3D.new()
+ mat.albedo_color = Color(0.1, 0.07, 0.05)
+ mat.roughness = 0.2
+ mat.metallic_specular = 0.8
+ box.material = mat
+ tar.mesh = box
+ tar.position.y = 0.04
+ root.add_child(tar)
+ var bucket := _instance("prop/bucket_001.tscn")
+ bucket.position = Vector3(0.55, 0.0, 0.55)
+ _strip_collision(bucket)
+ root.add_child(bucket)
+ "automated_defense":
+ var base := _instance("prop/barrel_001.tscn")
+ root.add_child(base)
+ var metal := StandardMaterial3D.new()
+ metal.albedo_color = Color(0.25, 0.27, 0.3)
+ metal.metallic = 0.6
+ var accent := StandardMaterial3D.new()
+ accent.albedo_color = Color(0.95, 0.55, 0.15)
+ var post := MeshInstance3D.new()
+ var cyl := CylinderMesh.new()
+ cyl.top_radius = 0.06
+ cyl.bottom_radius = 0.06
+ cyl.height = 0.55
+ cyl.material = metal
+ post.mesh = cyl
+ post.position.y = 1.2
+ root.add_child(post)
+ var head := Node3D.new()
+ head.name = "Head"
+ head.position.y = 1.5
+ root.add_child(head)
+ var body := MeshInstance3D.new()
+ var bm := BoxMesh.new()
+ bm.size = Vector3(0.3, 0.22, 0.4)
+ bm.material = accent
+ body.mesh = bm
+ head.add_child(body)
+ var gun := MeshInstance3D.new()
+ var gm := CylinderMesh.new()
+ gm.top_radius = 0.05
+ gm.bottom_radius = 0.05
+ gm.height = 0.6
+ gm.material = metal
+ gun.mesh = gm
+ gun.rotation.x = PI * 0.5
+ gun.position.z = -0.4
+ head.add_child(gun)
+ return root
+
+
+func _instance(path: String) -> Node3D:
+ return (load(PREF + path) as PackedScene).instantiate() as Node3D
+
+
+static func _strip_collision(node: Node) -> void:
+ for body in node.find_children("*", "CollisionObject3D", true, false):
+ (body as CollisionObject3D).collision_layer = 0
+ (body as CollisionObject3D).collision_mask = 0
+
+
+## Height of the ground under p (walkable terrain), for placing views.
+func _ground_y(p: Vector2) -> float:
+ if not is_inside_tree():
+ return 0.0
+ var ray := PhysicsRayQueryParameters3D.create(Vector3(p.x, 5.0, p.y), Vector3(p.x, -2.0, p.y), 1)
+ ray.exclude = body_rids()
+ var hit := get_world_3d().direct_space_state.intersect_ray(ray)
+ return maxf((hit["position"] as Vector3).y, 0.0) if not hit.is_empty() and (hit["position"] as Vector3).y < 1.0 else 0.0
+
+
+## Anything solid (not walkable terrain, not another structure) under the footprint, with its
+## ends trimmed so a fence may touch a wall or a post.
+func _world_blocked(fp: Dictionary) -> bool:
+ var h: Vector2 = fp["half"]
+ _query_box.size = Vector3(maxf(h.x * 2.0 - 0.3, 0.1), 1.4, maxf(h.y * 2.0, 0.1))
+ var c: Vector2 = fp["center"]
+ _query.transform = Transform3D(Basis(Vector3.UP, -float(fp["angle"])), Vector3(c.x, 1.05, c.y))
+ _query.exclude = body_rids()
+ for hit in get_world_3d().direct_space_state.intersect_shape(_query, 16):
+ var body := hit["collider"] as CollisionObject3D
+ if body == null:
+ continue
+ var owner_id := body.shape_find_owner(int(hit["shape"]))
+ var cs := body.shape_owner_get_owner(owner_id) as CollisionShape3D
+ if cs != null and cs.shape is ConcavePolygonShape3D:
+ continue # ground and road tiles
+ return true
+ return false
+
+
+func _debris(at: Vector3) -> void:
+ var p := CPUParticles3D.new()
+ var box := BoxMesh.new()
+ box.size = Vector3(0.14, 0.06, 0.3)
+ var mat := StandardMaterial3D.new()
+ mat.albedo_color = Color(0.45, 0.3, 0.18)
+ box.material = mat
+ p.mesh = box
+ p.amount = 18
+ p.lifetime = 1.0
+ p.one_shot = true
+ p.explosiveness = 1.0
+ p.direction = Vector3.UP
+ p.spread = 70.0
+ p.initial_velocity_min = 2.5
+ p.initial_velocity_max = 5.0
+ p.angular_velocity_min = -360.0
+ p.angular_velocity_max = 360.0
+ p.gravity = Vector3(0.0, -12.0, 0.0)
+ add_child(p)
+ p.global_position = at + Vector3(0.0, 0.8, 0.0)
+ p.emitting = true
+ get_tree().create_timer(1.5).timeout.connect(p.queue_free)
+
+
+static func _distance_to_outline(p: Vector2, outline: PackedVector2Array) -> float:
+ if Geometry2D.is_point_in_polygon(p, outline):
+ return 0.0
+ var best := INF
+ for k in outline.size() - 1:
+ best = minf(best, p.distance_to(Geometry2D.get_closest_point_to_segment(p, outline[k], outline[k + 1])))
+ return best
+
+
+static func _overlaps_rect(outline: PackedVector2Array, r: Rect2) -> bool:
+ var box := PackedVector2Array([r.position, Vector2(r.end.x, r.position.y), r.end, Vector2(r.position.x, r.end.y), r.position])
+ return _overlap(outline, box)
+
+
+## Separating-axis test for two closed convex outlines.
+static func _overlap(a: PackedVector2Array, b: PackedVector2Array) -> bool:
+ for poly in [a, b]:
+ for k in poly.size() - 1:
+ var edge: Vector2 = poly[k + 1] - poly[k]
+ var axis := Vector2(-edge.y, edge.x)
+ var a_lo := INF
+ var a_hi := -INF
+ var b_lo := INF
+ var b_hi := -INF
+ for i in a.size() - 1:
+ var d := a[i].dot(axis)
+ a_lo = minf(a_lo, d)
+ a_hi = maxf(a_hi, d)
+ for i in b.size() - 1:
+ var d := b[i].dot(axis)
+ b_lo = minf(b_lo, d)
+ b_hi = maxf(b_hi, d)
+ if a_hi <= b_lo or b_hi <= a_lo:
+ return false
+ return true
diff --git a/game/scripts/structure_system.gd.uid b/game/scripts/structure_system.gd.uid
new file mode 100644
index 0000000..884c711
--- /dev/null
+++ b/game/scripts/structure_system.gd.uid
@@ -0,0 +1 @@
+uid://di5ehcmuhbqy7
diff --git a/game/scripts/thief_behavior.gd b/game/scripts/thief_behavior.gd
new file mode 100644
index 0000000..d567ec7
--- /dev/null
+++ b/game/scripts/thief_behavior.gd
@@ -0,0 +1,506 @@
+class_name ThiefBehavior
+extends RefCounted
+## What each enemy wants, decided every tick (EnemySystem turns it into motion). Three types
+## (stats in GameConfig.enemy_types):
+## thief on foot, after its type's targets (animals and supplies): the theft lifecycle of
+## game/RULES.md below. Routes around barriers when it can, breaks through when not.
+## crow flies, after crops only: straight at a claimed crop (fences, gates, and traps mean
+## nothing to it), lands and takes it, then flies straight off the farm out its
+## nearest side. It never fights.
+## breaker the fence breaker, on foot; steals nothing. It walks (breaker_field) to the nearest
+## barrier guarding the crops, the pen, or the shed and smashes it, then goes for the
+## next. It turns on the scarecrow when it comes close or shoots it, and hunts the
+## scarecrow when nothing is left to break.
+## States:
+## SEEK claim something to take (LootSystem.claim, limited to the type's categories: dropped
+## loot in view first, then its wanted category, EnemySystem.want, then the others),
+## reserving it so it shows as targeted, and go there. On foot: along its category's
+## flow field (the crop rows, the pen, the shed piles) from afar, straight at it once
+## inside that area or close with a clear line. Flying: straight at it. A breaker
+## follows the breaker field instead.
+## STEAL stand at it for its steal time (the category's, times the type's steal_time; the
+## progress ring fills); a hit restarts it. An animal that moved off is chased again; a
+## sack finds the shed empty and seeks again.
+## CARRY take it off the farm at the type's carry_speed: on foot along the escape field to the
+## nearest point of the farm's edge (reaching the edge carries it off), flying straight
+## out the nearest side. The loot is lost.
+## RETREAT nothing left to take, or sunrise: leave the same way.
+## FLEE scared (the scarecrow's fear): run straight away for fear_duration, giving up any
+## claim; carriers drop their loot (D5) unless fear_drops_loot is off. Afterwards an
+## enemy seeks again, or keeps carrying what it still holds.
+## BREAK its route runs into a player-built barrier (FarmNavigation.barrier_ahead), or a
+## breaker reached the one it came for: it hits the barrier (structure_damage every
+## hit_interval) until it breaks, then goes back to what it was doing. Steering straight
+## at loot needs a line clear of barriers too, so a fence in the way is broken or walked
+## around, not ignored.
+## FIGHT a breaker goes for the scarecrow, until it's more than FIGHT_LEASH away and there's
+## still something to break.
+## An enemy whose claim disappears (another one took it, the scarecrow recovered it, an animal
+## followed the scarecrow away) claims another. Who hits the scarecrow (EnemySystem.
+## evaluate_attacks) depends on the type's aggression: thieves when touching it while seeking,
+## stealing, carrying, or breaking; breakers while fighting; crows never.
+
+enum State { SEEK, STEAL, CARRY, RETREAT, FLEE, BREAK, FIGHT }
+
+## Distance at which an enemy starts taking its loot.
+const STEAL_REACH := 0.9
+## Seconds a thief keeps walking toward dropped loot it can't see before choosing another.
+const GIVE_UP_TIME := 10.0
+## Flyers see dropped crops from above within this distance.
+const AIR_VIEW := 20.0
+## A flyer this far outside the farm has left it.
+const AIR_EXIT_MARGIN := 2.0
+const FIGHT_LEASH := 12.0
+
+var loot: LootSystem
+var nav: FarmNavigation
+var crop_field: PackedInt32Array
+var escape_field: PackedInt32Array
+var field_rect: Rect2
+## Set by FarmSim: the flow fields toward the pen, each shed pile (material -> field), and the
+## barriers guarding valuables; those areas; the farm (flyers leave over its edge); and, every
+## tick, where the scarecrow is.
+var animal_field := PackedInt32Array()
+var supply_fields := {}
+var breaker_field := PackedInt32Array()
+## Toward the scarecrow (FarmSim keeps it fresh while anything fights).
+var hunt_field := PackedInt32Array()
+var pen_rect := Rect2()
+var shed_rect := Rect2()
+var farm_rect := Rect2()
+var scarecrow := Vector2(INF, INF)
+## Co-op: where player 2's scarecrow is (INF when there's none, or it's down). Enemies go for the
+## nearer of the two.
+var scarecrow2 := Vector2(INF, INF)
+var cfg: GameConfig
+## Set by FarmSim: the barriers enemies break.
+var structures: StructureSystem
+var _dir := PackedFloat32Array([0.0, 0.0])
+
+
+func setup(p_cfg: GameConfig, p_nav: FarmNavigation, p_loot: LootSystem, p_crop_field: PackedInt32Array,
+ p_escape_field: PackedInt32Array, p_field_rect: Rect2) -> void:
+ cfg = p_cfg
+ nav = p_nav
+ loot = p_loot
+ crop_field = p_crop_field
+ escape_field = p_escape_field
+ field_rect = p_field_rect
+
+
+func update(es: EnemySystem, dt: float) -> void:
+ for i in es.active_count:
+ if es.alive[i] == 0:
+ continue
+ var t := es.type[i]
+ match es.state[i]:
+ State.SEEK:
+ if t == EnemySystem.TYPE_CROW:
+ _crow_seek(es, i)
+ elif es.t_breaks[t] == 1:
+ _breaker_seek(es, i)
+ else:
+ _seek(es, i, dt)
+ State.STEAL:
+ _steal(es, i, dt)
+ State.CARRY:
+ if es.t_flying[t] == 1:
+ _fly_off(es, i, EnemySystem.Removal.ESCAPED)
+ else:
+ _carry(es, i)
+ State.FLEE:
+ _flee(es, i, dt)
+ State.BREAK:
+ _break(es, i)
+ State.FIGHT:
+ _fight(es, i)
+ _:
+ if es.t_flying[t] == 1:
+ _fly_off(es, i, EnemySystem.Removal.LEFT)
+ else:
+ _leave(es, i)
+
+
+## A hit while stealing restarts the theft; a hit on a fighter makes it turn on the scarecrow.
+func on_hit(es: EnemySystem, d: int) -> void:
+ if es.state[d] == State.STEAL:
+ es.timer[d] = 0.0
+ loot.set_progress(es.target[d], es.handle_of(d), 0.0)
+ if es.t_aggression[es.type[d]] == EnemySystem.Aggression.FIGHT and (es.state[d] == State.SEEK or es.state[d] == State.BREAK):
+ _start_fight(es, d)
+
+
+func can_attack(es: EnemySystem, d: int) -> bool:
+ var st := es.state[d]
+ match es.t_aggression[es.type[d]]:
+ EnemySystem.Aggression.CONTACT:
+ return st == State.SEEK or st == State.STEAL or st == State.CARRY or st == State.BREAK
+ EnemySystem.Aggression.FIGHT:
+ return st == State.FIGHT
+ return false
+
+
+## Whether fear makes it flee: anything busy on the farm (not already fleeing or leaving).
+func can_be_scared(es: EnemySystem, d: int) -> bool:
+ var st := es.state[d]
+ return st == State.SEEK or st == State.STEAL or st == State.CARRY or st == State.BREAK or st == State.FIGHT
+
+
+## Fear from center: every enemy busy on the farm within radius flees straight away. Returns how
+## many were scared.
+func scare(es: EnemySystem, center: Vector2, radius: float) -> int:
+ var n := 0
+ for i in es.active_count:
+ if es.alive[i] == 0 or not can_be_scared(es, i):
+ continue
+ var away := Vector2(es.pos_x[i], es.pos_z[i]) - center
+ var d := away.length()
+ if d > radius:
+ continue
+ var h := es.handle_of(i)
+ if es.carry[i] >= 0 and cfg.fear_drops_loot:
+ loot.drop(es.carry[i], h, es.pos_x[i], es.pos_z[i])
+ es.carry[i] = -1
+ loot.release(es.target[i], h)
+ es.target[i] = -1
+ es.barrier[i] = -1
+ var dir := away / d if d > 1e-3 else Vector2(es.head_x[i], es.head_z[i])
+ es.desire_x[i] = dir.x
+ es.desire_z[i] = dir.y
+ es.timer[i] = cfg.fear_duration
+ es.state[i] = State.FLEE
+ n += 1
+ return n
+
+
+## Sunrise: every enemy gives up what it was after and leaves; carriers keep running.
+func retreat_all(es: EnemySystem) -> void:
+ for i in es.active_count:
+ if es.alive[i] == 1:
+ loot.release(es.target[i], es.handle_of(i))
+ es.target[i] = -1
+ es.barrier[i] = -1
+ es.state[i] = State.CARRY if es.carry[i] >= 0 else State.RETREAT
+
+
+## A flyer's visual altitude: cruising, coming down as it nears its crop, sitting on it while it
+## takes it.
+func altitude_for(es: EnemySystem, i: int) -> float:
+ match es.state[i]:
+ State.STEAL:
+ return cfg.land_altitude
+ State.SEEK:
+ var unit := es.target[i]
+ if unit > 0:
+ var d := loot.position_of(unit).distance_to(Vector2(es.pos_x[i], es.pos_z[i]))
+ return lerpf(cfg.land_altitude, cfg.cruise_altitude, clampf((d - 0.5) / 4.0, 0.0, 1.0))
+ return cfg.cruise_altitude
+
+
+func _seek(es: EnemySystem, i: int, dt: float) -> void:
+ var h := es.handle_of(i)
+ var p := Vector2(es.pos_x[i], es.pos_z[i])
+ var unit := es.target[i]
+ if unit < 0 or not loot.is_claimed_by(unit, h):
+ unit = loot.claim(h, p, nav, cfg.direct_seek_distance, es.want[i], es.t_targets[es.type[i]])
+ es.target[i] = unit
+ es.timer[i] = 0.0
+ if unit < 0:
+ es.state[i] = State.RETREAT
+ _leave(es, i)
+ return
+ var goal := loot.position_of(unit)
+ var to := goal - p
+ var d := to.length()
+ if d <= STEAL_REACH:
+ es.state[i] = State.STEAL
+ es.timer[i] = 0.0
+ _still(es, i, to / maxf(d, 1e-4))
+ return
+ es.pace[i] = 1.0
+ var field := field_for(unit)
+ if (area_for(loot.category[unit]).has_point(p) or d < cfg.direct_seek_distance) and nav.line_clear(p.x, p.y, goal.x, goal.y):
+ es.desire_x[i] = to.x / d
+ es.desire_z[i] = to.y / d
+ es.timer[i] = 0.0
+ return
+ if field.is_empty():
+ es.desire_x[i] = to.x / d
+ es.desire_z[i] = to.y / d
+ return
+ if loot.is_home(unit) and nav.flow_direction(field, p.x, p.y, _dir):
+ es.desire_x[i] = _dir[0]
+ es.desire_z[i] = _dir[1]
+ _check_barrier(es, i, field)
+ return
+ # Dropped loot out of sight: head for its home area meanwhile, and give up after a while.
+ es.timer[i] += dt
+ if es.timer[i] > GIVE_UP_TIME:
+ loot.release(unit, h)
+ es.target[i] = -1
+ if nav.flow_direction(field, p.x, p.y, _dir):
+ es.desire_x[i] = _dir[0]
+ es.desire_z[i] = _dir[1]
+ _check_barrier(es, i, field)
+ else:
+ es.desire_x[i] = to.x / d
+ es.desire_z[i] = to.y / d
+
+
+## A crow: straight at its crop, whatever is in the way.
+func _crow_seek(es: EnemySystem, i: int) -> void:
+ var h := es.handle_of(i)
+ var p := Vector2(es.pos_x[i], es.pos_z[i])
+ var unit := es.target[i]
+ if unit < 0 or not loot.is_claimed_by(unit, h):
+ unit = loot.claim(h, p, nav, AIR_VIEW, es.want[i], es.t_targets[es.type[i]], false)
+ es.target[i] = unit
+ es.timer[i] = 0.0
+ if unit < 0:
+ es.state[i] = State.RETREAT
+ return
+ var to := loot.position_of(unit) - p
+ var d := to.length()
+ if d <= STEAL_REACH:
+ es.state[i] = State.STEAL
+ es.timer[i] = 0.0
+ _still(es, i, to / maxf(d, 1e-4))
+ return
+ es.desire_x[i] = to.x / d
+ es.desire_z[i] = to.y / d
+ es.pace[i] = 1.0
+
+
+## A flyer heading straight off the farm out its nearest side (carrying its loot, or not); once
+## it's past the edge it's gone.
+func _fly_off(es: EnemySystem, i: int, reason: EnemySystem.Removal) -> void:
+ var p := Vector2(es.pos_x[i], es.pos_z[i])
+ if not farm_rect.grow(AIR_EXIT_MARGIN).has_point(p):
+ if es.carry[i] >= 0:
+ loot.escape(es.carry[i], es.handle_of(i))
+ es.carry[i] = -1
+ es.queue_removal(i, reason)
+ return
+ var exit := _nearest_exit(p)
+ var to := exit - p
+ var d := maxf(to.length(), 1e-4)
+ es.desire_x[i] = to.x / d
+ es.desire_z[i] = to.y / d
+ es.pace[i] = es.t_carry[es.type[i]] if es.carry[i] >= 0 else 1.0
+
+
+## Just past the nearest point of the farm's edge.
+func _nearest_exit(p: Vector2) -> Vector2:
+ return FarmZones.nearest_on_outline(farm_rect.grow(AIR_EXIT_MARGIN + 1.0), p)
+
+
+## A fence breaker: to the nearest barrier guarding something, and smash it.
+func _breaker_seek(es: EnemySystem, i: int) -> void:
+ if _aggro(es, i):
+ _start_fight(es, i)
+ return
+ var p := Vector2(es.pos_x[i], es.pos_z[i])
+ if breaker_field.is_empty() or breaker_field[nav.cell_of(p.x, p.y)] >= FarmNavigation.UNREACHABLE:
+ _start_fight(es, i) # nothing left to break
+ return
+ es.pace[i] = 1.0
+ if nav.flow_direction(breaker_field, p.x, p.y, _dir):
+ es.desire_x[i] = _dir[0]
+ es.desire_z[i] = _dir[1]
+ _check_barrier(es, i, breaker_field)
+ return
+ var id := _adjacent_structure(p)
+ if id >= 0:
+ es.barrier[i] = id
+ es.resume[i] = State.SEEK
+ es.state[i] = State.BREAK
+ var e := structures.campaign.state.structure(id)
+ var at := Vector2(float(e["x"]), float(e["z"])) - p
+ _still(es, i, at.normalized() if at.length_squared() > 1e-4 else Vector2(es.head_x[i], es.head_z[i]))
+ else:
+ _still(es, i, Vector2(es.head_x[i], es.head_z[i])) # the field is catching up after a breach
+
+
+## The structure (in the navigation's structure layer: every barrier) nearest to p within 1.5 m,
+## or -1.
+func _adjacent_structure(p: Vector2) -> int:
+ var best := -1
+ var best_d := INF
+ var r := 3
+ var c := nav.cell_of(p.x, p.y)
+ for dz in range(-r, r + 1):
+ for dx in range(-r, r + 1):
+ var cell := c + dz * nav.width + dx
+ if cell < 0 or cell >= nav.cell_count() or nav.structure_at[cell] < 0:
+ continue
+ var d := nav.cell_center(cell).distance_squared_to(p)
+ if d < best_d:
+ best_d = d
+ best = nav.structure_at[cell]
+ return best
+
+
+## The nearer scarecrow standing (INF if none).
+func nearest_scarecrow(p: Vector2) -> Vector2:
+ if not scarecrow2.is_finite():
+ return scarecrow
+ if not scarecrow.is_finite():
+ return scarecrow2
+ return scarecrow if p.distance_squared_to(scarecrow) <= p.distance_squared_to(scarecrow2) else scarecrow2
+
+
+func _aggro(es: EnemySystem, i: int) -> bool:
+ var t := es.type[i]
+ var p := Vector2(es.pos_x[i], es.pos_z[i])
+ var sc := nearest_scarecrow(p)
+ if es.t_aggression[t] != EnemySystem.Aggression.FIGHT or not sc.is_finite():
+ return false
+ return p.distance_to(sc) <= es.t_aggro_range[t] and nav.line_clear(p.x, p.y, sc.x, sc.y)
+
+
+func _start_fight(es: EnemySystem, i: int) -> void:
+ es.barrier[i] = -1
+ es.state[i] = State.FIGHT
+
+
+func _fight(es: EnemySystem, i: int) -> void:
+ var p := Vector2(es.pos_x[i], es.pos_z[i])
+ var sc := nearest_scarecrow(p)
+ if not sc.is_finite():
+ es.state[i] = State.SEEK
+ return
+ var to := sc - p
+ var d := to.length()
+ var has_work := not breaker_field.is_empty() and breaker_field[nav.cell_of(p.x, p.y)] < FarmNavigation.UNREACHABLE
+ if d > FIGHT_LEASH and has_work:
+ es.state[i] = State.SEEK
+ return
+ var contact := cfg.enemy_radius + FarmSim.SCARECROW_RADIUS + cfg.enemy_attack_reach * 0.5
+ if d <= contact:
+ _still(es, i, to / maxf(d, 1e-4))
+ return
+ es.pace[i] = 1.0
+ if not nav.line_clear(p.x, p.y, sc.x, sc.y) and not hunt_field.is_empty() \
+ and nav.flow_direction(hunt_field, p.x, p.y, _dir):
+ es.desire_x[i] = _dir[0]
+ es.desire_z[i] = _dir[1]
+ _check_barrier(es, i, hunt_field) # smash through to it
+ return
+ es.desire_x[i] = to.x / d
+ es.desire_z[i] = to.y / d
+
+
+## The flow field toward an item's home: the crop rows, the pen, or its sack's pile at the shed.
+func field_for(id: int) -> PackedInt32Array:
+ match loot.category[id]:
+ LootSystem.Category.ANIMAL:
+ return animal_field if animal_field.size() > 0 else crop_field
+ LootSystem.Category.SUPPLY:
+ return supply_fields.get(loot.sack_material[id], crop_field)
+ return crop_field
+
+
+func area_for(c: int) -> Rect2:
+ match c:
+ LootSystem.Category.ANIMAL:
+ return pen_rect
+ LootSystem.Category.SUPPLY:
+ return shed_rect
+ return field_rect
+
+
+func _steal(es: EnemySystem, i: int, dt: float) -> void:
+ var h := es.handle_of(i)
+ var unit := es.target[i]
+ if unit < 0 or not loot.is_claimed_by(unit, h):
+ es.state[i] = State.SEEK
+ return
+ if loot.category[unit] == LootSystem.Category.ANIMAL \
+ and loot.position_of(unit).distance_to(Vector2(es.pos_x[i], es.pos_z[i])) > STEAL_REACH + 0.4:
+ es.state[i] = State.SEEK # it got away (a loose animal): chase it
+ loot.set_progress(unit, h, 0.0)
+ return
+ es.pace[i] = 0.0
+ es.timer[i] += dt
+ var need := loot.steal_time(unit) * es.t_steal[es.type[i]]
+ loot.set_progress(unit, h, es.timer[i] / need)
+ if es.timer[i] >= need:
+ if loot.pick_up(unit, h):
+ es.carry[i] = unit
+ es.state[i] = State.CARRY
+ else:
+ es.state[i] = State.SEEK # nothing left to take there
+ es.target[i] = -1
+ es.timer[i] = 0.0
+
+
+func _flee(es: EnemySystem, i: int, dt: float) -> void:
+ es.pace[i] = cfg.flee_speed_factor
+ es.timer[i] -= dt
+ if es.timer[i] <= 0.0:
+ es.timer[i] = 0.0
+ es.state[i] = State.CARRY if es.carry[i] >= 0 else State.SEEK
+
+
+func _break(es: EnemySystem, i: int) -> void:
+ var id := es.barrier[i]
+ if structures == null or structures.campaign.state.structure(id).is_empty():
+ es.barrier[i] = -1
+ es.state[i] = es.resume[i]
+ return
+ if _aggro(es, i):
+ _start_fight(es, i)
+ return
+ es.pace[i] = 0.0
+ if es.attack_cd[i] == 0.0:
+ var t := es.type[i]
+ es.attack_cd[i] = es.t_hit_interval[t]
+ structures.damage(id, maxi(es.t_structure_damage[t], 1))
+
+
+## Following a field into a barrier: stop and break it.
+func _check_barrier(es: EnemySystem, i: int, field: PackedInt32Array) -> void:
+ var id := nav.barrier_ahead(field, es.pos_x[i], es.pos_z[i])
+ if id < 0:
+ return
+ es.barrier[i] = id
+ es.resume[i] = es.state[i]
+ es.state[i] = State.BREAK
+ es.pace[i] = 0.0
+
+
+func _carry(es: EnemySystem, i: int) -> void:
+ if _at_exit(es, i):
+ loot.escape(es.carry[i], es.handle_of(i))
+ es.carry[i] = -1
+ es.queue_removal(i, EnemySystem.Removal.ESCAPED)
+ return
+ _follow(es, i, escape_field, es.t_carry[es.type[i]])
+ _check_barrier(es, i, escape_field)
+
+
+func _leave(es: EnemySystem, i: int) -> void:
+ if _at_exit(es, i):
+ es.queue_removal(i, EnemySystem.Removal.LEFT)
+ return
+ _follow(es, i, escape_field, 1.0)
+ _check_barrier(es, i, escape_field)
+
+
+func _at_exit(es: EnemySystem, i: int) -> bool:
+ return escape_field[nav.cell_of(es.pos_x[i], es.pos_z[i])] == 0
+
+
+func _follow(es: EnemySystem, i: int, field: PackedInt32Array, p_pace: float) -> void:
+ if nav.flow_direction(field, es.pos_x[i], es.pos_z[i], _dir):
+ es.desire_x[i] = _dir[0]
+ es.desire_z[i] = _dir[1]
+ es.pace[i] = p_pace
+ else:
+ es.pace[i] = 0.0
+
+
+func _still(es: EnemySystem, i: int, facing: Vector2) -> void:
+ es.desire_x[i] = facing.x
+ es.desire_z[i] = facing.y
+ es.pace[i] = 0.0
diff --git a/game/scripts/thief_behavior.gd.uid b/game/scripts/thief_behavior.gd.uid
new file mode 100644
index 0000000..0981329
--- /dev/null
+++ b/game/scripts/thief_behavior.gd.uid
@@ -0,0 +1 @@
+uid://dhphyt0jmbwrq
diff --git a/game/scripts/toast_feed.gd b/game/scripts/toast_feed.gd
new file mode 100644
index 0000000..797d9ac
--- /dev/null
+++ b/game/scripts/toast_feed.gd
@@ -0,0 +1,95 @@
+class_name ToastFeed
+extends VBoxContainer
+## Short event messages stacked under the zone banner, each fading after a few seconds. A fixed
+## pool of labels is reused (the oldest message gives way). A message that's already showing
+## isn't repeated: it counts up instead ("A crow flew in from the east ×4") and stays longer,
+## so a flock arriving is one line.
+
+const LIFE := 3.2
+const FADE := 0.6
+const SLOTS := 5
+## Loot events per category (LootSystem.Category): the text ("%s" is the item's noun) and color.
+const MESSAGES := {
+ &"stolen": [["A crop was snatched!", "A %s was grabbed!", "Thieves took %s from the shed!"], Color(1.0, 0.6, 0.15)],
+ &"dropped": [["The thief dropped the crop. Grab it!", "The thief dropped the %s. Catch it before it runs off!",
+ "The thief dropped %s. Grab it!"], Color(1.0, 0.9, 0.3)],
+ &"recovered": [["Crop recovered", "The %s is back in the pen", "%s back in the shed"], Color(0.5, 1.0, 0.45)],
+ &"returned": [["A dropped crop went back to its plot", "The %s went back to the pen", "%s went back to the shed"],
+ Color(0.85, 0.95, 1.0)],
+ &"lost": [["A crop was carried off the farm", "A %s was lost", "%s was carried off the farm"], Color(1.0, 0.3, 0.25)],
+ &"following": [["", "The %s follows you: lead it back to the pen", ""], Color(0.85, 1.0, 0.7)],
+ &"follow_full": [["", "You can only lead %d animals at a time", ""], Color(1.0, 0.8, 0.5)],
+ &"strayed": [["", "A %s wandered out of the open pen!", ""], Color(1.0, 0.6, 0.15)],
+}
+
+## Set by FarmSim: what an event's item is.
+var loot: LootSystem
+
+var _labels: Array[Label] = []
+var _left := PackedFloat32Array()
+var _base: Array[String] = [] # each slot's message without its count
+var _count := PackedInt32Array()
+
+
+func _ready() -> void:
+ set_anchors_preset(Control.PRESET_TOP_WIDE)
+ offset_top = 152.0
+ mouse_filter = Control.MOUSE_FILTER_IGNORE
+ alignment = BoxContainer.ALIGNMENT_BEGIN
+ _left.resize(SLOTS)
+ _count.resize(SLOTS)
+ _base.resize(SLOTS)
+ for i in SLOTS:
+ var l := Label.new()
+ l.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
+ l.add_theme_font_size_override("font_size", 26)
+ l.add_theme_color_override("font_outline_color", Color.BLACK)
+ l.add_theme_constant_override("outline_size", 7)
+ l.visible = false
+ add_child(l)
+ _labels.append(l)
+
+
+func push(text: String, color: Color) -> void:
+ for i in SLOTS:
+ if _left[i] > FADE and _base[i] == text:
+ _count[i] += 1
+ _labels[i].text = "%s ×%d" % [text, _count[i]]
+ _left[i] = LIFE
+ return
+ var slot := 0
+ for i in SLOTS:
+ if _left[i] < _left[slot]:
+ slot = i
+ var l := _labels[slot]
+ _base[slot] = text
+ _count[slot] = 1
+ l.text = text
+ l.add_theme_color_override("font_color", color)
+ l.visible = true
+ _left[slot] = LIFE
+ move_child(l, get_child_count() - 1) # newest at the bottom
+
+
+func on_loot_event(kind: StringName, id: int, _position: Vector3) -> void:
+ if not MESSAGES.has(kind):
+ return
+ var m: Array = MESSAGES[kind]
+ var c := int(loot.category[id]) if loot != null else LootSystem.Category.CROP
+ var text: String = m[0][c]
+ if text == "":
+ return
+ if text.contains("%d"):
+ text = text % loot.config.max_following_animals
+ elif text.contains("%s"):
+ text = text % (loot.noun(id) if loot != null else "item")
+ push(text[0].to_upper() + text.substr(1), m[1])
+
+
+func _process(delta: float) -> void:
+ for i in SLOTS:
+ if _left[i] <= 0.0:
+ continue
+ _left[i] = maxf(_left[i] - delta, 0.0)
+ _labels[i].visible = _left[i] > 0.0
+ _labels[i].modulate.a = clampf(_left[i] / FADE, 0.0, 1.0)
diff --git a/game/scripts/toast_feed.gd.uid b/game/scripts/toast_feed.gd.uid
new file mode 100644
index 0000000..8a50a6b
--- /dev/null
+++ b/game/scripts/toast_feed.gd.uid
@@ -0,0 +1 @@
+uid://f647f4bijmdy
diff --git a/game/scripts/tutorial.gd b/game/scripts/tutorial.gd
new file mode 100644
index 0000000..6779a38
--- /dev/null
+++ b/game/scripts/tutorial.gd
@@ -0,0 +1,197 @@
+class_name Tutorial
+extends Control
+## Short contextual tips on the first day and night (night 1), one at a time in a box above the
+## hotbar. Each shows when it's useful and goes away once it's done:
+## Day: move -> gather -> store at the shed -> build (also once half the day has gone)
+## Dusk: where and when the thieves come
+## Night: fight (once enemies are in), fear (when crowded), recover (when something is
+## dropped), patch up (when hurt)
+## The most urgent one wins (recover, fear, patch, shoot, dusk, then the day's in order).
+## [Backspace / Back] hides them until the game is restarted; Settings turns them off.
+## Finished tips stay finished for the session, so a retry or a second vacation doesn't repeat
+## them.
+
+const TEXT := {
+ "move": "Move with [W A S D] or the left stick. You're the scarecrow: keep the farm safe until the farmers are back.",
+ "gather": "Hold [E / X] at a dead tree, the haystacks, or the scrap heap to gather wood, straw, and scrap.",
+ "store": "Your pouch only holds so much: walk onto the barn's apron (the Supply Shed) to store what you carry.",
+ "build": "Press [B / d-pad up] to build. Pick a fence [1], place it with left mouse / RT. Thieves have to break through fences.",
+ "dusk": "Dusk: thieves come at nightfall, from every side of the farm.",
+ "shoot": "Aim with the mouse or the right stick and hold left mouse / RT to stab with your pitchfork. The workbench sells a corn shooter and pumpkin bombs: switch with [Tab / 1-3].",
+ "fear": "Crowded? [Q / LB] Fear scares off everything nearby, and they drop what they carry.",
+ "recover": "Something was dropped! Walk over it to bring it home. A dropped animal follows you back to the pen.",
+ "patch": "Hurt? Hold [F / Y] to patch up with straw. Health carries over to the next night.",
+}
+const PRIORITY: Array[String] = ["recover", "fear", "patch", "shoot", "dusk", "move", "gather", "store", "build"]
+const DONE_TIME := 0.9
+const CROWD_RADIUS := 7.0
+
+var sim: FarmSim
+## Off when the player turned tips off in Settings.
+var enabled := true
+## The player hid them (for this session).
+var dismissed := false
+var done := {}
+var current := ""
+
+var _box: PanelContainer
+var _text: Label
+var _hint: Label
+var _start := Vector3.ZERO
+var _shots_at_night: int = 0
+var _done_left: float = 0.0
+
+
+func setup(p_sim: FarmSim) -> void:
+ sim = p_sim
+ sim.campaign.phase_changed.connect(_on_phase)
+ sim.interactions.deposited.connect(func(_moved: Dictionary) -> void: _finish("store"))
+ sim.scarecrow.fear_used.connect(func(_p: Vector3, _n: int) -> void: _finish("fear"))
+ sim.scarecrow.patched.connect(func(_hp: int) -> void: _finish("patch"))
+ sim.loot.loot_event.connect(func(kind: StringName, _id: int, _at: Vector3) -> void:
+ if kind == &"recovered" or kind == &"following":
+ _finish("recover"))
+ sim.campaign.campaign_ended.connect(func(_o: CampaignController.Outcome) -> void: _show(""))
+ _start = sim.player.global_position
+
+
+func _ready() -> void:
+ set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
+ mouse_filter = Control.MOUSE_FILTER_IGNORE
+ _box = PanelContainer.new()
+ var bg := StyleBoxFlat.new()
+ bg.bg_color = Color(0.08, 0.1, 0.08, 0.86)
+ bg.border_color = Color(0.95, 0.82, 0.45)
+ bg.set_border_width_all(2)
+ bg.set_corner_radius_all(6)
+ bg.content_margin_left = 18.0
+ bg.content_margin_right = 18.0
+ bg.content_margin_top = 10.0
+ bg.content_margin_bottom = 10.0
+ _box.add_theme_stylebox_override("panel", bg)
+ _box.mouse_filter = Control.MOUSE_FILTER_IGNORE
+ add_child(_box)
+ var col := VBoxContainer.new()
+ _box.add_child(col)
+ _text = Label.new()
+ _text.custom_minimum_size = Vector2(760.0, 0.0)
+ _text.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
+ _text.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
+ _text.add_theme_font_size_override("font_size", 24)
+ col.add_child(_text)
+ _hint = Label.new()
+ _hint.text = "Tip · [Backspace / Back] hide tips"
+ _hint.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
+ _hint.add_theme_font_size_override("font_size", 16)
+ _hint.add_theme_color_override("font_color", Color(0.7, 0.72, 0.65))
+ col.add_child(_hint)
+ _box.visible = false
+
+
+func _process(delta: float) -> void:
+ if sim == null:
+ return
+ var s := sim.campaign.state
+ if not enabled or dismissed or s.night != 1 or sim.campaign.is_over() \
+ or (sim.upgrade_panel != null and sim.upgrade_panel.is_open):
+ _show("")
+ return
+ _check_done()
+ if _done_left > 0.0:
+ _done_left -= delta
+ return
+ var want := ""
+ for id in PRIORITY:
+ if not done.has(id) and _wanted(id):
+ want = id
+ break
+ _show(want)
+
+
+## Whether the tip is useful right now.
+func _wanted(id: String) -> bool:
+ var c := sim.campaign
+ var phase := c.state.phase
+ var day := phase == CampaignController.Phase.DAY or phase == CampaignController.Phase.DUSK
+ var night := phase == CampaignController.Phase.NIGHT or phase == CampaignController.Phase.DAWN
+ match id:
+ "move":
+ return phase == CampaignController.Phase.DAY
+ "gather":
+ return day and done.has("move")
+ "store":
+ return day and c.state.resources.pouch_total() > 0
+ "build":
+ return day and (done.has("store") or c.state.phase_time_left < c.phase_length(CampaignController.Phase.DAY) * 0.5
+ or phase == CampaignController.Phase.DUSK)
+ "dusk":
+ return phase == CampaignController.Phase.DUSK
+ "shoot":
+ return night and sim.enemies.alive_count() > 0
+ "fear":
+ return night and sim.scarecrow.fear_left == 0.0 and _enemies_near() >= 2
+ "recover":
+ return sim.loot.count(LootSystem.Status.DROPPED) > 0
+ "patch":
+ return night and sim.scarecrow.hp() < sim.scarecrow.max_hp()
+ return false
+
+
+func _check_done() -> void:
+ var s := sim.campaign.state
+ if not done.has("move") and Vector2(sim.player.global_position.x - _start.x, sim.player.global_position.z - _start.z).length() > 4.0:
+ _finish("move")
+ var e := s.night_events
+ if not done.has("gather") and int(e.get("gathered_wood", 0)) + int(e.get("gathered_scrap", 0)) + int(e.get("gathered_straw", 0)) > 0:
+ _finish("gather")
+ if not done.has("build") and int(e.get("structures_built", 0)) > 0:
+ _finish("build")
+ if not done.has("shoot") and sim.combat.attacks() - _shots_at_night >= 4 and s.phase == CampaignController.Phase.NIGHT:
+ _finish("shoot")
+
+
+func _finish(id: String) -> void:
+ if done.has(id):
+ return
+ done[id] = true
+ if id == current and _box.visible:
+ _text.text = "Done! " + _text.text
+ _text.add_theme_color_override("font_color", Color(0.6, 1.0, 0.55))
+ _done_left = DONE_TIME
+
+
+func _show(id: String) -> void:
+ current = id
+ _box.visible = id != ""
+ if id == "":
+ return
+ _text.text = TEXT[id]
+ _text.remove_theme_color_override("font_color")
+ _box.reset_size()
+ _box.position = Vector2((size.x - _box.size.x) * 0.5, size.y - 250.0 - _box.size.y)
+
+
+func _enemies_near() -> int:
+ var p := Vector2(sim.player.global_position.x, sim.player.global_position.z)
+ var es := sim.enemies
+ var n := 0
+ for d in es.active_count:
+ if es.alive[d] == 1 and Vector2(es.pos_x[d], es.pos_z[d]).distance_to(p) <= CROWD_RADIUS:
+ n += 1
+ return n
+
+
+func _on_phase(phase: CampaignController.Phase, _previous: CampaignController.Phase) -> void:
+ match phase:
+ CampaignController.Phase.DAY:
+ _start = sim.player.global_position
+ CampaignController.Phase.NIGHT:
+ _finish("dusk")
+ _shots_at_night = sim.combat.attacks()
+
+
+func _unhandled_input(event: InputEvent) -> void:
+ if _box.visible and event.is_action_pressed("hide_tips"):
+ dismissed = true
+ _show("")
+ get_viewport().set_input_as_handled()
diff --git a/game/scripts/tutorial.gd.uid b/game/scripts/tutorial.gd.uid
new file mode 100644
index 0000000..4ef05fd
--- /dev/null
+++ b/game/scripts/tutorial.gd.uid
@@ -0,0 +1 @@
+uid://dtomrngv6su1c
diff --git a/game/scripts/ui_theme.gd b/game/scripts/ui_theme.gd
new file mode 100644
index 0000000..bc6501a
--- /dev/null
+++ b/game/scripts/ui_theme.gd
@@ -0,0 +1,113 @@
+class_name UiTheme
+extends RefCounted
+## The game's UI theme (the project's default theme, gui/theme/custom =
+## res://game/resources/ui_theme.tres, written by game/tools/build_ui_theme.gd from build()):
+## dark straw-trimmed panels, buttons that light up gold on hover and show a thick gold ring
+## when focused (keyboard and gamepad players always see where they are), sliders, check
+## boxes, and tabs to match. Labels keep the default look; the HUD sets its own sizes.
+
+const TEXT := Color(0.95, 0.93, 0.85)
+const GOLD := Color(0.95, 0.82, 0.45)
+const DIM := Color(0.5, 0.5, 0.45)
+
+
+static func build() -> Theme:
+ var t := Theme.new()
+ t.default_font_size = 22
+ t.set_stylebox("panel", "PanelContainer", ReviewPanel.backing())
+ t.set_stylebox("panel", "Panel", ReviewPanel.backing())
+ for type in ["Button", "OptionButton"]:
+ t.set_stylebox("normal", type, _box(Color(0.2, 0.24, 0.18), Color(0.45, 0.42, 0.3), 2))
+ t.set_stylebox("hover", type, _box(Color(0.3, 0.35, 0.24), GOLD, 2))
+ t.set_stylebox("pressed", type, _box(Color(0.15, 0.19, 0.13), GOLD, 2))
+ t.set_stylebox("disabled", type, _box(Color(0.14, 0.15, 0.13), Color(0.28, 0.28, 0.25), 2))
+ var focus := _box(Color(0, 0, 0, 0), GOLD, 4)
+ focus.draw_center = false
+ focus.set_expand_margin_all(3.0)
+ t.set_stylebox("focus", type, focus)
+ t.set_color("font_color", type, TEXT)
+ t.set_color("font_hover_color", type, Color(1.0, 0.95, 0.7))
+ t.set_color("font_focus_color", type, Color(1.0, 0.95, 0.7))
+ t.set_color("font_pressed_color", type, GOLD)
+ t.set_color("font_disabled_color", type, DIM)
+ for type in ["CheckBox", "CheckButton"]:
+ var none := StyleBoxEmpty.new()
+ t.set_stylebox("normal", type, none)
+ t.set_stylebox("pressed", type, none)
+ t.set_stylebox("hover", type, _box(Color(1, 1, 1, 0.05), Color(0, 0, 0, 0), 0))
+ t.set_stylebox("hover_pressed", type, _box(Color(1, 1, 1, 0.05), Color(0, 0, 0, 0), 0))
+ var focus := _box(Color(0, 0, 0, 0), GOLD, 3)
+ focus.draw_center = false
+ t.set_stylebox("focus", type, focus)
+ t.set_color("font_color", type, TEXT)
+ t.set_color("font_hover_color", type, Color(1.0, 0.95, 0.7))
+ t.set_color("font_focus_color", type, Color(1.0, 0.95, 0.7))
+ t.set_color("font_pressed_color", type, TEXT)
+ t.set_icon("checked", type, check_icon(true, false))
+ t.set_icon("unchecked", type, check_icon(false, false))
+ t.set_icon("checked_disabled", type, check_icon(true, true))
+ t.set_icon("unchecked_disabled", type, check_icon(false, true))
+ t.set_constant("h_separation", type, 12)
+ var track := _box(Color(0.22, 0.24, 0.2), Color(0, 0, 0, 0), 0)
+ track.content_margin_top = 4.0
+ track.content_margin_bottom = 4.0
+ t.set_stylebox("slider", "HSlider", track)
+ var filled := _box(Color(0.55, 0.78, 0.4), Color(0, 0, 0, 0), 0)
+ t.set_stylebox("grabber_area", "HSlider", filled)
+ t.set_stylebox("grabber_area_highlight", "HSlider", _box(Color(0.7, 0.9, 0.5), Color(0, 0, 0, 0), 0))
+ var slider_focus := _box(Color(0, 0, 0, 0), GOLD, 3)
+ slider_focus.draw_center = false
+ slider_focus.set_expand_margin_all(4.0)
+ t.set_stylebox("focus", "HSlider", slider_focus)
+ t.set_stylebox("tab_selected", "TabContainer", _box(Color(0.3, 0.35, 0.24), GOLD, 2))
+ t.set_stylebox("tab_unselected", "TabContainer", _box(Color(0.16, 0.19, 0.14), Color(0.35, 0.33, 0.25), 2))
+ t.set_stylebox("tab_hovered", "TabContainer", _box(Color(0.24, 0.28, 0.2), GOLD, 2))
+ var tab_focus := _box(Color(0, 0, 0, 0), GOLD, 3)
+ tab_focus.draw_center = false
+ t.set_stylebox("tab_focus", "TabContainer", tab_focus)
+ t.set_stylebox("panel", "TabContainer", _box(Color(0.12, 0.14, 0.11), Color(0.35, 0.33, 0.25), 2))
+ t.set_color("font_selected_color", "TabContainer", GOLD)
+ t.set_color("font_unselected_color", "TabContainer", TEXT)
+ t.set_color("font_hovered_color", "TabContainer", Color(1.0, 0.95, 0.7))
+ return t
+
+
+## A 30 px check box: a dark rounded square with a light border, filled gold with a dark tick
+## when checked.
+static func check_icon(checked: bool, disabled: bool) -> ImageTexture:
+ const N := 30
+ var img := Image.create(N, N, false, Image.FORMAT_RGBA8)
+ var border := Color(0.78, 0.74, 0.6) if not disabled else Color(0.4, 0.4, 0.36)
+ var fill := (GOLD if not disabled else Color(0.45, 0.42, 0.32)) if checked else Color(0.14, 0.16, 0.12)
+ var tick := Color(0.12, 0.1, 0.05)
+ for y in N:
+ for x in N:
+ var p := Vector2(x + 0.5, y + 0.5)
+ var q := (p - Vector2(N, N) * 0.5).abs() - Vector2(N * 0.5 - 5.0, N * 0.5 - 5.0)
+ var d := Vector2(maxf(q.x, 0.0), maxf(q.y, 0.0)).length() + minf(maxf(q.x, q.y), 0.0) - 4.0 # rounded square
+ var c := Color(0, 0, 0, 0)
+ if d <= 0.0:
+ c = fill if d < -2.0 else border
+ if checked and d < -2.0 and minf(_segment(p, Vector2(8, 15.5), Vector2(13, 21)), _segment(p, Vector2(13, 21), Vector2(22.5, 9))) < 2.0:
+ c = tick
+ img.set_pixel(x, y, c)
+ return ImageTexture.create_from_image(img)
+
+
+static func _segment(p: Vector2, a: Vector2, b: Vector2) -> float:
+ var ab := b - a
+ var t := clampf((p - a).dot(ab) / ab.length_squared(), 0.0, 1.0)
+ return p.distance_to(a + ab * t)
+
+
+static func _box(bg: Color, border: Color, width: int) -> StyleBoxFlat:
+ var s := StyleBoxFlat.new()
+ s.bg_color = bg
+ s.border_color = border
+ s.set_border_width_all(width)
+ s.set_corner_radius_all(6)
+ s.content_margin_left = 16.0
+ s.content_margin_right = 16.0
+ s.content_margin_top = 8.0
+ s.content_margin_bottom = 8.0
+ return s
diff --git a/game/scripts/ui_theme.gd.uid b/game/scripts/ui_theme.gd.uid
new file mode 100644
index 0000000..d229b5f
--- /dev/null
+++ b/game/scripts/ui_theme.gd.uid
@@ -0,0 +1 @@
+uid://dt30wm6hvbknn
diff --git a/game/scripts/upgrade_panel.gd b/game/scripts/upgrade_panel.gd
new file mode 100644
index 0000000..6c597a4
--- /dev/null
+++ b/game/scripts/upgrade_panel.gd
@@ -0,0 +1,140 @@
+class_name UpgradePanel
+extends CenterContainer
+## The workbench's upgrade menu (Upgrades): one row per upgrade, by track, with what it does and
+## what it costs. A done one says so; one you can't afford says what's missing. It opens with
+## interact at the workbench by day (Interactions). Buy with a click, or the arrows / d-pad and
+## Enter / A. Close it with Close, Escape / B, interact again, by walking off, or at nightfall.
+## The scarecrow stands still and can't shoot while it's open.
+
+signal message(text: String, color: Color)
+signal bought(id: String)
+
+var campaign: CampaignController
+var structures: StructureSystem
+var player: PlayerCharacter
+var is_open := false
+## Co-op partner: ask the host to buy (upgrade id); the result comes back as a message.
+var buy_request: Callable
+
+var _rows := {} # upgrade id -> Button
+var _title: Label
+var _close: Button
+
+
+func setup(p_campaign: CampaignController, p_structures: StructureSystem, p_player: PlayerCharacter) -> void:
+ campaign = p_campaign
+ structures = p_structures
+ player = p_player
+ var box := get_node("Panel/Margin/Box") as VBoxContainer
+ var track := ""
+ for id in Upgrades.ORDER:
+ var u: Dictionary = campaign.config.upgrades.get(id, {})
+ if u.is_empty():
+ continue
+ if String(u.get("track", "")) != track:
+ track = String(u.get("track", ""))
+ var head := Label.new()
+ head.text = track
+ head.add_theme_font_size_override("font_size", 20)
+ head.add_theme_color_override("font_color", Color(0.75, 0.85, 0.75))
+ box.add_child(head)
+ var b := Button.new()
+ b.alignment = HORIZONTAL_ALIGNMENT_LEFT
+ b.custom_minimum_size = Vector2(720.0, 44.0)
+ b.add_theme_font_size_override("font_size", 20)
+ b.pressed.connect(func() -> void: _buy(id))
+ box.add_child(b)
+ _rows[id] = b
+ _close = Button.new()
+ _close.text = "Close"
+ _close.custom_minimum_size = Vector2(200.0, 48.0)
+ _close.add_theme_font_size_override("font_size", 22)
+ _close.size_flags_horizontal = Control.SIZE_SHRINK_CENTER
+ _close.pressed.connect(close)
+ box.add_child(_close)
+
+
+func _ready() -> void:
+ set_anchors_preset(Control.PRESET_FULL_RECT)
+ var panel := PanelContainer.new()
+ panel.name = "Panel"
+ panel.add_theme_stylebox_override("panel", ReviewPanel.backing())
+ add_child(panel)
+ var margin := MarginContainer.new()
+ margin.name = "Margin"
+ for side in ["left", "right", "top", "bottom"]:
+ margin.add_theme_constant_override("margin_" + side, 24)
+ panel.add_child(margin)
+ var box := VBoxContainer.new()
+ box.name = "Box"
+ box.add_theme_constant_override("separation", 6)
+ margin.add_child(box)
+ _title = Label.new()
+ _title.add_theme_font_size_override("font_size", 32)
+ box.add_child(_title)
+ visible = false
+ mouse_filter = Control.MOUSE_FILTER_IGNORE
+
+
+func open() -> void:
+ if is_open:
+ return
+ is_open = true
+ visible = true
+ mouse_filter = Control.MOUSE_FILTER_STOP
+ player.start_channel(&"Idle_A")
+ refresh()
+ var first: Button = _close
+ for id in Upgrades.ORDER:
+ if _rows.has(id) and not (_rows[id] as Button).disabled:
+ first = _rows[id]
+ break
+ first.grab_focus.call_deferred()
+
+
+func close() -> void:
+ if not is_open:
+ return
+ is_open = false
+ visible = false
+ mouse_filter = Control.MOUSE_FILTER_IGNORE
+ player.stop_channel()
+
+
+## Rewrites every row for what's owned and affordable now.
+func refresh() -> void:
+ var cfg := campaign.config
+ var s := campaign.state
+ var done := 0
+ for id: String in _rows:
+ var u: Dictionary = cfg.upgrades[id]
+ var b := _rows[id] as Button
+ var why := Upgrades.blocker(campaign, id)
+ if Upgrades.owned(s, id):
+ done += 1
+ var price := "Done" if Upgrades.owned(s, id) else ResourceStore.describe(Upgrades.cost(cfg, id))
+ b.text = "%s — %s (%s)" % [u["name"], u["text"], price]
+ if why != "" and why != "Done":
+ b.text += " %s" % why
+ b.disabled = why != ""
+ _title.text = "Upgrades at the work area (%d of %d done)" % [done, _rows.size()]
+
+
+func _buy(id: String) -> void:
+ if buy_request.is_valid():
+ buy_request.call(id)
+ return
+ var was := Upgrades.owned(campaign.state, id)
+ var text := Upgrades.buy(campaign, id, structures)
+ if not was and Upgrades.owned(campaign.state, id):
+ bought.emit(id)
+ message.emit(text, Color(0.85, 0.75, 1.0) if text.contains("done:") else Color(1.0, 0.8, 0.5))
+ refresh()
+ if (_rows[id] as Button).has_focus() and (_rows[id] as Button).disabled:
+ _close.grab_focus()
+
+
+func _unhandled_input(event: InputEvent) -> void:
+ if is_open and event.is_action_pressed("ui_cancel"):
+ close()
+ get_viewport().set_input_as_handled()
diff --git a/game/scripts/upgrade_panel.gd.uid b/game/scripts/upgrade_panel.gd.uid
new file mode 100644
index 0000000..e34b4ab
--- /dev/null
+++ b/game/scripts/upgrade_panel.gd.uid
@@ -0,0 +1 @@
+uid://cq4ipv3nc7ual
diff --git a/game/scripts/upgrades.gd b/game/scripts/upgrades.gd
new file mode 100644
index 0000000..bbbc574
--- /dev/null
+++ b/game/scripts/upgrades.gd
@@ -0,0 +1,84 @@
+class_name Upgrades
+extends RefCounted
+## The work area's upgrades (definitions in GameConfig.upgrades, costs in GameConfig.costs):
+## bought once each, by day, at the workbench's menu (UpgradePanel), and kept in
+## FarmState.upgrades (id -> 1), so they carry over between nights and come back with a retry.
+## Systems ask value() for a stat with the owned upgrades applied instead of reading GameConfig
+## directly: the corn shooter's fire rate and shot damage, fear's radius and cooldown, fences' and gates'
+## health (barrier_hp), the automated defense's range, and the traps' slow time. Straw stuffing
+## raises the scarecrow's max health (FarmState) when bought. Sprint, the corn shooter, and
+## pumpkin bombs change no stat: owning them unlocks sprinting (PlayerCharacter) and the two
+## weapons (ScarecrowCombat). Rapid fire and heavy seeds need the corn shooter first ("requires").
+
+## Menu order, grouped by track.
+const ORDER: Array[String] = ["corn_shooter", "rapid_fire", "heavy_seeds", "pumpkin_bomb", "wide_fear", "quick_fear",
+ "straw_stuffing", "sprint", "reinforced_fences", "long_range", "sticky_tar"]
+
+
+static func owned(state: FarmState, id: String) -> bool:
+ return int(state.upgrades.get(id, 0)) > 0
+
+
+static func cost(cfg: GameConfig, id: String) -> Dictionary:
+ return cfg.costs.get(id, {})
+
+
+## A stat with every owned upgrade applied (barrier_hp is a multiplier, 1 without upgrades).
+static func value(cfg: GameConfig, state: FarmState, stat: String) -> float:
+ var v := 1.0 if stat == "barrier_hp" else float(cfg.get(stat))
+ if state == null:
+ return v
+ for id: String in cfg.upgrades:
+ var u: Dictionary = cfg.upgrades[id]
+ if String(u.get("stat", "")) != stat or not owned(state, id):
+ continue
+ if u.has("mult"):
+ v *= float(u["mult"])
+ if u.has("add"):
+ v += float(u["add"])
+ return v
+
+
+## Why an upgrade can't be bought right now ("" if it can).
+static func blocker(campaign: CampaignController, id: String) -> String:
+ var cfg := campaign.config
+ var s := campaign.state
+ if not cfg.upgrades.has(id):
+ return "No such upgrade"
+ if owned(s, id):
+ return "Done"
+ var needs := String(cfg.upgrades[id].get("requires", ""))
+ if needs != "" and not owned(s, needs):
+ return "Needs the %s first" % String(cfg.upgrades.get(needs, {}).get("name", needs)).to_lower()
+ if not campaign.is_daytime():
+ return "The work area is for daytime"
+ if not s.resources.can_afford(cost(cfg, id)):
+ return "Need %s more" % ResourceStore.describe(s.resources.missing(cost(cfg, id)))
+ return ""
+
+
+## Buys an upgrade if it can be bought. Returns the message for the player.
+static func buy(campaign: CampaignController, id: String, structures: StructureSystem = null) -> String:
+ var cfg := campaign.config
+ var s := campaign.state
+ var u: Dictionary = cfg.upgrades.get(id, {})
+ var why := blocker(campaign, id)
+ if why != "":
+ return "%s: %s" % [u.get("name", id), why.to_lower() if why != "Done" else "already done"]
+ var barrier_before := value(cfg, s, "barrier_hp")
+ s.pay(cost(cfg, id))
+ s.upgrades[id] = 1
+ s.record_event("upgrades_bought")
+ match String(u.get("stat", "")):
+ "scarecrow_max_hp": # both scarecrows'
+ s.scarecrow_max_hp += int(u.get("add", 0))
+ s.scarecrow_hp += int(u.get("add", 0))
+ s.partner_max_hp += int(u.get("add", 0))
+ s.partner_hp += int(u.get("add", 0))
+ "barrier_hp":
+ # Standing fences and gates keep their share of health.
+ var k := value(cfg, s, "barrier_hp") / barrier_before
+ for e in s.structures:
+ if e["type"] == "fence" or e["type"] == "gate":
+ e["hp"] = mini(roundi(int(e["hp"]) * k), structures.max_hp(e["type"]) if structures != null else 1 << 20)
+ return "%s done: %s" % [u.get("name", id), String(u.get("text", "")).to_lower()]
diff --git a/game/scripts/upgrades.gd.uid b/game/scripts/upgrades.gd.uid
new file mode 100644
index 0000000..2300674
--- /dev/null
+++ b/game/scripts/upgrades.gd.uid
@@ -0,0 +1 @@
+uid://buhpd5insq271
diff --git a/game/scripts/wave_director.gd b/game/scripts/wave_director.gd
new file mode 100644
index 0000000..d86e0c6
--- /dev/null
+++ b/game/scripts/wave_director.gd
@@ -0,0 +1,205 @@
+class_name WaveDirector
+extends Node3D
+## Night arrivals. By default it runs the night's NightPlan: each group's enemies (thieves, crows,
+## or fence breakers) arrive at their times after nightfall, each at its own random point along
+## the farm's edge (FarmZones.edge): on foot GameConfig.spawn_margin outside the map, at a free
+## cell with a route onto the farm (ground_spawns); flyers flyer_spawn_margin out. They go for the
+## group's target (crops, animals, supplies, or any of their type's targets by
+## GameConfig.target_weights); nothing arrives by day or after sunrise. From dusk until
+## WARN_AFTER_NIGHTFALL into the night the phase HUD says what tonight brings (not where: they come
+## from every side; nothing is marked on the farm itself). debug_plan (F2 in debug builds)
+## replaces tonight's plan. Trickle mode (GameConfig.night_thieves > 0, for tests and soaks)
+## ignores the plan and keeps that many enemies of GameConfig.trickle_type on the farm at night,
+## the next arriving thief_spawn_interval after one leaves. enabled = false stops all arrivals.
+## rng picks the points: seed it for a repeatable night.
+
+signal arrived(handle: int, at: Vector2)
+
+const WARN_AFTER_NIGHTFALL := 12.0
+const FIRST_TRICKLE_DELAY := 3.0
+## spawn()'s default spot: a random point along the edge.
+const ANYWHERE := Vector2(INF, INF)
+## NightPlan group target -> LootSystem.Category (or ANY).
+const TARGETS := {
+ "crops": LootSystem.Category.CROP,
+ "animals": LootSystem.Category.ANIMAL,
+ "supplies": LootSystem.Category.SUPPLY,
+ "any": LootSystem.ANY,
+}
+const TARGET_NAMES := {
+ LootSystem.Category.CROP: "crop",
+ LootSystem.Category.ANIMAL: "animal",
+ LootSystem.Category.SUPPLY: "supply",
+}
+
+var enabled := true
+var plans: Array[NightPlan] = []
+## Replaces tonight's plan when set (debug scenarios).
+var debug_plan: NightPlan
+var config: GameConfig
+var campaign: CampaignController
+var enemies: EnemySystem
+var zones: FarmZones
+## Set by FarmSim: where ground enemies can arrive (cell centers along the edge with a route in).
+var ground_spawns := PackedVector2Array()
+var rng := RandomNumberGenerator.new()
+## Seconds since nightfall, and arrivals so far tonight.
+var night_time: float = 0.0
+var spawned: int = 0
+
+var _queue: Array = [] # [time, want, type], sorted
+var _next: int = 0
+var _trickle_wait: float = FIRST_TRICKLE_DELAY
+
+
+func setup(p_campaign: CampaignController, p_enemies: EnemySystem, p_zones: FarmZones, p_plans: Array[NightPlan]) -> void:
+ campaign = p_campaign
+ config = p_campaign.config
+ enemies = p_enemies
+ zones = p_zones
+ plans = p_plans
+ rng.randomize()
+ campaign.phase_changed.connect(_on_phase_changed)
+
+
+func plan_for(night: int) -> NightPlan:
+ if plans.is_empty():
+ return null
+ return plans[clampi(night - 1, 0, plans.size() - 1)]
+
+
+func tonight() -> NightPlan:
+ return debug_plan if debug_plan != null else plan_for(campaign.state.night)
+
+
+## A night's length from its plan (0 or less: GameConfig.night_length). The debug plan counts
+## for tonight.
+func night_length(night: int) -> float:
+ var plan := debug_plan if debug_plan != null and night == campaign.state.night else plan_for(night)
+ return plan.night_length if plan != null else 0.0
+
+
+func trickle() -> bool:
+ return config.night_thieves > 0
+
+
+static func want_of(group: Dictionary) -> int:
+ return int(TARGETS.get(String(group.get("target", "any")), LootSystem.ANY))
+
+
+## A NightPlan group's enemy type ("thief", "crow", "breaker") as an EnemySystem type id.
+static func type_of(group: Dictionary) -> int:
+ return maxi(EnemySystem.TYPE_NAMES.find(String(group.get("type", "thief"))), 0)
+
+
+## What tonight brings: its groups' [type, want] pairs (in the plan's order, no repeats).
+func tonight_entries() -> Array:
+ var out := []
+ var plan := tonight()
+ if plan == null or trickle():
+ return out
+ for g in plan.groups:
+ var entry := [type_of(g), want_of(g)]
+ if not out.has(entry):
+ out.append(entry)
+ return out
+
+
+## What a [type, want] pair is called: "Crows", "Fence breakers", "Animal thieves", "Supply
+## thieves", or "Thieves" (any target).
+static func entry_label(entry: Array) -> String:
+ match int(entry[0]):
+ EnemySystem.TYPE_CROW:
+ return "Crows"
+ EnemySystem.TYPE_BREAKER:
+ return "Fence breakers"
+ if TARGET_NAMES.has(entry[1]):
+ return "%s thieves" % String(TARGET_NAMES[entry[1]]).capitalize()
+ return "Thieves"
+
+
+## Tonight's warning as lines for the HUD: "Tonight, from every side: crows, supply thieves and
+## fence breakers".
+func tonight_warning() -> PackedStringArray:
+ var labels := PackedStringArray()
+ for e in tonight_entries():
+ var label := entry_label(e).to_lower()
+ if not labels.has(label):
+ labels.append(label)
+ if labels.is_empty():
+ return PackedStringArray()
+ return PackedStringArray(["Tonight, from every side: %s" % PhaseHud.join_words(labels)])
+
+
+func warning_active() -> bool:
+ if not enabled or trickle():
+ return false
+ var phase := campaign.state.phase
+ return phase == CampaignController.Phase.DUSK or (phase == CampaignController.Phase.NIGHT and night_time < WARN_AFTER_NIGHTFALL)
+
+
+## A random point along the farm's edge for an enemy of type: a flyer anywhere on its ring, a
+## ground enemy at one of ground_spawns.
+func spawn_point(type: int) -> Vector2:
+ if enemies.t_flying[type] == 1 or ground_spawns.is_empty():
+ var margin := config.flyer_spawn_margin if enemies.t_flying[type] == 1 else config.spawn_margin
+ return zones.edge_point(rng.randf(), margin)
+ return ground_spawns[rng.randi_range(0, ground_spawns.size() - 1)]
+
+
+## Sends one enemy of type in, going for want: at a random point along the edge, or at the given
+## point. Returns its handle (-1 if the pool is full).
+func spawn(type: int, want: int = LootSystem.ANY, at: Vector2 = ANYWHERE) -> int:
+ var p := at if at.is_finite() else spawn_point(type)
+ var h := enemies.spawn(type, p.x, p.y, zones.playable.get_center() - p, want)
+ if h >= 0:
+ spawned += 1
+ arrived.emit(h, p)
+ return h
+
+
+## Sends an enemy of the trickle type in.
+func spawn_next(want: int = LootSystem.ANY) -> int:
+ return spawn(trickle_type(), want)
+
+
+func trickle_type() -> int:
+ return maxi(EnemySystem.TYPE_NAMES.find(config.trickle_type), 0)
+
+
+## Physics tick (FarmSim): arrivals while the night lasts.
+func step(dt: float) -> void:
+ if campaign.state.phase != CampaignController.Phase.NIGHT:
+ return
+ night_time += dt
+ if not enabled:
+ return
+ if trickle():
+ if enemies.alive_count() >= config.night_thieves:
+ _trickle_wait = config.thief_spawn_interval
+ return
+ _trickle_wait -= dt
+ if _trickle_wait <= 0.0:
+ spawn_next(int(TARGETS.get(config.trickle_target, LootSystem.ANY)))
+ _trickle_wait = config.thief_spawn_interval
+ return
+ while _next < _queue.size() and float(_queue[_next][0]) <= night_time:
+ spawn(int(_queue[_next][2]), int(_queue[_next][1]))
+ _next += 1
+
+
+func _on_phase_changed(phase: CampaignController.Phase, _previous: CampaignController.Phase) -> void:
+ if phase != CampaignController.Phase.NIGHT:
+ return
+ night_time = 0.0
+ spawned = 0
+ _trickle_wait = FIRST_TRICKLE_DELAY
+ _queue.clear()
+ _next = 0
+ var plan := tonight()
+ if plan != null:
+ for g in plan.groups:
+ var every := NightPlan.scaled_every(g, plan.spacing_scale_in(config))
+ for k in NightPlan.scaled_count(g, plan.count_scale_in(config)):
+ _queue.append([float(g.get("time", 0.0)) + k * every, want_of(g), type_of(g)])
+ _queue.sort_custom(func(a: Array, b: Array) -> bool: return float(a[0]) < float(b[0]))
diff --git a/game/scripts/wave_director.gd.uid b/game/scripts/wave_director.gd.uid
new file mode 100644
index 0000000..4dae873
--- /dev/null
+++ b/game/scripts/wave_director.gd.uid
@@ -0,0 +1 @@
+uid://cynkkyx0s7hqg
diff --git a/game/scripts/weapon_models.gd b/game/scripts/weapon_models.gd
new file mode 100644
index 0000000..a818381
--- /dev/null
+++ b/game/scripts/weapon_models.gd
@@ -0,0 +1,116 @@
+class_name WeaponModels
+extends Node3D
+## The scarecrow's weapons as it holds them (ScarecrowCombat), from the models in
+## assets/weapons/, on the scarecrow's model (which faces -Z), only the one in use showing. The
+## Blender exports sit far from the origin, so each mesh is re-centered (mesh_of) and posed here:
+## pitchfork held low like a spear at the right side, tines forward; a stab thrusts it out
+## corn shooter at the gun's spot, its corn-cob muzzle at the gameplay muzzle point; each shot
+## kicks it back
+## pumpkin bomb in the right hand; after a throw the next one grows back in the hand over the
+## recharge (set_bomb_charge)
+## attack() plays the weapon's motion (the pumpkin just leaves the hand: the thrown one is
+## PumpkinBombs').
+
+const PATHS: Array[String] = ["res://assets/weapons/PitchFork.glb", "res://assets/weapons/CornShooter.glb",
+ "res://assets/weapons/PumpkinBomb.glb"]
+## Model scale: the pitchfork is 3 m long as modeled, the pumpkin 0.75 m across.
+const SCALES: Array[float] = [0.6, 0.55, 0.45]
+## Pumpkin bombs in flight use the same scale.
+const BOMB_SCALE := 0.45
+## Seconds of each weapon's attack motion, and how far it goes.
+const STAB_TIME := 0.24
+const STAB_REACH := 0.75
+const KICK_TIME := 0.09
+const KICK := 0.09
+
+static var _meshes := {}
+
+var weapon: int = 0
+var _pivots: Array[Node3D] = []
+var _rest: Array[Transform3D] = []
+var _attack_t := -1.0
+var _bomb_charge := 1.0
+
+
+## A model's mesh, re-centered (the scene's root node sits where it was in Blender).
+static func mesh_of(index: int) -> Mesh:
+ if not _meshes.has(index):
+ var scene := (load(PATHS[index]) as PackedScene).instantiate()
+ var mi := scene.find_children("*", "MeshInstance3D", true, false)[0] as MeshInstance3D
+ _meshes[index] = mi.mesh
+ scene.free()
+ return _meshes[index]
+
+
+## Builds the three under model. muzzle: the gameplay muzzle point on the model (the corn
+## shooter's tip goes there).
+func setup(model: Node3D, muzzle: Vector3) -> void:
+ name = "Weapons"
+ model.add_child(self)
+ # Pitchfork: tines (the mesh's +Y) forward and a little down, the shaft past the right hip.
+ _add(0, Transform3D(Basis.from_euler(Vector3(-1.75, 0.0, 0.0)), Vector3(0.32, 1.15, -0.95)))
+ # Corn shooter: its tip (the mesh's +Z end, 0.59 m out) turned forward onto the muzzle point.
+ var tip := 0.589 * SCALES[1]
+ _add(1, Transform3D(Basis.from_euler(Vector3(0.0, PI, 0.0)), muzzle + Vector3(0.0, 0.0, tip)))
+ # Pumpkin: in the right hand, in front.
+ _add(2, Transform3D(Basis.IDENTITY, Vector3(0.42, 1.2, -0.5)))
+ show_weapon(0)
+
+
+func _add(index: int, rest: Transform3D) -> void:
+ var pivot := Node3D.new()
+ pivot.name = ["Pitchfork", "CornShooter", "PumpkinBomb"][index]
+ add_child(pivot)
+ var mi := MeshInstance3D.new()
+ mi.mesh = mesh_of(index)
+ mi.scale = Vector3.ONE * SCALES[index]
+ pivot.add_child(mi)
+ pivot.transform = rest
+ _pivots.append(pivot)
+ _rest.append(rest)
+
+
+## Shows only this weapon (ScarecrowCombat.Weapon).
+func show_weapon(index: int) -> void:
+ weapon = index
+ _attack_t = -1.0
+ for i in _pivots.size():
+ _pivots[i].visible = i == index
+ _pivots[i].transform = _rest[i]
+ _apply_charge()
+
+
+## The weapon's attack motion: a stab or a kick.
+func attack(index: int) -> void:
+ if index == weapon and index < 2:
+ _attack_t = 0.0
+
+
+## Share of the pumpkin bomb's recharge done (1 = a pumpkin in the hand).
+func set_bomb_charge(charge: float) -> void:
+ _bomb_charge = clampf(charge, 0.0, 1.0)
+ _apply_charge()
+
+
+func _apply_charge() -> void:
+ if _pivots.size() > 2:
+ var s := _bomb_charge * _bomb_charge
+ _pivots[2].scale = Vector3.ONE * maxf(s, 0.001)
+ _pivots[2].get_child(0).visible = s > 0.05
+
+
+func _process(delta: float) -> void:
+ if _attack_t < 0.0 or _pivots.is_empty():
+ return
+ _attack_t += delta / (STAB_TIME if weapon == 0 else KICK_TIME)
+ var u := clampf(_attack_t, 0.0, 1.0)
+ var at := _rest[weapon].origin
+ if weapon == 0: # out fast, back slower
+ var push := sin(PI * pow(u, 0.6)) * STAB_REACH
+ at += Vector3(0.0, 0.08 * push, -push)
+ else:
+ at += Vector3(0.0, 0.02, KICK) * (1.0 - u)
+ if _attack_t >= 1.0:
+ _attack_t = -1.0
+ at = _rest[weapon].origin
+ _pivots[weapon].position = at
diff --git a/game/scripts/weapon_models.gd.uid b/game/scripts/weapon_models.gd.uid
new file mode 100644
index 0000000..688d1d9
--- /dev/null
+++ b/game/scripts/weapon_models.gd.uid
@@ -0,0 +1 @@
+uid://125d2rkmeljs
diff --git a/game/scripts/workbench.gd b/game/scripts/workbench.gd
new file mode 100644
index 0000000..3188078
--- /dev/null
+++ b/game/scripts/workbench.gd
@@ -0,0 +1,35 @@
+class_name Workbench
+extends Node3D
+## The work area's tool table, where the scarecrow buys upgrades (Upgrades, UpgradePanel): press
+## interact here by day to open the menu. Its label shows how many are done.
+
+## How close the scarecrow's center has to be to this node's origin.
+@export var reach: float = 2.2
+
+var _label: Label3D
+
+
+func _ready() -> void:
+ _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 = Color(0.85, 0.75, 1.0)
+ _label.position = Vector3(0.0, 2.2, 0.0)
+ _label.visible = false
+ add_child(_label)
+
+
+func show_state(campaign: CampaignController, show: bool, focused: bool) -> void:
+ _label.visible = show
+ if not show:
+ return
+ var done := 0
+ for id in Upgrades.ORDER:
+ if Upgrades.owned(campaign.state, id):
+ done += 1
+ var hint := ("[E / X] Upgrades" if campaign.is_daytime() else "Upgrades by day") if focused else "Upgrades"
+ _label.text = "%s\n%d of %d done" % [hint, done, Upgrades.ORDER.size()]
diff --git a/game/scripts/workbench.gd.uid b/game/scripts/workbench.gd.uid
new file mode 100644
index 0000000..b1e0f73
--- /dev/null
+++ b/game/scripts/workbench.gd.uid
@@ -0,0 +1 @@
+uid://dr1dglq0p05hu
diff --git a/game/tests/run_tests.gd b/game/tests/run_tests.gd
index 1ac82a5..57c6c54 100644
--- a/game/tests/run_tests.gd
+++ b/game/tests/run_tests.gd
@@ -7,11 +7,33 @@ extends SceneTree
const SUITES := [
"res://game/tests/test_farm_state.gd",
+ "res://game/tests/test_save.gd",
"res://game/tests/test_outcome.gd",
"res://game/tests/test_campaign.gd",
"res://game/tests/test_farm_layout.gd",
+ "res://game/tests/test_theft.gd",
+ "res://game/tests/test_scarecrow.gd",
+ "res://game/tests/test_weapons.gd",
+ "res://game/tests/test_economy.gd",
+ "res://game/tests/test_structures.gd",
+ "res://game/tests/test_targets.gd",
+ "res://game/tests/test_roster.gd",
+ "res://game/tests/test_nights.gd",
+ "res://game/tests/test_cycle.gd",
+ "res://game/tests/test_flow.gd",
+ "res://game/tests/test_coop.gd",
]
const TICK := 1.0 / 60.0
+## Points on the farm's edge (FarmZones.edge) for tests that send an enemy in from a known side:
+## on foot GameConfig.spawn_margin (3 m) outside the map, where the perimeter gaps used to be...
+const EDGE := {
+ "north": Vector2(12.0, -48.0), "driveway": Vector2(50.0, -39.5), "east": Vector2(50.0, -18.5),
+ "south-east": Vector2(31.0, 18.0), "south-west": Vector2(-4.0, 18.0), "west": Vector2(-16.0, -6.0),
+}
+## ...and flying flyer_spawn_margin (8 m) out, where the crow approaches were.
+const SKY := {
+ "north": Vector2(17.0, -53.0), "east": Vector2(55.0, -5.0), "south": Vector2(17.0, 23.0), "west": Vector2(-21.0, -15.0),
+}
var passes: int = 0
var failures: int = 0
@@ -37,6 +59,11 @@ func _main() -> void:
var suite: Object = (load(path) as GDScript).new()
await suite.call("run", self)
print("TESTS: %d checks passed, %d failed (%.1f s)" % [passes, failures, (Time.get_ticks_msec() - t0) / 1000.0])
+ # Free whatever suites left behind and give the audio server a mix to drop stopped sounds.
+ for c in root.get_children():
+ c.queue_free()
+ await process_frame
+ await create_timer(0.25).timeout
quit(mini(failures, 125))
@@ -61,6 +88,15 @@ func make_campaign(cfg: GameConfig = null) -> CampaignController:
return c
+## Marks the next n crop units that are still on the farm as lost.
+static func lose_crops(s: FarmState, n: int) -> void:
+ var id := 1
+ while n > 0 and id <= s.crops_total:
+ if s.lose_crop(id):
+ n -= 1
+ id += 1
+
+
## Ticks at 60 Hz until the phase changes; returns the game seconds that took (INF if it
## never changed within max_seconds).
static func run_phase(c: CampaignController, max_seconds: float = 1000.0) -> float:
diff --git a/game/tests/test_campaign.gd b/game/tests/test_campaign.gd
index d7f82c7..2b56327 100644
--- a/game/tests/test_campaign.gd
+++ b/game/tests/test_campaign.gd
@@ -94,14 +94,14 @@ func _early_night(r: GameTestRunner) -> void:
func _night_log(r: GameTestRunner) -> void:
var c := r.make_campaign()
GameTestRunner.run_until(c, P.NIGHT)
- c.state.crops -= 3
+ GameTestRunner.lose_crops(c.state, 3)
GameTestRunner.run_until(c, P.DAWN)
- c.state.crops -= 1 # loot escaping during the dawn grace still counts for that night
+ GameTestRunner.lose_crops(c.state, 1) # loot escaping during the dawn grace still counts for that night
GameTestRunner.run_until(c, P.MORNING)
var e: Dictionary = c.state.night_log[0]
r.check(e["night"] == 1 and e["crops_lost"] == 4, "night 1 records 4 crops lost, dawn included (got %s)" % [e])
r.check(c.state.crops == c.config.start_crops - 4, "losses persist into the next day")
- c.state.crops -= 2 # lost during the day don't count against the next night
+ GameTestRunner.lose_crops(c.state, 2) # lost during the day don't count against the next night
c.begin_day()
GameTestRunner.run_until(c, P.MORNING)
r.check(c.state.night_log[1]["crops_lost"] == 0, "night 2 only counts losses after it started")
@@ -110,14 +110,14 @@ func _night_log(r: GameTestRunner) -> void:
func _retry(r: GameTestRunner) -> void:
var c := r.make_campaign()
GameTestRunner.run_until(c, P.NIGHT)
- c.state.crops -= 3
+ GameTestRunner.lose_crops(c.state, 3)
c.state.scarecrow_hp -= 4
GameTestRunner.run_until(c, P.MORNING)
var morning := c.state.to_dict()
c.begin_day()
GameTestRunner.run_until(c, P.NIGHT)
- c.state.crops -= 5
+ GameTestRunner.lose_crops(c.state, 5)
c.state.scarecrow_hp = 0
c.tick(GameTestRunner.TICK)
r.check(c.state.phase == P.GAME_OVER, "the scarecrow falls on night 2")
diff --git a/game/tests/test_coop.gd b/game/tests/test_coop.gd
new file mode 100644
index 0000000..eee61d9
--- /dev/null
+++ b/game/tests/test_coop.gd
@@ -0,0 +1,325 @@
+extends RefCounted
+## Co-op in one process: the host's farm in the main tree and the partner's in a SubViewport
+## with its own world (so the two don't share physics), joined by a loopback CoopLink and stepped
+## by hand, tick by tick. Covers the join (the welcome, both scarecrows on both farms, names,
+## co-op health), requests from the partner (start the day, build, buy), the partner's scarecrow
+## moving, gathering, and shooting on the host (and its pick of weapon), the weapons' stabs and
+## pumpkin bombs reaching the replica (drawn there, doing no damage of their own), enemies, loot,
+## and shots reaching the replica,
+## the co-op fall rule (one down is out until morning, both down is Game Over) and Retry, message
+## sizes with a crowd, dropped unreliable messages, and either side leaving.
+
+const P := CampaignController.Phase
+const DT := 1.0 / 60.0
+const AWAY := Vector3(-11.0, 0.0, 13.0)
+
+var r: GameTestRunner
+var host_farm: Node3D
+var client_farm: Node3D
+var host: FarmSim
+var client: FarmSim
+var hs: CoopSession
+var cs: CoopSession
+var links: Array[CoopLink]
+var _viewport: SubViewport
+
+
+func run(p_r: GameTestRunner) -> void:
+ r = p_r
+ await _setup()
+ _join()
+ _requests()
+ await _partner_moves_and_gathers()
+ _night()
+ _partner_shoots()
+ _weapons_shown()
+ _fall_rule()
+ _crowd()
+ _leaving()
+ for l in links:
+ l.close()
+ host_farm.queue_free()
+ _viewport.get_parent().queue_free()
+ await r.process_frame
+
+
+func _setup() -> void:
+ host_farm = (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
+ r.root.add_child(host_farm)
+ _viewport = SubViewport.new()
+ _viewport.own_world_3d = true
+ _viewport.size = Vector2i(320, 180)
+ var box := SubViewportContainer.new()
+ r.root.add_child(box)
+ box.add_child(_viewport)
+ client_farm = (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
+ _viewport.add_child(client_farm)
+ await r.process_frame
+ await r.physics_frame
+ host = host_farm.get_node("FarmSim") as FarmSim
+ client = client_farm.get_node("FarmSim") as FarmSim
+ for f: FarmSim in [host, client]:
+ f.set_physics_process(false)
+ f.coop.set_physics_process(false)
+ f.waves.enabled = false
+ host.player.global_position = AWAY
+ host.waves.rng.seed = 1 # repeatable arrival points
+ hs = host.coop
+ cs = client.coop
+ links = CoopLink.pair()
+
+
+## One tick on both machines, in the order the frames would run them.
+func _pump(n: int = 1) -> void:
+ for i in n:
+ for body: PlayerCharacter in _remote_bodies():
+ body._follow_net(DT)
+ host.step(DT)
+ hs._physics_process(DT)
+ client.step(DT)
+ cs._physics_process(DT)
+
+
+func _remote_bodies() -> Array[PlayerCharacter]:
+ var out: Array[PlayerCharacter] = []
+ for f: FarmSim in [host, client]:
+ for a in f.avatars:
+ if a.body.remote_driven:
+ out.append(a.body)
+ return out
+
+
+func _same_state() -> bool:
+ var a := host.campaign.state.to_dict()
+ var b := client.campaign.state.to_dict()
+ for d: Dictionary in [a, b]:
+ d.erase("phase_time_left")
+ d.erase("night_events")
+ return JSON.stringify(a, "", true, true) == JSON.stringify(b, "", true, true)
+
+
+func _join() -> void:
+ hs.start_host(host, links[0], "Ana", "Ben")
+ cs.start_client(client, links[1], "Ben")
+ _pump(2)
+ r.check(hs.is_host() and cs.is_client() and client.replica and not host.replica, "the host and the partner each take their role")
+ r.check(host.avatars.size() == 2 and client.avatars.size() == 2 and host.partner.remote != null and not host.partner.is_local
+ and client.local_avatar.slot == 1 and client.avatars[0].body.remote_driven and host.partner.body.remote_driven,
+ "both farms have both scarecrows: the host plays P1, the partner P2")
+ r.check(client.player == client.avatars[1].body and client.scarecrow.slot == 1 and client.hud.kit == client.scarecrow
+ and (client.camera as FollowCamera).target == client.player, "the partner's HUD and camera follow P2")
+ r.check(host.campaign.state.coop and client.campaign.state.coop and host.campaign.state.partner_hp == host.config.scarecrow_max_hp,
+ "co-op is on: P2 has full health")
+ r.check(client.campaign.state.phase == P.MORNING and _same_state(), "the partner's farm is the host's (the welcome)")
+ r.check(host.avatars[0].body._tag.text == "P1 Ana" and host.avatars[1].body._tag.text == "P2 Ben"
+ and client.avatars[0].body._tag.text == "P1 Ana" and client.avatars[1].body._tag.text == "P2 Ben", "name tags over both")
+ r.check(client.campaign.save_path == "" and client.audio.remote_cues and host.audio.forward.is_valid(), "only the host saves; sounds come from the host")
+
+
+func _requests() -> void:
+ client.review_panel._start.pressed.emit()
+ _pump(2)
+ r.check(host.campaign.state.phase == P.DAY and client.campaign.state.phase == P.DAY, "the partner can start the day (the host does it)")
+ host.campaign.state.resources.shed = {"wood": 40, "scrap": 30, "straw": 30}
+ client.player.global_position = Vector3(2.0, 0.0, 6.0)
+ _pump(4)
+ var before := host.structures.count()
+ client.build.place_request.call("fence", 3.5, 8.0, 0)
+ _pump(20)
+ r.check(host.structures.count() == before + 1 and client.structures.count() == before + 1 and _same_state(),
+ "the partner builds a fence: the host checks it, builds it, and both farms show it")
+ client.build.place_request.call("fence", 30.0, -30.0, 0)
+ _pump(20)
+ r.check(host.structures.count() == before + 1, "a placement out of the partner's reach is refused by the host")
+ client.upgrade_panel.buy_request.call("corn_shooter")
+ _pump(20)
+ r.check(Upgrades.owned(host.campaign.state, "corn_shooter") and Upgrades.owned(client.campaign.state, "corn_shooter"),
+ "the partner buys an upgrade at the workbench (the host does it)")
+
+
+func _partner_moves_and_gathers() -> void:
+ var tree: GatherNode
+ for n in host.interactions.nodes:
+ if n.name == "DeadTree":
+ tree = n
+ var at := tree.global_position + Vector3(tree.reach * 0.7, 0.0, 0.0)
+ client.player.global_position = at
+ _pump(10)
+ r.check(host.partner.body.global_position.distance_to(at) < 0.3, "the host's copy of P2 follows the partner's own moves")
+ host.campaign.state.resources.pouch = {"wood": 0, "scrap": 0, "straw": 0}
+ Input.action_press("interact")
+ _pump(roundi(host.config.gather_time * 60.0) - 20)
+ var gathering_there := client.interactions.gathering != null and String(client.interactions.gathering.name) == "DeadTree" and client.player.rooted
+ _pump(40)
+ Input.action_release("interact")
+ _pump(20)
+ r.check(gathering_there, "while P2 gathers, the partner sees it (the channel, rooted) from the host")
+ r.check(int(host.campaign.state.resources.pouch["wood"]) >= 2 and int(client.campaign.state.resources.pouch["wood"]) >= 2
+ and int(host.campaign.state.night_events.get("gathered_wood", 0)) >= 2, "P2 gathered wood into the shared pouch (%s)" % [host.campaign.state.resources.pouch])
+ r.check(not client.player.rooted, "and is free to move again")
+ await r.process_frame
+
+
+func _night() -> void:
+ host.campaign.advance_phase()
+ host.campaign.advance_phase()
+ _pump(2)
+ r.check(host.campaign.state.phase == P.NIGHT and client.campaign.state.phase == P.NIGHT, "night falls on both farms")
+ # Far from P1 (waiting at AWAY, on the farm's edge): where the north gaps were.
+ host.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["north"])
+ host.spawn_enemy(EnemySystem.TYPE_THIEF, LootSystem.ANY, GameTestRunner.EDGE["north"])
+ host.spawn_enemy(EnemySystem.TYPE_BREAKER, LootSystem.ANY, GameTestRunner.EDGE["driveway"])
+ _pump(30)
+ var types_host := _types(host.enemies)
+ var types_client := _types(client.enemies)
+ r.check(host.enemies.alive_count() == 3 and types_client == types_host, "the enemies reach the partner's farm, by type (%s)" % [types_client])
+ r.check(_enemies_match(0.6), "where the host has them (within 0.6 m)")
+ r.check(client.characters.in_use() == 2, "the partner draws the ground enemies with characters")
+ # A crow steals: the loot follows on the partner's farm.
+ var stolen := false
+ for i in 1800:
+ _pump()
+ if host.loot.count(LootSystem.Status.CARRIED) > 0:
+ stolen = true
+ break
+ _pump(8)
+ var carried := -1
+ for id in range(1, host.loot.item_count + 1):
+ if host.loot.status[id] == LootSystem.Status.CARRIED:
+ carried = id
+ r.check(stolen and carried > 0 and client.loot.status[carried] == LootSystem.Status.CARRIED
+ and client.enemies.resolve_handle(client.loot.holder[carried]) >= 0, "a carried crop is carried on both farms, by the same enemy")
+ var killed := host.enemies.alive_count()
+ for d in host.enemies.active_count:
+ host.enemies.apply_hit(d, 99)
+ _pump(6)
+ r.check(killed > 0 and host.enemies.alive_count() == 0 and client.enemies.alive_count() == 0, "killed on the host, gone on the partner's farm")
+
+
+func _partner_shoots() -> void:
+ var fired := host.partner.combat.shots_fired
+ var heard := int(client.audio.played.get("shot", 0))
+ r.check(client.combat.equip(ScarecrowCombat.Weapon.CORN_SHOOTER), "the partner takes the corn shooter (bought for both)")
+ client.player.global_position = Vector3(8.0, 0.0, -10.0) # open ground, nothing east of it
+ client.combat.device = ScarecrowCombat.Device.GAMEPAD # keeps the aim it's given
+ _pump(10)
+ r.check(host.partner.combat.weapon == ScarecrowCombat.Weapon.CORN_SHOOTER and host.avatars[0].combat.weapon == ScarecrowCombat.Weapon.PITCHFORK,
+ "the host sees P2 holding it, and P1 still has the pitchfork")
+ client.combat.aim = Vector2(1.0, 0.0)
+ Input.action_press("fire")
+ _pump(30)
+ r.check(client.projectiles.active_count > 0, "shots in flight show on the partner's farm (the host's, %d)" % client.projectiles.active_count)
+ Input.action_release("fire")
+ _pump(10)
+ r.check(host.partner.combat.shots_fired > fired, "the partner holds fire: P2's gun fires on the host (%d shots)" % (host.partner.combat.shots_fired - fired))
+ r.check(int(client.audio.played.get("shot", 0)) > heard, "and the partner hears the shots")
+ r.check(client.projectiles.fired == 0, "(the partner's own gun only aims: it fired nothing itself)")
+
+
+func _weapons_shown() -> void:
+ var p1 := client.avatars[0].combat # the host's scarecrow, on the partner's farm
+ p1.models._attack_t = -1.0
+ host.combat.equip(ScarecrowCombat.Weapon.PITCHFORK)
+ host.combat.reset()
+ host.combat.attack_toward(Vector2(host.player.global_position.x + 3.0, host.player.global_position.z))
+ _pump(3)
+ r.check(p1.weapon == ScarecrowCombat.Weapon.PITCHFORK and p1.models._attack_t >= 0.0, "P1's pitchfork stab shows on the partner's farm")
+ host.campaign.state.upgrades["pumpkin_bomb"] = 1
+ host.combat.equip(ScarecrowCombat.Weapon.PUMPKIN_BOMB)
+ host.combat.ready_for_morning()
+ var bursts := client.bombs.bursts
+ host.combat.attack_toward(Vector2(host.player.global_position.x + 6.0, host.player.global_position.z))
+ _pump(3)
+ r.check(p1.weapon == ScarecrowCombat.Weapon.PUMPKIN_BOMB and client.bombs.flying() == 1, "P1's pumpkin bomb flies on the partner's farm too")
+ _pump(90)
+ r.check(client.bombs.bursts == bursts + 1 and client.bombs.enemies_hit == 0 and host.bombs.flying() == 0,
+ "and bursts there, harmless (the host's burst does the damage)")
+ r.check(client.combat.equip(ScarecrowCombat.Weapon.PUMPKIN_BOMB), "the partner can take bombs up too (bought for both)")
+ var thrown := host.partner.combat.bombs_thrown
+ Input.action_press("fire")
+ _pump(10)
+ Input.action_release("fire")
+ _pump(4)
+ r.check(host.partner.combat.bombs_thrown == thrown + 1 and client.combat.bomb_left > 0.0, "P2's throw happens on the host, and its recharge shows on the partner's HUD")
+ _pump(90)
+ for c: ScarecrowCombat in [host.combat, client.combat]:
+ c.equip(ScarecrowCombat.Weapon.PITCHFORK)
+ host.campaign.state.upgrades.erase("pumpkin_bomb")
+ _pump(4)
+
+
+func _fall_rule() -> void:
+ host.partner.kit.invulnerable_left = 0.0
+ host.partner.kit.try_damage(99)
+ _pump(6)
+ r.check(not host.partner.kit.alive and host.campaign.state.phase == P.NIGHT and not host.campaign.is_over(),
+ "in co-op one scarecrow down is out until morning, not Game Over")
+ r.check(not client.scarecrow.alive and not client.player.alive, "the partner sees their own scarecrow fall")
+ client._process(0.0)
+ r.check((client.camera as FollowCamera).target == client.avatars[0].body, "and their camera watches P1 meanwhile")
+ host.scarecrow.invulnerable_left = 0.0
+ host.scarecrow.try_damage(99)
+ _pump(6)
+ r.check(host.campaign.outcome == CampaignController.Outcome.GAME_OVER_SCARECROW and client.campaign.outcome == host.campaign.outcome
+ and client.campaign.state.phase == P.GAME_OVER, "both down: Game Over on both farms")
+ client.end_panel._process(EndPanel.DELAY + 0.1)
+ r.check(client.end_panel.mode == "failure", "with the failure screen on the partner's too")
+ client.end_panel._retry.pressed.emit()
+ _pump(4)
+ r.check(host.campaign.state.phase == P.MORNING and client.campaign.state.phase == P.MORNING and host.scarecrow.alive
+ and host.partner.kit.alive and client.scarecrow.alive and host.campaign.state.coop, "Retry from the partner: both back at the morning")
+
+
+func _crowd() -> void:
+ host.campaign.begin_day()
+ host.campaign.advance_phase()
+ host.campaign.advance_phase()
+ for i in 90:
+ host.spawn_enemy([EnemySystem.TYPE_CROW, EnemySystem.TYPE_THIEF, EnemySystem.TYPE_BREAKER][i % 3])
+ links[0].drop_every = 3 # a third of the unreliable messages lost
+ _pump(60)
+ r.check(client.enemies.alive_count() == host.enemies.alive_count() and host.enemies.alive_count() > 40,
+ "a crowd of %d enemies, with a third of the snapshots lost, all show" % host.enemies.alive_count())
+ r.check(_enemies_match(1.0), "close to where the host has them")
+ r.check(links[0].oversized == 0 and links[1].oversized == 0 and links[0].largest_unreliable <= CoopLink.UNRELIABLE_LIMIT,
+ "no unreliable message is too big for a datagram (largest %d bytes)" % links[0].largest_unreliable)
+ r.info("co-op traffic: host sent %d messages, %.1f KB in %d ticks; partner %d messages" % [links[0].sent_messages,
+ links[0].sent_bytes / 1024.0, hs.ticks, links[1].sent_messages])
+ links[0].drop_every = 0
+
+
+func _leaving() -> void:
+ var gone: Array[String] = []
+ cs.ended.connect(func(why: String) -> void: gone.append(why))
+ links[1].close() # the partner quits
+ _pump(2)
+ r.check(not hs.is_active() and host.partner == null and host.avatars.size() == 1 and not host.campaign.state.coop
+ and not is_instance_valid(host.get_parent().get_node_or_null("Player2")) or host.get_parent().get_node("Player2").is_queued_for_deletion(),
+ "the partner leaves: the host plays on alone")
+ r.check(not cs.is_active() and gone.size() == 1, "and the partner's game is told the session is over ('%s')" % (gone[0] if not gone.is_empty() else ""))
+ host.campaign.state.coop = true # as a co-op morning's save would have it
+ host.campaign.retry_night()
+ r.check(not host.campaign.state.coop, "a co-op morning played alone goes back to the solo rules")
+
+
+func _types(es: EnemySystem) -> Dictionary:
+ var out := {}
+ for d in es.active_count:
+ if es.alive[d] == 1:
+ out[es.type[d]] = int(out.get(es.type[d], 0)) + 1
+ return out
+
+
+## Every host enemy has a partner-side copy within tolerance meters.
+func _enemies_match(tolerance: float) -> bool:
+ var es := host.enemies
+ for d in es.active_count:
+ if es.alive[d] == 0:
+ continue
+ var h := cs._local_handle(es.handle_of(d))
+ var c := client.enemies.resolve_handle(h)
+ if c < 0:
+ return false
+ if Vector2(es.pos_x[d] - client.enemies.pos_x[c], es.pos_z[d] - client.enemies.pos_z[c]).length() > tolerance:
+ return false
+ return true
diff --git a/game/tests/test_coop.gd.uid b/game/tests/test_coop.gd.uid
new file mode 100644
index 0000000..3c9e76a
--- /dev/null
+++ b/game/tests/test_coop.gd.uid
@@ -0,0 +1 @@
+uid://b2asymmile7yy
diff --git a/game/tests/test_cycle.gd b/game/tests/test_cycle.gd
new file mode 100644
index 0000000..5b11e64
--- /dev/null
+++ b/game/tests/test_cycle.gd
@@ -0,0 +1,231 @@
+extends RefCounted
+## One complete day and night on the real farm (FarmSim stepped by hand): the night plan's
+## arrivals (times, targets, random points all along the farm's edge, nothing by day or after
+## sunrise), the dusk warnings, the dawn
+## retreat and its record, carrying everything into the next morning (structures and their damage,
+## materials, losses in every category, the scarecrow's health), the morning review panel,
+## retrying from the morning snapshot, the lighting of each phase, and the phase and asset HUDs.
+
+const P := CampaignController.Phase
+const DT := 1.0 / 60.0
+const AWAY := Vector3(-11.0, 0.0, 13.0)
+
+var _broken: Array[int] = []
+var _start_structures: int = 0
+
+
+func run(r: GameTestRunner) -> void:
+ var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
+ r.root.add_child(farm)
+ await r.process_frame
+ await r.physics_frame
+ var sim := farm.get_node("FarmSim") as FarmSim
+ sim.set_physics_process(false)
+ sim.waves.rng.seed = 1 # tonight's 11 arrival points, drawn the same every run
+ var player := farm.get_node("Player") as PlayerCharacter
+ player.global_position = AWAY
+ var review := farm.get_node("Hud/ReviewPanel") as ReviewPanel
+ var hud := farm.get_node("Hud/PhaseHud") as PhaseHud
+ var assets := farm.get_node("Hud/AssetHud") as AssetHud
+ assets._process(0.0)
+ r.check(assets.describe() == "Crops 30/30 · Animals 8/8 · Supplies 10", "the asset HUD reads '%s'" % assets.describe())
+ sim.structures.destroyed.connect(func(_id: int, _t: String, _at: Vector3) -> void: _broken.append(1))
+ _morning(r, sim, review, hud)
+ _day(r, sim, player, hud)
+ var before_night := sim.campaign.state.to_dict()
+ _dusk(r, sim, hud)
+ _night(r, sim)
+ _dawn_and_morning(r, sim, review, before_night)
+ _retry(r, sim)
+ farm.queue_free()
+ await r.process_frame
+
+
+func _morning(r: GameTestRunner, sim: FarmSim, review: ReviewPanel, hud: PhaseHud) -> void:
+ r.check(sim.campaign.state.phase == P.MORNING and review.visible and review._title.text == "The farmers are away",
+ "the first morning shows the review panel with the introduction")
+ hud._process(0.0)
+ r.check(hud.describe() == "Night 1 of 5 · Morning", "the phase HUD reads '%s'" % hud.describe())
+ sim.day_night.snap()
+ var day_energy := sim.sun.light_energy
+ r.check(sim.day_night.lantern.light_energy < 0.6 and day_energy > 0.8, "morning light: bright sun, lantern nearly off")
+ review._start.pressed.emit()
+ r.check(sim.campaign.state.phase == P.DAY and not review.visible, "Start the day ends the review")
+
+
+func _day(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter, hud: PhaseHud) -> void:
+ var c := sim.campaign
+ var s := c.state
+ hud._process(0.0)
+ r.check(hud.describe() == "Night 1 of 5 · Day · 3:00 left", "the phase HUD reads '%s'" % hud.describe())
+ sim.day_night.snap()
+ r.check(is_equal_approx(sim.day_night.lantern.light_energy, 0.0) and sim.sun.light_energy > 1.0, "daylight: full sun, no lantern")
+ # A day's work: gather into the pouch, build, take some damage, patch up.
+ var tree: GatherNode
+ for n in sim.interactions.nodes:
+ if n.name == "DeadTree":
+ tree = n
+ player.global_position = tree.global_position + Vector3(tree.reach * 0.7, 0.0, 0.0)
+ Input.action_press("interact")
+ _step(sim, roundi(c.config.gather_time * 60.0) + 2)
+ Input.action_release("interact")
+ _step(sim, 1)
+ r.check(s.resources.pouch["wood"] == 2, "gathered 2 wood into the pouch")
+ s.resources.shed = {"wood": 20, "scrap": 20, "straw": 20}
+ _start_structures = sim.structures.count()
+ var fence := sim.structures.place("fence", 30.0, -18.5, 0)
+ sim.structures.place("automated_defense", 38.0, -17.0, 0)
+ sim.structures.damage(fence, 6)
+ s.scarecrow_hp = 7
+ player.global_position = AWAY
+ r.check(sim.structures.count() == _start_structures + 2, "built a fence and an automated defense (next to the pen's gate)")
+ var arrived: Array[int] = []
+ sim.waves.arrived.connect(func(h: int, _at: Vector2) -> void: arrived.append(h))
+ _step_until(sim, P.DUSK)
+ r.check(arrived.is_empty() and sim.enemies.active_count == 0, "no thieves come by day")
+
+
+func _dusk(r: GameTestRunner, sim: FarmSim, hud: PhaseHud) -> void:
+ var w := sim.waves
+ var plan := w.tonight()
+ r.check(plan != null and plan.total() == 11 and plan.type_counts() == {EnemySystem.TYPE_CROW: 11}
+ and plan.total(plan.count_scale_in(sim.config)) == 11, "tonight's plan: %d crows, played as designed (%d)" % [plan.total() if plan else -1,
+ plan.total(plan.count_scale_in(sim.config)) if plan else -1])
+ r.check(w.warning_active() and w.tonight_entries() == [[EnemySystem.TYPE_CROW, LootSystem.Category.CROP]], "dusk warns of what tonight brings: %s" % [w.tonight_entries()])
+ hud._process(0.0)
+ var warning := "Tonight, from every side: crows"
+ r.check(hud._hint.text == warning, "the HUD warns, by target: '%s'" % hud._hint.text.replace("\n", " / "))
+ var marked := w.get_children().filter(func(n: Node) -> bool: return n is Node3D and (n as Node3D).visible)
+ r.check(marked.is_empty() and sim.alerts.collect().is_empty(), "nothing marks tonight's arrivals on the farm or at the screen edge")
+ r.check(hud._dusk_hint.visible and hud._dusk_hint.text == plan.dusk_hint and hud._banner.text == "Dusk: %s" % plan.title,
+ "the dusk banner names tonight, and its hint shows: '%s'" % hud._dusk_hint.text)
+ r.check(sim.waves.enemies.active_count == 0, "still no thieves at dusk")
+
+
+func _night(r: GameTestRunner, sim: FarmSim) -> void:
+ var c := sim.campaign
+ var w := sim.waves
+ var log: Array = []
+ var cb := func(h: int, at: Vector2) -> void:
+ var d := sim.enemies.resolve_handle(h)
+ log.append([w.night_time, at, int(sim.enemies.want[d]), int(sim.enemies.type[d])])
+ w.arrived.connect(cb)
+ _step_until(sim, P.NIGHT)
+ sim.day_night.snap()
+ r.check(sim.sun.light_energy < float(DayNight.DAY["energy"]) and sim.day_night.lantern.light_energy > 0.0,
+ "nightfall: the light drops and the lantern comes on")
+ _step(sim, roundi(DayNight.NIGHTFALL * 60.0) + 2)
+ sim.day_night.snap()
+ r.check(sim.sun.light_energy < 0.5 and sim.day_night.lantern.light_energy > 1.5 and is_equal_approx(float(sim.day_night.current["glow"]), 1.0),
+ "full night: moonlight, the lantern lit, enemies glowing")
+ _step_until(sim, P.DAWN)
+ w.arrived.disconnect(cb)
+ var plan := w.tonight()
+ var expect: Array = []
+ var cfg := sim.config
+ for g in plan.groups:
+ for k in NightPlan.scaled_count(g, plan.count_scale_in(cfg)):
+ expect.append([float(g["time"]) + k * NightPlan.scaled_every(g, plan.spacing_scale_in(cfg)),
+ WaveDirector.want_of(g), WaveDirector.type_of(g)])
+ expect.sort_custom(func(a: Array, b: Array) -> bool: return a[0] < b[0])
+ var match_all := log.size() == expect.size()
+ var edge := sim.zones.edge(cfg.flyer_spawn_margin) # tonight is all crows
+ var sides := {}
+ var spots := {}
+ for i in mini(log.size(), expect.size()):
+ var at: Vector2 = log[i][1]
+ match_all = match_all and absf(float(log[i][0]) - float(expect[i][0])) < DT * 1.5 and log[i][2] == expect[i][1] \
+ and log[i][3] == expect[i][2] and FarmZones.nearest_on_outline(edge, at).distance_to(at) < 0.01
+ sides[sim.zones.side_of(at)] = true
+ spots[Vector2i(at.round())] = true
+ r.check(match_all, "the night plays the plan: %d arrivals of their types at their times, after their targets, on the farm's edge (got %d)" % [expect.size(), log.size()])
+ # Tonight's few arrivals land on a handful of sides; many more draws cover all eight.
+ var drawn := {}
+ for type in [EnemySystem.TYPE_CROW, EnemySystem.TYPE_THIEF]:
+ for k in 200:
+ drawn[sim.zones.side_of(w.spawn_point(type))] = true
+ r.check(sides.size() >= 3 and spots.size() > log.size() * 0.8 and drawn.size() == 8,
+ "each arrives at its own random point, all around the farm (%d sides, %d spots for %d arrivals; %d sides in 400 draws)" % [
+ sides.size(), spots.size(), log.size(), drawn.size()])
+ var ev := c.state.night_events
+ r.info("night 1 with the scarecrow away: %d crops lost (%d stolen), %d animals lost (%d grabbed, %d wandered out), %d supplies taken; fence at %s HP, %d structures broken" % [
+ c.state.crops_total - c.state.crops, int(ev.get("crops_stolen", 0)), c.state.animals_total - c.state.animals,
+ int(ev.get("animals_stolen", 0)), int(ev.get("animals_strayed", 0)), int(ev.get("supplies_stolen", 0)), _fence_hp(sim), _broken.size()])
+
+
+func _dawn_and_morning(r: GameTestRunner, sim: FarmSim, review: ReviewPanel, before: Dictionary) -> void:
+ var c := sim.campaign
+ r.check(c.state.phase == P.DAWN, "sunrise")
+ var still := 0
+ for d in sim.enemies.active_count:
+ var st := sim.enemies.state[d]
+ if sim.enemies.alive[d] == 1 and st != ThiefBehavior.State.RETREAT and st != ThiefBehavior.State.CARRY:
+ still += 1
+ r.check(still == 0, "at sunrise every thief retreats or runs with its loot")
+ var lost_before_morning := c.state.crops_total - c.state.crops
+ var stolen := int(c.state.night_events.get("crops_stolen", 0))
+ _step_until(sim, P.MORNING)
+ var s := c.state
+ r.check(sim.enemies.active_count == 0 and s.night == 2, "the next morning: no thieves left, night 2 ahead")
+ var e: Dictionary = s.night_log[0]
+ r.check(e["crops_lost"] == s.crops_total - s.crops and e["crops_lost"] >= lost_before_morning and e["crops_stolen"] == stolen,
+ "the night's record: %s" % [e])
+ var built: int = before["structures"].size()
+ r.check(s.to_dict()["structures"].size() == built - _broken.size() and _fence_hp(sim) <= sim.config.fence_hp - 6,
+ "structures stand, damage and all (%d of %d; %d broken)" % [s.structures.size(), built, _broken.size()])
+ var shed_before := 0
+ for m in ResourceStore.MATERIALS:
+ shed_before += int(before["resources"]["shed"][m])
+ r.check(s.resources.pouch == before["resources"]["pouch"] and s.resources.shed_total() == shed_before - int(e["supplies_lost"]),
+ "materials carry over, less what thieves carried off (pouch %s, %d lost from the shed)" % [s.resources.pouch, e["supplies_lost"]])
+ r.check(s.animals == s.animals_total - s.lost_animals.size() and e["animals_lost"] == s.lost_animals.size() and s.supplies_in_transit == 0,
+ "animal losses are recorded and no sack is left in transit")
+ r.check(s.scarecrow_hp == 7, "the scarecrow's health carries over")
+ r.check(review.visible and review._title.text == "Morning of day 2 of 5" and review._last_head.visible
+ and review._last_head.text == "Night 1: Crows at the crops" and review._body.text.contains("Needs repair"),
+ "the morning screen shows last night's results and what needs repair")
+ var rows := ReviewPanel.category_counts(e)
+ r.check(review.grid_text() == "Crops %d %d %d\nAnimals %d %d %d\nSupplies %d %d %d" % (rows["Crops"] + rows["Animals"] + rows["Supplies"])
+ and review._body.text.contains("%d of %d animals" % [s.animals, s.animals_total]), "with every category's taken, recovered, and lost")
+ var killed := int(e["killed_crow"]) + int(e["killed_thief"]) + int(e["killed_breaker"])
+ r.check(review._results.text.contains("Enemies defeated: ") and review._results.text.contains("Materials: gathered 2 wood")
+ and (killed == 0) == review._results.text.contains("defeated: none") and int(e["gathered_wood"]) == 2
+ and int(e["structures_built"]) == 2 and int(e["structures_damaged"]) >= 6, "enemies defeated, damage, and the day's gathering and building")
+ r.info("morning screen:\n" + review.grid_text() + "\n" + review._results.text + "\n" + review._body.text)
+
+
+func _retry(r: GameTestRunner, sim: FarmSim) -> void:
+ var c := sim.campaign
+ var morning := c.state.to_dict()
+ c.begin_day()
+ _step(sim, 60)
+ c.state.resources.shed["wood"] = 0
+ sim.structures.place("slowing_trap", 10.0, -10.0, 0)
+ c.state.scarecrow_hp = 0
+ _step(sim, 1)
+ r.check(c.state.phase == P.GAME_OVER, "the scarecrow falls on day 2")
+ c.retry_night()
+ _step(sim, 1)
+ var now := c.state.to_dict()
+ r.check(now == morning, "retry restores the morning snapshot exactly")
+ var n: int = morning["structures"].size()
+ r.check(sim.structures.count() == n and sim.structures._views.size() == n, "and the farm shows it (%d structures)" % n)
+
+
+func _fence_hp(sim: FarmSim) -> int:
+ for e in sim.campaign.state.structures:
+ if e["type"] == "fence":
+ return int(e["hp"])
+ return -1
+
+
+func _step_until(sim: FarmSim, phase: CampaignController.Phase) -> void:
+ var guard := 0
+ while sim.campaign.state.phase != phase and not sim.campaign.is_over() and guard < 30000:
+ sim.step(DT)
+ guard += 1
+
+
+func _step(sim: FarmSim, n: int) -> void:
+ for i in n:
+ sim.step(DT)
diff --git a/game/tests/test_cycle.gd.uid b/game/tests/test_cycle.gd.uid
new file mode 100644
index 0000000..66c452d
--- /dev/null
+++ b/game/tests/test_cycle.gd.uid
@@ -0,0 +1 @@
+uid://b0vulxeka70sr
diff --git a/game/tests/test_economy.gd b/game/tests/test_economy.gd
new file mode 100644
index 0000000..1a26573
--- /dev/null
+++ b/game/tests/test_economy.gd
@@ -0,0 +1,316 @@
+extends RefCounted
+## The resource economy: ResourceStore rules (pouch capacity, deposit, paying pouch first then
+## shed, all-or-nothing, validation), FarmState keeping materials, gather points, and upgrades
+## through JSON, and on the real farm (FarmSim stepped by hand): the gather points' layout,
+## gathering by day only (charges, rooted, cancelled by letting go / a hit / fear, a full pouch,
+## nightfall), the shed drop-off, overnight regrowth, retry restoring the morning's materials,
+## patching's straw cost, and buying the Straw Stuffing upgrade from the workbench's menu.
+
+const P := CampaignController.Phase
+const DT := 1.0 / 60.0
+
+
+func run(r: GameTestRunner) -> void:
+ _store(r)
+ _state(r)
+ var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
+ r.root.add_child(farm)
+ await r.process_frame
+ await r.physics_frame
+ var sim := farm.get_node("FarmSim") as FarmSim
+ sim.set_physics_process(false)
+ sim.waves.enabled = false
+ var player := farm.get_node("Player") as PlayerCharacter
+ _layout(r, sim)
+ _gathering(r, sim, player)
+ _deposit_and_night(r, sim, player)
+ _patch_cost(r, sim)
+ _stuffing(r, sim, player)
+ farm.queue_free()
+ await r.process_frame
+
+
+func _store(r: GameTestRunner) -> void:
+ var s := ResourceStore.new()
+ r.check(s.add_to_pouch("wood", 10) == 10 and s.add_to_pouch("straw", 10) == 5 and s.pouch_total() == 15 and s.pouch_room() == 0,
+ "the pouch takes only what fits (15 units across materials)")
+ var moved := s.deposit()
+ r.check(moved == {"wood": 10, "straw": 5} and s.pouch_total() == 0 and s.shed["wood"] == 10, "deposit moves the whole pouch into the shed")
+ s = ResourceStore.new()
+ s.shed["wood"] = 3
+ s.pouch["wood"] = 2
+ r.check(s.available("wood") == 5 and s.pay({"wood": 4}) and s.pouch["wood"] == 0 and s.shed["wood"] == 1,
+ "costs are paid from the pouch first, then the shed")
+ r.check(not s.pay({"wood": 2}) and s.shed["wood"] == 1 and s.missing({"wood": 2}) == {"wood": 1},
+ "a cost that can't be met pays nothing and says what's missing")
+ s.shed["straw"] = 5
+ r.check(not s.pay({"straw": 1, "scrap": 3}) and s.shed["straw"] == 5, "a cost is all-or-nothing across materials")
+ r.check(ResourceStore.describe({"straw": 2, "wood": 6}) == "6 wood, 2 straw", "costs read in material order")
+ s.pouch["scrap"] = 4
+ var back := ResourceStore.from_dict(JSON.parse_string(JSON.stringify(s.to_dict())))
+ r.check(back != null and back.to_dict() == s.to_dict(), "the store round-trips through JSON")
+ var bad := {
+ "a negative amount": func(d: Dictionary) -> void: d["shed"]["wood"] = -1,
+ "an unknown material": func(d: Dictionary) -> void: d["pouch"]["gold"] = 1,
+ "an overfull pouch": func(d: Dictionary) -> void: d["pouch"]["wood"] = 99,
+ "a missing part": func(d: Dictionary) -> void: d.erase("shed"),
+ }
+ for label: String in bad:
+ var d := s.to_dict()
+ d["shed"] = (d["shed"] as Dictionary).duplicate()
+ d["pouch"] = (d["pouch"] as Dictionary).duplicate()
+ (bad[label] as Callable).call(d)
+ r.check(ResourceStore.from_dict(d) == null, "the store rejects %s" % label)
+
+
+func _state(r: GameTestRunner) -> void:
+ var cfg := (load("res://game/resources/game_config.tres") as GameConfig).duplicate() as GameConfig
+ var s := FarmState.create(cfg)
+ r.check(s.resources.shed == {"wood": cfg.start_wood, "scrap": cfg.start_scrap, "straw": cfg.start_straw}
+ and s.resources.pouch_capacity == cfg.pouch_capacity, "a new farm starts with the configured stock and pouch size")
+ s.resources.add_to_pouch("scrap", 3)
+ s.gather_charges = {"Snag": 1, "Wreck": 0}
+ s.upgrades = {"straw_stuffing": 1}
+ var d := s.to_dict()
+ var back := FarmState.from_dict(JSON.parse_string(JSON.stringify(d)))
+ r.check(back != null and back.to_dict() == d, "FarmState keeps materials, used gather points, and upgrades through JSON")
+ d["gather_charges"] = {"Snag": -2}
+ r.check(FarmState.from_dict(d) == null, "FarmState rejects negative gather charges")
+
+
+func _layout(r: GameTestRunner, sim: FarmSim) -> void:
+ var by_material := {}
+ var names := {}
+ for n in sim.interactions.nodes:
+ by_material[n.material] = int(by_material.get(n.material, 0)) + 1
+ names[String(n.name)] = true
+ var zone := sim.zones.zone_at(n.global_position)
+ var want := {"wood": FarmZone.Kind.WOOD, "scrap": FarmZone.Kind.SCRAP, "straw": FarmZone.Kind.STRAW}[n.material] as FarmZone.Kind
+ r.check(zone != null and zone.kind == want and n.get_child_count() >= 2, "%s (%s) stands in its zone with its props" % [n.name, n.material])
+ var inside := {}
+ var outside := {}
+ for n in sim.interactions.nodes:
+ var bucket := inside if sim.zones.is_inside_fence(n.global_position) else outside
+ bucket[n.material] = int(bucket.get(n.material, 0)) + 1
+ if bucket == outside:
+ r.check(n.yield_amount > 2 and sim.zones.zone_at(n.global_position).outside, "%s, outside the fence, yields more (%d)" % [n.name, n.yield_amount])
+ for m in ResourceStore.MATERIALS:
+ r.check(int(inside.get(m, 0)) >= 3 and int(inside.get(m, 0)) <= 5, "3-5 gather points for %s on the farm (%d)" % [m, int(inside.get(m, 0))])
+ r.check(int(outside.get(m, 0)) >= 2, "and more outside the fence (%d)" % int(outside.get(m, 0)))
+ r.check(sim.zones.outside_zones().size() == 4 and sim.zones.zone(FarmZone.Kind.WOOD).display_name == "Woodlot",
+ "four gathering areas outside, and the farm's own zones still come first")
+ r.check(names.size() == sim.interactions.nodes.size(), "gather point names are unique (they key the farm state)")
+ # The scarecrow's body must be able to stand within reach of every point (and the workbench),
+ # walking there from its start: out through the gaps for the points outside.
+ var nav := FarmNavigation.new()
+ nav.build(sim.get_parent(), sim.zones.roam, 0.5, FarmSim.SCARECROW_RADIUS, 1 | 4)
+ var from := nav.nearest_free(nav.cell_of(sim.player.global_position.x, sim.player.global_position.z))
+ var walk := nav.distance_field(PackedInt32Array([from]))
+ var spots: Array[Node3D] = []
+ spots.assign(sim.interactions.nodes)
+ spots.append(sim.interactions.workbench)
+ for n in spots:
+ var reach: float = n.reach
+ var c := Vector2(n.global_position.x, n.global_position.z)
+ var closest := INF
+ for cell in nav.free_cells_in(Rect2(c - Vector2.ONE * reach, Vector2.ONE * reach * 2.0)):
+ if walk[cell] < FarmNavigation.UNREACHABLE:
+ closest = minf(closest, nav.cell_center(cell).distance_to(c))
+ r.check(closest <= reach - 0.25, "the scarecrow can walk to within reach of %s (%.1f of %.1f m)" % [n.name, closest, reach])
+ r.check(sim.interactions.workbench != null and sim.zones.zone(FarmZone.Kind.WORK_AREA).contains(sim.interactions.workbench.global_position),
+ "the workbench stands in the work area")
+
+
+func _gathering(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var it := sim.interactions
+ var res := sim.campaign.state.resources
+ var tree := _node(it, "DeadTree")
+ var msgs: Array[String] = []
+ it.message.connect(func(t: String, _c: Color) -> void: msgs.append(t))
+ _stand_at(player, tree)
+ _hold(sim, 30)
+ r.check(res.pouch_total() == 0 and msgs.has("Gathering is for daytime"), "no gathering before the day starts (once per press: %d)" % msgs.size())
+ Input.action_release("interact")
+ sim.campaign.begin_day()
+ _step(sim, 1)
+ _hold(sim, 30)
+ r.check(it.gathering == tree and player.rooted and not it.can_shoot(), "holding interact gathers: rooted, no shooting")
+ _hold(sim, roundi(sim.config.gather_time * 60.0) - 30 + 2)
+ r.check(res.pouch["wood"] == tree.yield_amount and it.charges(tree) == tree.max_charges - 1,
+ "after %.1f s: +%d wood in the pouch, one charge used" % [sim.config.gather_time, tree.yield_amount])
+ _hold(sim, roundi(sim.config.gather_time * 60.0) + 4)
+ r.check(it.charges(tree) == 0 and res.pouch["wood"] == tree.yield_amount * 2, "holding on gathers again until the point runs out")
+ _hold(sim, 10)
+ r.check(it.gathering == null and msgs.has("Nothing left here; it grows back overnight"), "a used-up point can't be gathered")
+ # Next to both a used-up point and a full one, interact goes to the full one.
+ var logs := _node(it, "LogPile")
+ player.global_position = (tree.global_position + logs.global_position) * 0.5
+ player.global_position.y = 0.0
+ Input.action_release("interact")
+ _step(sim, 1)
+ var both := Vector2(player.global_position.x - tree.global_position.x, player.global_position.z - tree.global_position.z).length() <= tree.reach \
+ and Vector2(player.global_position.x - logs.global_position.x, player.global_position.z - logs.global_position.z).length() <= logs.reach
+ _hold(sim, 5)
+ r.check(both and it.gathering == logs, "between a used-up point and a full one, the full one is gathered")
+ Input.action_release("interact")
+ _step(sim, 1)
+ res.pouch["wood"] = tree.yield_amount * 2
+ Input.action_release("interact")
+ _step(sim, 1)
+ var snag := _node(it, "Snag")
+ _stand_at(player, snag)
+ _hold(sim, 40)
+ Input.action_release("interact")
+ _step(sim, 1)
+ r.check(it.gathering == null and it.charges(snag) == snag.max_charges and not player.rooted, "letting go early gathers nothing")
+ _hold(sim, 40)
+ sim.scarecrow.try_damage(1)
+ r.check(it.gathering == null, "a hit stops gathering")
+ sim.scarecrow.invulnerable_left = 0.0
+ sim.campaign.state.scarecrow_hp = sim.campaign.state.scarecrow_max_hp
+ Input.action_release("interact")
+ _step(sim, 1)
+ _hold(sim, 40)
+ sim.scarecrow.use_fear()
+ sim.scarecrow.fear_left = 0.0
+ r.check(it.gathering == null, "using fear stops gathering")
+ Input.action_release("interact")
+ _step(sim, 1)
+ res.add_to_pouch("scrap", res.pouch_room() - 1)
+ _hold(sim, 20)
+ r.check(it.gathering == null and msgs.has("Pouch full: drop it off at the supply shed") and it.charges(snag) == snag.max_charges,
+ "without room for the whole yield, nothing is gathered (and no charge is wasted)")
+ Input.action_release("interact")
+ _step(sim, 1)
+
+
+func _deposit_and_night(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var c := sim.campaign
+ var res := c.state.resources
+ var it := sim.interactions
+ var shed_before: Dictionary = res.shed.duplicate()
+ var pouch: Dictionary = res.pouch.duplicate()
+ var moved: Array[Dictionary] = []
+ it.deposited.connect(func(m: Dictionary) -> void: moved.append(m))
+ var shed := sim.zones.zone(FarmZone.Kind.SUPPLY_SHED)
+ player.global_position = shed.global_position + Vector3(0.0, 0.0, 2.0)
+ _step(sim, 1)
+ r.check(res.pouch_total() == 0 and moved.size() == 1 and res.shed["wood"] == int(shed_before["wood"]) + int(pouch["wood"])
+ and res.shed["scrap"] == int(shed_before["scrap"]) + int(pouch["scrap"]), "walking into the supply shed stores the pouch")
+ var tree := _node(it, "DeadTree")
+ var deadfall := _node(it, "Deadfall")
+ c.state.gather_charges["Deadfall"] = 0
+ deadfall.regen_per_night = 1
+ c.advance_phase()
+ c.advance_phase()
+ r.check(c.state.phase == P.NIGHT, "night falls")
+ _stand_at(player, _node(it, "LogPile"))
+ _hold(sim, 30)
+ r.check(it.gathering == null and res.pouch_total() == 0, "no gathering at night")
+ Input.action_release("interact")
+ _step(sim, 1)
+ c.advance_phase()
+ c.advance_phase()
+ r.check(c.state.phase == P.MORNING and it.charges(tree) == tree.max_charges and it.charges(deadfall) == 1,
+ "overnight the points grow back (a point regrowing 1 a night has 1 again)")
+ deadfall.regen_per_night = 20
+ # Retry brings back the morning's materials and points.
+ var morning := c.state.to_dict()
+ c.begin_day()
+ _stand_at(player, _node(it, "Wreck"))
+ _hold(sim, roundi(sim.config.gather_time * 60.0) + 2)
+ Input.action_release("interact")
+ _step(sim, 1)
+ r.check(res.pouch["scrap"] > 0, "scrap gathered on day 2")
+ c.advance_phase()
+ c.advance_phase()
+ c.state.scarecrow_hp = 0
+ _step(sim, 1)
+ c.retry_night()
+ _step(sim, 1)
+ r.check(c.state.resources.to_dict() == morning["resources"] and c.state.gather_charges == morning["gather_charges"],
+ "retry restores the morning's materials and gather points")
+
+
+func _patch_cost(r: GameTestRunner, sim: FarmSim) -> void:
+ var s := sim.campaign.state
+ var kit := sim.scarecrow
+ var denied: Array[Dictionary] = []
+ kit.patch_denied.connect(func(m: Dictionary) -> void: denied.append(m))
+ s.resources.shed["straw"] = 2
+ s.resources.pouch["straw"] = 0
+ s.scarecrow_hp = 5
+ Input.action_press("patch")
+ _step(sim, roundi(sim.config.patch_time * 60.0) + 2)
+ r.check(s.scarecrow_hp == 5 + sim.config.patch_heal and s.resources.available("straw") == 0, "a patch costs 2 straw")
+ _step(sim, 30)
+ r.check(not kit.patching and denied.size() == 1 and denied[0] == {"straw": 2}, "without straw the patch is refused, once per press")
+ Input.action_release("patch")
+ _step(sim, 1)
+ s.scarecrow_hp = s.scarecrow_max_hp
+
+
+func _stuffing(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var c := sim.campaign
+ var s := c.state
+ var it := sim.interactions
+ var bench := it.workbench
+ var menu := sim.upgrade_panel
+ var add := int(sim.config.upgrades["straw_stuffing"]["add"])
+ var msgs: Array[String] = []
+ it.message.connect(func(t: String, _col: Color) -> void: msgs.append(t))
+ menu.message.connect(func(t: String, _col: Color) -> void: msgs.append(t))
+ player.global_position = bench.global_position + Vector3(0.0, 0.0, 1.2)
+ _press(sim)
+ r.check(not menu.is_open and msgs[-1] == "The work area is for daytime", "no upgrades during the morning review")
+ c.begin_day()
+ s.resources.shed = {"wood": 0, "scrap": 0, "straw": 3}
+ _press(sim)
+ r.check(menu.is_open and player.rooted and not it.can_shoot(), "interact at the workbench opens the upgrade menu; the scarecrow stands still")
+ var row := menu._rows["straw_stuffing"] as Button
+ r.check(row.disabled and row.text.contains("Need 4 wood, 9 straw more"), "short of materials, the row says what's missing: '%s'" % row.text)
+ s.resources.shed = {"wood": 3, "scrap": 0, "straw": 12}
+ s.resources.pouch = {"wood": 1, "scrap": 0, "straw": 0}
+ menu.refresh()
+ var max_hp := s.scarecrow_max_hp
+ row.pressed.emit()
+ r.check(Upgrades.owned(s, "straw_stuffing") and s.scarecrow_max_hp == max_hp + add and s.scarecrow_hp == s.scarecrow_max_hp,
+ "Straw stuffing: +%d max HP (%s)" % [add, msgs[-1]])
+ r.check(s.resources.shed == {"wood": 0, "scrap": 0, "straw": 0} and s.resources.pouch["wood"] == 0, "it costs 12 straw and 4 wood")
+ r.check(row.disabled and row.text.contains("Done"), "it can only be bought once")
+ _press(sim)
+ r.check(not menu.is_open and not player.rooted, "interact again closes the menu")
+ _press(sim)
+ menu.close()
+
+
+func _node(it: Interactions, node_name: String) -> GatherNode:
+ for n in it.nodes:
+ if n.name == node_name:
+ return n
+ return null
+
+
+## Puts the scarecrow next to a gather point, within its reach.
+func _stand_at(player: PlayerCharacter, n: GatherNode) -> void:
+ var to_center := Vector3(n.global_position.x, 0.0, n.global_position.z)
+ player.global_position = to_center + Vector3(n.reach * 0.7, 0.0, 0.0)
+
+
+func _hold(sim: FarmSim, ticks: int) -> void:
+ Input.action_press("interact")
+ _step(sim, ticks)
+
+
+func _press(sim: FarmSim) -> void:
+ Input.action_release("interact")
+ _step(sim, 1)
+ Input.action_press("interact")
+ _step(sim, 1)
+ Input.action_release("interact")
+ _step(sim, 1)
+
+
+func _step(sim: FarmSim, n: int) -> void:
+ for i in n:
+ sim.step(DT)
diff --git a/game/tests/test_economy.gd.uid b/game/tests/test_economy.gd.uid
new file mode 100644
index 0000000..0b0f820
--- /dev/null
+++ b/game/tests/test_economy.gd.uid
@@ -0,0 +1 @@
+uid://ceja0c6gemx3k
diff --git a/game/tests/test_farm_layout.gd b/game/tests/test_farm_layout.gd
index 2e32d3c..9dd3c09 100644
--- a/game/tests/test_farm_layout.gd
+++ b/game/tests/test_farm_layout.gd
@@ -1,8 +1,10 @@
extends RefCounted
## The playable farm: every zone exists once inside the 60 x 60 m map without overlapping,
-## lookups by position, the crop units, the perimeter markers, a perimeter fence without holes
-## except its gaps, ground navigation from every gap to every zone, scarecrow-only bounds,
-## zone-to-zone travel times (printed as the table kept in game/LAYOUT.md), and the zone banner.
+## lookups by position, the crop units, the farm's edge (where enemies arrive) and the gaps in
+## what's left of the perimeter fence (the north and east sides, without holes except their gaps;
+## the south and west are open), ground navigation from anywhere on the edge to every zone,
+## scarecrow-only bounds, zone-to-zone travel times (printed as the table kept in
+## game/LAYOUT.md), and the zone banner.
const RUN_SPEED := 5.0 # PlayerCharacter.run_speed
const MAX_TRAVEL := 12.0
@@ -73,52 +75,84 @@ func _crops(r: GameTestRunner, zones: FarmZones) -> void:
func _markers(r: GameTestRunner, zones: FarmZones) -> void:
var map := zones.playable
- var gaps := zones.markers(FarmMarker.Kind.GAP)
- r.check(gaps.size() == 6, "6 perimeter gaps (got %d)" % gaps.size())
+ var gaps := zones.gaps()
+ r.check(gaps.size() == 3, "3 gaps in what's left of the perimeter fence (got %d)" % gaps.size())
for m in gaps:
var p := Vector2(m.global_position.x, m.global_position.z)
r.check(not map.has_point(p) and map.grow(4.0).has_point(p), "%s sits just outside the perimeter" % m.name)
- var crows := zones.markers(FarmMarker.Kind.CROW)
- r.check(crows.size() == 4, "4 crow approach directions (got %d)" % crows.size())
- for m in crows:
- r.check(not map.grow(4.0).has_point(Vector2(m.global_position.x, m.global_position.z)), "%s is well outside the fence" % m.name)
+ var cfg := load("res://game/resources/game_config.tres") as GameConfig
+ var edge := zones.edge(cfg.spawn_margin)
+ var on_edge := true
+ for k in 40:
+ var p := zones.edge_point(k / 40.0 + 0.01, cfg.spawn_margin)
+ on_edge = on_edge and FarmZones.nearest_on_outline(edge, p).distance_to(p) < 1e-3
+ r.check(on_edge and zones.edge_point(0.0, cfg.spawn_margin).is_equal_approx(edge.position)
+ and zones.edge_point(0.5, cfg.spawn_margin).is_equal_approx(edge.end), "edge_point walks the farm's edge, %.0f m out" % cfg.spawn_margin)
+ var names := [zones.side_of(Vector2(17.0, -48.0)), zones.side_of(Vector2(50.0, -40.0)), zones.side_of(Vector2(-16.0, -15.0)),
+ zones.side_of(Vector2(31.0, 18.0)), zones.side_of(map.get_center())]
+ r.check(names == ["north", "north-east", "west", "south-east", ""], "the farm's sides are named by thirds: %s" % [names])
-## Every free cell on the fence line is part of a gap (near a gap marker), and every gap is open.
+## What's left of the perimeter fence (the north and east sides) has no holes except its gaps, and
+## every gap is open; the south and west sides are open ground.
func _fence(r: GameTestRunner, zones: FarmZones, nav: FarmNavigation) -> void:
var map := zones.playable
- var gaps := zones.markers(FarmMarker.Kind.GAP)
+ var gaps := zones.gaps()
var corners := [map.position, Vector2(map.end.x, map.position.y), map.end, Vector2(map.position.x, map.end.y)]
var holes: Array[Vector2] = []
- for side in 4:
+ var free_share: Array[float] = []
+ for side in 4: # north, east, south, west
var a: Vector2 = corners[side]
var b: Vector2 = corners[(side + 1) % 4]
var steps := ceili(a.distance_to(b) / (CELL * 0.5))
+ var free := 0
for k in steps + 1:
var p := a.lerp(b, k / float(steps))
- if nav.is_free(nav.cell_of(p.x, p.y)) and not gaps.any(func(m: FarmMarker) -> bool:
+ if not nav.is_free(nav.cell_of(p.x, p.y)):
+ continue
+ free += 1
+ if side < 2 and not gaps.any(func(m: FarmMarker) -> bool:
return Vector2(m.global_position.x, m.global_position.z).distance_to(p) < 4.5):
holes.append(p)
- r.check(holes.is_empty(), "the perimeter fence has no holes outside its gaps %s" % [holes.slice(0, 5)])
+ free_share.append(free / float(steps + 1))
+ r.check(holes.is_empty(), "the north and east fence has no holes outside its gaps %s" % [holes.slice(0, 5)])
+ r.check(free_share[2] > 0.9 and free_share[3] > 0.5, "the south and west sides are open (%.0f%% and %.0f%% free)" % [free_share[2] * 100.0, free_share[3] * 100.0])
for m in gaps:
var g := Vector2(m.global_position.x, m.global_position.z)
var edge := Vector2(clampf(g.x, map.position.x, map.end.x), clampf(g.y, map.position.y, map.end.y))
r.check(nav.is_free(nav.cell_of(edge.x, edge.y)), "%s is open for ground enemies" % m.name)
+## Ground enemies arrive anywhere on the edge with a route in (as FarmSim picks them: a route to
+## the pen) and can walk from there to every zone; the lengths printed are from the middle of each
+## side (the table in game/LAYOUT.md).
func _enemy_routes(r: GameTestRunner, zones: FarmZones, nav: FarmNavigation) -> void:
- var gaps := zones.markers(FarmMarker.Kind.GAP)
+ var cfg := load("res://game/resources/game_config.tres") as GameConfig
+ var edge := zones.edge(cfg.spawn_margin)
+ var ring := nav.free_cells_on_outline(edge, CELL * 0.75)
+ var pen := nav.distance_field(nav.free_cells_in(zones.zone(FarmZone.Kind.ANIMAL_PEN).rect().grow(-1.0)))
+ var spawns := PackedInt32Array()
+ for c in ring:
+ if pen[c] < FarmNavigation.UNREACHABLE:
+ spawns.append(c)
+ r.check(spawns.size() > ring.size() * 0.9, "enemies can arrive on nearly all of the farm's edge (%d of %d free cells)" % [spawns.size(), ring.size()])
+ var mid := edge.get_center()
+ var middles := {"north": Vector2(mid.x, edge.position.y), "east": Vector2(edge.end.x, mid.y), "south": Vector2(mid.x, edge.end.y), "west": Vector2(edge.position.x, mid.y)}
for zone in zones.zones():
var goal := nav.free_cells_in(zone.rect())
r.check(goal.size() > 0, "%s has walkable ground (%d cells)" % [zone.display_name, goal.size()])
var field := nav.distance_field(goal)
+ var cut_off := 0
+ for s in spawns:
+ if field[s] >= FarmNavigation.UNREACHABLE:
+ cut_off += 1
+ r.check(cut_off == 0, "ground enemies can walk from anywhere on the edge to the %s and back (%d cells can't)" % [zone.display_name, cut_off])
var lengths: Array[String] = []
- for m in gaps:
- var c := nav.nearest_free(nav.cell_of(m.global_position.x, m.global_position.z))
- var reachable := c >= 0 and field[c] < FarmNavigation.UNREACHABLE
- r.check(reachable, "ground enemies can walk from %s to the %s and back" % [m.name, zone.display_name])
- lengths.append("%.0f" % nav.meters(field[c]) if reachable else "-")
- r.info("%-12s from gaps (m): %s" % [zone.display_name, ", ".join(lengths)])
+ for side: String in middles:
+ var at: Vector2 = middles[side]
+ var m := nav.nearest_free(nav.cell_of(at.x, at.y))
+ lengths.append("%s %.0f" % [side, nav.meters(field[m])] if m >= 0 and field[m] < FarmNavigation.UNREACHABLE else "%s -" % side)
+ r.info("%-12s from the edge (m): %s" % [zone.display_name, ", ".join(lengths)])
func _scarecrow(r: GameTestRunner, farm: Node3D, zones: FarmZones) -> void:
@@ -127,16 +161,26 @@ func _scarecrow(r: GameTestRunner, farm: Node3D, zones: FarmZones) -> void:
r.check(zones.playable.has_point(Vector2(player.global_position.x, player.global_position.z)), "the scarecrow starts inside the map")
r.check(bounds.collision_layer == 4 and (player.collision_mask & 4) != 0 and (player.collision_mask & 1) != 0,
"PlayerBounds is on the player_bounds layer, which only the scarecrow collides with")
- # Stand in each gap and try to walk out: the invisible wall stops the scarecrow.
+ # Stand in each gap and walk out: nothing stops the scarecrow (the gathering areas outside).
var start := player.global_transform
- for m in zones.markers(FarmMarker.Kind.GAP):
+ for m in zones.gaps():
var g := Vector2(m.global_position.x, m.global_position.z)
var map := zones.playable
var edge := Vector2(clampf(g.x, map.position.x, map.end.x), clampf(g.y, map.position.y, map.end.y))
var out := (g - edge).normalized()
- player.global_position = Vector3(edge.x - out.x * 1.0, 0.3, edge.y - out.y * 1.0)
+ player.global_position = Vector3(edge.x - out.x * 1.0, 0.6, edge.y - out.y * 1.0) # above the driveway's road
var hit := player.move_and_collide(Vector3(out.x, 0.0, out.y) * 3.0, true)
- r.check(hit != null, "the scarecrow can't walk out through %s" % m.name)
+ r.check(hit == null, "the scarecrow can walk out through %s" % m.name)
+ # ...but not past the old farm's outer fences: the invisible walls are there now.
+ var roam := zones.roam
+ var sides := {"north": [Vector2(-20.0, roam.position.y + 1.0), Vector2(0, -1)], "south": [Vector2(5.0, roam.end.y - 1.0), Vector2(0, 1)],
+ "west": [Vector2(roam.position.x + 1.0, 0.0), Vector2(-1, 0)], "east": [Vector2(roam.end.x - 1.0, -30.0), Vector2(1, 0)]}
+ for side: String in sides:
+ var at: Vector2 = sides[side][0]
+ var dir: Vector2 = sides[side][1]
+ player.global_position = Vector3(at.x, 0.3, at.y)
+ var hit := player.move_and_collide(Vector3(dir.x, 0.0, dir.y) * 3.0, true)
+ r.check(hit != null, "the scarecrow can't go past the %s edge of the roaming area" % side)
player.global_transform = start
diff --git a/game/tests/test_farm_state.gd b/game/tests/test_farm_state.gd
index 2aa84ad..47d32ef 100644
--- a/game/tests/test_farm_state.gd
+++ b/game/tests/test_farm_state.gd
@@ -1,6 +1,7 @@
extends RefCounted
-## FarmState: creation from config, exact to_dict/from_dict round trips (also through JSON),
-## rejection of invalid data, snapshot independence, and night loss records.
+## FarmState: creation from config (all three asset categories and the pen's gate), exact
+## to_dict/from_dict round trips (also through JSON), rejection of invalid data, snapshot
+## independence, and night loss records for every category.
func run(r: GameTestRunner) -> void:
@@ -10,7 +11,11 @@ func run(r: GameTestRunner) -> void:
r.check(s.phase == CampaignController.Phase.MORNING, "a new farm starts in the morning")
r.check(s.scarecrow_hp == cfg.scarecrow_max_hp and s.scarecrow_max_hp == cfg.scarecrow_max_hp, "scarecrow starts at full HP")
r.check(s.crops == cfg.start_crops and s.crops_total == cfg.start_crops, "crops start at the configured count")
- r.check(s.animals_total == 0 and s.supplies_total == 0, "animals and supplies are not in play until Step 8")
+ r.check(s.animals == cfg.start_animals and s.animals_total == cfg.start_animals, "animals start at the configured count")
+ var stock := cfg.start_wood + cfg.start_scrap + cfg.start_straw
+ r.check(s.supplies == stock and s.supplies_total == stock and not s.shed_raided, "supplies are the shed's starting stock (%d)" % stock)
+ r.check(s.structures.size() == cfg.start_structures.size() and s.structures[0]["type"] == "gate"
+ and s.structures[0]["hp"] == cfg.gate_hp and s.next_structure_id == 2, "the pen's gate stands from the start")
r.check(s.is_valid(), "a new farm is valid")
# A state with every field away from its default.
@@ -20,13 +25,15 @@ func run(r: GameTestRunner) -> void:
s.phase_time_left = 12.5
s.scarecrow_hp = 6
s.crops_total = 40
- s.crops = 31
- s.animals_total = 8
- s.animals = 5
+ for id in [3, 7, 8, 12, 19, 20, 21, 33, 40]:
+ s.lose_crop(id)
+ s.night_events = {"crops_stolen": 2, "crops_recovered": 1, "animals_strayed": 1, "supplies_lost": 5}
+ for id in [2, 5, 7]:
+ s.lose_animal(id)
s.supplies_total = 120
- s.supplies = 77
- s.night_log.append({"night": 1, "crops_lost": 4, "animals_lost": 0, "supplies_lost": 0})
- s.night_log.append({"night": 2, "crops_lost": 5, "animals_lost": 3, "supplies_lost": 43})
+ s.shed_raided = true
+ s.night_log.append(_entry(1, 4, 0, 0))
+ s.night_log.append(_entry(2, 5, 3, 43))
var d := s.to_dict()
var copy := FarmState.from_dict(d)
@@ -43,17 +50,35 @@ func run(r: GameTestRunner) -> void:
_night_records(r, cfg)
+func _entry(night: int, crops: int, animals: int, supplies: int) -> Dictionary:
+ var e := {"night": night}
+ for key in FarmState.LOG_KEYS:
+ if key != "night":
+ e[key] = 0
+ e["crops_lost"] = crops
+ e["animals_lost"] = animals
+ e["supplies_lost"] = supplies
+ e["crops_stolen"] = crops + 1
+ e["animals_stolen"] = animals
+ e["supplies_stolen"] = supplies + 5
+ return e
+
+
func _rejects(r: GameTestRunner, good: Dictionary) -> void:
var cases := {
"another version": func(d: Dictionary) -> void: d["version"] = FarmState.VERSION + 1,
- "a missing key": func(d: Dictionary) -> void: d.erase("crops"),
+ "a missing key": func(d: Dictionary) -> void: d.erase("lost_crops"),
"an unknown phase": func(d: Dictionary) -> void: d["phase"] = 42,
- "more crops than the total": func(d: Dictionary) -> void: d["crops"] = d["crops_total"] + 1,
- "negative animals": func(d: Dictionary) -> void: d["animals"] = -1,
+ "a lost crop id beyond the total": func(d: Dictionary) -> void: d["lost_crops"] = [d["crops_total"] + 1],
+ "a crop lost twice": func(d: Dictionary) -> void: d["lost_crops"] = [3, 3],
+ "an unknown night event": func(d: Dictionary) -> void: d["night_events"] = {"cows_tipped": 1},
+ "a lost animal id beyond the total": func(d: Dictionary) -> void: d["lost_animals"] = [d["animals_total"] + 1],
+ "an animal lost twice": func(d: Dictionary) -> void: d["lost_animals"] = [2, 2],
+ "negative supplies in play": func(d: Dictionary) -> void: d["supplies_total"] = -1,
"HP above max": func(d: Dictionary) -> void: d["scarecrow_hp"] = d["scarecrow_max_hp"] + 1,
"night 0": func(d: Dictionary) -> void: d["night"] = 0,
"more nights survived than played": func(d: Dictionary) -> void: d["nights_survived"] = d["night"] + 1,
- "a malformed night log": func(d: Dictionary) -> void: d["night_log"] = [{"night": 1}],
+ "a malformed night log": func(d: Dictionary) -> void: d["night_log"] = [{"night": 1, "crops_lost": 0, "animals_lost": 0, "supplies_lost": 0}],
}
for name: String in cases:
var d := good.duplicate(true)
@@ -64,8 +89,33 @@ func _rejects(r: GameTestRunner, good: Dictionary) -> void:
func _night_records(r: GameTestRunner, cfg: GameConfig) -> void:
var s := FarmState.create(cfg)
var start := s.asset_counts()
- s.crops -= 7
+ for id in range(1, 8):
+ s.lose_crop(id)
+ s.lose_animal(3)
+ s.record_event("crops_stolen")
+ s.record_event("crops_stolen")
+ s.record_event("crops_recovered")
+ s.record_event("supplies_stolen", 5)
+ s.record_event("supplies_lost", 5)
+ s.resources.shed["wood"] = 99 # stored and spent materials don't count as losses
s.log_night(start)
var e: Dictionary = s.night_log[0]
- r.check(s.night_log.size() == 1 and e["night"] == 1 and e["crops_lost"] == 7 and e["animals_lost"] == 0,
- "log_night records the losses since the night started")
+ r.check(s.night_log.size() == 1 and e["night"] == 1 and e["crops_lost"] == 7 and e["animals_lost"] == 1,
+ "log_night records the crops and animals lost since the night started")
+ r.check(e["supplies_lost"] == 5 and e["supplies_stolen"] == 5, "supplies lost are the units carried off (%d)" % e["supplies_lost"])
+ r.check(e["crops_stolen"] == 2 and e["crops_recovered"] == 1 and s.night_events.is_empty(),
+ "log_night copies the night's theft events and clears them")
+
+ s = FarmState.create(cfg)
+ r.check(s.lose_crop(5) and not s.lose_crop(5) and not s.lose_crop(0) and not s.lose_crop(s.crops_total + 1),
+ "lose_crop accepts each known unit once")
+ r.check(s.crops == s.crops_total - 1 and s.is_crop_lost(5) and not s.is_crop_lost(6), "crops is derived from the lost units")
+ r.check(s.lose_animal(1) and not s.lose_animal(1) and not s.lose_animal(0) and s.animals == s.animals_total - 1,
+ "lose_animal accepts each known animal once; animals is derived")
+ s.supplies_in_transit = 4
+ r.check(s.supplies == s.resources.shed_total() + 4, "supplies count the shed's stock and the sacks still on the farm")
+ s.supplies_in_transit = 0
+ s.animals_total = 0
+ s.supplies_total = 0
+ s.lose_all_crops()
+ r.check(s.crops == 0 and s.is_stripped(), "losing every crop unit strips a crops-only farm")
diff --git a/game/tests/test_flow.gd b/game/tests/test_flow.gd
new file mode 100644
index 0000000..5d10f6e
--- /dev/null
+++ b/game/tests/test_flow.gd
@@ -0,0 +1,385 @@
+extends RefCounted
+## The whole game through its entry scene (main.tscn, with test save and settings paths): the
+## main menu over the paused farm; New vacation, Continue, and their questions; pausing freezes
+## the simulation tick; settings apply and persist from the pause menu; Restart the night and
+## Save & quit to menu put the farm back at the saved morning without touching the save; a
+## damaged save can't be continued; the failure screen and Retry; the farmers' return and the
+## final assessment; the first day's and night's tips; and the sounds hooked to the game.
+
+const P := CampaignController.Phase
+const SAVE := "user://test_flow_save.json"
+const SETTINGS := "user://test_flow_settings.cfg"
+const DT := 1.0 / 60.0
+
+var r: GameTestRunner
+var main: Main
+var sim: FarmSim
+var c: CampaignController
+
+
+func run(p_r: GameTestRunner) -> void:
+ r = p_r
+ _clean()
+ main = (load("res://game/scenes/main.tscn") as PackedScene).instantiate() as Main
+ main.save_path = SAVE
+ main.settings_path = SETTINGS
+ r.root.add_child(main)
+ await r.process_frame
+ await r.physics_frame
+ sim = main.sim
+ c = sim.campaign
+ await _title_screen()
+ await _pause()
+ await _settings()
+ await _restart_and_quit_to_menu()
+ await _continue_and_new()
+ await _tutorial()
+ await _failure()
+ await _ending()
+ _audio()
+ main.queue_free()
+ r.paused = false
+ await r.process_frame
+ _clean()
+
+
+func _clean() -> void:
+ for p in [SAVE, SAVE + ".tmp", SETTINGS]:
+ if FileAccess.file_exists(p):
+ DirAccess.remove_absolute(ProjectSettings.globalize_path(p))
+
+
+func _press(action: String) -> void:
+ for pressed in [true, false]:
+ var e := InputEventAction.new()
+ e.action = StringName(action)
+ e.pressed = pressed
+ Input.parse_input_event(e)
+ await r.process_frame
+ await r.process_frame
+
+
+func _hud_visible() -> bool:
+ return (main.farm.get_node("Hud") as CanvasLayer).visible
+
+
+func _same(a: Dictionary, b: Dictionary) -> bool:
+ return JSON.stringify(a, "", true, true) == JSON.stringify(b, "", true, true)
+
+
+func _title_screen() -> void:
+ r.check(main.screen == Main.Screen.MENU and r.paused and main.main_menu.visible and not _hud_visible()
+ and main.get_viewport().get_camera_3d() == main._menu_camera, "the game starts at the main menu: the farm paused behind it, no HUD")
+ r.check(main.main_menu.continue_button.disabled and main.main_menu.save_note.text == "No saved vacation",
+ "with nothing to continue, Continue is off and says so")
+ await r.process_frame
+ r.check(main.main_menu.new_button.has_focus(), "and New vacation has the focus (keyboard and gamepad)")
+ r.check(sim.audio.music_track == "farm" and (sim.audio._music["farm"] as AudioStreamPlayer).playing,
+ "\"On the Farm\" plays on the title screen (the paused farm's morning)")
+ r.check(not SaveGame.exists(SAVE), "the farm behind the menu isn't saved")
+ r.check(ProjectSettings.get_setting("gui/theme/custom") == "res://game/resources/ui_theme.tres"
+ and load("res://game/resources/ui_theme.tres") is Theme and main.main_menu.new_button.has_theme_stylebox("focus"),
+ "the UI theme is the project's default")
+ main.main_menu.new_button.pressed.emit()
+ var saved := SaveGame.read(SAVE)
+ r.check(main.screen == Main.Screen.PLAYING and not r.paused and _hud_visible() and c.state.phase == P.MORNING
+ and sim.review_panel.visible and main.get_viewport().get_camera_3d() == sim.camera,
+ "New vacation (no save to replace) starts at once: the morning screen, the HUD, the follow camera")
+ r.check(saved.status == SaveGame.Status.OK and saved.state.night == 1, "and saves the new vacation's first morning")
+
+
+func _pause() -> void:
+ c.begin_day()
+ for i in 3:
+ await r.physics_frame
+ r.check(c.state.phase == P.DAY and c.state.phase_time_left < c.phase_length(P.DAY), "the day's clock runs while playing")
+ await _press("pause")
+ r.check(main.screen == Main.Screen.PAUSED and r.paused and main.pause_menu.visible, "Escape / Start pauses")
+ var t := c.state.phase_time_left
+ var player := sim.player.global_position
+ for i in 10:
+ await r.physics_frame
+ r.check(c.state.phase_time_left == t and sim.player.global_position == player, "pausing freezes the simulation tick")
+ r.check(main.pause_menu._where.text == "Night 1 of 5 · Day" and main.pause_menu._note.text.contains("morning of day 1"),
+ "the pause menu says where you are and what Continue picks up ('%s')" % main.pause_menu._where.text)
+ r.check(main.pause_menu.resume_button.has_focus(), "with Resume focused")
+ await _press("pause")
+ r.check(main.screen == Main.Screen.PLAYING and not r.paused and not main.pause_menu.visible, "Escape / Start again resumes")
+ await r.physics_frame
+ await r.physics_frame
+ r.check(c.state.phase_time_left < t, "and the clock runs again")
+
+
+func _settings() -> void:
+ main.pause()
+ main.pause_menu.settings_button.pressed.emit()
+ var menu := main.settings_menu
+ r.check(menu.visible and menu.is_open, "Settings opens from the pause menu")
+ await r.process_frame
+ (menu.controls["volume/Music"] as HSlider).value = 0.3
+ var music := AudioServer.get_bus_index("Music")
+ r.check(is_equal_approx(GameSettings.load_from(SETTINGS).volume["Music"], 0.3)
+ and is_equal_approx(AudioServer.get_bus_volume_db(music), linear_to_db(0.3)), "a change applies and is saved at once")
+ (menu.controls["show_tips"] as CheckBox).button_pressed = false
+ r.check(not sim.tutorial.enabled and not GameSettings.load_from(SETTINGS).show_tips, "turning tips off reaches the tutorial")
+ (menu.controls["show_tips"] as CheckBox).button_pressed = true
+ (menu.controls["aim_dead_zone"] as HSlider).value = 0.4
+ r.check(is_equal_approx(sim.config.aim_dead_zone, 0.4), "the aim dead zone reaches the gun's config")
+ r.check(SettingsMenu.describe_keys(["fear"]) == "Q" and SettingsMenu.describe_pad(["fear"]) == "LB"
+ and SettingsMenu.describe_keys(["fire"]) == "Left mouse" and SettingsMenu.describe_pad(["fire"]).contains("RT")
+ and SettingsMenu.describe_keys(["hide_tips"]) == "Backspace" and SettingsMenu.describe_pad(["pause"]) == "Start",
+ "the bindings list reads the real input map")
+ await _press("ui_cancel")
+ r.check(not menu.visible and main.screen == Main.Screen.PAUSED and r.paused, "Escape / B closes Settings back to the pause menu")
+ await r.process_frame
+ r.check(main.pause_menu.settings_button.has_focus(), "with the focus back on Settings")
+ main.settings_menu.open(main.settings)
+ var reset := menu.back_button.get_parent().get_child(1) as Button
+ reset.pressed.emit()
+ r.check(is_equal_approx(GameSettings.load_from(SETTINGS).volume["Music"], GameSettings.DEFAULT_VOLUME["Music"])
+ and is_equal_approx((menu.controls["volume/Music"] as HSlider).value, GameSettings.DEFAULT_VOLUME["Music"]),
+ "Reset to defaults resets and saves")
+ menu.back_button.pressed.emit()
+ main.resume()
+
+
+func _restart_and_quit_to_menu() -> void:
+ var morning := SaveGame.read(SAVE).state.to_dict()
+ c.state.resources.pouch["wood"] = 4
+ main.pause()
+ main.pause_menu.restart_button.pressed.emit()
+ r.check(main.confirm.is_open and main.confirm.message.text.contains("Restart night 1") and main.screen == Main.Screen.PAUSED,
+ "Restart the night asks first")
+ await r.process_frame
+ r.check(main.confirm.no_button.has_focus(), "with Cancel focused")
+ main.confirm.yes_button.pressed.emit()
+ r.check(main.screen == Main.Screen.PLAYING and not r.paused and c.state.phase == P.MORNING and _same(c.state.to_dict(), morning),
+ "and restarts from the saved morning")
+ c.begin_day()
+ c.state.resources.pouch["scrap"] = 3
+ var file := FileAccess.get_file_as_string(SAVE)
+ main.pause()
+ main.pause_menu.menu_button.pressed.emit()
+ r.check(main.screen == Main.Screen.MENU and r.paused and main.main_menu.visible and not _hud_visible()
+ and c.state.phase == P.MORNING and c.state.resources.pouch["scrap"] == 0,
+ "Save & quit to menu: back at the menu, the farm at the saved morning")
+ r.check(FileAccess.get_file_as_string(SAVE) == file, "and the save itself is untouched")
+ r.check(not main.main_menu.continue_button.disabled and main.main_menu.save_note.text.begins_with("Morning of day 1 of 5"),
+ "Continue now offers that morning ('%s')" % main.main_menu.save_note.text)
+ await r.process_frame
+ r.check(main.main_menu.continue_button.has_focus(), "and has the focus")
+
+
+func _continue_and_new() -> void:
+ main.main_menu.continue_button.pressed.emit()
+ r.check(main.screen == Main.Screen.PLAYING and _hud_visible() and c.state.phase == P.MORNING
+ and _same(c.state.to_dict(), SaveGame.read(SAVE).state.to_dict()), "Continue resumes at the saved morning")
+ main.to_menu()
+ main.main_menu.new_button.pressed.emit()
+ r.check(main.confirm.is_open and main.confirm.message.text.contains("replaces your saved one") and main.screen == Main.Screen.MENU,
+ "New vacation over a save asks first")
+ await _press("ui_cancel")
+ r.check(not main.confirm.is_open and main.screen == Main.Screen.MENU, "Escape / B cancels")
+ main.main_menu.new_button.pressed.emit()
+ main.confirm.yes_button.pressed.emit()
+ r.check(main.screen == Main.Screen.PLAYING and c.state.night == 1 and c.state.night_log.is_empty(), "confirming starts the new vacation")
+ main.to_menu()
+ var f := FileAccess.open(SAVE, FileAccess.WRITE)
+ f.store_string("{\"game\": \"harvest-season\", \"state\": {\"version\": 3}}")
+ f.close()
+ main.show_main_menu()
+ r.check(main.main_menu.continue_button.disabled and main.main_menu.save_note.text.contains("damaged"),
+ "a damaged save can't be continued, and the menu says why")
+ r.check(not main.continue_vacation() and main.screen == Main.Screen.MENU, "Continue refuses it")
+ main.main_menu.new_button.pressed.emit()
+ r.check(main.screen == Main.Screen.PLAYING and SaveGame.read(SAVE).status == SaveGame.Status.OK,
+ "New vacation doesn't ask about a damaged save and replaces it")
+
+
+func _tutorial() -> void:
+ var t := sim.tutorial
+ t.done = {}
+ t.dismissed = false
+ t._process(0.0)
+ r.check(t.current == "" and not t._box.visible, "no tips during the morning screen")
+ c.begin_day()
+ t._process(0.0)
+ r.check(t.current == "move" and t._box.visible and t._text.text.contains("[W A S D]"), "day 1 starts with how to move")
+ sim.player.global_position += Vector3(5.0, 0.0, 0.0)
+ t._process(0.0)
+ r.check(t.done.has("move") and t._text.text.begins_with("Done!"), "moving finishes it (and says so)")
+ t._process(1.0)
+ t._process(0.0)
+ r.check(t.current == "gather", "then gathering")
+ c.state.resources.pouch["wood"] = 2
+ c.state.record_event("gathered_wood", 2)
+ t._process(0.0)
+ t._process(1.0)
+ t._process(0.0)
+ r.check(t.current == "store", "then storing at the shed, once the pouch has something")
+ sim.interactions.deposited.emit({"wood": 2})
+ c.state.resources.pouch["wood"] = 0
+ t._process(1.0)
+ t._process(0.0)
+ r.check(t.current == "build", "then building")
+ c.state.record_event("structures_built")
+ t._process(0.0)
+ t._process(1.0)
+ t._process(0.0)
+ r.check(t.current == "" and not t._box.visible, "and nothing more by day")
+ c.advance_phase()
+ t._process(0.0)
+ r.check(t.current == "dusk" and t._text.text.contains("nightfall"), "dusk says when and where the thieves come")
+ c.advance_phase()
+ sim.spawn_enemy(EnemySystem.TYPE_CROW)
+ t._process(0.0)
+ t._process(1.0)
+ t._process(0.0)
+ r.check(t.current == "shoot", "with an enemy in at night: how to shoot")
+ c.state.scarecrow_hp -= 1
+ t._process(0.0)
+ r.check(t.current == "patch", "hurt: how to patch up (more urgent than shooting)")
+ c.state.scarecrow_hp += 1
+ await _press("hide_tips")
+ t._process(0.0)
+ r.check(t.dismissed and not t._box.visible, "[Backspace / Back] hides the tips")
+ t.dismissed = false
+ t.enabled = false
+ t._process(0.0)
+ r.check(not t._box.visible, "and with tips off in Settings there are none")
+ t.enabled = true
+ c.retry_night()
+
+
+func _failure() -> void:
+ var morning := SaveGame.read(SAVE).state.to_dict()
+ var panel := sim.end_panel
+ c.begin_day()
+ c.advance_phase()
+ c.advance_phase()
+ r.check(c.state.phase == P.NIGHT, "night 1")
+ c.state.scarecrow_hp = 0
+ c.tick(DT)
+ panel._process(EndPanel.DELAY + 0.1)
+ r.check(c.state.phase == P.GAME_OVER and panel.is_visible_in_tree() and panel.mode == "failure" and panel._title.text == "The scarecrow has fallen"
+ and panel._rating.text.begins_with("Night 1 of 5: Crows at the crops"), "the failure screen gives the cause and the night ('%s')" % panel._rating.text)
+ r.check(panel._detail.text.contains("You kept the farm for 0 nights.") and panel._detail.text.contains("Left: 30 of 30 crops")
+ and panel._detail.text.contains("Tonight: "), "what was kept, what's left, and what tonight cost")
+ r.check(panel._retry.visible and panel._retry.has_focus() and panel._menu.visible and not panel._new.visible
+ and panel._retry.text.contains("morning of day 1"), "Retry the night (focused) and Main menu")
+ panel._retry.pressed.emit()
+ r.check(c.state.phase == P.MORNING and not panel.visible and _same(c.state.to_dict(), morning), "Retry restores the saved morning")
+ c.begin_day()
+ c.state.strip()
+ c.tick(DT)
+ panel._process(EndPanel.DELAY + 0.1)
+ r.check(panel.mode == "failure" and panel._title.text == "The farm was stripped bare", "a stripped farm says so")
+ panel._menu.pressed.emit()
+ r.check(main.screen == Main.Screen.MENU and main.main_menu.visible and c.state.phase == P.MORNING and not panel.visible,
+ "Main menu goes back to the menu")
+ main.main_menu.continue_button.pressed.emit()
+ r.check(main.screen == Main.Screen.PLAYING and _same(c.state.to_dict(), morning), "and Continue retries the failed night's morning")
+
+
+func _ending() -> void:
+ var cfg := c.config
+ var s := FarmState.create(cfg)
+ s.night = cfg.campaign_nights
+ s.nights_survived = cfg.campaign_nights - 1
+ GameTestRunner.lose_crops(s, 2)
+ for n in range(1, cfg.campaign_nights):
+ var e := {"night": n, "crops_lost": 1 if n <= 2 else 0, "animals_lost": 0}
+ for k in FarmState.EVENTS:
+ e[k] = 0
+ e["killed_crow"] = 10
+ e["killed_thief"] = 2
+ e["gathered_wood"] = 12
+ s.night_log.append(e)
+ c.load_state(s)
+ r.check(SaveGame.read(SAVE).state.night == cfg.campaign_nights, "the last morning is saved")
+ c.begin_day()
+ for i in 4: # dusk, night, dawn, and the end of the dawn grace
+ c.advance_phase()
+ var ending := sim.ending
+ r.check(c.state.phase == P.FARMERS_RETURN and not SaveGame.exists(SAVE), "the last dawn ends the vacation and deletes the save")
+ r.check(ending.running and ending.stage == "drive" and main.get_viewport().get_camera_3d() == ending._camera and not _hud_visible(),
+ "the farmers' return starts: the cutscene camera, no HUD")
+ var horn := int(sim.audio.played.get("horn", 0))
+ var steps := 0
+ while ending.stage == "drive" and steps < 3000:
+ ending.step(DT)
+ steps += 1
+ var park: Vector3 = FarmersReturn.ROUTE[FarmersReturn.ROUTE.size() - 1]
+ var car := ending._car.global_position
+ r.check(ending.stage == "walk" and Vector2(car.x - park.x, car.z - park.z).length() < 0.3 and steps * DT > 4.0 and steps * DT < 20.0,
+ "the car drives in by the driveway and parks by the house (%.1f s)" % (steps * DT))
+ r.check(int(sim.audio.played.get("horn", 0)) == horn + 1 and ending._farmers[0].visible and ending._farmers[1].visible,
+ "with a honk, and the farmers get out")
+ while not ending.done and steps < 9000:
+ ending.step(DT)
+ steps += 1
+ var at := true
+ for i in 2:
+ at = at and ending._farmers[i].global_position.distance_to(FarmersReturn.FARMER_SPOTS[i]) < 0.1 \
+ and ending._anims[i].current_animation == &"Cheering"
+ r.check(ending.done and ending.stage == "end" and at and steps * DT < 35.0,
+ "they walk to the door, wave, and cheer (%.1f s in all)" % (steps * DT))
+ r.info("farmers' return: %.1f s in all" % (steps * DT))
+ var panel := sim.end_panel
+ panel._process(0.1)
+ r.check(panel.is_visible_in_tree() and _hud_visible() and panel.mode == "assessment" and panel._title.text == "The farmers are home!"
+ and panel._rating.text.contains("points") and panel._bars.visible and panel._menu.visible and panel._menu.has_focus()
+ and not panel._retry.visible, "then the final assessment ('%s')" % panel._rating.text)
+ var a := Assessment.of(c.state, cfg)
+ r.check(panel._rating.text == "%s · %d points" % [a["tier"], a["score"]] and panel._stats.text.contains("Enemies defeated: 40 crows and 8 thieves")
+ and panel._stats.text.contains("Gathered 48 wood"), "with the rating, the shares kept, and the vacation's totals")
+ r.info("assessment: %s\n%s\n%s" % [panel._rating.text, panel._detail.text, panel._stats.text])
+ ending.clear()
+ ending.start()
+ ending.skip()
+ r.check(ending.done and ending._farmers[0].global_position.distance_to(FarmersReturn.FARMER_SPOTS[0]) < 0.01
+ and ending._car.global_position.distance_to(park) < 0.3, "skipping jumps to the end")
+ panel._menu.pressed.emit()
+ r.check(main.screen == Main.Screen.MENU and c.state.night == 1 and not ending.running and not SaveGame.exists(SAVE)
+ and main.main_menu.continue_button.disabled, "Main menu after the ending: a fresh farm behind the menu, nothing to continue")
+
+
+func _audio() -> void:
+ var audio := sim.audio
+ var missing: Array[String] = []
+ for cue: String in FarmAudio.CUES:
+ var bus := String(FarmAudio.CUES[cue].get("bus", "SFX"))
+ if (audio.streams.get(cue, []) as Array).is_empty() or AudioServer.get_bus_index(bus) < 0:
+ missing.append(cue)
+ r.check(missing.is_empty(), "every sound cue has its sounds and its bus (%d cues; missing: %s)" % [FarmAudio.CUES.size(), missing])
+ r.check(audio._day.playing and audio._night.playing and (audio._day.stream as AudioStreamWAV).loop_mode == AudioStreamWAV.LOOP_FORWARD
+ and audio._day.bus == &"Ambience", "the day and night ambience loop on the Ambience bus")
+ main.new_vacation()
+ var before := audio.played.duplicate()
+ var count := func(cue: String) -> int: return int(audio.played.get(cue, 0)) - int(before.get(cue, 0))
+ sim.combat.fired.emit()
+ c.begin_day()
+ var day_music := audio.music_track
+ c.advance_phase()
+ var dusk_music := audio.music_track
+ r.check(count.call("shot") == 1 and count.call("bell") == 1 and count.call("dusk") == 1, "the gun, the dusk bell, and the dusk stinger play")
+ var id := sim.structures.place("fence", 2.0, 8.0, 0)
+ sim.structures.damage(id, 3)
+ sim.structures.damage(id, 999)
+ r.check(count.call("build") == 1 and count.call("structure_hit") == 1 and count.call("smash") == 1 and count.call("breach") == 1,
+ "building, a hit, and a broken fence (with the breach alarm)")
+ sim.scarecrow.try_damage(1)
+ r.check(count.call("hurt") == 1, "the scarecrow's hurt sound")
+ c.advance_phase()
+ var night_music := audio.music_track
+ c.advance_phase()
+ r.check(day_music == "farm" and dusk_music == "" and night_music == "night" and audio.music_track == "",
+ "music by phase: the farm tune by day, Purgatory at night, only ambience at dusk and dawn")
+ r.check((audio._music["farm"] as AudioStreamPlayer).bus == &"Music" and ((audio._music["night"] as AudioStreamPlayer).stream as AudioStreamOggVorbis).loop
+ and ((audio._music["farm"] as AudioStreamPlayer).stream as AudioStreamWAV).loop_mode == AudioStreamWAV.LOOP_FORWARD,
+ "both tracks loop on the Music bus")
+ audio._last.erase("crow_arrive")
+ r.check(audio.play("crow_arrive") and not audio.play("crow_arrive"), "a cue rests for its gap (no caw pile-ups)")
+ r.check(main.main_menu.new_button.has_meta(&"sounds") and sim.review_panel._start.has_meta(&"sounds"),
+ "menu and panel buttons have hover and click sounds")
+ main.to_menu()
diff --git a/game/tests/test_flow.gd.uid b/game/tests/test_flow.gd.uid
new file mode 100644
index 0000000..099c1d8
--- /dev/null
+++ b/game/tests/test_flow.gd.uid
@@ -0,0 +1 @@
+uid://6yaguapi3704
diff --git a/game/tests/test_nights.gd b/game/tests/test_nights.gd
new file mode 100644
index 0000000..1be53fb
--- /dev/null
+++ b/game/tests/test_nights.gd
@@ -0,0 +1,278 @@
+extends RefCounted
+## The five-night progression (Step 10): every night plan and debug scenario is valid (markers
+## exist and suit the enemy type, types and targets are known, arrivals fit the night), each night
+## tests what the plan says it should, the upgrades apply to the systems they change and persist
+## (next morning, JSON, retry), and the five nights play back to back to the farmers' return, each
+## with its own plan and morning snapshot, everything carrying over.
+
+const P := CampaignController.Phase
+const T := ThiefBehavior.State
+const DT := 1.0 / 60.0
+const AWAY := Vector3(-11.0, 0.0, 13.0)
+const SCENARIOS := "res://game/resources/scenarios/"
+
+
+func run(r: GameTestRunner) -> void:
+ var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
+ r.root.add_child(farm)
+ await r.process_frame
+ await r.physics_frame
+ var sim := farm.get_node("FarmSim") as FarmSim
+ sim.set_physics_process(false)
+ sim.waves.enabled = false
+ var player := farm.get_node("Player") as PlayerCharacter
+ player.global_position = AWAY
+ _validation(r, sim)
+ _designs(r, sim)
+ _upgrades(r, sim, player)
+ _five_nights(r, farm, sim, player)
+ farm.queue_free()
+ await r.process_frame
+
+
+## Every plan (the five nights and the debug scenarios) checks out against the farm.
+func _validation(r: GameTestRunner, sim: FarmSim) -> void:
+ var plans: Array[NightPlan] = sim.waves.plans.duplicate()
+ r.check(plans.size() == sim.config.campaign_nights, "a plan for each of the %d nights" % sim.config.campaign_nights)
+ for f in DirAccess.get_files_at(SCENARIOS):
+ if f.ends_with(".tres"):
+ plans.append(load(SCENARIOS + f) as NightPlan)
+ for plan in plans:
+ var length := plan.night_length if plan.night_length > 0.0 else sim.config.night_length
+ var bad := plan.problems(length, plan.count_scale_in(sim.config), plan.spacing_scale_in(sim.config))
+ r.check(bad.is_empty() and plan.title != "", "'%s' is valid%s" % [plan.title, "" if bad.is_empty() else ": %s" % [bad]])
+ # The checks catch mistakes.
+ var broken := NightPlan.new()
+ broken.groups = [{"type": "crow", "target": "crops", "time": 5.0, "count": 1, "every": 1.0},
+ {"type": "thief", "target": "crops", "time": 200.0, "count": 2, "every": 1.0},
+ {"type": "crow", "target": "animals", "time": 5.0, "count": 0, "every": 1.0},
+ {"type": "dragon", "time": 5.0, "count": 1, "every": 1.0}]
+ var found := broken.problems(150.0)
+ r.check(found.size() == 5, "a broken plan is caught: %s" % [found])
+ for k in sim.waves.plans.size():
+ r.check(sim.waves.plans[k].dusk_hint.length() > 20, "night %d has a dusk hint" % (k + 1))
+
+
+## Each night tests what it's meant to.
+func _designs(r: GameTestRunner, sim: FarmSim) -> void:
+ var w := sim.waves
+ var n := w.plans
+ var crow := EnemySystem.TYPE_CROW
+ var thief := EnemySystem.TYPE_THIEF
+ var breaker := EnemySystem.TYPE_BREAKER
+ r.check(n[0].type_counts().keys() == [crow], "night 1: crows only, at the crops (%s)" % [n[0].type_counts()])
+ var targets_2 := {}
+ for g in n[1].groups:
+ if g["type"] == "thief":
+ targets_2[g["target"]] = true
+ r.check(n[1].type_counts().has(crow) and n[1].type_counts().has(thief) and not n[1].type_counts().has(breaker)
+ and targets_2.has("supplies") and targets_2.has("animals"), "night 2: crows, plus thieves at the shed and the pen")
+ r.check(int(n[2].type_counts().get(breaker, 0)) >= 2 and int(n[2].type_counts().get(thief, 0)) >= 3, "night 3: fence breakers, and thieves behind them (%s)" % [n[2].type_counts()])
+ var crowded := _crowded_moments(n[3])
+ r.check(crowded >= 3, "night 4: %d moments with two groups arriving at once" % crowded)
+ var waves_5 := _waves(n[4])
+ r.check(n[4].type_counts().size() == 3 and waves_5 >= 3 and n[4].night_length > sim.config.night_length,
+ "night 5: all three types in %d waves, over a longer %.0f s night" % [waves_5, n[4].night_length])
+ var totals := []
+ for p in n:
+ totals.append(p.total(p.count_scale_in(sim.config)))
+ r.check(totals[4] == totals.max() and totals[0] == totals.min(), "the first night is the smallest, the last the biggest, as played (%s)" % [totals])
+ r.check(is_equal_approx(n[0].count_scale_in(sim.config), 1.0) and is_equal_approx(n[0].spacing_scale_in(sim.config), 1.0)
+ and totals[0] <= 12 and n[1].count_scale == 0.0, "night 1 plays as designed, unscaled (%d crows); the later nights at the config's scale" % totals[0])
+
+
+## Times when two groups start arriving within 3 s of each other.
+func _crowded_moments(plan: NightPlan) -> int:
+ var moments := {}
+ for i in plan.groups.size():
+ for j in range(i + 1, plan.groups.size()):
+ var a := float(plan.groups[i]["time"])
+ var b := float(plan.groups[j]["time"])
+ if absf(a - b) <= 3.0:
+ moments[roundi(minf(a, b) / 10.0)] = true
+ return moments.size()
+
+
+## Clusters of arrivals at least 25 s apart.
+func _waves(plan: NightPlan) -> int:
+ var times: Array[float] = []
+ for g in plan.groups:
+ times.append(float(g["time"]))
+ times.sort()
+ var waves := 1
+ for k in range(1, times.size()):
+ if times[k] - times[k - 1] >= 25.0:
+ waves += 1
+ return waves
+
+
+## The upgrades change the systems they're about, can't be bought twice or at night, and persist.
+func _upgrades(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var c := sim.campaign
+ var s := c.state
+ var cfg := sim.config
+ var es := sim.enemies
+ var st := sim.structures
+ c.begin_day()
+ s.resources.shed = {"wood": 200, "scrap": 200, "straw": 200}
+ var fence := st.place("fence", 8.0, -8.0, 0)
+ _settle(sim)
+ var before := {
+ "interval": sim.combat.interval_ticks(), "damage": sim.combat.shot_damage(), "radius": sim.scarecrow.fear_radius(),
+ "cooldown": sim.scarecrow.fear_cooldown(), "max_hp": s.scarecrow_max_hp, "fence": st.max_hp("fence"),
+ "gate": st.max_hp("gate"), "range": st.turret_range(), "slow": st.trap_slow_time(),
+ }
+ var morning := s.to_dict()
+ var shed := s.resources.shed_total()
+ var spent := 0
+ r.check(not player.can_sprint(), "(no sprint before the Sprint upgrade)")
+ for id in Upgrades.ORDER:
+ spent += _sum(Upgrades.cost(cfg, id))
+ var text := Upgrades.buy(c, id, st)
+ r.check(Upgrades.owned(s, id) and text.contains("done:"), "bought %s: '%s'" % [id, text])
+ r.check(s.resources.shed_total() == shed - spent, "all %d cost %d materials together" % [Upgrades.ORDER.size(), spent])
+ r.check(player.can_sprint(), "sprint: the scarecrow can sprint")
+ r.check(Upgrades.buy(c, "rapid_fire", st).contains("already done"), "an upgrade can't be bought twice")
+ r.check(sim.combat.interval_ticks() < int(before["interval"]) and sim.combat.shot_damage() == int(before["damage"]) + 1,
+ "rapid fire and heavy seeds: a shot every %d ticks (was %d), %d damage" % [sim.combat.interval_ticks(), before["interval"], sim.combat.shot_damage()])
+ r.check(is_equal_approx(sim.scarecrow.fear_radius(), float(before["radius"]) * 1.3) and is_equal_approx(sim.scarecrow.fear_cooldown(), float(before["cooldown"]) * 0.8),
+ "wide and quick fear: %.1f m, %.1f s" % [sim.scarecrow.fear_radius(), sim.scarecrow.fear_cooldown()])
+ r.check(s.scarecrow_max_hp == int(before["max_hp"]) + 2 and s.scarecrow_hp == s.scarecrow_max_hp, "straw stuffing: +2 max health")
+ r.check(st.max_hp("fence") == roundi(int(before["fence"]) * 1.5) and st.max_hp("gate") == roundi(int(before["gate"]) * 1.5)
+ and int(s.structure(fence)["hp"]) == st.max_hp("fence"), "reinforced fences: fences %d HP, gates %d; a standing fence keeps its full health" % [st.max_hp("fence"), st.max_hp("gate")])
+ r.check(is_equal_approx(st.turret_range(), float(before["range"]) * 1.3) and is_equal_approx(st.trap_slow_time(), float(before["slow"]) * 1.5),
+ "long-range defenses %.1f m, sticky tar %.1f s" % [st.turret_range(), st.trap_slow_time()])
+ # The effects are real: a shot does 2 damage, a defense reaches a thief beyond its old range,
+ # a trap holds longer.
+ var keep := es.behavior
+ es.behavior = null
+ var h := es.spawn(EnemySystem.TYPE_THIEF, 10.0, -8.0, Vector2.DOWN)
+ _step(sim, 1)
+ sim.projectiles.fire(Vector3(10.0, cfg.combat_height, -2.0), Vector3(10.0, cfg.combat_height, -3.0), Vector3(0, 0, -1), sim.combat.shot_damage())
+ for i in 20:
+ sim.projectiles.step(DT)
+ r.check(es.health[es.resolve_handle(h)] == es.t_hp[EnemySystem.TYPE_THIEF] - 2, "a heavy seed takes 2 health off a thief")
+ es.apply_hit_handle(h, 99)
+ st.dismantle(fence)
+ var turret := st.place("automated_defense", 6.0, -13.0, 0)
+ var far := es.spawn(EnemySystem.TYPE_THIEF, 6.0 + float(before["range"]) + 1.0, -13.0, Vector2.UP)
+ _step(sim, 90)
+ r.check(es.resolve_handle(far) < 0 or es.health[es.resolve_handle(far)] < es.t_hp[EnemySystem.TYPE_THIEF], "a defense hits a thief %.0f m away (its old range: %.0f m)" % [float(before["range"]) + 1.0, before["range"]])
+ for d in es.active_count:
+ es.apply_hit(d, 99)
+ st.dismantle(turret)
+ var trap := st.place("slowing_trap", 8.0, -12.0, 0)
+ _settle(sim)
+ h = es.spawn(EnemySystem.TYPE_THIEF, 8.0, -12.0, Vector2.RIGHT)
+ _step(sim, 1)
+ r.check(absf(es.slow_left[es.resolve_handle(h)] - st.trap_slow_time()) < 0.05, "a trap slows for %.1f s" % es.slow_left[es.resolve_handle(h)])
+ es.apply_hit_handle(h, 99)
+ st.dismantle(trap)
+ es.behavior = keep
+ _step(sim, 1)
+ # They persist: into the next morning, through JSON, and in a retry from that morning; a retry
+ # from before they were bought takes them back.
+ var bought := s.upgrades.duplicate()
+ while s.phase != P.NIGHT:
+ c.advance_phase()
+ r.check(Upgrades.blocker(c, "rapid_fire") == "Done" and Upgrades.buy(c, "long_range", st).contains("already done"), "(owned ones stay owned at night)")
+ s.upgrades.erase("sticky_tar")
+ r.check(Upgrades.blocker(c, "sticky_tar") == "The work area is for daytime", "nothing can be bought at night")
+ s.upgrades["sticky_tar"] = 1
+ while s.phase != P.MORNING:
+ c.advance_phase()
+ r.check(s.upgrades == bought, "the upgrades carry into the next morning")
+ var back := FarmState.from_dict(JSON.parse_string(JSON.stringify(s.to_dict(), "", true, true)))
+ r.check(back != null and back.upgrades == bought, "and through a save")
+ c.begin_day()
+ s.scarecrow_hp = 0
+ _step(sim, 1)
+ c.retry_night()
+ r.check(s != c.state and c.state.upgrades == bought, "a retry from that morning keeps them")
+ var old := FarmState.from_dict(morning)
+ r.check(old.upgrades.is_empty() and old.resources.shed_total() == shed, "(the morning before they were bought had none, and the materials)")
+ c.new_campaign()
+ _step(sim, 1)
+ r.check(c.state.upgrades.is_empty() and sim.combat.shot_damage() == 1 and st.max_hp("fence") == cfg.fence_hp and not player.can_sprint(),
+ "a new vacation starts without them")
+ player.global_position = AWAY
+
+
+## All five nights back to back, each with its own plan and morning snapshot, to the farmers'
+## return. The farm is defended, and the scarecrow kept out of harm.
+func _five_nights(r: GameTestRunner, farm: Node3D, sim: FarmSim, player: PlayerCharacter) -> void:
+ var c := sim.campaign
+ var hud := farm.get_node("Hud/PhaseHud") as PhaseHud
+ c.new_campaign()
+ _step(sim, 1)
+ sim.waves.enabled = true
+ player.global_position = AWAY
+ var arrivals := {}
+ sim.waves.arrived.connect(func(h: int, _at: Vector2) -> void:
+ var t: int = sim.enemies.type[sim.enemies.resolve_handle(h)]
+ arrivals[t] = int(arrivals.get(t, 0)) + 1)
+ var broken: Array[int] = []
+ sim.structures.destroyed.connect(func(id: int, _t: String, _at: Vector3) -> void: broken.append(id))
+ var all_good := true
+ var lengths: Array[float] = []
+ var t0 := Time.get_ticks_msec()
+ for night in range(1, c.config.campaign_nights + 1):
+ var s := c.state
+ all_good = all_good and s.night == night and s.phase == P.MORNING and c._morning_snapshot == s.to_dict()
+ c.begin_day()
+ if night == 1:
+ _defend(sim)
+ s.resources.shed = {"wood": 99, "scrap": 99, "straw": 99}
+ while c.state.phase != P.NIGHT:
+ c.advance_phase()
+ lengths.append(c.state.phase_time_left)
+ hud._on_phase_changed(P.NIGHT, P.DUSK)
+ var title_ok := hud._banner.text == "Night %d: %s" % [night, sim.waves.plan_for(night).title]
+ arrivals.clear()
+ var structures_at_night := c.state.structures.size()
+ broken.clear()
+ while c.state.phase != P.MORNING and not c.is_over():
+ sim.scarecrow.invulnerable_left = 1.0
+ sim.step(DT)
+ var expect := sim.waves.plan_for(night).type_counts(sim.waves.plan_for(night).count_scale_in(c.config))
+ r.check(arrivals == expect and title_ok, "night %d, '%s': the plan's %s arrived %s" % [night, sim.waves.plan_for(night).title, expect, arrivals])
+ var e: Dictionary = c.state.night_log[c.state.night_log.size() - 1]
+ r.info("night %d: %d crops, %d animals, %d supplies lost; %d structures broken" % [night, e["crops_lost"], e["animals_lost"], e["supplies_lost"], broken.size()])
+ if night < c.config.campaign_nights:
+ all_good = all_good and c.state.structures.size() == structures_at_night - broken.size() and c.state.supplies_in_transit == 0
+ r.check(all_good, "every morning is its night's snapshot, and the farm carries over night to night")
+ r.check(c.state.phase == P.FARMERS_RETURN and c.state.nights_survived == 5 and c.state.night_log.size() == 5,
+ "all five nights played to the farmers' return (%.1f s)" % ((Time.get_ticks_msec() - t0) / 1000.0))
+ r.check(is_equal_approx(lengths[4], sim.waves.plans[4].night_length) and is_equal_approx(lengths[0], c.config.night_length),
+ "the last night is longer (%.0f s; the others %.0f s)" % [lengths[4], lengths[0]])
+ sim.waves.enabled = false
+
+
+## Automated defenses by the crops, the pen, and the shed.
+func _defend(sim: FarmSim) -> void:
+ var st := sim.structures
+ sim.campaign.state.resources.shed = {"wood": 99, "scrap": 99, "straw": 99}
+ for at in [Vector2(13.5, -15.0), Vector2(46.0, -15.0), Vector2(13.5, 9.0), Vector2(46.0, 9.0), Vector2(30.0, -17.5),
+ Vector2(30.0, 11.5), Vector2(7.0, -3.5), Vector2(9.5, -14.0), Vector2(-3.5, -12.0)]:
+ if st.validate("automated_defense", at.x, at.y, 0, at) in ["", "The scarecrow is in the way"]:
+ st.place("automated_defense", at.x, at.y, 0)
+ _settle(sim)
+
+
+static func _sum(cost: Dictionary) -> int:
+ var n := 0
+ for m in cost:
+ n += int(cost[m])
+ return n
+
+
+func _settle(sim: FarmSim) -> void:
+ var guard := 0
+ while sim.rebuilding and guard < 600:
+ sim.step(DT)
+ guard += 1
+
+
+func _step(sim: FarmSim, n: int) -> void:
+ for i in n:
+ sim.step(DT)
diff --git a/game/tests/test_nights.gd.uid b/game/tests/test_nights.gd.uid
new file mode 100644
index 0000000..e5cec42
--- /dev/null
+++ b/game/tests/test_nights.gd.uid
@@ -0,0 +1 @@
+uid://bxtlwyndaeris
diff --git a/game/tests/test_outcome.gd b/game/tests/test_outcome.gd
index 5578008..c63fb62 100644
--- a/game/tests/test_outcome.gd
+++ b/game/tests/test_outcome.gd
@@ -1,7 +1,8 @@
extends RefCounted
-## Outcome rules: scarecrow destruction, a stripped farm (only categories in play count),
-## completing the vacation, the failure-before-completion tie policy, failure in every phase,
-## and terminal phases staying terminal.
+## Outcome rules: scarecrow destruction, a stripped farm (all three categories; only those in
+## play count; supplies only when thieves emptied the shed), completing the vacation, the
+## failure-before-completion tie policy, failure in every phase, and terminal phases staying
+## terminal.
const O := CampaignController.Outcome
const P := CampaignController.Phase
@@ -18,20 +19,34 @@ func run(r: GameTestRunner) -> void:
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_SCARECROW, "0 HP is a Game Over")
s = FarmState.create(cfg)
- s.crops = 0
+ s.animals_total = 0
+ s.supplies_total = 0
+ s.lose_all_crops()
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_STRIPPED, "with only crops in play, no crops left is a stripped farm")
- s = _all_categories(cfg)
- s.crops = 0
+ s = FarmState.create(cfg)
+ s.lose_all_crops()
r.check(CampaignController.check_outcome(s, n) == O.CONTINUE, "losing every crop alone does not end the game")
- s.animals = 0
+ s.lose_all_animals()
r.check(CampaignController.check_outcome(s, n) == O.CONTINUE, "losing crops and animals with supplies left does not end the game")
- s.supplies = 0
- r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_STRIPPED, "losing every category ends the game")
+ for m in ResourceStore.MATERIALS:
+ s.resources.shed[m] = 0
+ r.check(CampaignController.check_outcome(s, n) == O.CONTINUE, "spending the last supplies doesn't strip the farm")
+ s.shed_raided = true
+ s.supplies_in_transit = 5
+ r.check(CampaignController.check_outcome(s, n) == O.CONTINUE, "a sack of supplies still on the farm keeps it going")
+ s.supplies_in_transit = 0
+ r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_STRIPPED, "losing every category ends the game (thieves emptied the shed)")
+ s.resources.shed["straw"] = 2
+ s.settle_supplies()
+ s.resources.shed["straw"] = 0
+ r.check(not s.shed_raided and CampaignController.check_outcome(s, n) == O.CONTINUE,
+ "storing anything clears the raid: spending it again doesn't strip the farm")
s = FarmState.create(cfg)
s.crops_total = 0
- s.crops = 0
+ s.animals_total = 0
+ s.supplies_total = 0
r.check(not s.is_stripped(), "a farm with nothing in play is not 'stripped'")
s = FarmState.create(cfg)
@@ -44,7 +59,7 @@ func run(r: GameTestRunner) -> void:
s.scarecrow_hp = 0
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_SCARECROW, "tie: scarecrow destroyed on the final night loses")
s.scarecrow_hp = 1
- s.crops = 0
+ s.strip()
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_STRIPPED, "tie: farm stripped on the final night loses")
s.scarecrow_hp = 0
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_SCARECROW, "scarecrow destruction is reported before a stripped farm")
@@ -54,15 +69,6 @@ func run(r: GameTestRunner) -> void:
_terminal(r)
-func _all_categories(cfg: GameConfig) -> FarmState:
- var s := FarmState.create(cfg)
- s.animals_total = 8
- s.animals = 8
- s.supplies_total = 50
- s.supplies = 50
- return s
-
-
func _failure_in_every_phase(r: GameTestRunner) -> void:
for phase: CampaignController.Phase in [P.MORNING, P.DAY, P.DUSK, P.NIGHT, P.DAWN]:
var c := r.make_campaign()
@@ -75,7 +81,7 @@ func _failure_in_every_phase(r: GameTestRunner) -> void:
"scarecrow destroyed during %s ends the game once" % P.keys()[phase])
c = r.make_campaign()
GameTestRunner.run_until(c, phase)
- c.state.crops = 0
+ c.state.strip()
c.tick(GameTestRunner.TICK)
r.check(c.state.phase == P.GAME_OVER and c.outcome == O.GAME_OVER_STRIPPED,
"farm stripped during %s ends the game" % P.keys()[phase])
diff --git a/game/tests/test_roster.gd b/game/tests/test_roster.gd
new file mode 100644
index 0000000..e88090a
--- /dev/null
+++ b/game/tests/test_roster.gd
@@ -0,0 +1,366 @@
+extends RefCounted
+## The enemy roster (Step 9) on the real farm, with FarmSim stepped by hand at 60 Hz: the type
+## table; crows flying over fences and traps but shot down by automated defenses, and never
+## fighting; ground thieves going only for animals and supplies; fence breakers smashing the
+## barriers that guard valuables, opening gaps other thieves walk through, and turning on the
+## scarecrow; the character pool for ground enemies; the alert manager's grouping, priorities,
+## escalation, and cap; and the debug scenarios.
+
+const P := CampaignController.Phase
+const C := LootSystem.Category
+const T := ThiefBehavior.State
+const DT := 1.0 / 60.0
+const AWAY := Vector3(-11.0, 0.0, 13.0)
+
+
+func run(r: GameTestRunner) -> void:
+ var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
+ r.root.add_child(farm)
+ await r.process_frame
+ await r.physics_frame
+ var sim := farm.get_node("FarmSim") as FarmSim
+ sim.set_physics_process(false)
+ sim.waves.enabled = false
+ var player := farm.get_node("Player") as PlayerCharacter
+ player.global_position = AWAY
+ sim.campaign.begin_day()
+ sim.campaign.state.resources.shed = {"wood": 60, "scrap": 60, "straw": 60}
+ _table(r, sim)
+ _crows(r, sim, player)
+ _thieves(r, sim, player)
+ _breakers(r, sim, player)
+ _characters(r, sim)
+ _alerts(r, farm, sim, player)
+ _scenarios(r, farm, sim)
+ farm.queue_free()
+ await r.process_frame
+
+
+func _table(r: GameTestRunner, sim: FarmSim) -> void:
+ var es := sim.enemies
+ var ok := es.t_flying[EnemySystem.TYPE_CROW] == 1 and es.t_flying[EnemySystem.TYPE_THIEF] == 0 and es.t_flying[EnemySystem.TYPE_BREAKER] == 0
+ ok = ok and es.t_targets[EnemySystem.TYPE_CROW] == 1 << C.CROP
+ ok = ok and es.t_targets[EnemySystem.TYPE_THIEF] == (1 << C.ANIMAL) | (1 << C.SUPPLY)
+ ok = ok and es.t_targets[EnemySystem.TYPE_BREAKER] == 0 and es.t_breaks[EnemySystem.TYPE_BREAKER] == 1
+ r.check(ok, "the type table: crows fly after crops, thieves walk after animals and supplies, fence breakers after structures")
+ r.check(es.t_hp[EnemySystem.TYPE_CROW] == 1 and es.t_hp[EnemySystem.TYPE_THIEF] == 3 and es.t_hp[EnemySystem.TYPE_BREAKER] == 6
+ and es.t_speed[EnemySystem.TYPE_CROW] > es.t_speed[EnemySystem.TYPE_THIEF] and es.t_speed[EnemySystem.TYPE_THIEF] > es.t_speed[EnemySystem.TYPE_BREAKER]
+ and es.t_structure_damage[EnemySystem.TYPE_BREAKER] > es.t_structure_damage[EnemySystem.TYPE_THIEF],
+ "crows are fast and fragile, breakers slow, tough, and heavy-handed")
+
+
+## Crows ignore fences and traps, but not automated defenses, and never fight.
+func _crows(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var es := sim.enemies
+ var st := sim.structures
+ var loot := sim.loot
+ # A wall of fences across its way, and a trap under it.
+ var fences: Array[int] = []
+ for k in 6:
+ fences.append(st.place("fence", 47.0 - 0.6, -9.0 + 2.0 * k, 2))
+ var trap := st.place("slowing_trap", 44.5, -3.0, 0)
+ _settle(sim)
+ var h := es.spawn(EnemySystem.TYPE_CROW, 52.0, -3.0, Vector2.LEFT)
+ var d := es.resolve_handle(h)
+ _step(sim, 1)
+ var unit := es.target[d]
+ r.check(unit > 0 and loot.category[unit] == C.CROP, "a crow goes for a crop")
+ var crossed := false
+ var slowed := false
+ var t := 0.0
+ while t < 20.0 and es.resolve_handle(h) >= 0 and es.state[es.resolve_handle(h)] == T.SEEK:
+ sim.step(DT)
+ t += DT
+ d = es.resolve_handle(h)
+ if d >= 0:
+ crossed = crossed or (es.pos_x[d] < 46.0 and absf(es.pos_z[d] + 3.0) < 2.0)
+ slowed = slowed or es.slow_left[d] > 0.0
+ d = es.resolve_handle(h)
+ r.check(crossed and d >= 0 and es.state[d] == T.STEAL, "it flies straight over a fence line to its crop (%.1f s)" % t)
+ r.check(not slowed and int(sim.campaign.state.structure(trap)["hp"]) == sim.config.trap_triggers, "a slowing trap does nothing to it")
+ r.check(fences.all(func(id: int) -> bool: return int(sim.campaign.state.structure(id)["hp"]) == sim.config.fence_hp), "and it breaks nothing")
+ # Standing right next to the scarecrow, it doesn't fight.
+ player.global_position = Vector3(es.pos_x[d] + 0.5, 0.0, es.pos_z[d])
+ var attacks := es.attacks_attempted
+ _step(sim, 90)
+ r.check(es.attacks_attempted == attacks, "a crow never attacks the scarecrow")
+ player.global_position = AWAY
+ es.apply_hit_handle(h, 99)
+ _step(sim, 1)
+ for id in fences:
+ st.dismantle(id)
+ st.dismantle(trap)
+ # An automated defense in its way shoots it down.
+ var turret := st.place("automated_defense", 42.0, -3.0, 0)
+ _settle(sim)
+ h = es.spawn(EnemySystem.TYPE_CROW, 52.0, -3.0, Vector2.LEFT)
+ var gone := _until(sim, func() -> bool: return es.resolve_handle(h) < 0, 15.0)
+ r.check(gone < 15.0 and es.kills >= 2, "an automated defense shoots a crow down (%.1f s)" % gone)
+ st.dismantle(turret)
+ _settle(sim)
+
+
+## Ground thieves go only for animals and supplies.
+func _thieves(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var es := sim.enemies
+ var loot := sim.loot
+ var s := sim.campaign.state
+ var h := sim.spawn_enemy(EnemySystem.TYPE_THIEF, C.CROP, GameTestRunner.EDGE["east"])
+ _step(sim, 1)
+ var item := es.target[es.resolve_handle(h)]
+ r.check(item > 0 and loot.category[item] != C.CROP, "a thief sent for crops goes for %s instead" % LootSystem.CATEGORY_KEYS[loot.category[item]])
+ es.apply_hit_handle(h, 99)
+ _step(sim, 1)
+ # A hit while it fills a sack restarts it.
+ h = sim.spawn_enemy(EnemySystem.TYPE_THIEF, C.SUPPLY, GameTestRunner.EDGE["north"])
+ _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.STEAL, 40.0)
+ _step(sim, 60)
+ var d := es.resolve_handle(h)
+ var sack := es.target[d]
+ r.check(loot.progress[sack] > 0.2, "it fills a sack (%.0f %%)" % (loot.progress[sack] * 100.0))
+ es.apply_hit(d)
+ r.check(es.timer[d] == 0.0 and loot.progress[sack] == 0.0 and es.health[d] == es.t_hp[EnemySystem.TYPE_THIEF] - 1,
+ "a hit while stealing restarts the theft")
+ es.apply_hit(d, 99)
+ _step(sim, 1)
+ # Nothing of its own left: it leaves, though the crops are still there.
+ var keep := s.lost_animals.duplicate()
+ var shed: Dictionary = s.resources.shed.duplicate()
+ s.lose_all_animals()
+ loot.sync_from_state()
+ for m in ResourceStore.MATERIALS:
+ s.resources.shed[m] = 0
+ h = sim.spawn_enemy(EnemySystem.TYPE_THIEF, LootSystem.ANY, GameTestRunner.EDGE["east"])
+ var events: Array[StringName] = []
+ var listen := func(kind: StringName, _id: int, _p: Vector3) -> void: events.append(kind)
+ loot.loot_event.connect(listen)
+ _step(sim, 2)
+ loot.loot_event.disconnect(listen)
+ d = es.resolve_handle(h)
+ r.check((d < 0 or es.state[d] == T.RETREAT) and not events.has(&"targeted") and s.crops > 0,
+ "with no animals or supplies left it claims nothing and leaves, crops or not")
+ if d >= 0:
+ es.apply_hit(d, 99)
+ _step(sim, 1)
+ s.lost_animals = keep
+ s.resources.shed = shed
+ loot.sync_from_state()
+ sim.animals.sync_from_state()
+ player.global_position = AWAY
+
+
+## Fence breakers smash what guards the valuables, open gaps thieves walk through, and fight.
+func _breakers(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var es := sim.enemies
+ var st := sim.structures
+ var s := sim.campaign.state
+ var gate := sim.nav.structure_at[sim.nav.cell_of(4.0, -6.0)]
+ var far_fence := st.place("fence", 25.0, -30.0, 0) # guards nothing
+ var shed_fence := st.place("fence", 1.0, -12.0, 0) # by the shed
+ _settle(sim)
+ var broken: Array[int] = []
+ st.destroyed.connect(func(id: int, _t: String, _at: Vector3) -> void: broken.append(id))
+ var h := sim.spawn_enemy(EnemySystem.TYPE_BREAKER, LootSystem.ANY, GameTestRunner.EDGE["south-west"])
+ var at := _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.BREAK, 40.0)
+ var d := es.resolve_handle(h)
+ var first := es.barrier[d]
+ var first_type := _type_of(sim, first)
+ r.check(at < 40.0 and (first == gate or first == shed_fence), "a fence breaker walks to a barrier guarding valuables (%.1f s; the %s)" % [at, first_type])
+ r.check(es.target[d] < 0 and es.carry[d] < 0, "it claims nothing to steal")
+ var took := _until(sim, func() -> bool: return broken.has(first), 20.0)
+ var hits := ceili(float(st.max_hp(first_type)) / es.t_structure_damage[EnemySystem.TYPE_BREAKER])
+ r.check(took < (hits - 1) * es.t_hit_interval[EnemySystem.TYPE_BREAKER] + 1.0, "it smashes it in %d heavy hits (%.1f s)" % [hits, took])
+ var second := _until(sim, func() -> bool:
+ var dd := es.resolve_handle(h)
+ return dd >= 0 and es.state[dd] == T.BREAK and es.barrier[dd] != first, 40.0)
+ d = es.resolve_handle(h)
+ r.check(second < 40.0 and (es.barrier[d] == gate or es.barrier[d] == shed_fence), "then it goes for the next guarding barrier (%.1f s)" % second)
+ _until(sim, func() -> bool: return broken.has(gate) and broken.has(shed_fence), 30.0)
+ r.check(not broken.has(far_fence) and not s.structure(far_fence).is_empty(), "guarding barriers come first: a fence guarding nothing still stands")
+ # Thieves walk through the breach.
+ var thief := sim.spawn_enemy(EnemySystem.TYPE_THIEF, C.ANIMAL, GameTestRunner.EDGE["west"])
+ var breaks := 0
+ var t := 0.0
+ while t < 40.0 and es.resolve_handle(thief) >= 0 and es.state[es.resolve_handle(thief)] != T.CARRY:
+ sim.step(DT)
+ t += DT
+ if es.resolve_handle(thief) >= 0 and es.state[es.resolve_handle(thief)] == T.BREAK:
+ breaks += 1
+ r.check(t < 40.0 and breaks == 0, "a thief walks in through the gap it opened and takes an animal (%.1f s, no breaking)" % t)
+ es.apply_hit_handle(thief, 99)
+ _step(sim, 1)
+ # With nothing guarding valuables left, it hunts the scarecrow.
+ st.dismantle(far_fence)
+ _settle(sim)
+ player.global_position = Vector3(-6.0, 0.0, 10.0)
+ var hunting := _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.FIGHT, 10.0)
+ var hp := s.scarecrow_hp
+ var reached := _until(sim, func() -> bool: return s.scarecrow_hp < hp, 40.0)
+ r.check(hunting < 10.0 and reached < 40.0 and hp - s.scarecrow_hp == es.t_damage[EnemySystem.TYPE_BREAKER],
+ "with nothing left to break it hunts the scarecrow down and hits it hard (-%d HP, %.1f s)" % [hp - s.scarecrow_hp, reached])
+ player.global_position = AWAY
+ es.apply_hit_handle(h, 99)
+ _step(sim, 1)
+ # Shot from range, a breaker turns on the scarecrow; it takes 6 hits.
+ st.place("gate", 4.0, -6.0, 2)
+ _settle(sim)
+ h = sim.spawn_enemy(EnemySystem.TYPE_BREAKER, LootSystem.ANY, GameTestRunner.EDGE["south-west"])
+ _step(sim, 30)
+ d = es.resolve_handle(h)
+ es.apply_hit(d)
+ r.check(es.state[d] == T.FIGHT, "shot, it turns on the scarecrow")
+ for k in es.t_hp[EnemySystem.TYPE_BREAKER] - 2:
+ es.apply_hit(d)
+ _step(sim, 1)
+ r.check(es.resolve_handle(h) >= 0, "five hits don't stop it")
+ es.apply_hit_handle(h)
+ _step(sim, 1)
+ r.check(es.resolve_handle(h) < 0, "the sixth does")
+ s.scarecrow_hp = s.scarecrow_max_hp
+ _settle(sim)
+
+
+## Ground enemies are drawn by pooled characters; flyers aren't.
+func _characters(r: GameTestRunner, sim: FarmSim) -> void:
+ var es := sim.enemies
+ var ch := sim.characters
+ var thieves := ch.free_count(EnemySystem.TYPE_THIEF)
+ r.check(thieves == EnemyCharacters.POOL[EnemySystem.TYPE_THIEF] and ch.in_use() == 0, "%d thief characters waiting in the pool (%d of them corpses still fading)" % [thieves, ch.corpses()])
+ var crow := es.spawn(EnemySystem.TYPE_CROW, 20.0, -30.0, Vector2.UP)
+ var handles: Array[int] = []
+ for k in thieves + 2:
+ handles.append(es.spawn(EnemySystem.TYPE_THIEF, 12.0 + k * 0.7, -30.0, Vector2.UP)) # all inside the farm's edge
+ var spawned := handles.filter(func(hh: int) -> bool: return hh >= 0).size()
+ r.check(crow >= 0 and spawned == thieves and ch.in_use() == thieves and ch.free_count(EnemySystem.TYPE_THIEF) == 0,
+ "one character per ground enemy, none for a crow; past the pool, spawns are skipped (%d of %d)" % [spawned, handles.size()])
+ var corpses := ch.corpses()
+ es.apply_hit_handle(handles[0], 99)
+ _step(sim, 1)
+ r.check(ch.in_use() == thieves - 1 and ch.corpses() == corpses + 1 and ch.free_count(EnemySystem.TYPE_THIEF) == 1,
+ "a killed thief's character lies there a moment, free to be taken over")
+ var again := es.spawn(EnemySystem.TYPE_THIEF, 25.0, -30.0, Vector2.UP)
+ r.check(again >= 0 and ch.in_use() == thieves and ch.corpses() == corpses, "a new thief takes it over")
+ handles.append(again)
+ for hh in handles + [crow]:
+ if hh >= 0:
+ es.apply_hit_handle(hh, 99)
+ _step(sim, 1)
+ ch._process(EnemyCharacters.CORPSE_TIME + 0.1)
+
+
+## The alert manager groups alerts by kind, type, and zone, orders them, escalates escapes, and
+## caps how many show.
+func _alerts(r: GameTestRunner, farm: Node3D, sim: FarmSim, player: PlayerCharacter) -> void:
+ var am := farm.get_node("Hud/Alerts") as AlertManager
+ var es := sim.enemies
+ var loot := sim.loot
+ var keep := es.behavior
+ es.behavior = null # everyone holds still where they're put
+ var crows: Array[int] = []
+ var units: Array[int] = []
+ for k in 3:
+ var u := _home_crop(loot, units)
+ units.append(u)
+ var h := es.spawn(EnemySystem.TYPE_CROW, loot.home[u].x, loot.home[u].y, Vector2.UP)
+ loot.holder[u] = h
+ crows.append(h)
+ var list := am.collect()
+ var theft := list.filter(func(a: Dictionary) -> bool: return a["kind"] == AlertManager.Kind.THEFT)
+ r.check(theft.size() == 1 and int(theft[0]["count"]) == 3 and theft[0]["label"] == "3 crows — Crop Field",
+ "three crows at the crops make one alert: '%s'" % (theft[0]["label"] if not theft.is_empty() else "-"))
+ # A carrier near the fence outranks one in the middle of the field, and both outrank thefts.
+ var near := _carrier(sim, Vector2(45.5, 5.0), _home_crop(loot, units))
+ var mid := _carrier(sim, Vector2(30.0, -3.0), _home_crop(loot, units))
+ list = am.collect()
+ var escapes := list.filter(func(a: Dictionary) -> bool: return a["kind"] == AlertManager.Kind.ESCAPE)
+ r.check(escapes.size() == 1 and int(escapes[0]["count"]) == 2, "two crows escaping from the field are grouped too")
+ r.check(list[0]["kind"] == AlertManager.Kind.ESCAPE and float(list[0]["escalation"]) > 0.7 and String(list[0]["label"]).contains("!"),
+ "escapes come first, escalated by the one nearly out: '%s'" % list[0]["label"])
+ var raw: Array[Dictionary] = [am._alert(AlertManager.Kind.ESCAPE, EnemySystem.TYPE_CROW, C.CROP, Vector2(45.5, 5.0), am._escalation(es.resolve_handle(near), Vector2(45.5, 5.0))),
+ am._alert(AlertManager.Kind.ESCAPE, EnemySystem.TYPE_CROW, C.CROP, Vector2(30.0, -3.0), am._escalation(es.resolve_handle(mid), Vector2(30.0, -3.0)))]
+ r.check(float(raw[0]["escalation"]) > float(raw[1]["escalation"]), "escape alerts escalate as the carrier nears its exit (%.2f > %.2f)" % [raw[0]["escalation"], raw[1]["escalation"]])
+ # A breach outranks a theft; at most MAX_SHOWN show.
+ var many: Array[Dictionary] = []
+ for k in 8:
+ many.append(am._alert(AlertManager.Kind.LOOSE if k % 2 == 0 else AlertManager.Kind.THEFT, k % 3, k % 3, Vector2(-10.0 + k * 7.0, -40.0 + k * 6.0), 0.0))
+ many.append(am._alert(AlertManager.Kind.BREACH, -1, -1, Vector2(3.5, -6.0), 1.0))
+ var sorted := AlertManager.sort_alerts(AlertManager.group_alerts(many))
+ var shown := AlertManager.cap(sorted, AlertManager.MAX_SHOWN)
+ r.check(sorted[0]["kind"] == AlertManager.Kind.BREACH and sorted[0]["label"] == "Breach! — Animal Pen", "a breach comes before thefts: '%s'" % sorted[0]["label"])
+ r.check(sorted.size() > AlertManager.MAX_SHOWN and shown.size() == AlertManager.MAX_SHOWN and shown[0] == sorted[0],
+ "of %d alerts, the top %d show" % [sorted.size(), AlertManager.MAX_SHOWN])
+ es.behavior = keep
+ for hh in crows + [near, mid]:
+ es.apply_hit_handle(hh, 99)
+ _step(sim, 1)
+ loot.return_dropped()
+ player.global_position = AWAY
+
+
+## Debug scenarios (F2): one enemy type at a time, then pairs, then all three.
+func _scenarios(r: GameTestRunner, farm: Node3D, sim: FarmSim) -> void:
+ var dbg := farm.get_node("CampaignDebug") as CampaignDebug
+ var c := sim.campaign
+ var titles: Array[String] = []
+ for k in CampaignDebug.SCENARIOS.size():
+ dbg.cycle_scenario()
+ titles.append(sim.waves.debug_plan.title if sim.waves.debug_plan != null else "")
+ r.check(not titles.has("") and titles.size() == 6, "F2 cycles through %d scenarios: %s" % [titles.size(), ", ".join(titles)])
+ r.check(sim.waves.tonight() == sim.waves.debug_plan and sim.waves.debug_plan.title == "All three", "the scenario is tonight's plan")
+ var types := {}
+ sim.waves.arrived.connect(func(h: int, _at: Vector2) -> void: types[sim.enemies.type[sim.enemies.resolve_handle(h)]] = true)
+ var skipped_before := sim.enemies.spawn_skipped
+ sim.waves.enabled = true
+ while c.state.phase != P.NIGHT:
+ if c.state.phase == P.MORNING:
+ c.begin_day()
+ else:
+ c.advance_phase()
+ _step(sim, 60 * 45)
+ r.check(types.size() == 3, "'All three' sends in crows, thieves, and a fence breaker (%s; %d spawns skipped)" % [types.keys(), sim.enemies.spawn_skipped - skipped_before])
+ dbg.cycle_scenario()
+ r.check(sim.waves.debug_plan == null and sim.waves.tonight() == sim.waves.plan_for(c.state.night), "and back to the night's own plan")
+ sim.waves.enabled = false
+
+
+func _carrier(sim: FarmSim, p: Vector2, unit: int) -> int:
+ var es := sim.enemies
+ var h := es.spawn(EnemySystem.TYPE_CROW, p.x, p.y, Vector2.RIGHT)
+ sim.loot.holder[unit] = h
+ sim.loot.pick_up(unit, h)
+ es.carry[es.resolve_handle(h)] = unit
+ es.state[es.resolve_handle(h)] = T.CARRY
+ return h
+
+
+func _home_crop(loot: LootSystem, not_these: Array[int]) -> int:
+ for id in range(1, loot.unit_count + 1):
+ if loot.status[id] == LootSystem.Status.HOME and loot.holder[id] == -1 and not not_these.has(id):
+ return id
+ return -1
+
+
+func _type_of(sim: FarmSim, id: int) -> String:
+ var e := sim.campaign.state.structure(id)
+ return String(e.get("type", "gate"))
+
+
+
+func _settle(sim: FarmSim) -> void:
+ var guard := 0
+ while sim.rebuilding and guard < 600:
+ sim.step(DT)
+ guard += 1
+
+
+func _step(sim: FarmSim, n: int) -> void:
+ for i in n:
+ sim.step(DT)
+
+
+func _until(sim: FarmSim, cond: Callable, max_seconds: float) -> float:
+ var t := 0.0
+ while t < max_seconds and not cond.call():
+ sim.step(DT)
+ t += DT
+ return t
diff --git a/game/tests/test_roster.gd.uid b/game/tests/test_roster.gd.uid
new file mode 100644
index 0000000..a9a90a7
--- /dev/null
+++ b/game/tests/test_roster.gd.uid
@@ -0,0 +1 @@
+uid://bod0f1rp68iwq
diff --git a/game/tests/test_save.gd b/game/tests/test_save.gd
new file mode 100644
index 0000000..c1daf99
--- /dev/null
+++ b/game/tests/test_save.gd
@@ -0,0 +1,253 @@
+extends RefCounted
+## Saving and settings without the farm scene: a save written and read back reproduces the farm
+## state field for field; missing, damaged, newer, and too-old saves are refused with a reason
+## and version 2 saves are upgraded; the campaign autosaves every morning, a retry restores that
+## morning, and finishing the vacation deletes the save; settings persist, fall back on bad
+## values, and apply to the audio buses, the dead zones, and the config; and the final
+## assessment's score and tiers.
+
+const P := CampaignController.Phase
+const SAVE := "user://test_savegame.json"
+const SETTINGS := "user://test_settings.cfg"
+
+
+func run(r: GameTestRunner) -> void:
+ _clean()
+ _round_trip(r)
+ _bad_saves(r)
+ _migration(r)
+ _autosave(r)
+ _settings(r)
+ _assessment(r)
+ _clean()
+
+
+func _clean() -> void:
+ for p in [SAVE, SAVE + ".tmp", SETTINGS]:
+ if FileAccess.file_exists(p):
+ DirAccess.remove_absolute(ProjectSettings.globalize_path(p))
+
+
+## A morning with something in every field.
+static func busy_state(cfg: GameConfig) -> FarmState:
+ var s := FarmState.create(cfg)
+ s.night = 3
+ s.nights_survived = 2
+ s.phase = P.MORNING
+ s.scarecrow_max_hp = 12
+ s.scarecrow_hp = 7
+ s.lose_crop(4)
+ s.lose_crop(17)
+ s.lose_animal(2)
+ s.resources.shed = {"wood": 13, "scrap": 2, "straw": 21}
+ s.resources.pouch = {"wood": 0, "scrap": 3, "straw": 1}
+ s.gather_charges = {"DeadTree": 1, "Haystack": 0}
+ s.upgrades = {"rapid_fire": 1, "sticky_tar": 1}
+ s.structures.append({"id": s.next_structure_id, "type": "fence", "x": 30.5, "z": -18.5, "rot": 3, "hp": 11})
+ s.next_structure_id += 1
+ s.structures.append({"id": s.next_structure_id, "type": "slowing_trap", "x": 12.0, "z": -7.25, "rot": 0, "hp": 2})
+ s.next_structure_id += 1
+ for n in [1, 2]:
+ var e := {"night": n, "crops_lost": n, "animals_lost": n - 1}
+ for k in FarmState.EVENTS:
+ e[k] = n * 3 + FarmState.EVENTS.find(k)
+ s.night_log.append(e)
+ return s
+
+
+func _round_trip(r: GameTestRunner) -> void:
+ var cfg := load("res://game/resources/game_config.tres") as GameConfig
+ var s := busy_state(cfg)
+ var before := s.to_dict()
+ var err := SaveGame.write(before, SAVE)
+ r.check(err == OK and FileAccess.file_exists(SAVE) and not FileAccess.file_exists(SAVE + ".tmp"),
+ "the save is written (through a temporary file that's renamed into place)")
+ var loaded := SaveGame.read(SAVE)
+ r.check(loaded.status == SaveGame.Status.OK and loaded.state != null and loaded.message == "" and loaded.saved_at != "",
+ "and reads back (saved at %s)" % loaded.saved_at)
+ if loaded.state == null:
+ return
+ var after := loaded.state.to_dict()
+ var differ: Array[String] = []
+ for key in before:
+ if JSON.stringify(before[key], "", true, true) != JSON.stringify(after.get(key), "", true, true):
+ differ.append(key)
+ r.check(differ.is_empty() and before.size() == after.size(), "saving then loading reproduces the farm state field for field (differ: %s)" % [differ])
+ r.check(loaded.state.crops == s.crops and loaded.state.animals == s.animals and loaded.state.supplies == s.supplies
+ and loaded.state.structures[-2]["x"] == 30.5 and loaded.state.structures[-1]["z"] == -7.25
+ and loaded.state.night_log[1]["killed_crow"] == s.night_log[1]["killed_crow"],
+ "derived counts, positions, and the nightly records survive")
+
+
+func _bad_saves(r: GameTestRunner) -> void:
+ var cfg := load("res://game/resources/game_config.tres") as GameConfig
+ _clean()
+ var missing := SaveGame.read(SAVE)
+ r.check(missing.status == SaveGame.Status.MISSING and missing.state == null and missing.message == "No saved vacation",
+ "no save: MISSING")
+ _write_text("{ this is not json")
+ var garbage := SaveGame.read(SAVE)
+ r.check(garbage.status == SaveGame.Status.CORRUPT and garbage.state == null and garbage.message.contains("damaged"),
+ "unreadable JSON: CORRUPT ('%s')" % garbage.message)
+ _write_text(JSON.stringify({"game": "another-game", "state": {}}))
+ r.check(SaveGame.read(SAVE).status == SaveGame.Status.CORRUPT, "another game's file: CORRUPT")
+ var d := busy_state(cfg).to_dict()
+ d["scarecrow_hp"] = 99 # more than its maximum
+ SaveGame.write(d, SAVE)
+ r.check(SaveGame.read(SAVE).status == SaveGame.Status.CORRUPT, "a state that breaks the rules: CORRUPT")
+ d = busy_state(cfg).to_dict()
+ d["phase"] = int(P.NIGHT)
+ SaveGame.write(d, SAVE)
+ r.check(SaveGame.read(SAVE).status == SaveGame.Status.CORRUPT, "a save that isn't a morning: CORRUPT")
+ d = busy_state(cfg).to_dict()
+ d.erase("night_log")
+ SaveGame.write(d, SAVE)
+ r.check(SaveGame.read(SAVE).status == SaveGame.Status.CORRUPT, "a missing field: CORRUPT")
+ d = busy_state(cfg).to_dict()
+ d["version"] = FarmState.VERSION + 1
+ SaveGame.write(d, SAVE)
+ var newer := SaveGame.read(SAVE)
+ r.check(newer.status == SaveGame.Status.NEWER and newer.state == null and newer.version == FarmState.VERSION + 1
+ and newer.message.contains("newer"), "a save from a newer version: NEWER, not loaded")
+ d["version"] = 1
+ SaveGame.write(d, SAVE)
+ var old := SaveGame.read(SAVE)
+ r.check(old.status == SaveGame.Status.OLD and old.state == null and old.message.contains("older"),
+ "a save from version 1 (no way forward): OLD, not loaded")
+
+
+func _migration(r: GameTestRunner) -> void:
+ var cfg := load("res://game/resources/game_config.tres") as GameConfig
+ var s := busy_state(cfg)
+ var d := s.to_dict()
+ d["version"] = 2
+ var v2_keys := ["night", "crops_lost", "animals_lost", "supplies_lost", "crops_stolen", "crops_recovered",
+ "animals_stolen", "animals_strayed", "animals_recovered", "supplies_stolen", "supplies_recovered"]
+ for e: Dictionary in d["night_log"]:
+ for k in e.keys():
+ if not v2_keys.has(k):
+ e.erase(k)
+ SaveGame.write(d, SAVE)
+ var loaded := SaveGame.read(SAVE)
+ r.check(loaded.status == SaveGame.Status.OK and loaded.version == 2, "a version 2 save is upgraded and loads")
+ if loaded.state == null:
+ return
+ var e: Dictionary = loaded.state.night_log[1]
+ r.check(e["crops_stolen"] == s.night_log[1]["crops_stolen"] and e["killed_crow"] == 0 and e["gathered_wood"] == 0
+ and loaded.state.scarecrow_hp == 7 and loaded.state.structures.size() == s.structures.size(),
+ "keeping what it had and counting the new nightly records from zero")
+
+
+func _autosave(r: GameTestRunner) -> void:
+ _clean()
+ var c := r.make_campaign()
+ c.save_path = SAVE
+ c.new_campaign()
+ var first := SaveGame.read(SAVE)
+ r.check(first.status == SaveGame.Status.OK and first.state.night == 1 and c.last_save_error == OK,
+ "a new vacation is saved at once (the morning of night 1)")
+ GameTestRunner.run_until(c, P.DAY)
+ c.state.resources.shed["wood"] = 99
+ GameTestRunner.run_until(c, P.NIGHT)
+ GameTestRunner.run_until(c, P.MORNING)
+ var second := SaveGame.read(SAVE)
+ r.check(second.status == SaveGame.Status.OK and second.state.night == 2 and second.state.resources.shed["wood"] == 99
+ and second.state.night_log.size() == 1, "every morning is autosaved (now the morning of night 2)")
+ var morning := c.state.to_dict()
+ GameTestRunner.run_until(c, P.NIGHT)
+ c.state.scarecrow_hp = 1
+ GameTestRunner.lose_crops(c.state, 5)
+ r.check(c.retry_night() and JSON.stringify(c.state.to_dict(), "", true, true) == JSON.stringify(morning, "", true, true)
+ and JSON.stringify(SaveGame.read(SAVE).state.to_dict(), "", true, true) == JSON.stringify(morning, "", true, true),
+ "retry restores the morning state, which is also what's saved")
+ var guard := 0
+ while not c.is_over() and guard < 100:
+ GameTestRunner.run_until(c, P.MORNING if c.state.phase != P.MORNING else P.DAY)
+ guard += 1
+ r.check(c.outcome == CampaignController.Outcome.VACATION_COMPLETE and not SaveGame.exists(SAVE),
+ "finishing the vacation deletes the save (nothing left to continue)")
+ c.queue_free()
+ var quiet := r.make_campaign()
+ r.check(quiet.save_path == "" and not SaveGame.exists(SAVE), "without a save path nothing is written")
+ quiet.queue_free()
+
+
+func _settings(r: GameTestRunner) -> void:
+ _clean()
+ var fresh := GameSettings.load_from(SETTINGS)
+ r.check(fresh.volume == GameSettings.DEFAULT_VOLUME and fresh.show_tips and fresh.vsync and not fresh.fullscreen
+ and fresh.resolution_scale == 1.0, "no settings file: the defaults")
+ var g := GameSettings.new()
+ g.volume = {"Master": 0.5, "Music": 0.25, "SFX": 0.0, "Ambience": 1.0, "Voice": 0.6}
+ g.move_dead_zone = 0.35
+ g.aim_dead_zone = 0.15
+ g.fullscreen = true
+ g.vsync = false
+ g.resolution_scale = 0.75
+ g.show_tips = false
+ g.player_name = "Ana"
+ g.microphone = false
+ r.check(g.save_to(SETTINGS) == OK, "settings save")
+ var back := GameSettings.load_from(SETTINGS)
+ r.check(back.volume == g.volume and back.move_dead_zone == 0.35 and back.aim_dead_zone == 0.15 and back.fullscreen
+ and not back.vsync and back.resolution_scale == 0.75 and not back.show_tips and back.player_name == "Ana"
+ and not back.microphone, "and load back unchanged (co-op name and microphone too)")
+ var f := ConfigFile.new()
+ f.set_value("audio", "master", 7.0)
+ f.set_value("audio", "music", "loud")
+ f.set_value("display", "fullscreen", "yes")
+ f.set_value("display", "resolution_scale", 0.1)
+ f.save(SETTINGS)
+ var odd := GameSettings.load_from(SETTINGS)
+ r.check(odd.volume["Master"] == 1.0 and odd.volume["Music"] == GameSettings.DEFAULT_VOLUME["Music"] and not odd.fullscreen
+ and odd.resolution_scale == 0.5, "out-of-range and wrong-typed values are clamped or fall back")
+ var cfg := (load("res://game/resources/game_config.tres") as GameConfig).duplicate() as GameConfig
+ g.apply(null, cfg)
+ var music := AudioServer.get_bus_index("Music")
+ var sfx := AudioServer.get_bus_index("SFX")
+ r.check(music >= 0 and sfx >= 0 and AudioServer.get_bus_index("Ambience") >= 0, "the audio buses exist (Master, Music, SFX, Ambience)")
+ r.check(is_equal_approx(AudioServer.get_bus_volume_db(music), linear_to_db(0.25)) and AudioServer.is_bus_mute(sfx)
+ and not AudioServer.is_bus_mute(music), "volumes apply to the buses (and zero mutes)")
+ r.check(is_equal_approx(InputMap.action_get_deadzone("move_left"), 0.35) and is_equal_approx(cfg.aim_dead_zone, 0.15),
+ "dead zones apply to the move actions and the aim")
+ GameSettings.new().apply(null, cfg) # back to the defaults for the other suites
+
+
+func _assessment(r: GameTestRunner) -> void:
+ var cfg := load("res://game/resources/game_config.tres") as GameConfig
+ var s := FarmState.create(cfg)
+ GameTestRunner.lose_crops(s, 3)
+ s.lose_animal(1)
+ s.lose_animal(2)
+ var e := {"night": 1, "crops_lost": 3, "animals_lost": 2}
+ for k in FarmState.EVENTS:
+ e[k] = 0
+ e["gathered_wood"] = 50
+ e["gathered_straw"] = 40
+ e["supplies_lost"] = 4
+ s.night_log.append(e)
+ var a := Assessment.of(s, cfg)
+ var handled := s.supplies_total + 90
+ var want := roundi(100.0 * (0.5 * 27.0 / 30.0 + 0.3 * 6.0 / 8.0 + 0.2 * (1.0 - 4.0 / handled)))
+ r.check(a["score"] == want and a["tier"] == "Bumper crop" and a["supplies_handled"] == handled and a["supplies_lost"] == 4,
+ "the score weighs each category kept (%d points, %s)" % [a["score"], a["tier"]])
+ var perfect := Assessment.of(FarmState.create(cfg), cfg)
+ r.check(perfect["score"] == 100 and perfect["tier"] == "Blue-ribbon harvest" and perfect["text"] != "", "nothing lost: 100, the top tier")
+ s.lose_all_crops()
+ s.lose_all_animals()
+ r.check(Assessment.of(s, cfg)["tier"] == "Hanging by a thread", "little left: the bottom tier")
+ var no_animals := FarmState.create(cfg)
+ no_animals.animals_total = 0
+ GameTestRunner.lose_crops(no_animals, 15)
+ var b := Assessment.of(no_animals, cfg)
+ r.check(not (b["parts"] as Dictionary).has("animals") and b["score"] == roundi(100.0 * (0.5 * 0.5 + 0.2) / 0.7),
+ "categories not in play are left out and the weights renormalized")
+ r.check(Assessment.enemies_line({"killed_crow": 3, "killed_thief": 1, "killed_breaker": 0}) == "3 crows and 1 thief"
+ and Assessment.materials_line({"spent_wood": 4, "spent_straw": 2}, "spent_") == "4 wood, 2 straw"
+ and Assessment.materials_line({}, "gathered_") == "nothing", "the totals read as words")
+
+
+func _write_text(text: String) -> void:
+ var f := FileAccess.open(SAVE, FileAccess.WRITE)
+ f.store_string(text)
+ f.close()
diff --git a/game/tests/test_save.gd.uid b/game/tests/test_save.gd.uid
new file mode 100644
index 0000000..0330629
--- /dev/null
+++ b/game/tests/test_save.gd.uid
@@ -0,0 +1 @@
+uid://b630ievxokts1
diff --git a/game/tests/test_scarecrow.gd b/game/tests/test_scarecrow.gd
new file mode 100644
index 0000000..dcc1ebe
--- /dev/null
+++ b/game/tests/test_scarecrow.gd
@@ -0,0 +1,304 @@
+extends RefCounted
+## The scarecrow's kit on the real farm, with FarmSim stepped by hand at 60 Hz: health and
+## invulnerability (several hits on one tick cost one), thief melee (touching, on a cooldown,
+## not through cover, not while fleeing), fear (only thieves in range flee, carriers drop their
+## crop, thieves mid-steal lose their progress, the cooldown, thieves come back afterwards),
+## patching up (heals after the full channel while rooted; release, a hit, or fear cancel it;
+## not at full health), sprint (only with the Sprint upgrade: faster while held and moving, 3 s at
+## most, then a 10 s recharge; letting go or stopping ends it early; the HUD line), defeat (Game
+## Over ahead of a stripped farm, the fall, the end panel and its Retry), the morning revive, and
+## the new input actions.
+
+const S := LootSystem.Status
+const T := ThiefBehavior.State
+const DT := 1.0 / 60.0
+const AWAY := Vector3(-11.0, 0.0, 13.0)
+const SPOT := Vector2(8.0, -10.0) # open ground between the pen, the shed, and the field
+
+
+func run(r: GameTestRunner) -> void:
+ _input_actions(r)
+ var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
+ r.root.add_child(farm)
+ await r.process_frame
+ await r.physics_frame
+ var sim := farm.get_node("FarmSim") as FarmSim
+ sim.set_physics_process(false)
+ sim.waves.enabled = false
+ var player := farm.get_node("Player") as PlayerCharacter
+ player.global_position = Vector3(SPOT.x, 0.0, SPOT.y)
+ r.check(sim.scarecrow != null and sim.scarecrow.hp() == sim.config.scarecrow_max_hp and sim.scarecrow.fear_left == 0.0,
+ "the scarecrow starts at full health with fear ready")
+ _damage(r, sim)
+ _melee(r, sim)
+ _fear(r, sim)
+ _patch(r, sim, player)
+ await _sprint(r, sim, player, farm.get_node("Hud/ScarecrowHud") as ScarecrowHud)
+ _defeat(r, sim, player, farm.get_node("Hud/EndPanel") as EndPanel)
+ farm.queue_free()
+ await r.process_frame
+
+
+func _input_actions(r: GameTestRunner) -> void:
+ for action in ["fear", "patch", "interact", "build_mode", "rotate_left", "rotate_right", "cancel", "pause", "sprint"]:
+ var keyboard := false
+ var pad := false
+ if InputMap.has_action(action):
+ for e in InputMap.action_get_events(action):
+ keyboard = keyboard or e is InputEventKey or e is InputEventMouseButton
+ pad = pad or e is InputEventJoypadButton
+ r.check(keyboard and pad, "input action '%s' has a keyboard/mouse and a gamepad binding" % action)
+
+
+func _damage(r: GameTestRunner, sim: FarmSim) -> void:
+ var kit := sim.scarecrow
+ var s := sim.campaign.state
+ var hits: Array[int] = [] # lambdas capture ints by value, so count in an array
+ kit.damaged.connect(func(hp: int) -> void: hits.append(hp))
+ r.check(kit.try_damage(1) and s.scarecrow_hp == 9 and is_equal_approx(kit.invulnerable_left, sim.config.invulnerability_time),
+ "an accepted hit costs 1 HP and starts the invulnerability")
+ r.check(not kit.try_damage(1) and s.scarecrow_hp == 9 and kit.rejected_hits == 1, "hits during invulnerability are rejected")
+ _step(sim, roundi(sim.config.invulnerability_time * 60.0) + 1)
+ var accepted := 0
+ for i in 3:
+ if kit.try_damage(1):
+ accepted += 1
+ r.check(accepted == 1 and s.scarecrow_hp == 8 and hits == [9, 8], "three hits on one tick cost one hit")
+ _heal(sim)
+
+
+func _melee(r: GameTestRunner, sim: FarmSim) -> void:
+ var es := sim.enemies
+ var kit := sim.scarecrow
+ var s := sim.campaign.state
+ var h := es.spawn(EnemySystem.TYPE_THIEF, SPOT.x + 0.6, SPOT.y, Vector2.LEFT)
+ _step(sim, 1)
+ r.check(s.scarecrow_hp == s.scarecrow_max_hp - 1 and es.attacks_attempted == 1, "a thief touching the scarecrow hits it")
+ var d := es.resolve_handle(h)
+ r.check(es.attack_cd[d] > 1.0, "the thief's attack cooldown started")
+ _place(es, h, Vector2(SPOT.x + 0.6, SPOT.y))
+ _step(sim, 30)
+ r.check(s.scarecrow_hp == s.scarecrow_max_hp - 1 and es.attacks_attempted == 1, "no second attack while the cooldown runs")
+ # Fleeing thieves don't fight.
+ _heal(sim)
+ _place(es, h, Vector2(SPOT.x + 0.6, SPOT.y))
+ d = es.resolve_handle(h)
+ es.attack_cd[d] = 0.0
+ es.state[d] = T.FLEE
+ es.timer[d] = 5.0
+ es.grid.rebuild(es.pos_x, es.pos_z, es.active_count)
+ es.evaluate_attacks(SPOT, FarmSim.SCARECROW_RADIUS, kit)
+ r.check(s.scarecrow_hp == s.scarecrow_max_hp, "a fleeing thief doesn't attack")
+ # Cover: a thief on the far side of the south fence, within (an enlarged) reach.
+ es.state[d] = T.SEEK
+ _place(es, h, Vector2(20.25, 15.75))
+ es.grid.rebuild(es.pos_x, es.pos_z, es.active_count)
+ var blocked := es.attacks_blocked_by_cover
+ es.evaluate_attacks(Vector2(20.25, 14.6), 0.8, kit)
+ r.check(es.attacks_blocked_by_cover == blocked + 1 and s.scarecrow_hp == s.scarecrow_max_hp, "a thief can't hit through the fence")
+ _kill_all(sim)
+
+
+func _fear(r: GameTestRunner, sim: FarmSim) -> void:
+ var es := sim.enemies
+ var loot := sim.loot
+ var kit := sim.scarecrow
+ var near := es.spawn(EnemySystem.TYPE_THIEF, SPOT.x + 3.0, SPOT.y, Vector2.LEFT)
+ var far := es.spawn(EnemySystem.TYPE_THIEF, SPOT.x + 9.0, SPOT.y, Vector2.LEFT)
+ var carrier := es.spawn(EnemySystem.TYPE_THIEF, SPOT.x, SPOT.y + 4.0, Vector2.UP)
+ var stealer := es.spawn(EnemySystem.TYPE_THIEF, SPOT.x - 3.0, SPOT.y - 3.5, Vector2.UP)
+ var cu := _home_unit(loot, -1)
+ loot.holder[cu] = carrier
+ loot.pick_up(cu, carrier)
+ es.carry[es.resolve_handle(carrier)] = cu
+ es.state[es.resolve_handle(carrier)] = T.CARRY
+ var su := _home_unit(loot, cu)
+ loot.holder[su] = stealer
+ loot.set_progress(su, stealer, 0.6)
+ es.target[es.resolve_handle(stealer)] = su
+ es.state[es.resolve_handle(stealer)] = T.STEAL
+ var used: Array[int] = []
+ kit.fear_used.connect(func(_p: Vector3, n: int) -> void: used.append(n))
+ Input.action_press("fear")
+ _step(sim, 1)
+ Input.action_release("fear")
+ r.check(used == [3], "the fear action scares the 3 thieves within %.0f m (got %s)" % [sim.config.fear_radius, used])
+ for h in [near, carrier, stealer]:
+ r.check(es.state[es.resolve_handle(h)] == T.FLEE, "a thief in range flees")
+ r.check(es.state[es.resolve_handle(far)] != T.FLEE, "the thief 9 m away is unaffected")
+ r.check(loot.status[cu] == S.DROPPED and es.carry[es.resolve_handle(carrier)] == -1, "the scared carrier drops its crop")
+ r.check(loot.holder[su] == -1 and loot.progress[su] == 0.0, "the scared thief loses its claim and progress")
+ var d0 := Vector2(es.pos_x[es.resolve_handle(near)], es.pos_z[es.resolve_handle(near)]).distance_to(SPOT)
+ _step(sim, 30)
+ var d1 := Vector2(es.pos_x[es.resolve_handle(near)], es.pos_z[es.resolve_handle(near)]).distance_to(SPOT)
+ r.check(d1 > d0 + 1.0, "fleeing thieves run away from the scarecrow (%.1f -> %.1f m)" % [d0, d1])
+ r.check(kit.use_fear() == -1 and kit.fear_left > 10.0, "fear can't be used again during its cooldown")
+ _step(sim, roundi(sim.config.fear_duration * 60.0))
+ r.check(es.state[es.resolve_handle(near)] == T.SEEK and es.state[es.resolve_handle(carrier)] == T.SEEK,
+ "after %.0f s the thieves get back to stealing" % sim.config.fear_duration)
+ _kill_all(sim)
+ var readied: Array[int] = []
+ kit.fear_ready.connect(func() -> void: readied.append(1))
+ _step(sim, roundi(sim.config.fear_cooldown * 60.0))
+ r.check(kit.fear_left == 0.0 and readied.size() == 1 and kit.use_fear() == 0, "fear is ready again after its cooldown")
+ kit.fear_left = 0.0
+ _step(sim, 1)
+ _return_crops(sim)
+
+
+func _patch(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var kit := sim.scarecrow
+ var s := sim.campaign.state
+ s.resources.shed["straw"] = 40 # patching costs straw (Step 5)
+ kit.step_patch(DT, true)
+ r.check(not kit.patching, "no patching at full health")
+ s.scarecrow_hp = 5
+ Input.action_press("patch")
+ _step(sim, 30)
+ r.check(kit.patching and player.rooted and not kit.can_shoot(), "patching roots the scarecrow and stops it shooting")
+ _step(sim, roundi(sim.config.patch_time * 60.0) - 30 + 2) # +2: float sums land a tick late
+ r.check(s.scarecrow_hp == 5 + sim.config.patch_heal,
+ "a full %.0f s patch restores %d HP (now %d)" % [sim.config.patch_time, sim.config.patch_heal, s.scarecrow_hp])
+ r.check(kit.patching, "still holding (and not at full health): the next patch starts")
+ Input.action_release("patch")
+ _step(sim, 1)
+ r.check(not kit.patching and not player.rooted, "letting go frees the scarecrow")
+ s.scarecrow_hp = 5
+ Input.action_press("patch")
+ _step(sim, 60)
+ Input.action_release("patch")
+ _step(sim, 60)
+ r.check(s.scarecrow_hp == 5 and not kit.patching, "releasing early cancels the patch")
+ Input.action_press("patch")
+ _step(sim, 60)
+ kit.invulnerable_left = 0.0
+ kit.try_damage(1)
+ r.check(not kit.patching and s.scarecrow_hp == 4, "a hit cancels the patch")
+ _step(sim, 60)
+ r.check(s.scarecrow_hp == 4 and kit.patching, "holding on starts the patch over from the beginning")
+ kit.use_fear()
+ r.check(not kit.patching, "using fear cancels the patch")
+ Input.action_release("patch")
+ _step(sim, 1)
+ kit.fear_left = 0.0
+ _heal(sim)
+
+
+func _sprint(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter, hud: ScarecrowHud) -> void:
+ var cfg := sim.config
+ var s := sim.campaign.state
+ s.upgrades.erase("sprint")
+ hud._process(0.0)
+ r.check(not player.can_sprint() and not hud._sprint_label.visible, "no sprint (and no sprint line on the HUD) before the upgrade")
+ # On the real body, over physics frames: the open ground south-west of the pen.
+ player.global_position = Vector3(0.0, 0.0, 6.0)
+ player.velocity = Vector3.ZERO
+ Input.action_press("move_right")
+ Input.action_press("sprint")
+ await _frames(r, 30)
+ var speed := Vector2(player.velocity.x, player.velocity.z).length()
+ r.check(not player.sprinting and speed <= player.run_speed + 0.05, "without it, holding sprint just runs (%.1f m/s)" % speed)
+ s.upgrades["sprint"] = 1
+ await _frames(r, 30)
+ speed = Vector2(player.velocity.x, player.velocity.z).length()
+ r.check(player.sprinting and absf(speed - player.run_speed * cfg.sprint_speed_mult) < 0.1,
+ "with the Sprint upgrade, holding sprint while moving sprints: %.1f m/s (runs at %.1f)" % [speed, player.run_speed])
+ r.check(player.animation_player.current_animation == player.run_animation and player.animation_player.speed_scale > 1.5,
+ "the run clip plays faster (x%.2f)" % player.animation_player.speed_scale)
+ r.check(player.move_strength() > 1.5, "the partner's machine is told it's sprinting (strength %.2f)" % player.move_strength())
+ hud._process(0.0)
+ r.check(hud._sprint_label.visible and hud._sprint_label.text.begins_with("Sprinting"), "the HUD shows the sprint running: '%s'" % hud._sprint_label.text)
+ Input.action_release("move_right")
+ await _frames(r, 2)
+ r.check(not player.sprinting and player.sprint_recharge > cfg.sprint_cooldown - 0.1, "stopping ends it, and the recharge starts")
+ hud._process(0.0)
+ r.check(hud._sprint_label.text == "Sprint %.0f s" % ceilf(player.sprint_recharge), "the HUD counts the recharge down: '%s'" % hud._sprint_label.text)
+ Input.action_release("sprint")
+ await _frames(r, 30)
+ player.velocity = Vector3.ZERO
+ player.global_position = Vector3(SPOT.x, 0.0, SPOT.y)
+ # The timing, tick by tick.
+ player.reset_sprint()
+ var ticks := 0
+ player.step_sprint(DT, true, true)
+ while player.sprinting and ticks < 1200:
+ player.step_sprint(DT, true, true)
+ ticks += 1
+ r.check(absf(ticks * DT - cfg.sprint_time) < DT * 2.0, "held, a sprint lasts %.1f s" % (ticks * DT))
+ ticks = 0
+ while not player.sprinting and ticks < 1200:
+ player.step_sprint(DT, true, true)
+ ticks += 1
+ r.check(absf(ticks * DT - cfg.sprint_cooldown) < DT * 2.0, "then %.1f s to recharge, and still held it starts again" % (ticks * DT))
+ player.step_sprint(1.0, true, true)
+ player.step_sprint(DT, false, true)
+ r.check(not player.sprinting and is_equal_approx(player.sprint_recharge, cfg.sprint_cooldown), "letting go early ends it, and the full recharge starts")
+ player.step_sprint(DT, true, false)
+ r.check(not player.sprinting, "and it doesn't start standing still")
+ sim.scarecrow.reset_for_morning()
+ hud._process(0.0)
+ r.check(player.sprint_recharge == 0.0 and hud._sprint_label.text == "Sprint hold Shift / L3", "a new morning has it ready: '%s'" % hud._sprint_label.text)
+ s.upgrades.erase("sprint")
+
+
+func _frames(r: GameTestRunner, n: int) -> void:
+ for i in n:
+ await r.physics_frame
+
+
+func _defeat(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter, panel: EndPanel) -> void:
+ var kit := sim.scarecrow
+ var c := sim.campaign
+ var s := c.state
+ s.scarecrow_hp = 1
+ s.strip() # the farm is stripped on the same tick the scarecrow falls
+ r.check(kit.try_damage(1) and not kit.alive and not player.alive, "the last HP lost: the scarecrow falls")
+ r.check(player.animation_player.current_animation == player.death_animation, "the death clip plays")
+ sim.step(DT)
+ r.check(c.state.phase == CampaignController.Phase.GAME_OVER and c.outcome == CampaignController.Outcome.GAME_OVER_SCARECROW,
+ "Game Over, reported as the scarecrow's fall ahead of the stripped farm")
+ r.check(not kit.try_damage(1) and kit.use_fear() == -1 and not kit.can_shoot(), "a fallen scarecrow takes no hits and can't act")
+ r.check(not panel.visible, "the end panel waits a moment so the fall can play")
+ panel._process(EndPanel.DELAY + 0.1)
+ r.check(panel.visible and panel._retry.visible and panel._retry.has_focus(), "the end panel shows with Retry focused")
+ panel._retry.pressed.emit()
+ sim.step(DT)
+ r.check(c.state.phase == CampaignController.Phase.MORNING and not panel.visible, "Retry goes back to the morning")
+ r.check(kit.alive and player.alive and kit.fear_left == 0.0 and c.state.scarecrow_hp == c.state.scarecrow_max_hp and c.state.crops == c.state.crops_total,
+ "the scarecrow is back on its feet and the farm as it was that morning")
+
+
+func _heal(sim: FarmSim) -> void:
+ sim.campaign.state.scarecrow_hp = sim.campaign.state.scarecrow_max_hp
+ sim.scarecrow.invulnerable_left = 0.0
+
+
+func _kill_all(sim: FarmSim) -> void:
+ for d in sim.enemies.active_count:
+ sim.enemies.apply_hit(d, 99)
+ _step(sim, 1)
+ _heal(sim)
+
+
+func _return_crops(sim: FarmSim) -> void:
+ sim.loot.return_dropped()
+
+
+func _place(es: EnemySystem, handle: int, p: Vector2) -> void:
+ var d := es.resolve_handle(handle)
+ es.pos_x[d] = p.x
+ es.pos_z[d] = p.y
+ es.prev_x[d] = p.x
+ es.prev_z[d] = p.y
+
+
+func _home_unit(loot: LootSystem, other: int) -> int:
+ for id in range(1, loot.unit_count + 1):
+ if id != other and loot.status[id] == S.HOME and loot.holder[id] == -1:
+ return id
+ return -1
+
+
+func _step(sim: FarmSim, n: int) -> void:
+ for i in n:
+ sim.step(DT)
diff --git a/game/tests/test_scarecrow.gd.uid b/game/tests/test_scarecrow.gd.uid
new file mode 100644
index 0000000..3e75d01
--- /dev/null
+++ b/game/tests/test_scarecrow.gd.uid
@@ -0,0 +1 @@
+uid://nl0xkav8xpmi
diff --git a/game/tests/test_structures.gd b/game/tests/test_structures.gd
new file mode 100644
index 0000000..a0eb0f1
--- /dev/null
+++ b/game/tests/test_structures.gd
@@ -0,0 +1,436 @@
+extends RefCounted
+## Construction on the real farm, with FarmSim stepped by hand: placement rules (each reason),
+## build mode driven by gamepad input (build, dismantle, leave), paying and recording, the sliced
+## flow-field rebuild, gates (the scarecrow passes, enemies can't), a walled-in thief breaking
+## out through a fence (barrier routing), slowing traps (speed, triggers), the automated
+## defense (range), damage and breaking (breach), repair (cost, any phase), dismantling (refund),
+## persistence and retry, and an A/B night: the same attack on an open and on a fenced crop field.
+
+const P := CampaignController.Phase
+const T := ThiefBehavior.State
+const DT := 1.0 / 60.0
+const AWAY := Vector3(-11.0, 0.0, 13.0)
+
+
+func run(r: GameTestRunner) -> void:
+ var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
+ r.root.add_child(farm)
+ await r.process_frame
+ await r.physics_frame
+ var sim := farm.get_node("FarmSim") as FarmSim
+ sim.set_physics_process(false)
+ sim.waves.enabled = false
+ var player := farm.get_node("Player") as PlayerCharacter
+ var c := sim.campaign
+ c.begin_day()
+ _rich(c)
+ _validation(r, sim)
+ _place_and_rebuild(r, sim)
+ _build_mode(r, sim, player)
+ await _gate(r, sim, player)
+ _breakout(r, sim, player)
+ _trap(r, sim)
+ _turret(r, sim)
+ _repair_and_dismantle(r, sim, player)
+ _persistence(r, sim)
+ _ab_night(r, sim, player)
+ farm.queue_free()
+ await r.process_frame
+
+
+func _rich(c: CampaignController) -> void:
+ c.state.resources.shed = {"wood": 999, "scrap": 999, "straw": 999}
+
+
+func _validation(r: GameTestRunner, sim: FarmSim) -> void:
+ var st := sim.structures
+ var cases := [
+ ["open ground", "fence", Vector2(8.0, -8.0), 0, ""],
+ ["outside the fence", "fence", Vector2(-14.0, 0.0), 0, "Build inside the farm"],
+ ["in the north fence's gap", "fence", Vector2(12.0, -44.0), 0, "Keep the gap clear"],
+ ["where the west fence was", "fence", Vector2(-11.5, -6.0), 2, ""],
+ ["at the barn doors", "fence", Vector2(1.0, -19.5), 0, "Keep the barn doors clear"],
+ ["on a crop row", "fence", sim.loot.home[1], 2, "Not on the crops"],
+ ["in the house", "automated_defense", Vector2(20.5, -26.0), 0, "Blocked"],
+ ["on the pen fence", "fence", Vector2(-3.0, -11.0), 0, "Blocked"],
+ ]
+ for case in cases:
+ var why := st.validate(case[1], case[2].x, case[2].y, case[3], case[2] + Vector2(2.0, 2.0))
+ r.check(why == case[4], "%s %s: '%s' (got '%s')" % [StructureSystem.NAMES[case[1]], case[0], case[4], why])
+ var at := Vector2(8.0, -8.0)
+ r.check(st.validate("fence", at.x, at.y, 0, at) == "The scarecrow is in the way", "not on top of the scarecrow")
+ r.check(st.validate("gate", at.x, at.y, 0, at) == "", "a gate may go where the scarecrow stands (it walks through)")
+ r.check(st.validate("fence", at.x, at.y, 0, at + Vector2(12.0, 0.0)) == "Too far from the scarecrow", "only within reach of the scarecrow")
+ var h := sim.enemies.spawn(EnemySystem.TYPE_THIEF, at.x, at.y, Vector2.LEFT)
+ r.check(st.validate("fence", at.x, at.y, 0, at + Vector2(2.0, 2.0)) == "An enemy is in the way", "not on top of an enemy")
+ sim.enemies.apply_hit_handle(h, 99)
+ _step(sim, 1)
+ var res := sim.campaign.state.resources
+ var keep: Dictionary = res.shed.duplicate()
+ res.shed = {"wood": 1, "scrap": 0, "straw": 0}
+ r.check(st.validate("fence", at.x, at.y, 0, at + Vector2(2.0, 2.0)) == "Not enough: need 1 wood more", "and only if it's affordable")
+ res.shed = keep
+ sim.campaign.advance_phase()
+ sim.campaign.advance_phase()
+ r.check(st.validate("fence", at.x, at.y, 0, at + Vector2(2.0, 2.0)) == "Building is for daytime", "no building at night")
+ _to_day(sim)
+
+
+func _place_and_rebuild(r: GameTestRunner, sim: FarmSim) -> void:
+ var st := sim.structures
+ var s := sim.campaign.state
+ var wood := int(s.resources.shed["wood"])
+ var rebuilds := sim.rebuilds
+ var id := st.place("fence", 8.0, -8.0, 0)
+ var e := s.structure(id)
+ r.check(id >= 1 and e.get("hp") == sim.config.fence_hp and int(s.resources.shed["wood"]) == wood - 2, "a fence costs 2 wood and is recorded with 20 HP")
+ r.check(sim.nav.structure_at[sim.nav.cell_of(8.0, -8.0)] == id and sim.nav.structure_at[sim.nav.cell_of(6.0, -8.0)] < 0,
+ "its cells (inflated) are barrier cells for enemies")
+ r.check(sim.rebuilding, "placing it starts a flow-field rebuild")
+ var ticks := 0
+ while sim.rebuilding and ticks < 600:
+ sim.step(DT)
+ ticks += 1
+ r.check(not sim.rebuilding and sim.rebuilds == rebuilds + 1, "the rebuild completes over %d ticks" % sim.last_rebuild_ticks)
+ r.info("flow-field rebuild (escape, pen, 3 shed piles, fence breakers): %.1f ms over %d ticks, largest slice %.2f ms (%d cells per tick)" % [
+ sim.last_rebuild_usec / 1000.0, sim.last_rebuild_ticks, sim.max_rebuild_slice_usec / 1000.0, sim.config.flow_slice_cells])
+ r.check(st.validate("fence", 8.0, -8.0, 0, Vector2(10.0, -6.0)) == "Something is built here already", "no stacking structures")
+ r.check(st.validate("fence", 9.0, -7.0, 2, Vector2(11.0, -5.0)) == "", "a fence may touch another at its end (corners)")
+ r.check(st.validate("slowing_trap", 8.0, -8.5, 0, Vector2(10.0, -6.0)) == "Something is built here already", "a trap can't overlap a fence")
+ st.dismantle(id)
+ _settle(sim)
+
+
+## Gamepad: aim right, open build mode, build a fence ahead, dismantle it, and leave.
+func _build_mode(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var b := sim.build
+ var st := sim.structures
+ player.global_position = Vector3(6.0, 0.0, -2.0)
+ sim.combat.device = ScarecrowCombat.Device.GAMEPAD
+ Input.action_press("aim_right", 1.0)
+ _tap(sim, "build_mode")
+ r.check(b.active, "build mode opens")
+ _tap(sim, "build_2")
+ r.check(b.type() == "gate", "2 picks the gate")
+ _tap(sim, "build_next")
+ _tap(sim, "build_next")
+ _tap(sim, "build_next")
+ r.check(b.type() == "fence", "build_next cycles back to the fence")
+ _tap(sim, "rotate_right")
+ _tap(sim, "rotate_left")
+ _step(sim, 2)
+ var expect := StructureSystem.snap(Vector2(player.global_position.x, player.global_position.z) + b._stick_dir * BuildMode.GAMEPAD_REACH)
+ r.check(b.cursor == expect and b.reason == "", "the cursor is 3 m along the stick, snapped (%s, '%s')" % [b.cursor, b.reason])
+ var n := st.count()
+ _tap(sim, "fire")
+ r.check(st.count() == n + 1 and sim.combat.shots_fired == 0, "fire builds (and doesn't shoot) in build mode")
+ _step(sim, 1)
+ r.check(b.hover >= 0, "the cursor is over the new fence")
+ var wood := int(sim.campaign.state.resources.shed["wood"])
+ _tap(sim, "cancel")
+ r.check(st.count() == n and int(sim.campaign.state.resources.shed["wood"]) == wood + 1 and b.active,
+ "cancel over a structure dismantles it, refunding half (1 wood)")
+ _tap(sim, "cancel")
+ r.check(not b.active, "cancel elsewhere leaves build mode")
+ Input.action_release("aim_right")
+ sim.combat.device = ScarecrowCombat.Device.MOUSE
+ _settle(sim)
+
+
+func _gate(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var st := sim.structures
+ var gate := st.place("gate", 8.0, -4.0, 0)
+ var fence := st.place("fence", 12.0, -4.0, 0)
+ _settle(sim)
+ await r.physics_frame # new bodies join the physics space on the next physics frame
+ player.global_position = Vector3(8.0, 0.2, -5.2)
+ var through := player.move_and_collide(Vector3(0.0, 0.0, 2.4), true)
+ player.global_position = Vector3(12.0, 0.2, -5.2)
+ var blocked := player.move_and_collide(Vector3(0.0, 0.0, 2.4), true)
+ r.check(through == null and blocked != null, "the scarecrow walks through a gate but not a fence")
+ r.check(sim.nav.structure_at[sim.nav.cell_of(8.0, -4.0)] == gate, "enemies can't: the gate is a barrier cell")
+ st.dismantle(gate)
+ st.dismantle(fence)
+ _settle(sim)
+ player.global_position = AWAY
+
+
+## A thief inside the pen, whose only opening is shut by the pen's gate, breaks the gate to get
+## out; a new gate can go back in the opening.
+func _breakout(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var st := sim.structures
+ var es := sim.enemies
+ player.global_position = AWAY
+ var id := sim.nav.structure_at[sim.nav.cell_of(4.0, -6.0)]
+ r.check(id >= 1 and sim.campaign.state.structure(id)["type"] == "gate" and not sim.animals.pen_open,
+ "the vacation starts with a gate shutting the pen")
+ var inside := sim.nav.cell_of(-4.0, -6.0)
+ r.check(sim.escape_field[inside] < FarmNavigation.UNREACHABLE, "the walled-in pen still has a route out (through the barrier)")
+ var broken: Array[int] = []
+ st.destroyed.connect(func(sid: int, _t: String, _at: Vector3) -> void: broken.append(sid))
+ var h := es.spawn(EnemySystem.TYPE_THIEF, -2.0, -6.0, Vector2.RIGHT)
+ es.state[es.resolve_handle(h)] = T.RETREAT
+ var reached := _until(sim, func() -> bool: return es.resolve_handle(h) >= 0 and es.state[es.resolve_handle(h)] == T.BREAK, 20.0)
+ r.check(reached < 20.0 and es.barrier[es.resolve_handle(h)] == id, "the thief walks to the fence and starts breaking it (%.1f s)" % reached)
+ var took := _until(sim, func() -> bool: return broken.has(id), 30.0)
+ var expect := ceilf(float(sim.config.gate_hp) / es.t_structure_damage[EnemySystem.TYPE_THIEF]) * es.t_hit_interval[EnemySystem.TYPE_THIEF]
+ r.check(took < 30.0 and absf(took - expect) < es.t_hit_interval[EnemySystem.TYPE_THIEF] + 0.5,
+ "it breaks the gate in about %.0f s (took %.1f s)" % [expect, took])
+ r.check(sim.nav.structure_at[sim.nav.cell_of(4.0, -6.0)] < 0 and sim.animals.pen_open, "the broken gate is gone from navigation: the pen is open")
+ var out := _until(sim, func() -> bool: return es.resolve_handle(h) == -1, 40.0)
+ r.check(out < 40.0, "then it leaves the farm through the breach (%.1f s)" % out)
+ r.check(st.validate("gate", 4.0, -6.0, 2, Vector2(6.0, -6.0)) == "", "a new gate can go in the pen opening")
+ st.place("gate", 4.0, -6.0, 2)
+ _settle(sim)
+ r.check(not sim.animals.pen_open, "and shuts the pen again")
+
+
+func _trap(r: GameTestRunner, sim: FarmSim) -> void:
+ var st := sim.structures
+ var es := sim.enemies
+ var id := st.place("slowing_trap", 8.0, -12.0, 0)
+ _settle(sim)
+ var h := es.spawn(EnemySystem.TYPE_THIEF, 8.0, -12.0, Vector2.RIGHT)
+ var keep := es.behavior
+ es.behavior = null # drive it by hand: full pace to the east
+ var d := es.resolve_handle(h)
+ es.desire_x[d] = 1.0
+ es.pace[d] = 1.0
+ _step(sim, 1)
+ r.check(es.slow_left[d] > 0.0 and int(sim.campaign.state.structure(id)["hp"]) == sim.config.trap_triggers - 1,
+ "stepping on the trap slows the thief and uses a trigger")
+ _step(sim, 40)
+ var speed := Vector2(es.vel_x[d], es.vel_z[d]).length()
+ r.check(speed <= es.t_speed[EnemySystem.TYPE_THIEF] * sim.config.trap_slow_factor + 0.05 and int(sim.campaign.state.structure(id)["hp"]) == sim.config.trap_triggers - 1,
+ "it moves at half speed (%.2f m/s), one trigger per crossing" % speed)
+ es.pos_x[d] = 8.0
+ es.pos_z[d] = -12.0
+ es.slow_left[d] = 0.0
+ sim.campaign.state.structure(id)["hp"] = 0
+ _step(sim, 1)
+ r.check(es.slow_left[d] == 0.0, "a used-up trap slows no one")
+ es.behavior = keep
+ es.apply_hit(d, 99)
+ st.dismantle(id)
+ _settle(sim)
+
+
+func _turret(r: GameTestRunner, sim: FarmSim) -> void:
+ var st := sim.structures
+ var es := sim.enemies
+ var id := st.place("automated_defense", 8.0, -6.0, 0)
+ _settle(sim)
+ var far := es.spawn(EnemySystem.TYPE_THIEF, 8.0 + sim.config.turret_range + 2.0, -6.0, Vector2.UP)
+ var fired := sim.projectiles.fired
+ var keep := es.behavior
+ es.behavior = null # keep both thieves where they are
+ _step(sim, 90)
+ r.check(sim.projectiles.fired == fired, "nothing in range: the automated defense holds fire")
+ var near := es.spawn(EnemySystem.TYPE_THIEF, 11.0, -6.0, Vector2.UP)
+ var hp := es.health[es.resolve_handle(near)]
+ _step(sim, 90)
+ var dn := es.resolve_handle(near)
+ r.check(sim.projectiles.fired > fired and (dn < 0 or es.health[dn] < hp), "a thief 3 m away gets shot")
+ r.check(es.health[es.resolve_handle(far)] == es.t_hp[EnemySystem.TYPE_THIEF], "the one beyond %.0f m doesn't" % sim.config.turret_range)
+ es.behavior = keep
+ for dd in es.active_count:
+ es.apply_hit(dd, 99)
+ st.dismantle(id)
+ _settle(sim)
+
+
+func _repair_and_dismantle(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var st := sim.structures
+ var s := sim.campaign.state
+ var id := st.place("fence", 8.0, -8.0, 0)
+ _settle(sim)
+ r.check(not st.damage(id, 5) and int(s.structure(id)["hp"]) == 15, "damage takes HP off")
+ st.damage(id, 5)
+ r.check(st.repair_cost(id) == {"wood": 1}, "half broken: repairing costs half the build cost, rounded up (1 wood)")
+ sim.campaign.advance_phase()
+ sim.campaign.advance_phase()
+ r.check(s.phase == P.NIGHT, "night falls")
+ player.global_position = Vector3(8.0, 0.0, -7.2)
+ var wood := int(s.resources.shed["wood"])
+ Input.action_press("interact")
+ _step(sim, roundi(sim.config.repair_time * 60.0) + 2)
+ Input.action_release("interact")
+ _step(sim, 1)
+ r.check(int(s.structure(id)["hp"]) == sim.config.fence_hp and int(s.resources.shed["wood"]) == wood - 1,
+ "holding interact repairs it fully, at night too")
+ var destroyed: Array[String] = []
+ st.destroyed.connect(func(_i: int, t: String, _at: Vector3) -> void: destroyed.append(t))
+ r.check(st.damage(id, 99) and s.structure(id).is_empty() and destroyed == ["fence"], "at 0 HP it breaks (breach)")
+ _to_day(sim)
+ player.global_position = AWAY
+ _settle(sim)
+
+
+func _persistence(r: GameTestRunner, sim: FarmSim) -> void:
+ var c := sim.campaign
+ var st := sim.structures
+ var n0 := st.count() # the pen's gate
+ st.place("fence", 8.0, -8.0, 0)
+ st.place("slowing_trap", 10.0, -12.0, 0)
+ var d := c.state.to_dict()
+ var back := FarmState.from_dict(JSON.parse_string(JSON.stringify(d, "", true, true))) # full float precision
+ r.check(back != null and back.to_dict() == d, "structures round-trip through JSON")
+ var bad := d.duplicate(true)
+ (bad["structures"] as Array)[0]["rot"] = 9
+ r.check(FarmState.from_dict(bad) == null, "a structure with a bad rotation is rejected")
+ # Through the night into the next morning, then build more and fail: retry restores the morning.
+ c.advance_phase()
+ c.advance_phase()
+ c.advance_phase()
+ c.advance_phase()
+ r.check(c.state.phase == P.MORNING and st.count() == n0 + 2, "structures stand into the next morning")
+ var morning: Array = c.state.to_dict()["structures"]
+ c.begin_day()
+ st.place("automated_defense", 8.0, -4.0, 0)
+ c.advance_phase()
+ c.advance_phase()
+ st.damage(int(c.state.structures[0]["id"]), 99)
+ c.state.scarecrow_hp = 0
+ _step(sim, 1)
+ c.retry_night()
+ _step(sim, 1)
+ r.check(c.state.to_dict()["structures"] == morning and st.count() == n0 + 2 and st._views.size() == n0 + 2,
+ "retry brings back the morning's structures (the broken one stands, the new one is gone)")
+ _settle(sim)
+
+
+## The same night (seed, two enemies at a time, no scarecrow) against different defenses: crows
+## on the crops (fences mean nothing to them, automated defenses do), and thieves after supplies
+## (a fence around the shed makes them break in; automated defenses stop them).
+func _ab_night(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var crows_open := _night_losses(sim, player, "crow", "crops", [])
+ var crows_fenced := _night_losses(sim, player, "crow", "crops", _field_fences())
+ var crows_shot := _night_losses(sim, player, "crow", "crops", _field_fences() + _field_turrets())
+ r.info("A/B night, crows (2 at a time, %.0f s + dawn, scarecrow away): open field lost %d crops; fenced %d (%d breaks); fenced with automated defenses %d" % [
+ sim.config.night_length, crows_open[0], crows_fenced[0], crows_fenced[1], crows_shot[0]])
+ r.check(crows_fenced[0] == crows_open[0] and crows_fenced[1] == 0, "fences don't change a crow attack (%d = %d crops lost, nothing broken)" % [crows_fenced[0], crows_open[0]])
+ r.check(crows_shot[0] < crows_open[0], "automated defenses shoot crows down (%d < %d crops lost)" % [crows_shot[0], crows_open[0]])
+ var open := _night_losses(sim, player, "thief", "supplies", [])
+ var fenced := _night_losses(sim, player, "thief", "supplies", _shed_fences())
+ var defended := _night_losses(sim, player, "thief", "supplies", _shed_fences() + _shed_turrets())
+ r.info("A/B night, thieves after supplies (2 at a time): open shed lost %d units; fenced %d (%d breaks); fenced with automated defenses %d (%d breaks)" % [
+ open[0], fenced[0], fenced[1], defended[0], defended[1]])
+ r.check(fenced[1] >= 1 and fenced[0] <= open[0], "a fence around the shed makes thieves break in, and costs them time (%d <= %d units lost)" % [fenced[0], open[0]])
+ r.check(defended[0] < open[0], "defenses change the outcome of the same attack (%d < %d units lost)" % [defended[0], open[0]])
+
+
+func _field_fences() -> Array:
+ var parts: Array = []
+ for k in 15:
+ parts.append(["fence", Vector2(16.0 + 2.0 * k, -16.5), 0])
+ parts.append(["fence", Vector2(16.0 + 2.0 * k, 10.5), 0])
+ for k in 14:
+ parts.append(["fence", Vector2(15.0, -15.5 + 2.0 * k), 2])
+ parts.append(["fence", Vector2(45.0, -15.5 + 2.0 * k), 2])
+ return parts
+
+
+func _field_turrets() -> Array:
+ var parts: Array = []
+ for at in [Vector2(13.5, -15.0), Vector2(46.0, -15.0), Vector2(13.5, 9.0), Vector2(46.0, 9.0), Vector2(30.0, -17.5), Vector2(30.0, 11.5)]:
+ parts.append(["automated_defense", at, 0])
+ return parts
+
+
+## A U of fences around the shed's apron, from the barn wall out and across.
+func _shed_fences() -> Array:
+ var parts: Array = []
+ for z in [-20.0, -18.0, -16.0, -14.0]:
+ parts.append(["fence", Vector2(-7.0, z), 2])
+ if z > -19.0: # the work area's barrels close the top of the east side
+ parts.append(["fence", Vector2(8.5, z), 2])
+ for k in 8:
+ parts.append(["fence", Vector2(-6.0 + 2.0 * k, -12.75), 0])
+ return parts
+
+
+func _shed_turrets() -> Array:
+ var parts: Array = []
+ for at in [Vector2(-3.5, -12.0), Vector2(5.0, -11.0), Vector2(1.0, -14.5)]:
+ parts.append(["automated_defense", at, 0])
+ return parts
+
+
+## Plays one night of the trickle (two of `type` at a time, after `target`) against a layout;
+## returns [crops or supply units lost, barriers broken].
+func _night_losses(sim: FarmSim, player: PlayerCharacter, type: String, target: String, parts: Array) -> Array[int]:
+ var c := sim.campaign
+ c.new_campaign()
+ _step(sim, 1)
+ sim.loot._rng.seed = 7
+ sim.waves.rng.seed = 7
+ sim.waves.enabled = true
+ sim.config.night_thieves = 2
+ sim.config.trickle_type = type
+ sim.config.trickle_target = target
+ player.global_position = AWAY
+ c.begin_day()
+ _rich(c)
+ var breaks: Array[int] = []
+ var cb := func(_i: int, _t: String, _at: Vector3) -> void: breaks.append(1)
+ sim.structures.destroyed.connect(cb)
+ var refused := []
+ for part in parts:
+ var why := sim.structures.validate(part[0], part[1].x, part[1].y, part[2], part[1])
+ if why == "" or why == "The scarecrow is in the way":
+ sim.structures.place(part[0], part[1].x, part[1].y, part[2])
+ else:
+ refused.append("%s at %s: %s" % [part[0], part[1], why])
+ if not refused.is_empty():
+ push_warning("A/B layout pieces refused: %s" % [refused])
+ _settle(sim)
+ c.advance_phase()
+ c.advance_phase()
+ var guard := 0
+ while c.state.phase != P.MORNING and not c.is_over() and guard < 20000:
+ sim.step(DT)
+ guard += 1
+ sim.structures.destroyed.disconnect(cb)
+ sim.config.night_thieves = 0
+ sim.config.trickle_type = "crow"
+ sim.config.trickle_target = "any"
+ sim.waves.enabled = false
+ var e: Dictionary = c.state.night_log[c.state.night_log.size() - 1]
+ return [int(e["crops_lost"]) if target == "crops" else int(e["supplies_lost"]), breaks.size()]
+
+
+func _to_day(sim: FarmSim) -> void:
+ var c := sim.campaign
+ while c.state.phase != P.DAY:
+ if c.state.phase == P.MORNING:
+ c.begin_day()
+ else:
+ c.advance_phase()
+
+
+## Lets the flow-field rebuild finish.
+func _settle(sim: FarmSim) -> void:
+ var guard := 0
+ while sim.rebuilding and guard < 2000:
+ sim.step(DT)
+ guard += 1
+
+
+func _tap(sim: FarmSim, action: String) -> void:
+ Input.action_press(action)
+ sim.step(DT)
+ Input.action_release(action)
+ sim.step(DT)
+
+
+func _step(sim: FarmSim, n: int) -> void:
+ for i in n:
+ sim.step(DT)
+
+
+func _until(sim: FarmSim, cond: Callable, max_seconds: float) -> float:
+ var t := 0.0
+ while t < max_seconds and not cond.call():
+ sim.step(DT)
+ t += DT
+ return t
diff --git a/game/tests/test_structures.gd.uid b/game/tests/test_structures.gd.uid
new file mode 100644
index 0000000..98e8771
--- /dev/null
+++ b/game/tests/test_structures.gd.uid
@@ -0,0 +1 @@
+uid://3doiag5vf4yk
diff --git a/game/tests/test_targets.gd b/game/tests/test_targets.gd
new file mode 100644
index 0000000..288d9be
--- /dev/null
+++ b/game/tests/test_targets.gd
@@ -0,0 +1,460 @@
+extends RefCounted
+## All three farm targets on the real farm, with FarmSim stepped by hand at 60 Hz: the animals in
+## the pen (wandering, kept in by the pen's gate), an animal thief breaking in, catching and
+## carrying one off, a dropped animal running for the farm's edge, leading animals back (at most
+## three, through a gate), a pen breach letting animals wander out at night (and not by day), supply
+## thieves taking bundles from the shed's piles (never more than there is), dropping, recovering,
+## and losing them, the piles growing and shrinking with the stock, thieves falling back to another
+## target, the asset HUD, the end of the dawn grace, retry, and a farm stripped of all three.
+
+const P := CampaignController.Phase
+const S := LootSystem.Status
+const C := LootSystem.Category
+const T := ThiefBehavior.State
+const DT := 1.0 / 60.0
+const AWAY := Vector3(-11.0, 0.0, 13.0)
+
+var _events: Array = [] # [kind, id]
+
+
+func run(r: GameTestRunner) -> void:
+ var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
+ r.root.add_child(farm)
+ await r.process_frame
+ await r.physics_frame
+ var sim := farm.get_node("FarmSim") as FarmSim
+ sim.set_physics_process(false)
+ sim.waves.enabled = false # every thief here is sent in by hand
+ var player := farm.get_node("Player") as PlayerCharacter
+ player.global_position = AWAY
+ sim.loot.loot_event.connect(func(kind: StringName, id: int, _p: Vector3) -> void: _events.append([kind, id]))
+ sim.campaign.begin_day()
+ _layout(r, sim)
+ _pen_by_day(r, sim)
+ _animal_theft(r, sim, player)
+ _leading(r, sim, player)
+ _breach(r, sim, player)
+ _supplies(r, sim, player)
+ _bundle_limits(r, sim)
+ _piles(r, sim)
+ _fallback(r, sim)
+ _hud(r, farm, sim)
+ _stripped(r, sim)
+ farm.queue_free()
+ await r.process_frame
+
+
+func _layout(r: GameTestRunner, sim: FarmSim) -> void:
+ var loot := sim.loot
+ var cfg := sim.config
+ r.check(sim.animals.count == cfg.start_animals and loot.animal_count == cfg.start_animals and sim.campaign.state.animals == cfg.start_animals,
+ "%d animals in the pen, matching GameConfig.start_animals" % sim.animals.count)
+ r.check(loot.item_count == loot.unit_count + loot.animal_count + LootSystem.SACKS and loot.category[loot.unit_count] == C.CROP
+ and loot.category[loot.animal_item(1)] == C.ANIMAL and loot.category[loot.first_sack()] == C.SUPPLY,
+ "one id space: crops, then animals, then sacks")
+ var kinds := {}
+ var pen := sim.zones.zone(FarmZone.Kind.ANIMAL_PEN)
+ var inside := true
+ for id in range(1, sim.animals.count + 1):
+ kinds[sim.animals.kind(id)] = true
+ inside = inside and pen.rect().has_point(sim.animals.position(id))
+ r.check(inside and kinds.keys().size() == 3, "chickens, pigs, and sheep (%s), all inside the pen" % [kinds.keys()])
+ r.check(not sim.animals.pen_open and sim.campaign.state.structure(1).get("type", "") == "gate", "the pen's gate shuts the pen")
+ var gap := _edge_cell(sim, "south-west")
+ r.check(sim.animal_field[gap] < FarmNavigation.UNREACHABLE, "thieves have a route into the pen (through its gate)")
+ for m in ResourceStore.MATERIALS:
+ var spot := sim.shed_stock.spot(m)
+ var c := sim.nav.cell_of(spot.x, spot.y)
+ r.check(sim.nav.is_walkable(c) and sim.supply_fields[m][_edge_cell(sim, "north")] < FarmNavigation.UNREACHABLE
+ and sim.escape_field[c] < FarmNavigation.UNREACHABLE, "the %s pile has a spot thieves can reach and leave" % m)
+
+
+## By day the animals wander but stay in the pen: the gate keeps them in.
+func _pen_by_day(r: GameTestRunner, sim: FarmSim) -> void:
+ var start := sim.animals.pos.duplicate()
+ var pen := sim.zones.zone(FarmZone.Kind.ANIMAL_PEN).rect()
+ var outside := 0
+ for i in 1800:
+ sim.step(DT)
+ for id in range(1, sim.animals.count + 1):
+ if not pen.has_point(sim.animals.position(id)):
+ outside += 1
+ var moved := 0
+ for id in range(1, sim.animals.count + 1):
+ if sim.animals.position(id).distance_to(start[id]) > 1.0:
+ moved += 1
+ r.check(moved >= sim.animals.count / 2.0 and outside == 0, "30 s by day: %d of %d animals wandered, none left the pen" % [moved, sim.animals.count])
+
+
+## An animal thief breaks the pen's gate, catches an animal, and carries it; killed, it drops the
+## animal, which runs for the edge of the farm; touched, the animal follows the scarecrow.
+func _animal_theft(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var es := sim.enemies
+ var loot := sim.loot
+ var s := sim.campaign.state
+ var gate := 1
+ var h := sim.spawn_thief(C.ANIMAL, GameTestRunner.EDGE["south-west"])
+ _step(sim, 1)
+ var item := es.target[es.resolve_handle(h)]
+ r.check(item > 0 and loot.category[item] == C.ANIMAL, "an animal thief claims an animal")
+ loot.update_visuals()
+ r.check(loot.threat[item] == LootSystem.Threat.TARGETED, "the animal shows as targeted")
+ var at_gate := _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.BREAK, 40.0)
+ r.check(at_gate < 40.0 and es.barrier[es.resolve_handle(h)] == gate, "the thief comes to the pen's gate and breaks it (%.1f s)" % at_gate)
+ var caught := _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.CARRY, 50.0)
+ var d := es.resolve_handle(h)
+ r.check(caught < 50.0 and s.structure(gate).is_empty() and loot.status[item] == S.CARRIED and es.carry[d] == item,
+ "it gets in through the broken gate and catches the animal (%.1f s more)" % caught)
+ r.check(int(s.night_events.get("animals_stolen", 0)) == 1, "the theft counts toward the night's record")
+ var pen := sim.zones.zone(FarmZone.Kind.ANIMAL_PEN).rect().grow(1.5)
+ var out := _until(sim, func() -> bool: return not pen.has_point(Vector2(es.pos_x[es.resolve_handle(h)], es.pos_z[es.resolve_handle(h)])), 20.0)
+ d = es.resolve_handle(h)
+ var index := loot.animal_index(item)
+ r.check(out < 20.0 and sim.animals.position(index).distance_to(Vector2(es.pos_x[d], es.pos_z[d])) < 0.1,
+ "the animal rides with its thief out of the pen (%.1f s)" % out)
+ var at := Vector2(es.pos_x[d], es.pos_z[d])
+ es.apply_hit(d, 99)
+ _step(sim, 1)
+ r.check(loot.status[item] == S.DROPPED and sim.animals.position(index).distance_to(at) < 0.2, "killing the carrier drops the animal where it fell")
+ var near_edge := _edge_distance(sim, sim.animals.position(index))
+ _step(sim, 300)
+ var later := _edge_distance(sim, sim.animals.position(index))
+ r.check(loot.status[item] == S.DROPPED and later < near_edge - 2.0, "the loose animal makes for the edge of the farm (%.1f m -> %.1f m from it)" % [near_edge, later])
+ var p := sim.animals.position(index)
+ player.global_position = Vector3(p.x + 0.8, 0.0, p.y)
+ _step(sim, 1)
+ r.check(loot.status[item] == S.FOLLOWING and _has(&"following", item), "walking up to it: it follows the scarecrow")
+ loot.status[item] = S.DROPPED # loose again for the next part
+ sim.animals.place(index, p)
+ player.global_position = AWAY
+ _step(sim, 1)
+
+
+## Lead loose animals back: at most three follow at once; they pass through a gate behind the
+## scarecrow, and inside the pen they are home.
+func _leading(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var loot := sim.loot
+ var st := sim.structures
+ var s := sim.campaign.state
+ s.resources.shed = {"wood": 50, "scrap": 50, "straw": 50}
+ r.check(st.validate("gate", 4.0, -6.0, 2, Vector2(6.0, -6.0)) == "" and st.place("gate", 4.0, -6.0, 2) > 0, "a new gate goes in the pen opening")
+ _settle(sim)
+ r.check(not sim.animals.pen_open, "the pen is shut again")
+ var loose: Array[int] = []
+ for id in range(1, sim.animals.count + 1):
+ if loot.status[loot.animal_item(id)] == S.DROPPED:
+ loose.append(id)
+ for id in range(1, sim.animals.count + 1):
+ if loose.size() < 4 and loot.status[loot.animal_item(id)] == S.HOME:
+ loose.append(id)
+ for k in loose.size():
+ _make_loose(sim, loose[k], Vector2(9.0 + k * 3.0, -2.0))
+ var recovered_before := int(s.night_events.get("animals_recovered", 0))
+ for k in loose.size():
+ player.global_position = Vector3(9.0 + k * 3.0 + 0.6, 0.0, -2.0)
+ _step(sim, 1)
+ r.check(loot.followers() == sim.config.max_following_animals and loot.status[loot.animal_item(loose[3])] == S.DROPPED
+ and _has(&"follow_full", loot.animal_item(loose[3])), "three animals follow; the fourth waits (and the scarecrow is told why)")
+ # Walk the line in through the gate: east of the pen, then west through the opening.
+ var path: Array[Vector2] = [Vector2(15.0, -2.0), Vector2(7.5, -2.0), Vector2(7.5, -6.0), Vector2(0.0, -6.0), Vector2(-3.0, -6.0)]
+ var from := Vector2(player.global_position.x, player.global_position.z)
+ for target in path:
+ while from.distance_to(target) > 0.05:
+ from = from.move_toward(target, 4.5 * DT)
+ player.global_position = Vector3(from.x, 0.0, from.y)
+ sim.step(DT)
+ _step(sim, 120)
+ var home := 0
+ for k in 3:
+ if loot.status[loot.animal_item(loose[k])] == S.HOME:
+ home += 1
+ r.check(home == 3 and not st.validate("gate", 4.0, -6.0, 2, Vector2(6.0, -6.0)).is_empty(), "the three follow the scarecrow through the gate into the pen")
+ r.check(int(s.night_events.get("animals_recovered", 0)) == recovered_before + 3, "each counts as led back")
+ _make_loose(sim, loose[3], Vector2(-1.0, -2.5)) # the fourth wanders back in by itself
+ _step(sim, 1)
+ r.check(loot.status[loot.animal_item(loose[3])] == S.HOME, "a loose animal inside the pen is home again")
+ player.global_position = AWAY
+ _step(sim, 1)
+
+
+## With the gate down at night, animals wander out of the pen one at a time; a loose one that
+## reaches the farm's edge is lost. By day an open pen keeps its animals. The end of the dawn grace brings
+## loose ones back; retry restores the morning.
+func _breach(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var c := sim.campaign
+ var loot := sim.loot
+ var st := sim.structures
+ var gate := sim.nav.structure_at[sim.nav.cell_of(4.0, -6.0)]
+ st.damage(gate, 999)
+ _settle(sim)
+ r.check(sim.animals.pen_open, "a broken gate opens the pen")
+ _events.clear()
+ _step(sim, roundi(sim.config.animal_wander_interval * 60.0))
+ r.check(not _has(&"strayed", -1) and loot.count(S.HOME, C.ANIMAL) == loot.animal_count - loot.count(S.LOST, C.ANIMAL),
+ "by day the animals stay in an open pen")
+ _to_night(sim)
+ var morning_lost := c.state.lost_animals.duplicate()
+ var first := _until(sim, func() -> bool: return _has(&"strayed", -1), sim.config.animal_wander_interval + 1.0)
+ r.check(first <= sim.config.animal_wander_interval * 0.3 + 0.1, "at night an animal soon wanders out of the open pen (%.1f s)" % first)
+ var strays := _until(sim, func() -> bool: return _count(&"strayed") >= 2, sim.config.animal_wander_interval + 1.0)
+ r.check(strays <= sim.config.animal_wander_interval + 0.1, "then another every %.0f s" % sim.config.animal_wander_interval)
+ var lost := _until(sim, func() -> bool: return c.state.lost_animals.size() > morning_lost.size(), 90.0)
+ r.check(lost < 90.0, "a wandering animal that reaches the farm's edge is lost (%.1f s later)" % lost)
+ var loose_at_dawn := loot.count(S.DROPPED, C.ANIMAL)
+ r.check(loose_at_dawn > 0, "some are still loose on the farm (%d)" % loose_at_dawn)
+ var still_lost := c.state.lost_animals.duplicate()
+ c.advance_phase()
+ c.advance_phase()
+ r.check(c.state.phase == P.MORNING and loot.count(S.DROPPED, C.ANIMAL) == 0 and c.state.lost_animals == still_lost
+ and loot.count(S.HOME, C.ANIMAL) == loot.animal_count - still_lost.size(), "the end of the dawn grace brings the loose ones back to the pen")
+ var pen := sim.zones.zone(FarmZone.Kind.ANIMAL_PEN).rect()
+ var inside := true
+ for id in range(1, sim.animals.count + 1):
+ if loot.status[loot.animal_item(id)] == S.HOME:
+ inside = inside and pen.has_point(sim.animals.position(id))
+ r.check(inside and sim.animals.pen_open, "every animal left is in the pen (still open: the gate is gone)")
+ r.check(sim.review_panel._body.text.contains("The pen is open"), "the morning review says the pen is open")
+ var e: Dictionary = c.state.night_log[c.state.night_log.size() - 1]
+ r.check(e["animals_lost"] == still_lost.size() - morning_lost.size() and e["animals_strayed"] >= 2, "the night's record: %s" % [e])
+ # Retry: lose another one tonight, fall, and the morning comes back.
+ var morning := c.state.to_dict()
+ c.begin_day()
+ c.state.resources.shed = {"wood": 50, "scrap": 50, "straw": 50}
+ st.place("gate", 4.0, -6.0, 2)
+ _to_night(sim)
+ var h := sim.spawn_thief(C.ANIMAL, GameTestRunner.EDGE["west"])
+ _until(sim, func() -> bool: return sim.enemies.resolve_handle(h) == -1, 90.0)
+ r.check(c.state.lost_animals.size() >= still_lost.size() + 1, "an unopposed animal thief carries one off the farm")
+ c.state.scarecrow_hp = 0
+ _step(sim, 1)
+ c.retry_night()
+ _step(sim, 1)
+ r.check(c.state.to_dict() == morning and loot.count(S.LOST, C.ANIMAL) == still_lost.size() and sim.animals.pen_open,
+ "retry restores the morning (that animal is back, the new gate gone)")
+ player.global_position = AWAY
+ c.begin_day()
+ c.state.resources.shed = {"wood": 50, "scrap": 50, "straw": 50}
+ st.place("gate", 4.0, -6.0, 2)
+ _settle(sim)
+
+
+## A supply thief takes a bundle of the material the shed holds most of; killed, it drops the
+## sack, which the scarecrow takes back to the shed; unopposed, it carries it off.
+func _supplies(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var es := sim.enemies
+ var loot := sim.loot
+ var s := sim.campaign.state
+ var r0 := s.resources
+ r0.shed = {"wood": 3, "scrap": 9, "straw": 4}
+ var total := r0.shed_total()
+ var stolen0 := int(s.night_events.get("supplies_stolen", 0))
+ var h := sim.spawn_thief(C.SUPPLY, GameTestRunner.EDGE["north"])
+ _step(sim, 1)
+ var sack := es.target[es.resolve_handle(h)]
+ r.check(sack >= loot.first_sack() and loot.sack_material[sack] == "scrap" and loot.home[sack] == sim.shed_stock.spot("scrap"),
+ "a supply thief heads for the pile the shed holds most of (scrap)")
+ var took := _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.CARRY, 40.0)
+ r.check(took < 40.0 and int(r0.shed["scrap"]) == 9 - sim.config.supply_bundle and loot.sack_amount[sack] == sim.config.supply_bundle
+ and loot.status[sack] == S.CARRIED, "it fills a sack with %d scrap (%.1f s)" % [sim.config.supply_bundle, took])
+ r.check(s.supplies == total and s.supplies_in_transit == sim.config.supply_bundle
+ and int(s.night_events.get("supplies_stolen", 0)) == stolen0 + sim.config.supply_bundle, "a carried sack still counts as on the farm")
+ _step(sim, 60)
+ var d := es.resolve_handle(h)
+ var at := Vector2(es.pos_x[d], es.pos_z[d])
+ es.apply_hit(d, 99)
+ _step(sim, 1)
+ loot.update_visuals()
+ r.check(loot.status[sack] == S.DROPPED and loot.ground[sack].distance_to(at) < 0.2 and loot._tokens[sack].visible, "killing the carrier drops the sack")
+ player.global_position = Vector3(at.x + 0.8, 0.0, at.y)
+ _step(sim, 1)
+ r.check(loot.status[sack] == S.HOME and int(r0.shed["scrap"]) == 9 and s.supplies_in_transit == 0 and loot.sack_amount[sack] == 0,
+ "walking up to the sack puts the scrap back in the shed")
+ player.global_position = AWAY
+ # Unopposed, it gets away with the sack.
+ var lost0 := int(s.night_events.get("supplies_lost", 0))
+ h = sim.spawn_thief(C.SUPPLY, GameTestRunner.EDGE["north"])
+ _until(sim, func() -> bool: return es.resolve_handle(h) == -1, 70.0)
+ r.check(int(r0.shed["scrap"]) == 9 - sim.config.supply_bundle and s.supplies == total - sim.config.supply_bundle
+ and int(s.night_events.get("supplies_lost", 0)) == lost0 + sim.config.supply_bundle, "an unopposed thief carries %d scrap off the farm" % sim.config.supply_bundle)
+ r.check(loot.count(S.HOME, C.SUPPLY) == LootSystem.SACKS and s.supplies_in_transit == 0, "its sack is free for the next theft")
+
+
+## A bundle never holds more than the shed has; an emptied shed leaves the thief nothing to take.
+func _bundle_limits(r: GameTestRunner, sim: FarmSim) -> void:
+ var es := sim.enemies
+ var loot := sim.loot
+ var s := sim.campaign.state
+ s.resources.shed = {"wood": 2, "scrap": 1, "straw": 0}
+ var h := sim.spawn_thief(C.SUPPLY, GameTestRunner.EDGE["north"])
+ _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.CARRY, 40.0)
+ var d := es.resolve_handle(h)
+ var sack := es.carry[d]
+ r.check(sack > 0 and loot.sack_amount[sack] == 2 and int(s.resources.shed["wood"]) == 0, "with 2 wood in the shed, the bundle is 2 wood")
+ es.apply_hit(d, 99)
+ _step(sim, 1)
+ loot.return_dropped()
+ r.check(int(s.resources.shed["wood"]) == 2, "(the dropped sack goes back)")
+ h = sim.spawn_thief(C.SUPPLY, GameTestRunner.EDGE["north"])
+ _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.STEAL, 40.0)
+ d = es.resolve_handle(h)
+ sack = es.target[d]
+ for m in ResourceStore.MATERIALS:
+ s.resources.shed[m] = 0 # spent while the thief fills its sack
+ _until(sim, func() -> bool: return es.resolve_handle(h) < 0 or es.state[es.resolve_handle(h)] != T.STEAL, 10.0)
+ d = es.resolve_handle(h)
+ r.check(d >= 0 and es.carry[d] == -1 and loot.status[sack] == S.HOME and s.supplies_in_transit == 0 and s.resources.shed_total() == 0,
+ "the shed emptied before it finished: it takes nothing")
+ r.check(not s.shed_raided, "spending the last supplies isn't a raid")
+ _step(sim, 1)
+ d = es.resolve_handle(h)
+ r.check(d >= 0 and (es.target[d] < 0 or loot.category[es.target[d]] != C.SUPPLY), "and goes for something else")
+ es.apply_hit(d, 99)
+ _step(sim, 1)
+ r.check(not loot.available(C.SUPPLY), "an empty shed has nothing to claim")
+ s.resources.shed = {"wood": 3, "scrap": 0, "straw": 0}
+ h = sim.spawn_thief(C.SUPPLY, GameTestRunner.EDGE["north"])
+ _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == T.CARRY, 40.0)
+ r.check(s.resources.shed_total() == 0 and s.shed_raided, "a thief taking the last of the stock raids the shed")
+ es.apply_hit(es.resolve_handle(h), 99)
+ _step(sim, 1)
+ loot.return_dropped()
+ _step(sim, 1)
+ r.check(int(s.resources.shed["wood"]) == 3 and not s.shed_raided, "stock back in the shed: no longer raided")
+
+
+## The shed's piles show one prop per few units, and hidden props don't collide.
+func _piles(r: GameTestRunner, sim: FarmSim) -> void:
+ var ss := sim.shed_stock
+ var s := sim.campaign.state
+ var wood: Array = ss.slots["wood"]
+ var per: int = ShedStock.PILES["wood"]["per"]
+ for amount in [0, per * 2 + 1, 999]:
+ s.resources.shed["wood"] = amount
+ ss._process(0.0)
+ var want := mini(ceili(amount / float(per)), wood.size())
+ var shown := 0
+ var colliding := 0
+ for n: Node3D in wood:
+ if n.visible:
+ shown += 1
+ for b: CollisionObject3D in n.find_children("*", "CollisionObject3D", true, false):
+ if b.collision_layer != 0:
+ colliding += 1
+ r.check(shown == want and colliding == want, "%d wood: %d of %d log piles shown (and colliding)" % [amount, shown, wood.size()])
+ s.resources.shed["wood"] = 10
+ ss._process(0.0)
+
+
+## A thief whose target is gone goes for another; one with no set target takes anything.
+func _fallback(r: GameTestRunner, sim: FarmSim) -> void:
+ var es := sim.enemies
+ var loot := sim.loot
+ var s := sim.campaign.state
+ var keep := s.lost_animals.duplicate()
+ s.lose_all_animals()
+ loot.sync_from_state()
+ var h := sim.spawn_thief(C.ANIMAL, GameTestRunner.EDGE["south-west"])
+ _step(sim, 1)
+ var item := es.target[es.resolve_handle(h)]
+ r.check(item > 0 and loot.category[item] != C.ANIMAL, "with no animals left, an animal thief goes for %s" % LootSystem.CATEGORY_KEYS[loot.category[item]])
+ es.apply_hit_handle(h, 99)
+ var any := sim.spawn_thief(LootSystem.ANY, GameTestRunner.EDGE["east"])
+ _step(sim, 1)
+ r.check(es.target[es.resolve_handle(any)] > 0, "a thief with no set target claims something")
+ es.apply_hit_handle(any, 99)
+ _step(sim, 1)
+ s.lost_animals = keep
+ loot.sync_from_state()
+ sim.animals.sync_from_state()
+
+
+func _hud(r: GameTestRunner, farm: Node3D, sim: FarmSim) -> void:
+ var hud := farm.get_node("Hud/AssetHud") as AssetHud
+ var s := sim.campaign.state
+ hud._process(0.0)
+ var before := hud.describe()
+ s.lose_animal(s.animals_total if not s.is_animal_lost(s.animals_total) else 1)
+ hud._process(0.05)
+ r.check(hud.describe() == "Crops %d/%d · Animals %d/%d · Supplies %d" % [s.crops, s.crops_total, s.animals, s.animals_total, s.supplies]
+ and hud.describe() != before and hud._flash[1] > 0.0 and hud._flash_color[1] == AssetHud.LOSS, "the asset HUD updates and flashes red on a loss: '%s'" % hud.describe())
+
+
+## The farm is stripped when the last supplies are carried off with every crop and animal gone.
+func _stripped(r: GameTestRunner, sim: FarmSim) -> void:
+ var c := sim.campaign
+ var s := c.state
+ s.lose_all_crops()
+ s.lose_all_animals()
+ sim.loot.sync_from_state()
+ s.resources.shed = {"wood": 0, "scrap": 4, "straw": 0}
+ _step(sim, 1)
+ r.check(c.state.phase != P.GAME_OVER, "crops and animals gone, supplies left: the vacation goes on")
+ var h := sim.spawn_thief(C.SUPPLY, GameTestRunner.EDGE["north"])
+ var stolen := _until(sim, func() -> bool: return sim.enemies.resolve_handle(h) >= 0 and sim.enemies.carry[sim.enemies.resolve_handle(h)] > 0, 40.0)
+ r.check(stolen < 40.0 and c.state.phase != P.GAME_OVER, "the last supplies in a thief's sack still count")
+ _until(sim, func() -> bool: return c.is_over(), 70.0)
+ r.check(c.state.phase == P.GAME_OVER and c.outcome == CampaignController.Outcome.GAME_OVER_STRIPPED,
+ "carried off with nothing else left: the farm is stripped (D2)")
+
+
+## Puts an animal loose at p (as if dropped there).
+func _make_loose(sim: FarmSim, id: int, p: Vector2) -> void:
+ var item := sim.loot.animal_item(id)
+ sim.loot.status[item] = S.DROPPED
+ sim.loot.holder[item] = -1
+ sim.loot.ground[item] = p
+ sim.animals.place(id, p)
+
+
+func _to_night(sim: FarmSim) -> void:
+ var c := sim.campaign
+ while c.state.phase != P.NIGHT:
+ if c.state.phase == P.MORNING:
+ c.begin_day()
+ else:
+ c.advance_phase()
+
+
+func _has(kind: StringName, id: int) -> bool:
+ for e in _events:
+ if e[0] == kind and (id < 0 or e[1] == id):
+ return true
+ return false
+
+
+func _count(kind: StringName) -> int:
+ var n := 0
+ for e in _events:
+ if e[0] == kind:
+ n += 1
+ return n
+
+
+func _edge_distance(sim: FarmSim, p: Vector2) -> float:
+ return sim.nav.meters(sim.escape_field[sim.nav.cell_of(p.x, p.y)])
+
+
+func _edge_cell(sim: FarmSim, side: String) -> int:
+ var p: Vector2 = GameTestRunner.EDGE[side]
+ return sim.nav.nearest_free(sim.nav.cell_of(p.x, p.y))
+
+
+func _settle(sim: FarmSim) -> void:
+ var guard := 0
+ while sim.rebuilding and guard < 600:
+ sim.step(DT)
+ guard += 1
+
+
+func _step(sim: FarmSim, n: int) -> void:
+ for i in n:
+ sim.step(DT)
+
+
+## Steps until cond() holds; returns the seconds it took (or max_seconds).
+func _until(sim: FarmSim, cond: Callable, max_seconds: float) -> float:
+ var t := 0.0
+ while t < max_seconds and not cond.call():
+ sim.step(DT)
+ t += DT
+ return t
diff --git a/game/tests/test_targets.gd.uid b/game/tests/test_targets.gd.uid
new file mode 100644
index 0000000..f1007af
--- /dev/null
+++ b/game/tests/test_targets.gd.uid
@@ -0,0 +1 @@
+uid://bf0qhvcwr8pxg
diff --git a/game/tests/test_theft.gd b/game/tests/test_theft.gd
new file mode 100644
index 0000000..c485bac
--- /dev/null
+++ b/game/tests/test_theft.gd
@@ -0,0 +1,334 @@
+extends RefCounted
+## Crop theft and recovery on the real farm, with FarmSim stepped by hand at 60 Hz. Crops are the
+## crows' (Step 9): claiming a crop (targeted), flying in and landing on it, the steal timer,
+## carrying it off over the fence, the crop lost when the crow escapes, one hit killing a crow and
+## dropping its crop exactly once, recovery by touch, stale handles after slot reuse, shots
+## hitting thieves and cruising crows and stopping at walls, the sunrise retreat, the end-of-dawn
+## rules (carriers take their loot, dropped crops return), retrying a night, and FarmState staying
+## consistent with the loot state.
+
+const P := CampaignController.Phase
+const S := LootSystem.Status
+const DT := 1.0 / 60.0
+## Where the scarecrow waits when it must not touch anything.
+const AWAY := Vector3(-11.0, 0.0, 13.0)
+
+var _events: Dictionary = {}
+
+
+func run(r: GameTestRunner) -> void:
+ var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
+ r.root.add_child(farm)
+ await r.process_frame
+ await r.physics_frame
+ var sim := farm.get_node("FarmSim") as FarmSim
+ sim.set_physics_process(false)
+ sim.waves.enabled = false # no automatic arrivals: every thief here is sent in by hand
+ var player := farm.get_node("Player") as PlayerCharacter
+ player.global_position = AWAY
+ sim.loot.loot_event.connect(func(kind: StringName, _id: int, _p: Vector3) -> void:
+ _events[kind] = int(_events.get(kind, 0)) + 1)
+ r.info("farm sim loaded in %d ms (nav %d cells)" % [sim.load_msec, sim.nav.cell_count()])
+ r.check(sim.loot.unit_count == 30 and sim.loot.count(S.HOME, LootSystem.Category.CROP) == 30 and sim.campaign.state.crops == 30,
+ "30 crop units start at home")
+ var edge_cells := [Vector2(-16.0, -6.0), Vector2(20.0, 18.0), Vector2(50.0, 0.0), Vector2(-16.0, 10.0)].filter(func(p: Vector2) -> bool:
+ return sim.escape_field[sim.nav.cell_of(p.x, p.y)] == 0)
+ r.check(edge_cells.size() == 4 and sim.escape_field[sim.nav.cell_of(10.0, -8.0)] > 0, "the farm's edge, all around, is where carriers escape")
+
+ _steal_and_drop(r, sim, player)
+ _escape(r, sim)
+ _stale_handles(r, sim)
+ _shots(r, sim)
+ _combat_input(r, sim, player)
+ _sunrise_and_dawn_end(r, sim)
+ _retry(r, sim)
+ _night_arrivals(r, sim)
+ farm.queue_free()
+ await r.process_frame
+
+
+func _steal_and_drop(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var es := sim.enemies
+ var loot := sim.loot
+ var h := sim.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["east"])
+ _step(sim, 1)
+ var d := es.resolve_handle(h)
+ var unit := es.target[d]
+ loot.update_visuals()
+ r.check(unit >= 1 and loot.category[unit] == LootSystem.Category.CROP and loot.is_claimed_by(unit, h)
+ and loot.threat[unit] == LootSystem.Threat.TARGETED, "a new crow claims a crop, which shows as targeted")
+ var steal_at := _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == ThiefBehavior.State.STEAL, 30.0)
+ r.check(steal_at < 30.0, "the crow flies in from the east to its crop (%.1f s)" % steal_at)
+ var steal := sim.config.crop_steal_time * es.t_steal[EnemySystem.TYPE_CROW]
+ _step(sim, 60)
+ d = es.resolve_handle(h)
+ r.check(loot.progress[unit] > 0.4 and loot.progress[unit] < 0.6, "after 1 s of %.1f s the ring shows %.0f %%" % [steal, loot.progress[unit] * 100.0])
+ r.check(absf(es.alt[d] - sim.config.land_altitude) < 0.3, "it has come down onto the crop (altitude %.1f m)" % es.alt[d])
+ var took := _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == ThiefBehavior.State.CARRY, 10.0)
+ r.check(absf(took + 1.0 - steal) < 0.1, "a full steal takes %.1f s (took %.2f s)" % [steal, took + 1.0])
+ d = es.resolve_handle(h)
+ r.check(loot.status[unit] == S.CARRIED and es.carry[d] == unit and not loot._units[unit].visible,
+ "the crop is carried: gone from its plot, riding on the crow")
+ r.check(int(sim.campaign.state.night_events.get("crops_stolen", 0)) == 1, "the steal counts toward the night's record")
+ _step(sim, 30)
+ d = es.resolve_handle(h)
+ var at := Vector2(es.pos_x[d], es.pos_z[d])
+ es.apply_hit(es.resolve_handle(h))
+ _step(sim, 1)
+ r.check(es.resolve_handle(h) == -1 and loot.status[unit] == S.DROPPED and loot.ground[unit].distance_to(at) < 0.2,
+ "one hit kills the crow, and it drops the crop where it fell")
+ r.check(int(_events.get(&"dropped", 0)) == 1 and not es.apply_hit_handle(h), "the crop drops exactly once; the dead crow takes no more hits")
+ _step(sim, 30)
+ r.check(loot.status[unit] == S.DROPPED, "a dropped crop stays put while the scarecrow is away")
+ var g := loot.ground[unit]
+ player.global_position = Vector3(g.x + 1.0, 0.0, g.y)
+ _step(sim, 1)
+ r.check(loot.status[unit] == S.HOME and loot._units[unit].visible and int(sim.campaign.state.night_events.get("crops_recovered", 0)) == 1,
+ "walking up to the dropped crop recovers it to its plot")
+ player.global_position = AWAY
+ _consistent(r, sim)
+
+
+func _escape(r: GameTestRunner, sim: FarmSim) -> void:
+ var h := sim.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["south"])
+ var took := _until(sim, func() -> bool: return sim.enemies.resolve_handle(h) == -1, 60.0)
+ r.check(took < 60.0 and sim.enemies.escapes == 1, "an unopposed crow steals a crop and flies off over the fence (%.1f s)" % took)
+ r.check(sim.loot.count(S.LOST, LootSystem.Category.CROP) == 1 and sim.campaign.state.crops == 29 and sim.campaign.state.lost_crops.size() == 1,
+ "the escaped crop is lost for good")
+ var lost := sim.campaign.state.lost_crops[0]
+ r.check(not sim.loot._units[lost].visible and int(_events.get(&"lost", 0)) == 1, "a lost crop stays gone from its plot")
+ _consistent(r, sim)
+
+
+func _stale_handles(r: GameTestRunner, sim: FarmSim) -> void:
+ var es := sim.enemies
+ var h1 := sim.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["east"])
+ _step(sim, 1)
+ var unit := es.target[es.resolve_handle(h1)]
+ es.apply_hit(es.resolve_handle(h1), 99)
+ _step(sim, 1)
+ r.check(not sim.loot.is_claimed_by(unit, h1) and sim.loot.holder[unit] == -1, "a killed crow's claim is released")
+ var h2 := sim.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["east"])
+ r.check(es.resolve_handle(h1) == -1 and es.resolve_handle(h2) >= 0 and (h1 & EnemySystem.ID_MASK) == (h2 & EnemySystem.ID_MASK),
+ "the reused slot has a new generation: the old handle is stale")
+ var some := 1
+ while not sim.loot.is_home(some):
+ some += 1
+ sim.loot.holder[some] = h1 # a claim forged with the stale handle
+ r.check(not sim.loot.pick_up(some, h2) and sim.loot.status[some] == S.HOME, "another handle can't take a unit it doesn't hold")
+ sim.loot.holder[some] = -1
+ sim.loot.drop(some, h1, 0.0, 0.0)
+ sim.loot.escape(some, h1)
+ r.check(sim.loot.status[some] == S.HOME and not sim.campaign.state.is_crop_lost(some), "a stale handle can't drop or lose a crop")
+ es.apply_hit_handle(h2, 99)
+ _step(sim, 1)
+ _consistent(r, sim)
+
+
+func _shots(r: GameTestRunner, sim: FarmSim) -> void:
+ var es := sim.enemies
+ var h := es.spawn(EnemySystem.TYPE_THIEF, 10.0, -8.0, Vector2.DOWN)
+ _step(sim, 1)
+ var d := es.resolve_handle(h)
+ var y := sim.config.combat_height
+ var hp := es.health[d]
+ es.pos_x[d] = 10.0
+ es.pos_z[d] = -8.0
+ es.prev_x[d] = 10.0
+ es.prev_z[d] = -8.0
+ es.grid.rebuild(es.pos_x, es.pos_z, es.active_count)
+ sim.projectiles.fire(Vector3(10.0, y, -2.0), Vector3(10.0, y, -3.0), Vector3(0, 0, -1))
+ for i in 20:
+ sim.projectiles.step(DT)
+ r.check(es.health[d] == hp - 1 and sim.projectiles.hits_enemy == 1, "a shot hits the thief in its path")
+ var walls := sim.projectiles.hits_world
+ sim.projectiles.fire(Vector3(1.0, y, -16.0), Vector3(1.0, y, -17.0), Vector3(0, 0, -1))
+ for i in 30:
+ sim.projectiles.step(DT)
+ r.check(sim.projectiles.hits_world == walls + 1 and sim.projectiles.active_count == 0, "a shot stops at the barn")
+ es.apply_hit(d, 99)
+ _step(sim, 1)
+ # A crow cruising high is still hit by a shot at combat height (its altitude is only visual).
+ var keep := es.behavior
+ es.behavior = null
+ var crow := es.spawn(EnemySystem.TYPE_CROW, 10.0, -8.0, Vector2.DOWN)
+ _step(sim, 1)
+ var c := es.resolve_handle(crow)
+ r.check(es.alt[c] > y + 1.0, "a crow cruises at %.1f m" % es.alt[c])
+ sim.projectiles.fire(Vector3(10.0, y, -2.0), Vector3(10.0, y, -3.0), Vector3(0, 0, -1))
+ for i in 20:
+ sim.projectiles.step(DT)
+ _step(sim, 1)
+ r.check(es.resolve_handle(crow) == -1, "a shot brings it down")
+ es.behavior = keep
+
+
+## The real input path: right-stick aim at a thief and the fire action held (after the fresh
+## press the gun requires) shoot it.
+func _combat_input(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var es := sim.enemies
+ player.global_position = Vector3(8.0, 0.0, -9.0)
+ var keep := es.behavior
+ es.behavior = null # it stands still
+ var h := es.spawn(EnemySystem.TYPE_THIEF, 14.0, -9.0, Vector2.LEFT)
+ _step(sim, 1)
+ var d := es.resolve_handle(h)
+ var hp := es.health[d]
+ var b := sim.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 want := Vector2(es.pos_x[d] - 8.0, es.pos_z[d] + 9.0).normalized()
+ var stick := Vector2(want.dot(right), want.dot(fwd))
+ Input.action_press("aim_right" if stick.x > 0.0 else "aim_left", absf(stick.x))
+ Input.action_press("aim_up" if stick.y > 0.0 else "aim_down", absf(stick.y))
+ sim.campaign.state.upgrades["corn_shooter"] = 1 # the gun, from the workbench
+ r.check(sim.combat.equip(ScarecrowCombat.Weapon.CORN_SHOOTER), "(the corn shooter in hand)")
+ sim.combat.reset() # as every new morning does
+ Input.action_press("fire")
+ _step(sim, 10)
+ r.check(sim.combat.shots_fired == 0, "a fire button held through a reset doesn't shoot until pressed again")
+ Input.action_release("fire")
+ _step(sim, 1)
+ Input.action_press("fire")
+ _step(sim, 30)
+ for a in ["aim_right", "aim_left", "aim_up", "aim_down", "fire"]:
+ Input.action_release(a)
+ d = es.resolve_handle(h)
+ r.check(sim.combat.device == ScarecrowCombat.Device.GAMEPAD and sim.combat.aim.dot(want) > 0.99,
+ "the right stick aims camera-relative")
+ r.check(sim.combat.shots_fired >= 2 and (d < 0 or es.health[d] < hp), "holding fire shoots the thief (%d shots)" % sim.combat.shots_fired)
+ sim.campaign.state.upgrades.erase("corn_shooter")
+ sim.combat.tick(DT, true)
+ r.check(sim.combat.weapon == ScarecrowCombat.Weapon.PITCHFORK, "(back to the pitchfork)")
+ es.behavior = keep
+ if d >= 0:
+ es.apply_hit(d, 99)
+ _step(sim, 1)
+ player.global_position = AWAY
+
+
+func _sunrise_and_dawn_end(r: GameTestRunner, sim: FarmSim) -> void:
+ var c := sim.campaign
+ var es := sim.enemies
+ var loot := sim.loot
+ c.begin_day()
+ c.advance_phase()
+ c.advance_phase()
+ r.check(c.state.phase == P.NIGHT, "night falls")
+ var lost_before := c.state.crops
+ # A crow taking a crop retreats at sunrise and leaves without it.
+ var h := sim.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["east"])
+ _until(sim, func() -> bool: return es.state[es.resolve_handle(h)] == ThiefBehavior.State.STEAL, 30.0)
+ var unit := es.target[es.resolve_handle(h)]
+ # A carrier, and a crop lying dropped, both forced into place.
+ var carrier := sim.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["west"])
+ _place(es, carrier, Vector2(20.0, -5.0))
+ var cu := _home_unit(loot, unit)
+ loot.holder[cu] = carrier
+ loot.pick_up(cu, carrier)
+ es.carry[es.resolve_handle(carrier)] = cu
+ es.state[es.resolve_handle(carrier)] = ThiefBehavior.State.CARRY
+ var victim := sim.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["north"])
+ _place(es, victim, Vector2(8.0, -10.0))
+ var du := _home_unit(loot, cu)
+ loot.holder[du] = victim
+ loot.pick_up(du, victim)
+ es.carry[es.resolve_handle(victim)] = du
+ es.apply_hit(es.resolve_handle(victim), 99)
+ _step(sim, 1)
+ r.check(loot.status[du] == S.DROPPED, "a crop lies dropped")
+ c.advance_phase()
+ r.check(c.state.phase == P.DAWN and es.state[es.resolve_handle(h)] == ThiefBehavior.State.RETREAT and loot.holder[unit] == -1,
+ "sunrise: the stealing crow gives up its crop and retreats")
+ r.check(es.state[es.resolve_handle(carrier)] == ThiefBehavior.State.CARRY, "sunrise: the carrier keeps running")
+ _step(sim, 30)
+ var stolen := int(c.state.night_events.get("crops_stolen", 0))
+ c.advance_phase() # the dawn grace ends now
+ r.check(c.state.phase == P.MORNING and es.active_count == 0, "the end of the dawn grace clears the farm of enemies")
+ r.check(loot.status[cu] == S.LOST and c.state.is_crop_lost(cu), "a carrier still on the farm takes its crop along")
+ r.check(loot.status[du] == S.HOME and loot.status[unit] == S.HOME, "the dropped crop returns, the abandoned one is untouched")
+ var e: Dictionary = c.state.night_log[c.state.night_log.size() - 1]
+ r.check(e["crops_lost"] == lost_before - c.state.crops and e["crops_lost"] == 1 and e["crops_stolen"] == stolen,
+ "the night's record: %s" % [e])
+ _consistent(r, sim)
+
+
+func _retry(r: GameTestRunner, sim: FarmSim) -> void:
+ var c := sim.campaign
+ var es := sim.enemies
+ var morning_lost := c.state.lost_crops.duplicate()
+ c.begin_day()
+ c.advance_phase()
+ c.advance_phase()
+ var h := sim.spawn_enemy(EnemySystem.TYPE_CROW, LootSystem.ANY, GameTestRunner.SKY["south"])
+ _until(sim, func() -> bool: return es.resolve_handle(h) == -1, 60.0)
+ r.check(c.state.lost_crops.size() == morning_lost.size() + 1, "a crop is lost on the second night")
+ c.state.scarecrow_hp = 0
+ _step(sim, 1)
+ r.check(c.state.phase == P.GAME_OVER, "the scarecrow falls")
+ c.retry_night()
+ _step(sim, 1)
+ r.check(c.state.lost_crops == morning_lost and sim.loot.count(S.LOST, LootSystem.Category.CROP) == morning_lost.size() and es.active_count == 0,
+ "retry restores the morning: the crop lost that night is back in its plot")
+ _consistent(r, sim)
+
+
+## Trickle mode (tests and soaks): crows trickle in one at a time, and only at night.
+func _night_arrivals(r: GameTestRunner, sim: FarmSim) -> void:
+ var c := sim.campaign
+ sim.config.night_thieves = 1
+ sim.waves.enabled = true
+ c.begin_day()
+ _step(sim, 600)
+ r.check(sim.enemies.active_count == 0, "no crows arrive by day")
+ c.advance_phase()
+ c.advance_phase()
+ _step(sim, roundi(WaveDirector.FIRST_TRICKLE_DELAY * 60.0) + 2)
+ r.check(sim.enemies.alive_count() == 1 and sim.enemies.type[0] == EnemySystem.TYPE_CROW,
+ "the first crow arrives %.0f s into the night" % WaveDirector.FIRST_TRICKLE_DELAY)
+ var most := 0
+ for i in 1200:
+ sim.step(DT)
+ most = maxi(most, sim.enemies.alive_count())
+ r.check(most == 1, "never more than one at a time (night_thieves = 1)")
+ sim.config.night_thieves = 0
+ sim.waves.enabled = false
+
+
+## FarmState's lost crops and the loot system's LOST units are the same set.
+func _consistent(r: GameTestRunner, sim: FarmSim) -> void:
+ var lost := PackedInt32Array()
+ for id in range(1, sim.loot.unit_count + 1):
+ if sim.loot.status[id] == S.LOST:
+ lost.append(id)
+ r.check(lost == sim.campaign.state.lost_crops and sim.campaign.state.crops == sim.loot.unit_count - lost.size(),
+ "FarmState agrees with the loot state (%d lost)" % lost.size())
+
+
+func _place(es: EnemySystem, handle: int, p: Vector2) -> void:
+ var d := es.resolve_handle(handle)
+ es.pos_x[d] = p.x
+ es.pos_z[d] = p.y
+ es.prev_x[d] = p.x
+ es.prev_z[d] = p.y
+
+
+func _home_unit(loot: LootSystem, other: int) -> int:
+ for id in range(1, loot.unit_count + 1):
+ if id != other and loot.status[id] == S.HOME and loot.holder[id] == -1:
+ return id
+ return -1
+
+
+func _step(sim: FarmSim, n: int) -> void:
+ for i in n:
+ sim.step(DT)
+
+
+## Steps until cond() holds; returns the seconds it took (or max_seconds).
+func _until(sim: FarmSim, cond: Callable, max_seconds: float) -> float:
+ var t := 0.0
+ while t < max_seconds and not cond.call():
+ sim.step(DT)
+ t += DT
+ return t
diff --git a/game/tests/test_theft.gd.uid b/game/tests/test_theft.gd.uid
new file mode 100644
index 0000000..7b69d4c
--- /dev/null
+++ b/game/tests/test_theft.gd.uid
@@ -0,0 +1 @@
+uid://djllti2122mck
diff --git a/game/tests/test_weapons.gd b/game/tests/test_weapons.gd
new file mode 100644
index 0000000..403aa4b
--- /dev/null
+++ b/game/tests/test_weapons.gd
@@ -0,0 +1,261 @@
+extends RefCounted
+## The scarecrow's three weapons on the real farm (FarmSim stepped by hand at 60 Hz): only the
+## pitchfork to start; its stab (in reach and in the arc of the aim only, the nearest few, its
+## damage, once per interval, again and again while fire is held, not through a wall); the corn
+## shooter and pumpkin bombs bought at the workbench (rapid fire and heavy seeds need the corn
+## shooter first; a weapon bought goes into the hand); switching (Tab / 1-3, owned ones only, not
+## in build mode; one no longer owned falls back to the pitchfork); a bomb's throw (at the aim,
+## its range clamped), flight, and burst (everything in its radius, crows too, nothing beyond,
+## not the scarecrow), its recharge and the morning refill; the models on the scarecrow; and the
+## HUD's weapon panel.
+
+const DT := 1.0 / 60.0
+const AT := Vector2(0.0, 6.0) # open ground south-west of the pen
+const W := ScarecrowCombat.Weapon
+const THIEF := EnemySystem.TYPE_THIEF
+
+
+func run(r: GameTestRunner) -> void:
+ var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
+ r.root.add_child(farm)
+ await r.process_frame
+ await r.physics_frame
+ var sim := farm.get_node("FarmSim") as FarmSim
+ sim.set_physics_process(false)
+ sim.waves.enabled = false
+ var player := farm.get_node("Player") as PlayerCharacter
+ player.global_position = Vector3(AT.x, 0.0, AT.y)
+ var keep := sim.enemies.behavior
+ sim.enemies.behavior = null # enemies stand still
+ _start(r, sim, player)
+ _pitchfork(r, sim)
+ await _wall(r, sim, farm)
+ _unlocks(r, farm, sim)
+ _switching(r, sim)
+ _bombs(r, sim)
+ _hud(r, farm, sim)
+ sim.enemies.behavior = keep
+ farm.queue_free()
+ await r.process_frame
+
+
+func _start(r: GameTestRunner, sim: FarmSim, player: PlayerCharacter) -> void:
+ var c := sim.combat
+ r.check(c.weapon == W.PITCHFORK and c.owns(W.PITCHFORK) and not c.owns(W.CORN_SHOOTER) and not c.owns(W.PUMPKIN_BOMB),
+ "a new vacation: the pitchfork in hand, and nothing else")
+ var pivots := c.models._pivots
+ r.check(pivots.size() == 3 and pivots[0].visible and not pivots[1].visible and not pivots[2].visible, "only the pitchfork shows on the scarecrow")
+ var near := true
+ for p in pivots:
+ near = near and p.global_position.distance_to(player.global_position) < 3.0
+ r.check(near, "the models sit on the scarecrow (their exports were 1.8 km off the origin)")
+
+
+func _pitchfork(r: GameTestRunner, sim: FarmSim) -> void:
+ var c := sim.combat
+ var cfg := sim.config
+ var es := sim.enemies
+ var front := es.spawn(THIEF, AT.x + 1.2, AT.y, Vector2.LEFT)
+ var front2 := es.spawn(THIEF, AT.x + 1.7, AT.y + 0.7, Vector2.LEFT)
+ var behind := es.spawn(THIEF, AT.x - 1.2, AT.y, Vector2.RIGHT)
+ var far := es.spawn(THIEF, AT.x + cfg.pitchfork_reach + 1.5, AT.y, Vector2.LEFT)
+ _step(sim, 1)
+ var full := es.t_hp[THIEF]
+ r.check(c.attack_toward(AT + Vector2(5.0, 0.0)) and c.stabs == 1, "a stab to the east")
+ r.check(_hp(es, front) == full - cfg.pitchfork_damage and _hp(es, front2) == full - cfg.pitchfork_damage,
+ "both thieves in front, in reach, take %d" % cfg.pitchfork_damage)
+ r.check(_hp(es, behind) == full and _hp(es, far) == full, "the one behind and the one out of reach don't")
+ r.check(not c.attack_toward(AT + Vector2(5.0, 0.0)), "one stab per %.1f s: not again at once" % cfg.pitchfork_interval)
+ _step(sim, c.stab_ticks())
+ r.check(c.attack_toward(AT + Vector2(5.0, 0.0)), "and again after it")
+ _step(sim, 1)
+ r.check(es.resolve_handle(front) < 0 and es.resolve_handle(front2) < 0, "two stabs stop a thief")
+ _clear(sim)
+ # The nearest few only, crows too.
+ var crowd: Array[int] = []
+ for k in 5:
+ crowd.append(es.spawn(THIEF, AT.x + 0.9 + k * 0.28, AT.y + (0.5 if k % 2 == 0 else -0.5), Vector2.LEFT))
+ _step(sim, 1)
+ _step(sim, c.stab_ticks())
+ c.attack_toward(AT + Vector2(5.0, 0.0))
+ var hit := crowd.filter(func(h: int) -> bool: return _hp(es, h) < full).size()
+ r.check(hit == cfg.pitchfork_targets, "a stab hits the nearest %d of a crowd (%d)" % [cfg.pitchfork_targets, hit])
+ _clear(sim)
+ var crow := es.spawn(EnemySystem.TYPE_CROW, AT.x + 1.5, AT.y, Vector2.LEFT)
+ _step(sim, c.stab_ticks())
+ c.attack_toward(AT + Vector2(5.0, 0.0))
+ _step(sim, 1)
+ r.check(es.resolve_handle(crow) < 0, "a crow in reach is stabbed out of the air")
+ # Held fire stabs again and again.
+ c.reset()
+ _step(sim, 1)
+ var before := c.stabs
+ Input.action_press("fire")
+ _step(sim, c.stab_ticks() * 2)
+ Input.action_release("fire")
+ _step(sim, 1)
+ r.check(c.stabs - before == 2, "holding fire stabs every %.1f s (%d in %.1f s)" % [cfg.pitchfork_interval, c.stabs - before, cfg.pitchfork_interval * 2.0])
+
+
+func _wall(r: GameTestRunner, sim: FarmSim, farm: Node3D) -> void:
+ var c := sim.combat
+ var es := sim.enemies
+ var h := es.spawn(THIEF, AT.x + 1.5, AT.y, Vector2.LEFT)
+ var wall := StaticBody3D.new()
+ var shape := CollisionShape3D.new()
+ var box := BoxShape3D.new()
+ box.size = Vector3(0.2, 3.0, 2.0)
+ shape.shape = box
+ wall.add_child(shape)
+ farm.add_child(wall)
+ wall.global_position = Vector3(AT.x + 0.75, 1.5, AT.y)
+ await r.physics_frame # it joins the physics space on the next physics frame
+ _step(sim, c.stab_ticks())
+ c.attack_toward(AT + Vector2(5.0, 0.0))
+ r.check(_hp(es, h) == es.t_hp[THIEF], "no stab through a wall")
+ wall.queue_free()
+ await r.physics_frame
+ _clear(sim)
+
+
+func _unlocks(r: GameTestRunner, farm: Node3D, sim: FarmSim) -> void:
+ var c := sim.campaign
+ var s := c.state
+ var combat := sim.combat
+ var st := sim.structures
+ c.begin_day()
+ s.resources.shed = {"wood": 99, "scrap": 99, "straw": 99}
+ r.check(not combat.equip(W.CORN_SHOOTER) and combat.weapon == W.PITCHFORK, "the corn shooter can't be taken up before it's bought")
+ r.check(Upgrades.blocker(c, "rapid_fire") == "Needs the corn shooter first" and Upgrades.buy(c, "heavy_seeds", st).contains("needs the corn shooter")
+ and not Upgrades.owned(s, "heavy_seeds"), "rapid fire and heavy seeds need the corn shooter first")
+ r.check(Upgrades.buy(c, "corn_shooter", st).contains("done:") and combat.owns(W.CORN_SHOOTER) and Upgrades.blocker(c, "rapid_fire") == "",
+ "the corn shooter is bought at the workbench; then rapid fire can be")
+ var panel := farm.get_node("Hud/UpgradePanel") as UpgradePanel
+ panel._buy("pumpkin_bomb")
+ r.check(combat.owns(W.PUMPKIN_BOMB) and combat.weapon == W.PUMPKIN_BOMB, "a weapon bought from the menu goes into the hand")
+ r.check(combat.models._pivots[2].visible and not combat.models._pivots[0].visible, "and shows on the scarecrow")
+
+
+func _switching(r: GameTestRunner, sim: FarmSim) -> void:
+ var c := sim.combat
+ var s := sim.campaign.state
+ c.equip(W.PITCHFORK)
+ var seen: Array[int] = []
+ for k in 3:
+ _tap(sim, "weapon_next")
+ seen.append(c.weapon)
+ r.check(seen == [W.CORN_SHOOTER, W.PUMPKIN_BOMB, W.PITCHFORK], "Tab / d-pad down cycles through them: %s" % [seen])
+ _tap(sim, "weapon_3")
+ var third := c.weapon
+ _tap(sim, "weapon_1")
+ r.check(third == W.PUMPKIN_BOMB and c.weapon == W.PITCHFORK, "1-3 pick one")
+ var east := AT + Vector2(5.0, 0.0)
+ _step(sim, c.stab_ticks())
+ c.attack_toward(east)
+ c.equip(W.CORN_SHOOTER)
+ var shot := c.attack_toward(east)
+ c.equip(W.PITCHFORK)
+ r.check(shot and not c.attack_toward(east), "each weapon keeps its own wait: swapping doesn't skip the pitchfork's")
+ sim.build.set_active(true)
+ _tap(sim, "weapon_2")
+ _tap(sim, "weapon_next")
+ var building := c.weapon
+ sim.build.set_active(false)
+ r.check(building == W.PITCHFORK, "not in build mode (those keys pick structures there)")
+ s.upgrades.erase("pumpkin_bomb")
+ c.equip(W.CORN_SHOOTER)
+ _tap(sim, "weapon_next")
+ var skipped := c.weapon
+ _tap(sim, "weapon_3")
+ r.check(skipped == W.PITCHFORK and c.weapon == W.PITCHFORK, "only weapons owned: no pumpkin bombs without the upgrade")
+ c.equip(W.CORN_SHOOTER)
+ s.upgrades.erase("corn_shooter")
+ _step(sim, 1)
+ r.check(c.weapon == W.PITCHFORK, "one no longer owned (a retry from before it was bought) goes back to the pitchfork")
+ s.upgrades["corn_shooter"] = 1
+ s.upgrades["pumpkin_bomb"] = 1
+
+
+func _bombs(r: GameTestRunner, sim: FarmSim) -> void:
+ var c := sim.combat
+ var cfg := sim.config
+ var es := sim.enemies
+ var kit := sim.scarecrow
+ c.equip(W.PUMPKIN_BOMB)
+ c.ready_for_morning()
+ var target := AT + Vector2(6.0, 0.0)
+ var on := es.spawn(THIEF, target.x, target.y, Vector2.LEFT)
+ var near := es.spawn(THIEF, target.x + cfg.bomb_radius - 0.5, target.y, Vector2.LEFT)
+ var crow := es.spawn(EnemySystem.TYPE_CROW, target.x, target.y + 1.5, Vector2.LEFT)
+ var out := es.spawn(THIEF, target.x + cfg.bomb_radius + 2.0, target.y, Vector2.LEFT)
+ _step(sim, 1)
+ var hp := kit.hp()
+ r.check(c.attack_toward(target) and sim.bombs.flying() == 1 and is_equal_approx(c.bomb_left, cfg.bomb_cooldown),
+ "a pumpkin bomb is thrown at the aim point")
+ r.check(not c.attack_toward(target), "only one every %.0f s" % cfg.bomb_cooldown)
+ r.check(c.models._pivots[2].scale.x < 0.05, "it's gone from the hand")
+ var ticks := 0
+ while sim.bombs.flying() > 0 and ticks < 200:
+ _step(sim, 1)
+ ticks += 1
+ _step(sim, 1)
+ r.check(ticks * DT >= PumpkinBombs.MIN_FLIGHT - DT and ticks * DT <= PumpkinBombs.MAX_FLIGHT + DT, "it flies %.2f s" % (ticks * DT))
+ r.check(es.resolve_handle(on) < 0 and es.resolve_handle(near) < 0 and es.resolve_handle(crow) < 0,
+ "its burst stops everything within %.0f m (%d damage), crows too" % [cfg.bomb_radius, cfg.bomb_damage])
+ r.check(_hp(es, out) == es.t_hp[THIEF] and kit.hp() == hp and sim.bombs.bursts == 1, "nothing beyond, and not the scarecrow")
+ _clear(sim)
+ c.device = ScarecrowCombat.Device.MOUSE
+ var me := Vector2(sim.player.global_position.x, sim.player.global_position.z)
+ c.ground_point = Vector3(me.x + 30.0, 0.0, me.y)
+ var long := Vector2(c.throw_target().x, c.throw_target().z).distance_to(me)
+ c.ground_point = Vector3(me.x + 0.5, 0.0, me.y)
+ var short := Vector2(c.throw_target().x, c.throw_target().z).distance_to(me)
+ r.check(is_equal_approx(long, cfg.bomb_range) and is_equal_approx(short, cfg.bomb_min_range),
+ "it lands %.0f .. %.0f m away (%.1f, %.1f)" % [cfg.bomb_min_range, cfg.bomb_range, short, long])
+ _step(sim, roundi(cfg.bomb_cooldown * 60.0) + 2)
+ r.check(c.bomb_left == 0.0 and c.models._pivots[2].scale.x > 0.99, "after %.0f s another one is in hand" % cfg.bomb_cooldown)
+ c.attack_toward(target)
+ c.ready_for_morning()
+ r.check(c.bomb_left == 0.0, "a new morning puts one in hand")
+ sim.bombs.clear()
+
+
+func _hud(r: GameTestRunner, farm: Node3D, sim: FarmSim) -> void:
+ var hud := farm.get_node("Hud/ScarecrowHud") as ScarecrowHud
+ var c := sim.combat
+ var s := sim.campaign.state
+ s.upgrades.erase("corn_shooter")
+ c.equip(W.PUMPKIN_BOMB)
+ c.attack_toward(AT + Vector2(6.0, 0.0))
+ hud._process(0.0)
+ var rows := hud._weapon_rows.map(func(l: Label) -> String: return l.text)
+ r.check(rows[0] == "1 Pitchfork" and rows[1] == "2 Corn shooter (workbench)" and rows[2] == "3 Pumpkin bombs 4 s",
+ "the HUD lists the weapons: %s" % [rows])
+ r.check(hud._weapon_title.visible and hud._weapon_hint.text.contains("Tab"), "with how to switch")
+ s.upgrades.erase("pumpkin_bomb")
+ _step(sim, 1)
+ sim.bombs.clear()
+ _step(sim, 1)
+
+
+func _tap(sim: FarmSim, action: String) -> void:
+ Input.action_press(action)
+ _step(sim, 1)
+ Input.action_release(action)
+ _step(sim, 1)
+
+
+func _hp(es: EnemySystem, handle: int) -> int:
+ var d := es.resolve_handle(handle)
+ return es.health[d] if d >= 0 else 0
+
+
+func _clear(sim: FarmSim) -> void:
+ for d in sim.enemies.active_count:
+ sim.enemies.apply_hit(d, 99)
+ _step(sim, 1)
+
+
+func _step(sim: FarmSim, n: int) -> void:
+ for i in n:
+ sim.step(DT)
diff --git a/game/tests/test_weapons.gd.uid b/game/tests/test_weapons.gd.uid
new file mode 100644
index 0000000..45612b0
--- /dev/null
+++ b/game/tests/test_weapons.gd.uid
@@ -0,0 +1 @@
+uid://bw3sedxvmb27f
diff --git a/game/tools/build_player_animations.gd b/game/tools/build_player_animations.gd
index 9475f0d..87b97fc 100644
--- a/game/tools/build_player_animations.gd
+++ b/game/tools/build_player_animations.gd
@@ -1,35 +1,77 @@
extends SceneTree
-## Builds res://game/resources/player_animations.res: the KayKit Rig_Medium clips the farmer
-## uses, copied out of the shared animation files into one AnimationLibrary so the player
-## scene's AnimationPlayer can reference (and the editor can preview) them.
-## Tracks for bones the mannequin lacks (handslot.l/.r) are dropped; loop flags are set here
-## because every source clip is imported as non-looping. Source assets are not modified.
-## Re-run after editing CLIPS (editor closed):
+## Builds the KayKit animation libraries the game's characters use, copied out of the shared
+## animation files into one AnimationLibrary per rig so AnimationPlayers can reference (and the
+## editor can preview) them:
+## res://game/resources/player_animations.res Rig_Medium: the scarecrow and ground thieves
+## res://game/resources/breaker_animations.res Rig_Large: the fence breaker
+## Tracks for bones the mannequin lacks (handslot.l/.r on the medium one) are dropped; loop flags
+## are set here because every source clip is imported as non-looping. Source assets are not
+## modified. Re-run after editing BUILDS (editor closed):
## godot --headless --path . --script res://game/tools/build_player_animations.gd
-const MANNEQUIN := "res://assets/kaykit_characters/characters/Mannequin_Medium.glb"
-const ANIM_DIR := "res://assets/kaykit_characters/animations/Rig_Medium/"
-const OUTPUT := "res://game/resources/player_animations.res"
-const SKELETON_PATH := "Rig_Medium/Skeleton3D"
+const KIT := "res://assets/kaykit_characters/"
+## Per library: mannequin, animation folder, skeleton path, output, and clips (name as in
+## KayKit -> [source file, loops]).
+const BUILDS := [
+ {
+ "mannequin": KIT + "characters/Mannequin_Medium.glb",
+ "anims": KIT + "animations/Rig_Medium/",
+ "skeleton": "Rig_Medium/Skeleton3D",
+ "output": "res://game/resources/player_animations.res",
+ "clips": {
+ "Idle_A": ["Rig_Medium_General.glb", true],
+ "Idle_B": ["Rig_Medium_General.glb", true],
+ "Interact": ["Rig_Medium_General.glb", false],
+ "PickUp": ["Rig_Medium_General.glb", false],
+ "Use_Item": ["Rig_Medium_General.glb", false],
+ "Walking_A": ["Rig_Medium_MovementBasic.glb", true],
+ "Running_A": ["Rig_Medium_MovementBasic.glb", true],
+ "Sneaking": ["Rig_Medium_MovementAdvanced.glb", true],
+ "Digging": ["Rig_Medium_Tools.glb", true],
+ "Chopping": ["Rig_Medium_Tools.glb", true],
+ "Hammering": ["Rig_Medium_Tools.glb", true],
+ "Lockpicking": ["Rig_Medium_Tools.glb", true],
+ "Melee_Unarmed_Attack_Punch_A": ["Rig_Medium_CombatMelee.glb", true],
+ "Hit_A": ["Rig_Medium_General.glb", false],
+ "Waving": ["Rig_Medium_Simulation.glb", false],
+ "Cheering": ["Rig_Medium_Simulation.glb", true],
+ "Death_A": ["Rig_Medium_General.glb", false],
+ },
+ },
+ {
+ "mannequin": KIT + "characters/Mannequin_Large.glb",
+ "anims": KIT + "animations/Rig_Large/",
+ "skeleton": "Rig_Large/Skeleton3D",
+ "output": "res://game/resources/breaker_animations.res",
+ "clips": {
+ "Idle_A": ["Rig_Large_General.glb", true],
+ "Walking_A": ["Rig_Large_MovementBasic.glb", true],
+ "Running_A": ["Rig_Large_MovementBasic.glb", true],
+ "Melee_2H_Idle": ["Rig_Large_CombatMelee.glb", true],
+ "Melee_2H_Attack": ["Rig_Large_CombatMelee.glb", true],
+ "Melee_2H_Slam": ["Rig_Large_CombatMelee.glb", true],
+ "Hit_A": ["Rig_Large_General.glb", false],
+ "Death_A": ["Rig_Large_General.glb", false],
+ },
+ },
+]
-## Clip name (kept as in KayKit) -> [source file, loops].
-const CLIPS := {
- "Idle_A": ["Rig_Medium_General.glb", true],
- "Idle_B": ["Rig_Medium_General.glb", true],
- "Interact": ["Rig_Medium_General.glb", false],
- "PickUp": ["Rig_Medium_General.glb", false],
- "Use_Item": ["Rig_Medium_General.glb", false],
- "Walking_A": ["Rig_Medium_MovementBasic.glb", true],
- "Running_A": ["Rig_Medium_MovementBasic.glb", true],
- "Digging": ["Rig_Medium_Tools.glb", true],
- "Chopping": ["Rig_Medium_Tools.glb", true],
- "Hammering": ["Rig_Medium_Tools.glb", true],
- "Waving": ["Rig_Medium_Simulation.glb", false],
-}
+var _mannequin := ""
+var _anim_dir := ""
+var _output := ""
+var _skeleton := ""
+var _clips := {}
func _initialize() -> void:
- var ok := _build()
+ var ok := true
+ for b: Dictionary in BUILDS:
+ _mannequin = b["mannequin"]
+ _anim_dir = b["anims"]
+ _output = b["output"]
+ _skeleton = b["skeleton"]
+ _clips = b["clips"]
+ ok = _build() and ok
quit(0 if ok else 1)
@@ -41,10 +83,10 @@ func _build() -> bool:
var sources := {} # file -> instantiated scene root (freed at the end)
var dropped := 0
var ok := true
- for clip: String in CLIPS:
- var file: String = CLIPS[clip][0]
+ for clip: String in _clips:
+ var file: String = _clips[clip][0]
if not sources.has(file):
- var scene := load(ANIM_DIR + file) as PackedScene
+ var scene := load(_anim_dir + file) as PackedScene
if scene == null:
push_error("missing animation file " + file)
ok = false
@@ -58,36 +100,36 @@ func _build() -> bool:
var anim := player.get_animation(clip).duplicate(true) as Animation
for t in range(anim.get_track_count() - 1, -1, -1):
var path := anim.track_get_path(t)
- var keep := String(path.get_concatenated_names()) == SKELETON_PATH \
+ var keep := String(path.get_concatenated_names()) == _skeleton \
and path.get_subname_count() == 1 and bones.has(String(path.get_subname(0)))
if not keep:
anim.remove_track(t)
dropped += 1
- anim.loop_mode = Animation.LOOP_LINEAR if CLIPS[clip][1] else Animation.LOOP_NONE
+ anim.loop_mode = Animation.LOOP_LINEAR if _clips[clip][1] else Animation.LOOP_NONE
library.add_animation(clip, anim)
for file: String in sources:
(sources[file] as Node).free()
if not ok:
return false
- DirAccess.make_dir_recursive_absolute(ProjectSettings.globalize_path(OUTPUT.get_base_dir()))
- var err := ResourceSaver.save(library, OUTPUT)
+ DirAccess.make_dir_recursive_absolute(ProjectSettings.globalize_path(_output.get_base_dir()))
+ var err := ResourceSaver.save(library, _output)
if err != OK:
- push_error("could not save %s (error %d)" % [OUTPUT, err])
+ push_error("could not save %s (error %d)" % [_output, err])
return false
- print("saved %s: %d clips, %d foreign tracks dropped" % [OUTPUT, library.get_animation_list().size(), dropped])
+ print("saved %s: %d clips, %d foreign tracks dropped" % [_output, library.get_animation_list().size(), dropped])
return true
func _mannequin_bones() -> Dictionary:
- var scene := load(MANNEQUIN) as PackedScene
+ var scene := load(_mannequin) as PackedScene
if scene == null:
- push_error("missing mannequin " + MANNEQUIN)
+ push_error("missing mannequin " + _mannequin)
return {}
var root := scene.instantiate()
- var skel := root.get_node_or_null(SKELETON_PATH) as Skeleton3D
+ var skel := root.get_node_or_null(_skeleton) as Skeleton3D
var bones := {}
if skel == null:
- push_error("mannequin skeleton not found at " + SKELETON_PATH)
+ push_error("mannequin skeleton not found at " + _skeleton)
else:
for b in skel.get_bone_count():
bones[skel.get_bone_name(b)] = true
diff --git a/game/tools/build_ui_theme.gd b/game/tools/build_ui_theme.gd
new file mode 100644
index 0000000..ee3a481
--- /dev/null
+++ b/game/tools/build_ui_theme.gd
@@ -0,0 +1,10 @@
+extends SceneTree
+## Writes the game's UI theme (UiTheme.build()) to res://game/resources/ui_theme.tres, the
+## project's default theme (gui/theme/custom). Re-run after editing UiTheme (editor closed):
+## godot --headless --path . --script res://game/tools/build_ui_theme.gd
+
+
+func _initialize() -> void:
+ var err := ResourceSaver.save(UiTheme.build(), "res://game/resources/ui_theme.tres")
+ print("build_ui_theme: save -> %s" % error_string(err))
+ quit(0 if err == OK else 1)
diff --git a/game/tools/build_ui_theme.gd.uid b/game/tools/build_ui_theme.gd.uid
new file mode 100644
index 0000000..ab1f0bc
--- /dev/null
+++ b/game/tools/build_ui_theme.gd.uid
@@ -0,0 +1 @@
+uid://v7qxh2v2w8q3
diff --git a/game/tools/configure_input.gd b/game/tools/configure_input.gd
new file mode 100644
index 0000000..ef30275
--- /dev/null
+++ b/game/tools/configure_input.gd
@@ -0,0 +1,72 @@
+extends SceneTree
+## Writes the game's InputMap actions into project.godot (the prototype's actions, set by
+## prototype/tools/configure_project.gd, are left as they are). Idempotent: re-running replaces
+## only these actions. Run with the editor closed:
+## godot --headless --path . --script res://game/tools/configure_input.gd
+##
+## | Action | Keyboard / mouse | Gamepad | Used from |
+## |--------------|------------------|----------------|-----------|
+## | fear | Q | Left shoulder | Step 4 |
+## | patch (hold) | F | Y | Step 4 |
+## | interact | E | X | Step 5 |
+## | build_mode | B | D-pad up | Step 6 |
+## | rotate_left | Z | D-pad left | Step 6 |
+## | rotate_right | C | D-pad right | Step 6 |
+## | build_next | Tab | D-pad down | Step 6 |
+## | build_1..4 | 1, 2, 3, 4 | - | Step 6 |
+## | cancel | Right mouse | B | Step 6 |
+## | pause | Escape | Start | Step 11 |
+## | hide_tips | Backspace | Back | Step 11 |
+## | toggle_mic | M | - | Co-op |
+## | sprint (hold)| Shift | L3 (stick) | Sprint |
+## | weapon_next | Tab | D-pad down | Weapons |
+## | weapon_1..3 | 1, 2, 3 | - | Weapons |
+## The weapon keys are build mode's (build_next, build_1..3): outside build mode they pick weapons.
+
+
+func _initialize() -> void:
+ _action("fear", [_key(KEY_Q), _joy(JOY_BUTTON_LEFT_SHOULDER)])
+ _action("patch", [_key(KEY_F), _joy(JOY_BUTTON_Y)])
+ _action("interact", [_key(KEY_E), _joy(JOY_BUTTON_X)])
+ _action("build_mode", [_key(KEY_B), _joy(JOY_BUTTON_DPAD_UP)])
+ _action("rotate_left", [_key(KEY_Z), _joy(JOY_BUTTON_DPAD_LEFT)])
+ _action("rotate_right", [_key(KEY_C), _joy(JOY_BUTTON_DPAD_RIGHT)])
+ _action("build_next", [_key(KEY_TAB), _joy(JOY_BUTTON_DPAD_DOWN)])
+ var number_keys: Array[Key] = [KEY_1, KEY_2, KEY_3, KEY_4]
+ for i in 4:
+ _action("build_%d" % (i + 1), [_key(number_keys[i])])
+ _action("cancel", [_mouse(MOUSE_BUTTON_RIGHT), _joy(JOY_BUTTON_B)])
+ _action("pause", [_key(KEY_ESCAPE), _joy(JOY_BUTTON_START)])
+ _action("hide_tips", [_key(KEY_BACKSPACE), _joy(JOY_BUTTON_BACK)])
+ _action("toggle_mic", [_key(KEY_M)])
+ _action("sprint", [_key(KEY_SHIFT), _joy(JOY_BUTTON_LEFT_STICK)])
+ _action("weapon_next", [_key(KEY_TAB), _joy(JOY_BUTTON_DPAD_DOWN)])
+ for i in 3:
+ _action("weapon_%d" % (i + 1), [_key(number_keys[i])])
+ var err := ProjectSettings.save()
+ print("configure_input: save -> %s" % error_string(err))
+ quit(0 if err == OK else 1)
+
+
+func _action(action_name: String, events: Array[InputEvent]) -> void:
+ for e in events:
+ e.device = -1 # all devices, matching events created in the editor
+ ProjectSettings.set_setting("input/" + action_name, {"deadzone": 0.5, "events": events})
+
+
+func _key(code: Key) -> InputEventKey:
+ var e := InputEventKey.new()
+ e.physical_keycode = code
+ return e
+
+
+func _mouse(button: MouseButton) -> InputEventMouseButton:
+ var e := InputEventMouseButton.new()
+ e.button_index = button
+ return e
+
+
+func _joy(button: JoyButton) -> InputEventJoypadButton:
+ var e := InputEventJoypadButton.new()
+ e.button_index = button
+ return e
diff --git a/game/tools/configure_input.gd.uid b/game/tools/configure_input.gd.uid
new file mode 100644
index 0000000..3fb48f5
--- /dev/null
+++ b/game/tools/configure_input.gd.uid
@@ -0,0 +1 @@
+uid://b6hxj4xpi5h2a
diff --git a/game/tools/coop_smoke.gd b/game/tools/coop_smoke.gd
new file mode 100644
index 0000000..0395685
--- /dev/null
+++ b/game/tools/coop_smoke.gd
@@ -0,0 +1,160 @@
+extends SceneTree
+## Co-op over real GD-Sync (LAN mode, peer to peer on this machine): run two of these at once,
+## a host and a partner. Each loads the game (main.tscn, with its own save and settings files),
+## the host starts a vacation and opens a lobby, the partner finds it on the network and joins,
+## and both play a day and a night with enemies. Each prints what it saw and exits 0 when it
+## all checked out:
+## godot --headless --path . --script res://game/tools/coop_smoke.gd -- --role=host &
+## godot --headless --path . --script res://game/tools/coop_smoke.gd -- --role=join
+## Options: --seconds=N how long to play once joined (default 20); --discover makes the partner
+## find the host by GD-Sync's LAN announcements (broadcast) instead of joining by address
+## (127.0.0.1), for networks where broadcasts reach this machine. --online plays over GD-Sync's
+## servers instead (needs the API keys): the partner finds the host's lobby in the online list.
+## --host-name=Ana names the host (and so its lobby, "Ana's farm"); give both sides the same one.
+
+var role := "host"
+var seconds := 20.0
+var discover := false
+var online := false
+var host_name := "Ana"
+## --shot=path: a screenshot at night with the enemies in (needs a window, not --headless).
+var shot := ""
+var main: Main
+var failures: Array[String] = []
+
+
+func _initialize() -> void:
+ for a in OS.get_cmdline_user_args():
+ if String(a).begins_with("--role="):
+ role = String(a).trim_prefix("--role=")
+ elif String(a).begins_with("--shot="):
+ shot = String(a).trim_prefix("--shot=")
+ elif String(a) == "--discover":
+ discover = true
+ elif String(a) == "--online":
+ online = true
+ elif String(a).begins_with("--host-name="):
+ host_name = String(a).trim_prefix("--host-name=")
+ elif String(a).begins_with("--seconds="):
+ seconds = float(String(a).trim_prefix("--seconds="))
+ _run.call_deferred()
+
+
+func _say(text: String) -> void:
+ print("[%s %6.2f] %s" % [role, Time.get_ticks_msec() / 1000.0, text])
+
+
+func _check(ok: bool, what: String) -> void:
+ _say(("OK " if ok else "FAIL ") + what)
+ if not ok:
+ failures.append(what)
+
+
+func _run() -> void:
+ main = (load("res://game/scenes/main.tscn") as PackedScene).instantiate() as Main
+ main.save_path = "user://coop_smoke_%s_save.json" % role
+ main.settings_path = "user://coop_smoke_%s_settings.cfg" % role
+ root.add_child(main)
+ current_scene = main # as in the game: GD-Sync looks at the current scene
+ await process_frame
+ await process_frame
+ var lobby := main.lobby
+ var sim := main.sim
+ lobby.failed.connect(func(t: String) -> void: _say("lobby failed: " + t))
+ lobby.status_changed.connect(func(t: String) -> void:
+ if t != "":
+ _say("lobby: " + t))
+ if role == "host":
+ main.new_vacation()
+ lobby.host(CoopLobby.Mode.ONLINE if online else CoopLobby.Mode.LAN, host_name)
+ if not await _wait(func() -> bool: return sim.coop.is_host(), 60.0):
+ _check(false, "a partner joined within 60 s")
+ await _finish()
+ return
+ _check(true, "a partner joined: %s" % sim.coop.partner_name)
+ await _wait(func() -> bool: return false, 3.0)
+ sim.campaign.begin_day()
+ await _wait(func() -> bool: return false, 2.0)
+ sim.campaign.advance_phase()
+ sim.campaign.advance_phase()
+ for i in 24:
+ sim.spawn_enemy([EnemySystem.TYPE_CROW, EnemySystem.TYPE_THIEF, EnemySystem.TYPE_BREAKER][i % 3])
+ await _wait(func() -> bool: return false, 8.0)
+ await _screenshot()
+ await _wait(func() -> bool: return false, seconds - 8.0)
+ _check(sim.partner != null and sim.partner.body.global_position.distance_to(Vector3(-4.0, 0.0, -2.0)) < 1.0,
+ "P2 walked where the partner moved it, twice (%s)" % [sim.partner.body.global_position if sim.partner != null else "gone"])
+ _check(sim.partner != null and sim.partner.combat.attacks() > 0, "P2's weapon attacked on the host (%d attacks)" % (sim.partner.combat.attacks() if sim.partner != null else 0))
+ _check(sim.campaign.state.coop, "co-op is on in the farm state")
+ _say("waiting for the partner to finish")
+ await _wait(func() -> bool: return not sim.coop.is_active(), 30.0)
+ _check(not sim.coop.is_active() and sim.partner == null, "the partner left; the host plays on alone")
+ else:
+ if discover or online:
+ var want := "%s's farm" % host_name
+ lobby.search(CoopLobby.Mode.ONLINE if online else CoopLobby.Mode.LAN, "Ben")
+ var found: Array = []
+ lobby.lobbies_found.connect(func(list: Array) -> void:
+ found.assign(list.filter(func(l: Dictionary) -> bool: return String(l["name"]) == want)))
+ if not await _wait(func() -> bool: return not found.is_empty(), 40.0):
+ _check(false, "found the host's game \"%s\" %s within 40 s" % [want, "online" if online else "on the network"])
+ await _finish()
+ return
+ _check(true, "found %s %s" % [found[0]["name"], "online" if online else "on the network"])
+ lobby.join(String(found[0]["name"]))
+ else:
+ lobby.join_address("127.0.0.1", "Ben")
+ if not await _wait(func() -> bool: return sim.coop.is_client() and sim.coop._is_welcomed, 40.0):
+ _check(false, "joined and got the farm within 40 s")
+ await _finish()
+ return
+ _check(main.screen == Main.Screen.PLAYING and sim.replica and sim.local_avatar.slot == 1, "joined: playing P2 on a replica of the host's farm")
+ sim.player.global_position = Vector3(4.0, 0.0, -8.0)
+ await _wait(func() -> bool: return sim.campaign.state.phase == CampaignController.Phase.NIGHT, 30.0)
+ _check(sim.campaign.state.phase == CampaignController.Phase.NIGHT, "the host's nightfall reached the partner")
+ Input.action_press("fire")
+ await _wait(func() -> bool: return false, 4.0)
+ Input.action_release("fire")
+ await _wait(func() -> bool: return sim.enemies.alive_count() >= 10, 10.0)
+ _check(sim.enemies.alive_count() >= 10, "the host's enemies show on the partner's farm (%d)" % sim.enemies.alive_count())
+ _check(sim.coop.voices.size() == 2, "voice chat is set up (a VoiceChat per player)")
+ sim.player.global_position = Vector3(-4.0, 0.0, -2.0) # off the host's screen: the arrow
+ await _wait(func() -> bool: return false, 2.0)
+ await _screenshot()
+ await _wait(func() -> bool: return false, seconds - 4.0)
+ _say("leaving")
+ lobby.leave()
+ await _wait(func() -> bool: return false, 2.0)
+ _finish()
+
+
+func _screenshot() -> void:
+ if shot == "":
+ return
+ await RenderingServer.frame_post_draw
+ root.get_texture().get_image().save_png(shot)
+ _say("screenshot " + shot)
+
+
+## Waits up to timeout seconds for done() (real time); returns whether it happened.
+func _wait(done: Callable, timeout: float) -> bool:
+ var t0 := Time.get_ticks_msec()
+ while Time.get_ticks_msec() - t0 < timeout * 1000.0:
+ if done.call():
+ return true
+ await process_frame
+ return bool(done.call())
+
+
+func _finish() -> void:
+ _say("%s: %d failed" % ["PASS" if failures.is_empty() else "FAILURES", failures.size()])
+ for p in ["save.json", "settings.cfg"]:
+ var path := "user://coop_smoke_%s_%s" % [role, p]
+ if FileAccess.file_exists(path):
+ DirAccess.remove_absolute(ProjectSettings.globalize_path(path))
+ if is_instance_valid(main):
+ main.lobby.leave()
+ main.queue_free()
+ await process_frame
+ await create_timer(0.3).timeout
+ quit(failures.size())
diff --git a/game/tools/coop_smoke.gd.uid b/game/tools/coop_smoke.gd.uid
new file mode 100644
index 0000000..b6abb12
--- /dev/null
+++ b/game/tools/coop_smoke.gd.uid
@@ -0,0 +1 @@
+uid://d21h7dqshp4j8
diff --git a/game/tools/soak_night.gd b/game/tools/soak_night.gd
new file mode 100644
index 0000000..9759533
--- /dev/null
+++ b/game/tools/soak_night.gd
@@ -0,0 +1,505 @@
+extends SceneTree
+## Plays whole nights headless against the night thief trickle with a scripted scarecrow and
+## reports each night, as supporting evidence for Step 4's exit gate (the gate itself is a
+## human playtest). Days are skipped; each night runs its full night_length plus the dawn grace.
+## godot --headless --path . --script res://game/tools/soak_night.gd -- --mode=guard
+## Options:
+## --mode=cycle plays whole cycles: by day it gathers until GATHER_UNTIL, then puts a
+## gate back in the pen opening if it's gone and builds BUILD_PLAN in order
+## (what it can afford, walking to each site), and at night it guards (as
+## --mode=guard) against the night's plan. Reports each cycle (per target)
+## and checks that structures, materials, and health carry over.
+## --cycles=3 sets how many (5 plays the whole vacation, one night plan
+## each); --build=0 skips building, --guard=0 leaves the night to the
+## defenses. With materials left after the plan it buys upgrades
+## (UPGRADE_ORDER) at the workbench; --upgrades=0 skips them.
+## --mode=gather plays one day instead: the scarecrow walks (along the navigation
+## grid) to the nearest gather point with charges, holds interact until it
+## is used up or the pouch is full, stores the pouch at the shed, and
+## reports how long gathering everything takes and what it yields.
+## --mode=idle | guard idle: the scarecrow stands in the open doing nothing (baseline).
+## guard: it goes for the most urgent threat (carriers, then thieves
+## taking something, then dropped loot and loose animals, then other
+## thieves), attacks thieves in range with a clear line with its best
+## weapon (a pumpkin bomb into a crowd, the corn shooter once bought, else
+## the pitchfork, closing in to stab), uses fear on a
+## carrier or a crowd in range, leads animals following it back to the pen
+## when no carrier is close, and patches up when hurt and nothing is close.
+## --minutes=10 night time to play (rounded up to whole nights)
+## --thieves=1 GameConfig.night_thieves (at most this many at once)
+## --seed=1 randomizes thief targets and arrival points
+
+const DT := 1.0 / 60.0
+const GATHER_UNTIL := 115.0
+## The scripted scarecrow's defenses, in order: automated defenses around the crop field's
+## corners, slowing traps on the approaches, then fences down the field's east side.
+const BUILD_PLAN := [
+ ["automated_defense", Vector2(46.0, -15.0), 0],
+ ["automated_defense", Vector2(34.0, 12.5), 0],
+ ["slowing_trap", Vector2(43.5, -17.0), 0],
+ ["automated_defense", Vector2(13.5, -15.0), 0],
+ ["slowing_trap", Vector2(31.0, 11.5), 0],
+ ["fence", Vector2(45.0, -15.5), 2], ["fence", Vector2(45.0, -13.5), 2], ["fence", Vector2(45.0, -11.5), 2],
+ ["fence", Vector2(45.0, -9.5), 2], ["fence", Vector2(45.0, -7.5), 2], ["fence", Vector2(45.0, -5.5), 2],
+ ["automated_defense", Vector2(13.5, 9.0), 0],
+ ["automated_defense", Vector2(7.0, -3.5), 0],
+ ["automated_defense", Vector2(9.5, -14.0), 0],
+]
+## The scripted scarecrow's upgrades, in order, bought with what's left after building.
+const UPGRADE_ORDER: Array[String] = ["corn_shooter", "long_range", "rapid_fire", "heavy_seeds", "pumpkin_bomb",
+ "reinforced_fences", "quick_fear", "wide_fear", "sticky_tar", "straw_stuffing"]
+const PEN_GATE := Vector2(4.0, -6.0)
+const PEN_INSIDE := Vector2(-2.0, -6.0)
+const HOME := Vector2(10.0, -8.0) # open ground between the pen, the shed, and the field
+const SHOOT_RANGE := 11.0
+
+var _sim: FarmSim
+var _player: PlayerCharacter
+var _mode := "guard"
+var _fears: int = 0
+var _shots: int = 0
+
+
+func _initialize() -> void:
+ _run.call_deferred()
+
+
+func _run() -> void:
+ var minutes := 10.0
+ var thieves := 1
+ var seed_value := 1
+ for a in OS.get_cmdline_user_args():
+ var arg := String(a)
+ if arg.begins_with("--mode="):
+ _mode = arg.trim_prefix("--mode=")
+ elif arg.begins_with("--minutes="):
+ minutes = float(arg.trim_prefix("--minutes="))
+ elif arg.begins_with("--thieves="):
+ thieves = int(arg.trim_prefix("--thieves="))
+ elif arg.begins_with("--seed="):
+ seed_value = int(arg.trim_prefix("--seed="))
+ var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
+ root.add_child(farm)
+ await process_frame
+ _sim = farm.get_node("FarmSim") as FarmSim
+ _sim.set_physics_process(false)
+ _player = farm.get_node("Player") as PlayerCharacter
+ _player.set_physics_process(false)
+ var c := _sim.campaign
+ var cfg := _sim.config
+ cfg.night_thieves = thieves
+ cfg.campaign_nights = 99
+ _sim.loot._rng.seed = seed_value
+ _sim.waves.rng.seed = seed_value
+ _player.global_position = Vector3(HOME.x, 0.0, HOME.y)
+ if _mode == "gather":
+ _gather_day()
+ _quit()
+ return
+ if _mode == "cycle":
+ var cycles := 3
+ for a in OS.get_cmdline_user_args():
+ if String(a).begins_with("--cycles="):
+ cycles = int(String(a).trim_prefix("--cycles="))
+ cfg.night_thieves = 0 # the night's plan
+ for a in OS.get_cmdline_user_args():
+ if String(a).begins_with("--thieves="):
+ cfg.night_thieves = int(String(a).trim_prefix("--thieves="))
+ for a in OS.get_cmdline_user_args():
+ if String(a) == "--build=0":
+ _do_build = false
+ elif String(a) == "--guard=0":
+ _do_guard = false
+ elif String(a) == "--upgrades=0":
+ _do_upgrades = false
+ _cycles(cycles)
+ _quit()
+ return
+ var nights := ceili(minutes * 60.0 / cfg.night_length)
+ print("soak: mode=%s, %d nights of %.0f s + %.0f s dawn, night_thieves=%d, seed=%d" % [
+ _mode, nights, cfg.night_length, cfg.dawn_grace, thieves, seed_value])
+ print("| Night | Stolen | Recovered | Lost | Crops left | Scarecrow HP | Fears | Attacks | Kills |")
+ print("|---|---|---|---|---|---|---|---|---|")
+ var t0 := Time.get_ticks_msec()
+ for n in nights:
+ c.begin_day()
+ c.advance_phase()
+ c.advance_phase()
+ var kills0 := _sim.enemies.kills
+ var fears0 := _fears
+ var shots0 := _shots
+ while c.state.phase != CampaignController.Phase.MORNING and not c.is_over():
+ if _mode == "guard":
+ _guard()
+ _sim.step(DT)
+ if c.is_over():
+ print("| %d | campaign over: %s |" % [c.state.night, CampaignController.Outcome.keys()[c.outcome]])
+ break
+ var e: Dictionary = c.state.night_log[c.state.night_log.size() - 1]
+ print("| %d | %d | %d | %d | %d/%d | %d/%d | %d | %d | %d |" % [e["night"], e["crops_stolen"], e["crops_recovered"],
+ e["crops_lost"], c.state.crops, c.state.crops_total, c.state.scarecrow_hp, c.state.scarecrow_max_hp,
+ _fears - fears0, _shots - shots0, _sim.enemies.kills - kills0])
+ Input.action_release("patch")
+ print("soak: %.1f s of wall time" % ((Time.get_ticks_msec() - t0) / 1000.0))
+ _quit()
+
+
+## Frees the farm, then quits once the audio server has dropped its stopped sounds.
+func _quit() -> void:
+ for n in root.get_children():
+ n.queue_free()
+ await process_frame
+ await create_timer(0.25).timeout
+ quit()
+
+
+var _fields := {}
+var _built := {} # BUILD_PLAN index -> true
+var _do_build := true
+var _do_guard := true
+var _do_upgrades := true
+var _carry_errors: Array[String] = []
+
+
+func _cycles(n: int) -> void:
+ var c := _sim.campaign
+ var s := c.state
+ print("soak cycle: %d cycles, night plan '%s' (%d thieves), gather until %.0f s, build %s, guard %s" % [
+ n, _sim.waves.tonight().title, _sim.waves.tonight().total(), GATHER_UNTIL, _do_build, _do_guard])
+ print("| Night | Gathered | Built (total) | Upgrades | Crops: stolen / recovered / lost | Animals: grabbed / out / led back / lost | Supplies: taken / back / lost | Left | HP | Broken | Shed after |")
+ print("|---|---|---|---|---|---|---|---|---|---|")
+ var lost_by := {}
+ _sim.loot.loot_event.connect(func(kind: StringName, id: int, _p: Vector3) -> void:
+ if kind == &"lost" and _sim.loot.category[id] == LootSystem.Category.SUPPLY:
+ lost_by[_sim.loot.sack_material[id]] = int(lost_by.get(_sim.loot.sack_material[id], 0)) + _sim.loot.sack_amount[id])
+ var t0 := Time.get_ticks_msec()
+ for k in n:
+ if c.is_over():
+ break
+ var shed0: Dictionary = s.resources.shed.duplicate()
+ var built0 := _sim.structures.count()
+ var gathered := {"wood": 0, "scrap": 0, "straw": 0}
+ var cb := func(m: String, amount: int, _node: GatherNode) -> void: gathered[m] += amount
+ _sim.interactions.gathered.connect(cb)
+ c.begin_day()
+ var t := 0.0
+ while c.is_daytime():
+ var me := Vector2(_player.global_position.x, _player.global_position.z)
+ if not (t < GATHER_UNTIL and _gather_tick(me)):
+ Input.action_release("interact")
+ if _do_build:
+ _build_tick(me)
+ else:
+ _walk_field(Vector2(30.0, -3.0), me)
+ _sim.step(DT)
+ t += DT
+ Input.action_release("interact")
+ _sim.interactions.gathered.disconnect(cb)
+ # Night: guard. Record what should carry over.
+ var breaks: Array[int] = [] # a lambda can't add to a captured int
+ var cb2 := func(_i: int, _t: String, _at: Vector3) -> void: breaks.append(1)
+ _sim.structures.destroyed.connect(cb2)
+ var built_night := _sim.structures.count()
+ var res_night: Dictionary = s.resources.to_dict()
+ lost_by.clear()
+ var fears0 := _fears
+ if not _do_guard:
+ _player.global_position = Vector3(HOME.x, 0.0, HOME.y)
+ while s.phase != CampaignController.Phase.MORNING and not c.is_over():
+ if _do_guard:
+ _guard()
+ _sim.step(DT)
+ _sim.structures.destroyed.disconnect(cb2)
+ var broken := breaks.size()
+ Input.action_release("patch")
+ if c.is_over():
+ print("| %d | campaign over: %s |" % [k + 1, CampaignController.Outcome.keys()[c.outcome]])
+ break
+ # Carry-over checks: nothing is built at night, so structures only go down by breaks;
+ # wood and scrap only go down by what thieves carried off (straw also by patches).
+ if _sim.structures.count() != built_night - broken:
+ _carry_errors.append("cycle %d: %d structures at night - %d broken != %d in the morning" % [k + 1, built_night, broken, _sim.structures.count()])
+ var now := s.resources.to_dict()
+ for m in ["wood", "scrap"]:
+ var before := int(res_night["shed"][m]) + int(res_night["pouch"][m])
+ var after := int(now["shed"][m]) + int(now["pouch"][m])
+ if after != before - int(lost_by.get(m, 0)):
+ _carry_errors.append("cycle %d: %s %d -> %d overnight, %d carried off" % [k + 1, m, before, after, int(lost_by.get(m, 0))])
+ if s.supplies_in_transit != 0:
+ _carry_errors.append("cycle %d: %d supplies still in transit in the morning" % [k + 1, s.supplies_in_transit])
+ var e: Dictionary = s.night_log[s.night_log.size() - 1]
+ print("| %d %s | %s | %d (%d) | %d | %d / %d / %d | %d / %d / %d / %d | %d / %d / %d | %d crops, %d animals | %d/%d | %d | %s |" % [k + 1,
+ _sim.waves.plan_for(k + 1).title, ResourceStore.describe(gathered), built_night - built0, built_night, s.upgrades.size(),
+ e["crops_stolen"], e["crops_recovered"], e["crops_lost"],
+ e["animals_stolen"], e["animals_strayed"], e["animals_recovered"], e["animals_lost"], e["supplies_stolen"], e["supplies_recovered"],
+ e["supplies_lost"], s.crops, s.animals, s.scarecrow_hp, s.scarecrow_max_hp, broken, ResourceStore.describe(s.resources.shed)])
+ print("soak cycle: carry-over %s; %.1f s of wall time" % ["OK" if _carry_errors.is_empty() else "ERRORS %s" % [_carry_errors],
+ (Time.get_ticks_msec() - t0) / 1000.0])
+
+
+## One gathering tick: walk to the nearest point with charges and gather, or store a full pouch.
+## Returns false when nothing is left to gather or store.
+func _gather_tick(me: Vector2) -> bool:
+ var it := _sim.interactions
+ var r := _sim.campaign.state.resources
+ var target: GatherNode = null
+ var best := INF
+ for n in it.nodes:
+ var d := Vector2(n.global_position.x, n.global_position.z).distance_to(me)
+ if it.charges(n) > 0 and d < best:
+ best = d
+ target = n
+ if target == null and r.pouch_total() == 0:
+ return false
+ if target == null or r.pouch_room() < target.yield_amount:
+ Input.action_release("interact")
+ var shed := _sim.zones.zone(FarmZone.Kind.SUPPLY_SHED)
+ _walk_field(Vector2(shed.global_position.x, shed.global_position.z + 3.0), me)
+ return true
+ if Vector2(target.global_position.x, target.global_position.z).distance_to(me) > target.reach - 0.1:
+ Input.action_release("interact")
+ _walk_field(_stand_spot(target), me)
+ else:
+ Input.action_press("interact")
+ return true
+
+
+## One building tick: put a gate back in the pen opening if it's gone, else walk to the next
+## BUILD_PLAN site it can afford and place it; otherwise wait in the middle of the crop field.
+func _build_tick(me: Vector2) -> void:
+ var st := _sim.structures
+ var r := _sim.campaign.state.resources
+ if _sim.nav.structure_at[_sim.nav.cell_of(PEN_GATE.x, PEN_GATE.y)] < 0 and r.can_afford(_sim.config.costs["gate"]):
+ if PEN_GATE.distance_to(me) > 4.0:
+ _walk_field(PEN_GATE + Vector2(2.5, 0.0), me)
+ elif st.validate("gate", PEN_GATE.x, PEN_GATE.y, 2, me) == "":
+ st.place("gate", PEN_GATE.x, PEN_GATE.y, 2)
+ return
+ for i in BUILD_PLAN.size():
+ if _built.has(i):
+ continue
+ var part: Array = BUILD_PLAN[i]
+ if not r.can_afford(_sim.config.costs.get(part[0], {})):
+ continue
+ var at: Vector2 = part[1]
+ if at.distance_to(me) > 6.0:
+ _walk_field(at + Vector2(-2.0, 0.0), me)
+ return
+ var why := st.validate(part[0], at.x, at.y, part[2], me)
+ if why == "":
+ st.place(part[0], at.x, at.y, part[2])
+ else:
+ print("soak: can't build %s at %s: %s" % [part[0], at, why])
+ _built[i] = true # built, or impossible here: either way move on
+ return
+ if _do_upgrades and _upgrade_tick(me):
+ return
+ _walk_field(Vector2(30.0, -3.0), me)
+
+
+## Walks to the workbench and buys the next upgrade it can afford. Returns false if there's none.
+func _upgrade_tick(me: Vector2) -> bool:
+ var c := _sim.campaign
+ for id in UPGRADE_ORDER:
+ if Upgrades.blocker(c, id) != "":
+ continue
+ var bench := _sim.interactions.workbench
+ var at := Vector2(bench.global_position.x, bench.global_position.z)
+ if at.distance_to(me) > bench.reach - 0.3:
+ _walk_field(at, me)
+ else:
+ Upgrades.buy(c, id, _sim.structures)
+ return true
+ return false
+
+
+func _gather_day() -> void:
+ var c := _sim.campaign
+ var it := _sim.interactions
+ var r := c.state.resources
+ var shed_start: Dictionary = r.shed.duplicate()
+ var shed := _sim.zones.zone(FarmZone.Kind.SUPPLY_SHED)
+ var drop_off := Vector2(shed.global_position.x, shed.global_position.z + 3.0)
+ c.begin_day()
+ var t := 0.0
+ var trips := 0
+ var walking := 0.0
+ var gathering := 0.0
+ var done_at := -1.0
+ while c.is_daytime():
+ var me := Vector2(_player.global_position.x, _player.global_position.z)
+ var target: GatherNode = null
+ var best := INF
+ for n in it.nodes:
+ var d := Vector2(n.global_position.x, n.global_position.z).distance_to(me)
+ if it.charges(n) > 0 and d < best:
+ best = d
+ target = n
+ if target == null and r.pouch_total() == 0:
+ done_at = t
+ break
+ var store := target == null or r.pouch_room() < target.yield_amount
+ if store:
+ Input.action_release("interact")
+ _walk_field(drop_off, me)
+ walking += DT
+ if r.pouch_total() == 0:
+ pass
+ else:
+ var at := Vector2(target.global_position.x, target.global_position.z)
+ if at.distance_to(me) > target.reach - 0.1:
+ Input.action_release("interact")
+ _walk_field(_stand_spot(target), me)
+ walking += DT
+ else:
+ Input.action_press("interact")
+ gathering += DT
+ var before := r.pouch_total()
+ _sim.step(DT)
+ if before > 0 and r.pouch_total() == 0:
+ trips += 1
+ t += DT
+ Input.action_release("interact")
+ var got := {}
+ for m in ResourceStore.MATERIALS:
+ got[m] = int(r.shed[m]) - int(shed_start[m])
+ print("gather: %s stored in %d trips; everything gathered and stored after %s (day %.0f s + dusk %.0f s)" % [
+ ResourceStore.describe(got), trips, ("%.0f s" % done_at) if done_at >= 0.0 else "the day ran out", _sim.config.day_length, _sim.config.dusk_length])
+ print("gather: %.0f s walking, %.0f s gathering" % [walking, gathering])
+
+
+## The free spot closest to a gather point (where the bot stands to gather it).
+func _stand_spot(n: GatherNode) -> Vector2:
+ var nav := _sim.nav
+ var c := Vector2(n.global_position.x, n.global_position.z)
+ var best := c
+ var best_d := INF
+ for cell in nav.free_cells_in(Rect2(c - Vector2.ONE * n.reach, Vector2.ONE * n.reach * 2.0)):
+ var d := nav.cell_center(cell).distance_to(c)
+ if d < best_d:
+ best_d = d
+ best = nav.cell_center(cell)
+ return best
+
+
+## Walks along the navigation grid toward goal (one distance field per goal cell, cached).
+func _walk_field(goal: Vector2, me: Vector2) -> void:
+ var nav := _sim.nav
+ var cell := nav.nearest_free(nav.cell_of(goal.x, goal.y))
+ if not _fields.has(cell):
+ _fields[cell] = nav.distance_field(PackedInt32Array([cell]))
+ var dir := PackedFloat32Array([0.0, 0.0])
+ if nav.flow_direction(_fields[cell], me.x, me.y, dir):
+ var next := me + Vector2(dir[0], dir[1]) * _player.run_speed * DT
+ _player.global_position = Vector3(next.x, 0.0, next.y)
+
+
+func _guard() -> void:
+ var es := _sim.enemies
+ var loot := _sim.loot
+ var kit := _sim.scarecrow
+ var cfg := _sim.config
+ var me := Vector2(_player.global_position.x, _player.global_position.z)
+ # Most urgent threat: carriers, then thieves taking a crop, then dropped crops, then others.
+ var goal := HOME
+ var best := INF
+ var near := 0
+ var carrier_near := false
+ var nearest_thief := -1
+ var nearest_d := INF
+ for d in es.active_count:
+ if es.alive[d] == 0:
+ continue
+ var p := Vector2(es.pos_x[d], es.pos_z[d])
+ var dist := p.distance_to(me)
+ var urgency := dist
+ match es.state[d]:
+ ThiefBehavior.State.CARRY:
+ urgency -= 40.0
+ carrier_near = carrier_near or dist < cfg.fear_radius
+ ThiefBehavior.State.STEAL:
+ urgency -= 20.0
+ if urgency < best:
+ best = urgency
+ goal = p
+ if dist < cfg.fear_radius and es.state[d] != ThiefBehavior.State.FLEE:
+ near += 1
+ if dist < nearest_d and _sim.nav.line_clear(me.x, me.y, p.x, p.y):
+ nearest_d = dist
+ nearest_thief = d
+ for id in range(1, loot.item_count + 1):
+ if loot.status[id] == LootSystem.Status.DROPPED:
+ var at := loot.position_of(id)
+ var dist := at.distance_to(me) - 10.0
+ if loot.category[id] == LootSystem.Category.ANIMAL and loot.followers() >= cfg.max_following_animals:
+ continue
+ if dist < best:
+ best = dist
+ goal = at
+ # Lead followers home when no carrier is close.
+ if loot.followers() > 0 and best > -25.0:
+ goal = PEN_INSIDE
+ best = -25.0
+ var hurt := kit.hp() <= cfg.scarecrow_max_hp / 2
+ if hurt and nearest_d > 8.0:
+ Input.action_press("patch")
+ return
+ Input.action_release("patch")
+ if carrier_near or near >= 2:
+ if kit.use_fear() >= 0:
+ _fears += 1
+ if nearest_thief >= 0 and nearest_d < SHOOT_RANGE:
+ var target := Vector2(es.pos_x[nearest_thief], es.pos_z[nearest_thief])
+ var reach := _attack(target, me)
+ if nearest_d < reach:
+ return # hold ground and attack rather than walk into it
+ if _sim.combat.weapon == ScarecrowCombat.Weapon.PITCHFORK:
+ goal = target # close in to stab it
+ _walk_toward(goal, me)
+
+
+## Attacks the thief at target with the best weapon owned: a pumpkin bomb into a crowd of three
+## or more when one is ready, else the corn shooter, else the pitchfork (only within its reach).
+## Returns the distance it holds ground at.
+func _attack(target: Vector2, me: Vector2) -> float:
+ var c := _sim.combat
+ var cfg := _sim.config
+ var es := _sim.enemies
+ var crowd := 0
+ for d in es.active_count:
+ if es.alive[d] == 1 and Vector2(es.pos_x[d], es.pos_z[d]).distance_to(target) <= cfg.bomb_radius:
+ crowd += 1
+ var far := target.distance_to(me)
+ if crowd >= 3 and c.bomb_left == 0.0 and far >= cfg.bomb_min_range and far <= cfg.bomb_range and c.equip(ScarecrowCombat.Weapon.PUMPKIN_BOMB):
+ if c.attack_toward(target):
+ _shots += 1
+ if c.equip(ScarecrowCombat.Weapon.CORN_SHOOTER):
+ if c.attack_toward(target):
+ _shots += 1
+ return 3.0
+ c.equip(ScarecrowCombat.Weapon.PITCHFORK)
+ if far <= cfg.pitchfork_reach and c.attack_toward(target):
+ _shots += 1
+ return cfg.pitchfork_reach * 0.8
+
+
+func _walk_toward(goal: Vector2, me: Vector2) -> void:
+ var inside := _sim.zones.playable.grow(-1.0) # the scarecrow can't leave the farm
+ goal = Vector2(clampf(goal.x, inside.position.x, inside.end.x), clampf(goal.y, inside.position.y, inside.end.y))
+ if not _sim.nav.line_clear(me.x, me.y, goal.x, goal.y, true) and goal.distance_to(me) > 2.0:
+ _walk_field((goal / 2.0).round() * 2.0, me) # around walls (gates and fences are no wall to it)
+ return
+ var to := goal - me
+ if to.length() < 0.5:
+ return
+ var step := to.normalized() * _player.run_speed * DT
+ var nav := _sim.nav
+ var next := me + step
+ if not nav.is_free(nav.cell_of(next.x, next.y)):
+ next = Vector2(me.x + step.x, me.y) if nav.is_free(nav.cell_of(me.x + step.x, me.y)) else Vector2(me.x, me.y + step.y)
+ if not nav.is_free(nav.cell_of(next.x, next.y)):
+ var side := Vector2(-step.y, step.x) # boxed in: sidestep
+ next = me + side
+ if not nav.is_free(nav.cell_of(next.x, next.y)):
+ return
+ _player.global_position = Vector3(next.x, 0.0, next.y)
diff --git a/game/tools/soak_night.gd.uid b/game/tools/soak_night.gd.uid
new file mode 100644
index 0000000..0a6c674
--- /dev/null
+++ b/game/tools/soak_night.gd.uid
@@ -0,0 +1 @@
+uid://br30toryks4ty
diff --git a/game/tools/synth_audio.gd b/game/tools/synth_audio.gd
new file mode 100644
index 0000000..cb3cf20
--- /dev/null
+++ b/game/tools/synth_audio.gd
@@ -0,0 +1,302 @@
+extends SceneTree
+## Synthesizes the sounds the Kenney CC0 packs don't have (assets/audio/kenney/) into
+## assets/audio/synth/ as 16-bit mono WAV files, deterministically (fixed seeds):
+## day_ambience.wav 24 s loop: soft wind, rustling leaves, birdsong
+## night_ambience.wav 24 s loop: low wind, three crickets, an owl
+## crow_caw_1/2.wav a crow's caw (arrivals), crow_squawk.wav (a crow shot down)
+## truck_engine.wav 2 s loop: the farmers' truck idling / driving
+## truck_horn.wav beep-beep (the farmers are home)
+## pitchfork_whoosh.wav a quick swish through the air (a stab)
+## pumpkin_boom.wav a deep thump, a burst of noise, and a wet splat (a pumpkin bomb)
+## Loops carry a WAV 'smpl' loop point, so the importer's "Detect From WAV" loops them; every
+## periodic part of a loop has a whole number of cycles in it and filtered noise is warmed up
+## on the loop's own tail, so the seam is silent. Run with the editor closed, then let the
+## editor import the files:
+## godot --headless --path . --script res://game/tools/synth_audio.gd
+
+const RATE := 22050
+const OUT := "res://assets/audio/synth/"
+
+var _rng := RandomNumberGenerator.new()
+
+
+func _initialize() -> void:
+ DirAccess.make_dir_recursive_absolute(ProjectSettings.globalize_path(OUT))
+ _rng.seed = 7
+ _write("day_ambience.wav", _day(24.0), true)
+ _rng.seed = 11
+ _write("night_ambience.wav", _night(24.0), true)
+ _rng.seed = 3
+ _write("crow_caw_1.wav", _caw(0.46, 560.0, 470.0, 1), false)
+ _write("crow_caw_2.wav", _caw(0.62, 640.0, 520.0, 2), false)
+ _write("crow_squawk.wav", _caw(0.2, 820.0, 610.0, 1), false)
+ _rng.seed = 5
+ _write("truck_engine.wav", _engine(2.0), true)
+ _write("truck_horn.wav", _horn(), false)
+ _rng.seed = 13
+ _write("pitchfork_whoosh.wav", _whoosh(0.22), false)
+ _write("pumpkin_boom.wav", _boom(0.9), false)
+ quit(0)
+
+
+# --- Pieces -----------------------------------------------------------------------------------
+
+## White noise through two one-pole low-passes, warmed up on the buffer's own tail so the start
+## continues the end (seamless when looped).
+func _noise_lowpass(n: int, cutoff: float) -> PackedFloat32Array:
+ var white := PackedFloat32Array()
+ white.resize(n)
+ for i in n:
+ white[i] = _rng.randf_range(-1.0, 1.0)
+ var a := exp(-TAU * cutoff / RATE)
+ var y1 := 0.0
+ var y2 := 0.0
+ var out := PackedFloat32Array()
+ out.resize(n)
+ for pass_i in 2:
+ for i in n:
+ y1 = a * y1 + (1.0 - a) * white[i]
+ y2 = a * y2 + (1.0 - a) * y1
+ if pass_i == 1:
+ out[i] = y2
+ return _normalize(out, 1.0)
+
+
+func _normalize(buf: PackedFloat32Array, peak: float) -> PackedFloat32Array:
+ var top := 0.0
+ for v in buf:
+ top = maxf(top, absf(v))
+ if top > 0.0:
+ for i in buf.size():
+ buf[i] *= peak / top
+ return buf
+
+
+## Adds a tone with a frequency glide and an envelope into buf at t0 (wrapping around the end).
+func _tone(buf: PackedFloat32Array, t0: float, length: float, f0: float, f1: float, amp: float,
+ vibrato: float = 0.0, harmonics: PackedFloat32Array = PackedFloat32Array([1.0])) -> void:
+ var n := buf.size()
+ var count := int(length * RATE)
+ var phase := 0.0
+ var start := int(t0 * RATE)
+ for k in count:
+ var u := float(k) / count
+ var f := lerpf(f0, f1, u) * (1.0 + vibrato * sin(TAU * 6.0 * k / RATE))
+ phase += f / RATE
+ var env := sin(PI * u)
+ env *= env
+ var s := 0.0
+ for h in harmonics.size():
+ s += harmonics[h] * sin(TAU * phase * (h + 1))
+ buf[(start + k) % n] += amp * env * s
+
+
+# --- Loops ------------------------------------------------------------------------------------
+
+func _day(seconds: float) -> PackedFloat32Array:
+ var n := int(seconds * RATE)
+ var wind := _noise_lowpass(n, 480.0)
+ var leaves := _noise_lowpass(n, 2600.0)
+ var leaves_low := _noise_lowpass(n, 900.0)
+ var buf := PackedFloat32Array()
+ buf.resize(n)
+ for i in n:
+ var t := float(i) / n # 0..1 over the loop: whole cycles only
+ var gust := 0.55 + 0.45 * (0.5 + 0.5 * sin(TAU * 2.0 * t + 0.7)) * (0.7 + 0.3 * sin(TAU * 5.0 * t))
+ var rustle := 0.3 + 0.7 * pow(0.5 + 0.5 * sin(TAU * 7.0 * t + 1.9), 3.0)
+ buf[i] = 0.07 * gust * wind[i] + 0.025 * rustle * (leaves[i] - leaves_low[i])
+ var t := 0.6
+ while t < seconds:
+ _bird(buf, t)
+ t += _rng.randf_range(1.6, 3.8)
+ return _normalize(buf, 0.5)
+
+
+func _bird(buf: PackedFloat32Array, t0: float) -> void:
+ var amp := _rng.randf_range(0.05, 0.12)
+ match _rng.randi_range(0, 2):
+ 0: # rising chirps
+ var f := _rng.randf_range(2800.0, 3400.0)
+ for k in _rng.randi_range(3, 5):
+ _tone(buf, t0 + k * 0.11, 0.07, f, f * 1.35, amp)
+ 1: # two-note whistle
+ var f := _rng.randf_range(2200.0, 2700.0)
+ _tone(buf, t0, 0.2, f, f * 1.02, amp, 0.01)
+ _tone(buf, t0 + 0.26, 0.24, f * 0.8, f * 0.78, amp, 0.01)
+ _: # trill
+ var f := _rng.randf_range(4600.0, 5400.0)
+ for k in 10:
+ _tone(buf, t0 + k * 0.04, 0.025, f, f * 0.95, amp * 0.7)
+
+
+func _night(seconds: float) -> PackedFloat32Array:
+ var n := int(seconds * RATE)
+ var wind := _noise_lowpass(n, 320.0)
+ var buf := PackedFloat32Array()
+ buf.resize(n)
+ for i in n:
+ var t := float(i) / n
+ buf[i] = 0.05 * (0.6 + 0.4 * sin(TAU * 3.0 * t + 0.3)) * wind[i]
+ # Crickets: (carrier Hz, chirps per loop, level). A chirp is 3 short pulses.
+ var crickets := [[4400.0, 50, 0.07], [4800.0, 39, 0.05], [5150.0, 44, 0.04]]
+ for c: Array in crickets:
+ var period := seconds / int(c[1])
+ var offset := _rng.randf_range(0.0, period)
+ for k in int(c[1]):
+ var swell := 0.7 + 0.3 * sin(TAU * 2.0 * k / int(c[1]) + offset)
+ for p in 3:
+ _tone(buf, offset + k * period + p * 0.032, 0.016, c[0], c[0] * 0.99, c[2] * swell)
+ for at in [6.0, 17.5]: # the owl: hoo ... hoo-hoo
+ var h := PackedFloat32Array([1.0, 0.18, 0.05])
+ _tone(buf, at, 0.42, 410.0, 380.0, 0.08, 0.004, h)
+ _tone(buf, at + 0.75, 0.22, 400.0, 385.0, 0.065, 0.004, h)
+ _tone(buf, at + 1.05, 0.38, 395.0, 360.0, 0.07, 0.004, h)
+ return _normalize(buf, 0.45)
+
+
+func _engine(seconds: float) -> PackedFloat32Array:
+ var n := int(seconds * RATE)
+ var rumble := _noise_lowpass(n, 180.0)
+ var buf := PackedFloat32Array()
+ buf.resize(n)
+ var f := 42.0 # 84 cycles in 2 s
+ for i in n:
+ var t := float(i) / RATE
+ var s := 0.0
+ for h in range(1, 9):
+ s += sin(TAU * f * h * t) / h
+ var throb := 0.8 + 0.2 * sin(TAU * 7.0 * t) # 14 cycles in 2 s
+ buf[i] = throb * (0.5 * s + 0.6 * rumble[i])
+ return _normalize(buf, 0.6)
+
+
+# --- One-shots --------------------------------------------------------------------------------
+
+## A crow: a harmonic-rich glide shaped by two formants, roughened by fast random amplitude
+## wobble, with breathy noise; caws = how many in a row.
+func _caw(length: float, f_start: float, f_end: float, caws: int) -> PackedFloat32Array:
+ var one := int(length * RATE)
+ var gap := int(0.09 * RATE)
+ var n := one * caws + gap * (caws - 1)
+ var buf := PackedFloat32Array()
+ buf.resize(n)
+ var breath := _noise_lowpass(n, 3000.0)
+ var breath_low := _noise_lowpass(n, 900.0)
+ for c in caws:
+ var start := c * (one + gap)
+ var phase := 0.0
+ var rough := 1.0
+ var shift := 1.0 - 0.06 * c
+ for k in one:
+ var u := float(k) / one
+ var f := lerpf(f_start, f_end, pow(u, 0.7)) * shift
+ phase += f / RATE
+ if k % 160 == 0:
+ rough = _rng.randf_range(0.45, 1.0)
+ var s := 0.0
+ for h in range(1, 13):
+ var hf := f * h
+ var formant := exp(-pow((hf - 1350.0) / 420.0, 2.0)) + 0.6 * exp(-pow((hf - 2500.0) / 600.0, 2.0)) + 0.12
+ s += formant / pow(h, 0.6) * sin(TAU * phase * h)
+ var env := minf(u / 0.04, 1.0) * (1.0 if u < 0.6 else exp(-(u - 0.6) * 9.0))
+ buf[start + k] = env * (rough * s + 0.5 * (breath[start + k] - breath_low[start + k]))
+ return _normalize(buf, 0.8)
+
+
+## Noise swept through a resonant band that rises then falls, swelling and fading.
+func _whoosh(length: float) -> PackedFloat32Array:
+ var n := int(length * RATE)
+ var white := PackedFloat32Array()
+ white.resize(n)
+ for i in n:
+ white[i] = _rng.randf_range(-1.0, 1.0)
+ var buf := PackedFloat32Array()
+ buf.resize(n)
+ var low := 0.0
+ var band := 0.0
+ for i in n:
+ var u := float(i) / n
+ var f := lerpf(500.0, 2400.0, sin(PI * pow(u, 0.7))) # the band's center
+ var q := 0.12
+ var w := TAU * f / RATE
+ # State-variable band-pass.
+ var high := white[i] - low - q * band
+ band += w * high
+ low += w * band
+ buf[i] = band * pow(sin(PI * u), 1.5)
+ return _normalize(buf, 0.7)
+
+
+## A pumpkin bursting: a low sine thump dropping in pitch, a burst of low-passed noise, and a
+## short splat of brighter noise just after.
+func _boom(length: float) -> PackedFloat32Array:
+ var n := int(length * RATE)
+ var rumble := _noise_lowpass(n, 260.0)
+ var splat := _noise_lowpass(n, 2200.0)
+ var buf := PackedFloat32Array()
+ buf.resize(n)
+ var phase := 0.0
+ for i in n:
+ var t := float(i) / RATE
+ phase += lerpf(95.0, 38.0, minf(t / 0.35, 1.0)) / RATE
+ var attack := minf(t / 0.006, 1.0)
+ var thump := sin(TAU * phase) * exp(-t * 7.0)
+ var crack := rumble[i] * exp(-t * 5.5)
+ var wet := splat[i] * exp(-maxf(t - 0.03, 0.0) * 16.0) * (1.0 if t > 0.03 else 0.0)
+ buf[i] = attack * (1.0 * thump + 0.9 * crack + 0.35 * wet)
+ return _normalize(buf, 0.85)
+
+
+func _horn() -> PackedFloat32Array:
+ var n := int(0.9 * RATE)
+ var buf := PackedFloat32Array()
+ buf.resize(n)
+ for beep in [[0.0, 0.3], [0.42, 0.34]]:
+ var start := int(beep[0] * RATE)
+ var count := int(beep[1] * RATE)
+ for k in count:
+ var t := float(k) / RATE
+ var env := minf(minf(t / 0.012, 1.0), minf((beep[1] - t) / 0.03, 1.0))
+ var s := 0.0
+ for f in [410.0, 520.0]:
+ for h in [1, 3, 5, 7]:
+ s += sin(TAU * f * h * t) / h
+ buf[start + k] = env * s
+ return _normalize(buf, 0.7)
+
+
+# --- WAV --------------------------------------------------------------------------------------
+
+func _write(file: String, buf: PackedFloat32Array, loop: bool) -> void:
+ var frames := buf.size()
+ var data := PackedByteArray()
+ data.resize(frames * 2)
+ for i in frames:
+ data.encode_s16(i * 2, clampi(roundi(buf[i] * 32767.0), -32768, 32767))
+ var smpl := PackedByteArray()
+ if loop:
+ smpl.resize(60)
+ var fields := [0, 0, int(1e9 / RATE), 60, 0, 0, 0, 1, 0, 0, 0, 0, frames - 1, 0, 0]
+ for i in fields.size():
+ smpl.encode_u32(i * 4, fields[i])
+ var f := FileAccess.open(OUT + file, FileAccess.WRITE)
+ f.store_buffer("RIFF".to_ascii_buffer())
+ f.store_32(4 + (8 + 16) + ((8 + smpl.size()) if loop else 0) + 8 + data.size())
+ f.store_buffer("WAVE".to_ascii_buffer())
+ f.store_buffer("fmt ".to_ascii_buffer())
+ f.store_32(16)
+ f.store_16(1) # PCM
+ f.store_16(1) # mono
+ f.store_32(RATE)
+ f.store_32(RATE * 2)
+ f.store_16(2)
+ f.store_16(16)
+ if loop:
+ f.store_buffer("smpl".to_ascii_buffer())
+ f.store_32(smpl.size())
+ f.store_buffer(smpl)
+ f.store_buffer("data".to_ascii_buffer())
+ f.store_32(data.size())
+ f.store_buffer(data)
+ f.close()
+ print("synth_audio: %s %.2f s%s" % [file, float(frames) / RATE, " (loop)" if loop else ""])
diff --git a/game/tools/synth_audio.gd.uid b/game/tools/synth_audio.gd.uid
new file mode 100644
index 0000000..28e1f8d
--- /dev/null
+++ b/game/tools/synth_audio.gd.uid
@@ -0,0 +1 @@
+uid://smhouv51mdjq
diff --git a/project.godot b/project.godot
index 25e7136..2dadac2 100644
--- a/project.godot
+++ b/project.godot
@@ -11,10 +11,19 @@ config_version=5
[application]
config/name="Harvest-Season"
-run/main_scene="res://game/scenes/farm.tscn"
+run/main_scene="res://game/scenes/main.tscn"
config/features=PackedStringArray("4.7", "Mobile")
config/icon="res://icon.svg"
+[audio]
+
+buses/default_bus_layout="res://game/resources/audio_buses.tres"
+driver/enable_input=true
+
+[autoload]
+
+GDSync="*res://addons/GD-Sync/MultiplayerClient.gd"
+
[display]
window/size/viewport_width=1920
@@ -22,6 +31,14 @@ window/size/viewport_height=1080
window/stretch/mode="canvas_items"
window/stretch/aspect="expand"
+[editor_plugins]
+
+enabled=PackedStringArray("res://addons/GD-Sync/plugin.cfg")
+
+[gui]
+
+theme/custom="res://game/resources/ui_theme.tres"
+
[input]
move_left={
@@ -91,6 +108,118 @@ toggle_overlay={
, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":4,"pressure":0.0,"pressed":false,"script":null)
])
}
+fear={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":81,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":9,"pressure":0.0,"pressed":false,"script":null)
+])
+}
+patch={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":70,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":3,"pressure":0.0,"pressed":false,"script":null)
+])
+}
+interact={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":69,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":2,"pressure":0.0,"pressed":false,"script":null)
+])
+}
+build_mode={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":66,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":11,"pressure":0.0,"pressed":false,"script":null)
+])
+}
+rotate_left={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":90,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":13,"pressure":0.0,"pressed":false,"script":null)
+])
+}
+rotate_right={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":67,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":14,"pressure":0.0,"pressed":false,"script":null)
+])
+}
+cancel={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventMouseButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"button_mask":0,"position":Vector2(0, 0),"global_position":Vector2(0, 0),"factor":1.0,"button_index":2,"canceled":false,"pressed":false,"double_click":false,"script":null)
+, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":1,"pressure":0.0,"pressed":false,"script":null)
+])
+}
+pause={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194305,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":6,"pressure":0.0,"pressed":false,"script":null)
+])
+}
+build_next={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194306,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":12,"pressure":0.0,"pressed":false,"script":null)
+])
+}
+build_1={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":49,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+])
+}
+build_2={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":50,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+])
+}
+build_3={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":51,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+])
+}
+build_4={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":52,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+])
+}
+hide_tips={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194308,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":4,"pressure":0.0,"pressed":false,"script":null)
+])
+}
+toggle_mic={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":77,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+])
+}
+sprint={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194325,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":7,"pressure":0.0,"pressed":false,"script":null)
+])
+}
+weapon_next={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194306,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":12,"pressure":0.0,"pressed":false,"script":null)
+])
+}
+weapon_1={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":49,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+])
+}
+weapon_2={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":50,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+])
+}
+weapon_3={
+"deadzone": 0.5,
+"events": Array[InputEvent]([Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":51,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
+])
+}
[layer_names]