From 0a843bad415f99cb306a5e9e908ade29d991a5ff Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 23:53:53 +0200 Subject: [PATCH 1/4] fix(skeleton): the Summon on Kill "on" line is "Thy shall raise again." MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit As written by the author; Italian "Tu rialzerai ancora.", Russian "Ты вновь поднимешь.". README changelog line too. --- JotunnModStub/Translations/English/messages.json | 2 +- JotunnModStub/Translations/Italian/messages.json | 2 +- JotunnModStub/Translations/Russian/messages.json | 2 +- README.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/JotunnModStub/Translations/English/messages.json b/JotunnModStub/Translations/English/messages.json index 1edf32c..a764b92 100644 --- a/JotunnModStub/Translations/English/messages.json +++ b/JotunnModStub/Translations/English/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "The vulture spirals down.", "rov_msg_boneship_no_shore": "No shore in reach. They stay at the oars.", "rov_msg_boneship_sunk": "The ship goes down, and $1 go with it.", - "rov_msg_skeleton_summon_on": "Thy dead shall rise again.", + "rov_msg_skeleton_summon_on": "Thy shall raise again.", "rov_msg_skeleton_summon_off": "Raising... nevermore.", "rov_msg_skeleton_summon_locked": "Summon on Kill awakens once The Queen falls." } diff --git a/JotunnModStub/Translations/Italian/messages.json b/JotunnModStub/Translations/Italian/messages.json index 20caf0b..2c6ed4c 100644 --- a/JotunnModStub/Translations/Italian/messages.json +++ b/JotunnModStub/Translations/Italian/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "L'avvoltoio scende a spirale.", "rov_msg_boneship_no_shore": "Nessuna riva a portata. Restano ai remi.", "rov_msg_boneship_sunk": "La nave affonda, e con lei $1.", - "rov_msg_skeleton_summon_on": "I tuoi morti risorgeranno ancora.", + "rov_msg_skeleton_summon_on": "Tu rialzerai ancora.", "rov_msg_skeleton_summon_off": "Risorgere... mai più.", "rov_msg_skeleton_summon_locked": "Evoca all'uccisione si risveglia quando cade la Regina." } diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json index 5b0f03e..c4f2975 100644 --- a/JotunnModStub/Translations/Russian/messages.json +++ b/JotunnModStub/Translations/Russian/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "Стервятник кружит, спускаясь по спирали.", "rov_msg_boneship_no_shore": "Берега не видно. Они остаются на веслах.", "rov_msg_boneship_sunk": "Корабль идет ко дну, и $1 вместе с ним.", - "rov_msg_skeleton_summon_on": "Твои мёртвые вновь восстанут.", + "rov_msg_skeleton_summon_on": "Ты вновь поднимешь.", "rov_msg_skeleton_summon_off": "Восстание... никогда более.", "rov_msg_skeleton_summon_locked": "Призыв при убийстве пробудится, когда падёт Королева." } diff --git a/README.md b/README.md index cb169ae..35bd680 100644 --- a/README.md +++ b/README.md @@ -454,7 +454,7 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ### v1.5.15 - **Balance - Skeleton max health:** lower in the early and middle game. The bonus over the base 25 is now +25 / +45 / +65 / +90 / +125 / +165 / +215 / +275, from no bosses to Fader (it was +50 / +80 / +110 / +140 / +170 / +200 / +230 / +275). A fresh Skeleton starts at 50 instead of 75; from Yagluth on the gap closes, and Fader is unchanged at 300. A Skeleton never needs food and never spends stamina, so it was well ahead of a fed viking at every tier. Thanks to Jondar Korric and everyone else who asked for this. - **Fix - Auto-Resurrect on any hit:** a Skeleton's Auto-Resurrect now triggers only on a hit that would actually kill you. It used to compare the raw hit, before armour and blocking, with its poison and fire counted all at once, so with good armour it fired on almost any hit. On dedicated servers it could also miss a real deathblow when the server or another player controlled the attacker. Thanks to akira for the report. -- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy dead shall rise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. +- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy shall raise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. ### v1.5.14 - **New - Fenrir night eyes:** at night a Fenrir's eyes glow in the Fenring's orange, the way a wolf's eyes catch the light. Faint while no form is ready, bright when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Under `Fenrir - Appearance` each player can turn off the glow or the "Ready!" message for themselves. Thanks to lexsonn for the idea. From 9e9790d1e99730970e2e30f3e3b632f058f48dd4 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 23:55:26 +0200 Subject: [PATCH 2/4] docs(readme): the v1.5.15 entry quotes the line that shipped The new line goes out in v1.5.16 and is listed for that release. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 35bd680..cb169ae 100644 --- a/README.md +++ b/README.md @@ -454,7 +454,7 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ### v1.5.15 - **Balance - Skeleton max health:** lower in the early and middle game. The bonus over the base 25 is now +25 / +45 / +65 / +90 / +125 / +165 / +215 / +275, from no bosses to Fader (it was +50 / +80 / +110 / +140 / +170 / +200 / +230 / +275). A fresh Skeleton starts at 50 instead of 75; from Yagluth on the gap closes, and Fader is unchanged at 300. A Skeleton never needs food and never spends stamina, so it was well ahead of a fed viking at every tier. Thanks to Jondar Korric and everyone else who asked for this. - **Fix - Auto-Resurrect on any hit:** a Skeleton's Auto-Resurrect now triggers only on a hit that would actually kill you. It used to compare the raw hit, before armour and blocking, with its poison and fire counted all at once, so with good armour it fired on almost any hit. On dedicated servers it could also miss a real deathblow when the server or another player controlled the attacker. Thanks to akira for the report. -- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy shall raise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. +- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy dead shall rise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. ### v1.5.14 - **New - Fenrir night eyes:** at night a Fenrir's eyes glow in the Fenring's orange, the way a wolf's eyes catch the light. Faint while no form is ready, bright when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Under `Fenrir - Appearance` each player can turn off the glow or the "Ready!" message for themselves. Thanks to lexsonn for the idea. From 3f8cf1ee27b0ee48badd7fdd34d6ffcea0bce9e2 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Sun, 25 Oct 2026 17:38:28 +0100 Subject: [PATCH 3/4] feat(alfar): v1.6.0 - the Alfar, an eleventh race Grey, tall and thin, with black eyes. Eitr is armour and fuel (shield, diet, soft fall, levitation), Heimkall sends a lethal blow home at one health every 20 minutes. Caster powers from Skrid to the archon Sameining, with on-screen cooldowns. Automated base around the Ljoskjarne: drones, three constructs, crystals, Ljosgard, Prismavard. Compendium page in EN/IT/RU. README: New in block, race section, progression, station line, changelog. Co-Authored-By: Claude Sonnet 5.5 --- JotunnModStub/Alfar/AlfarArchon.cs | 176 ++ JotunnModStub/Alfar/AlfarChests.cs | 134 ++ JotunnModStub/Alfar/AlfarCommands.cs | 110 + JotunnModStub/Alfar/AlfarConfig.cs | 159 ++ JotunnModStub/Alfar/AlfarConstructs.cs | 397 ++++ JotunnModStub/Alfar/AlfarDroneAI.cs | 1950 +++++++++++++++++ JotunnModStub/Alfar/AlfarDrones.cs | 365 +++ JotunnModStub/Alfar/AlfarEitr.cs | 166 ++ JotunnModStub/Alfar/AlfarHeimkall.cs | 171 ++ JotunnModStub/Alfar/AlfarLevitation.cs | 120 + JotunnModStub/Alfar/AlfarLjosgard.cs | 108 + JotunnModStub/Alfar/AlfarMark.cs | 149 ++ JotunnModStub/Alfar/AlfarMiners.cs | 104 + JotunnModStub/Alfar/AlfarNexus.cs | 576 +++++ JotunnModStub/Alfar/AlfarNexusConfig.cs | 144 ++ JotunnModStub/Alfar/AlfarNexusStore.cs | 171 ++ JotunnModStub/Alfar/AlfarPatches.cs | 149 ++ JotunnModStub/Alfar/AlfarPowerConfig.cs | 170 ++ JotunnModStub/Alfar/AlfarPowers.cs | 616 ++++++ JotunnModStub/Alfar/AlfarProbe.cs | 434 ++++ JotunnModStub/Alfar/AlfarRace.cs | 40 + JotunnModStub/Alfar/AlfarStatusEffects.cs | 169 ++ JotunnModStub/Alfar/AlfarTowers.cs | 239 ++ JotunnModStub/Alfar/AlfarVisuals.cs | 495 +++++ JotunnModStub/ConfigSync.cs | 1 + JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RaceCompendium.cs | 57 +- JotunnModStub/RaceRadial.cs | 13 + JotunnModStub/RaceScale.cs | 2 + JotunnModStub/RaceStationLock.cs | 5 + JotunnModStub/RacesOfValheim.cs | 51 +- .../Translations/English/compendium.json | 24 + JotunnModStub/Translations/English/items.json | 35 + .../Translations/English/messages.json | 30 +- JotunnModStub/Translations/English/races.json | 4 +- .../Translations/English/status_effects.json | 12 +- .../Translations/Italian/compendium.json | 24 + JotunnModStub/Translations/Italian/items.json | 35 + .../Translations/Italian/messages.json | 30 +- JotunnModStub/Translations/Italian/races.json | 4 +- .../Translations/Italian/status_effects.json | 12 +- .../Translations/Russian/compendium.json | 24 + JotunnModStub/Translations/Russian/items.json | 35 + .../Translations/Russian/messages.json | 30 +- JotunnModStub/Translations/Russian/races.json | 4 +- .../Translations/Russian/status_effects.json | 12 +- README.md | 35 +- manifest.json | 2 +- 48 files changed, 7779 insertions(+), 16 deletions(-) create mode 100644 JotunnModStub/Alfar/AlfarArchon.cs create mode 100644 JotunnModStub/Alfar/AlfarChests.cs create mode 100644 JotunnModStub/Alfar/AlfarCommands.cs create mode 100644 JotunnModStub/Alfar/AlfarConfig.cs create mode 100644 JotunnModStub/Alfar/AlfarConstructs.cs create mode 100644 JotunnModStub/Alfar/AlfarDroneAI.cs create mode 100644 JotunnModStub/Alfar/AlfarDrones.cs create mode 100644 JotunnModStub/Alfar/AlfarEitr.cs create mode 100644 JotunnModStub/Alfar/AlfarHeimkall.cs create mode 100644 JotunnModStub/Alfar/AlfarLevitation.cs create mode 100644 JotunnModStub/Alfar/AlfarLjosgard.cs create mode 100644 JotunnModStub/Alfar/AlfarMark.cs create mode 100644 JotunnModStub/Alfar/AlfarMiners.cs create mode 100644 JotunnModStub/Alfar/AlfarNexus.cs create mode 100644 JotunnModStub/Alfar/AlfarNexusConfig.cs create mode 100644 JotunnModStub/Alfar/AlfarNexusStore.cs create mode 100644 JotunnModStub/Alfar/AlfarPatches.cs create mode 100644 JotunnModStub/Alfar/AlfarPowerConfig.cs create mode 100644 JotunnModStub/Alfar/AlfarPowers.cs create mode 100644 JotunnModStub/Alfar/AlfarProbe.cs create mode 100644 JotunnModStub/Alfar/AlfarRace.cs create mode 100644 JotunnModStub/Alfar/AlfarStatusEffects.cs create mode 100644 JotunnModStub/Alfar/AlfarTowers.cs create mode 100644 JotunnModStub/Alfar/AlfarVisuals.cs diff --git a/JotunnModStub/Alfar/AlfarArchon.cs b/JotunnModStub/Alfar/AlfarArchon.cs new file mode 100644 index 0000000..0be4415 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarArchon.cs @@ -0,0 +1,176 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// SAMEINING, the archon (Alfar_Progettazione.txt sec. 13.8): Fader's power, an all-or-nothing form. + /// + /// - needs 75% of the maximum eitr and a READY Heimkall, and spends ALL the eitr; + /// - lasts up to three minutes: bigger (x1.5), glowing, +20% speed; + /// - instead of armour there is a POOL of points, three per eitr spent: every blow lands on it, + /// and when it is gone the form ends early; + /// - no weapons: a psionic pulse strikes everything hostile around the body, once a second; + /// - Ljosstorm and Geisli cost nothing in the form, but wait a few seconds between uses; + /// - it ENDS (time up, pool gone) with a teleport home at one hit point, eitr at zero, and the + /// Heimkall wait starting. The form IS a Heimkall spent on purpose. + /// + /// The form is published in the ZDO so other players see the size and the glow. + /// + public static class AlfarArchon + { + public const string ZdoKey = "Alfar_Archon"; + + public static bool Active { get; private set; } + public static float Pool { get; private set; } + public static float EndsAt { get; private set; } + public static float StartedAt { get; private set; } + + private static float nextPulse; + + /// True for any player in range: the form is read off the ZDO, not local state. + public static bool IsArchon(Player player) + { + if (player == null) return false; + ZNetView nview = player.GetComponent(); + return nview != null && nview.IsValid() && nview.GetZDO().GetInt(ZdoKey, 0) == 1; + } + + public static bool IsLocalActive => Active && Player.m_localPlayer != null; + + private static void Publish(Player player, bool on) + { + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set(ZdoKey, on ? 1 : 0); + } + + // ─── Entering ──────────────────────────────────────────────────────── + + public static bool TryActivate(Player player) + { + if (Active || player == null) return false; + + float max = player.GetMaxEitr(); + float eitr = player.GetEitr(); + if (max <= 0f || eitr < max * AlfarPowerConfig.ArchonThreshold.Value) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_not_charged")); + return false; + } + + if (!AlfarHeimkall.IsReady(player)) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_not_ready")); + return false; + } + + // Everything goes in: the strength of the form is what the Alfr had eaten. + Pool = eitr * AlfarPowerConfig.ArchonPoolPerEitr.Value; + AlfarEitr.Spend(player, eitr); + + Active = true; + StartedAt = Time.time; + EndsAt = Time.time + AlfarPowerConfig.ArchonSeconds.Value; + AlfarStatusEffects.ShowTimer("archon", AlfarPowerConfig.ArchonSeconds.Value); + nextPulse = Time.time + AlfarPowerConfig.ArchonPulseInterval.Value; + Publish(player, true); + + Jotunn.Logger.LogInfo($"[Alfar] Sameining on: pool {Pool:0} for {AlfarPowerConfig.ArchonSeconds.Value:0}s."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_on")); + return true; + } + + // ─── In the form ───────────────────────────────────────────────────── + + /// + /// Takes a blow into the pool. Called from the shield prefix before anything else, because in + /// the form the pool IS the defence: every type of damage, drowning and the edge of the world + /// included, since nothing else can end the form but the pool and the clock. + /// + public static void Absorb(Player player, HitData hit) + { + if (!Active || hit == null) return; + + float total = hit.m_damage.GetTotalDamage(); + hit.m_damage = default(HitData.DamageTypes); + if (total <= 0f) return; + + Pool -= total; + // The exit itself is done in Tick, outside the damage call. + } + + public static void Tick(Player player) + { + if (!Active) return; + + if (player == null || player.IsDead()) + { + // The body is gone (or the world is): nothing to teleport, only the state to drop. + Active = false; + if (player != null) Publish(player, false); + return; + } + + if (Pool <= 0f || Time.time >= EndsAt) + { + Exit(player, Pool <= 0f ? "pool gone" : "time up"); + return; + } + + if (Time.time >= nextPulse) + { + nextPulse = Time.time + AlfarPowerConfig.ArchonPulseInterval.Value; + AlfarPowers.Pulse(player, AlfarPowerConfig.ArchonPulseRadius.Value, AlfarPowerConfig.ArchonPulseDamage.Value); + } + } + + // ─── Leaving ───────────────────────────────────────────────────────── + + public static void Exit(Player player, string reason) + { + if (!Active) return; + + Active = false; + Pool = 0f; + Publish(player, false); + AlfarStatusEffects.ClearTimer("archon"); + + // Eitr to zero, then the Heimkall: the form spends the one that was ready. + AlfarEitr.Spend(player, player.GetEitr()); + AlfarHeimkall.TryTrigger(player, "Sameining " + reason, force: true); + + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_off")); + Jotunn.Logger.LogInfo($"[Alfar] Sameining off ({reason})."); + } + + /// The cooldown Ljosstorm and Geisli wait in the form, instead of costing eitr. + public static float FreePowerCooldown => AlfarPowerConfig.ArchonFreePowerCooldown.Value; + + /// + /// NO WEAPONS in the form: the psionic pulse is the attack. Humanoid.StartAttack is the one + /// door every swing, shot and draw goes through (verified, doc sec. 16B); returning false + /// with a false result is "nothing started". + /// + [HarmonyLib.HarmonyPatch(typeof(Humanoid), "StartAttack")] + public static class Alfar_Archon_NoWeapons_Patch + { + public static bool Prefix(Humanoid __instance, ref bool __result) + { + if (Active && __instance == Player.m_localPlayer) + { + __result = false; + return false; + } + return true; + } + } + + /// Clears the state without teleporting (used by the reset command). + public static void ForceClear(Player player) + { + Active = false; + Pool = 0f; + if (player != null) Publish(player, false); + AlfarStatusEffects.ClearTimer("archon"); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarChests.cs b/JotunnModStub/Alfar/AlfarChests.cs new file mode 100644 index 0000000..e8fc1d9 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarChests.cs @@ -0,0 +1,134 @@ +using System.Collections.Generic; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The EIRINNSIGLI, the verdigris seal (Alfar_Progettazione.txt sec. 9.2c): a bronze nail turned at + /// the forge. Put inside a chest it tells the drones NOT to look there - the inverse of the + /// Butler's, where the seal says "this one is yours". Only the colour differs from the nail: a model + /// recolour does not touch the inventory icon (guide 5.2), so in the pack it looks like a bronze + /// nail and only the name tells it apart. + /// + public static class AlfarSigil + { + public const string PrefabName = "AlfarSigil"; + public const string DisplayName = "$rov_item_alfar_sigil_name"; + + public static void Register() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, "BronzeNails"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Alfar] Could not clone BronzeNails: no verdigris seal."); + return; + } + + ItemDrop drop = prefab.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = DisplayName; + shared.m_description = "$rov_item_alfar_sigil_desc"; + + AlfarConstructs.Tint(prefab, new Color(0.36f, 0.68f, 0.58f, 1f)); + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + + ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig + { + Item = PrefabName, + Amount = 1, + CraftingStation = CraftingStations.Forge, + MinStationLevel = 1, + Requirements = new[] { new RequirementConfig("BronzeNails", 1, 0, true) }, + })); + } + } + + /// + /// The two special chests (sec. 9.2c): built like an ordinary chest with Greydwarf eyes added to + /// the price. The ENTRY chest is where everything is thrown and where the drones sort from; the + /// WOOD chest holds the wood the drones may burn - the only wood they ever consume. + /// + public static class AlfarChests + { + public const string EntryName = "AlfarInngangskista"; + public const string WoodName = "AlfarEldividarkista"; + + public static void Register() + { + RegisterOne(EntryName, "$rov_piece_alfar_inngangskista_name", "$rov_piece_alfar_inngangskista_desc", + new Color(0.62f, 0.80f, 1f, 1f)); + RegisterOne(WoodName, "$rov_piece_alfar_eldividarkista_name", "$rov_piece_alfar_eldividarkista_desc", + new Color(0.85f, 0.62f, 0.36f, 1f)); + } + + private static void RegisterOne(string pieceName, string display, string description, Color tint) + { + GameObject source = PrefabManager.Cache.GetPrefab("piece_chest_wood"); + if (source == null) + { + Jotunn.Logger.LogWarning("[Alfar] No 'piece_chest_wood': the chest " + pieceName + " is not registered."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(pieceName, source); + if (prefab == null) return; + + // The price of a plain chest, read from the game (guide 3.2), plus the eyes. + var requirements = new List(); + Piece vanilla = source.GetComponent(); + if (vanilla != null && vanilla.m_resources != null) + { + foreach (Piece.Requirement r in vanilla.m_resources) + { + if (r.m_resItem == null) continue; + requirements.Add(new RequirementConfig(r.m_resItem.gameObject.name, r.m_amount, 0, true)); + } + } + requirements.Add(new RequirementConfig("GreydwarfEye", AlfarNexusConfig.ChestEyes.Value, 0, true)); + + Container container = prefab.GetComponent(); + if (container != null) container.m_name = display; + + Piece piece = prefab.GetComponent(); + if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The chest has no Piece: " + pieceName); return; } + piece.m_name = display; + piece.m_description = description; + + AlfarConstructs.Tint(prefab, tint); + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = display, + Description = description, + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = piece.m_icon, + Requirements = requirements.ToArray(), + })); + + // One of each inside the reach of a Ljoskjarne, and only for the Alfar, and only where a core stands. + PieceDensityLimit.Register(pieceName, AlfarNexusConfig.NexusRadius.Value, 1, "rov_msg_build_limit_alfar_chest"); + PieceDensityLimit.RegisterGate(pieceName, (player, position) => + { + if (!AlfarRace.IsLocalAlfar()) + { + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar")); + return false; + } + if (AlfarNexusBehaviour.Covering(position) == null) + { + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_chest_needs_nexus")); + return false; + } + return true; + }); + + AlfarPieces.Extra.Add(pieceName); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarCommands.cs b/JotunnModStub/Alfar/AlfarCommands.cs new file mode 100644 index 0000000..a0f4785 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarCommands.cs @@ -0,0 +1,110 @@ +using Jotunn.Entities; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Test helpers for the Alfar, in the F5 console. They exist so the phases of Alfar_Test.txt can + /// be walked through without waiting twenty minutes between steps. + /// + /// alfarstatus what the race is doing right now (eitr, Heimkall timer, SE, form...) + /// alfarreset clears every Alfar timer and cooldown + /// alfareitr sets the eitr pool: a number, "full", or 0 + /// alfarhp sets the current health, to try the lethal-blow case without dying + /// + public class AlfarStatusCommand : ConsoleCommand + { + public override string Name => "alfarstatus"; + public override string Help => "[DEBUG] Prints the Alfar's eitr, health, Heimkall timer and passive."; + + public override void Run(string[] args) + { + Player player = Player.m_localPlayer; + if (player == null) { Console.instance.Print("No local player."); return; } + + string race = AlfarVisuals.GetPlayerRace(player); + Print($"race={race} progression state={BossProgressionManager.GetCurrentProgressionState()}"); + Print($"health={player.GetHealth():0}/{player.GetMaxHealth():0} eitr={player.GetEitr():0.0}/{player.GetMaxEitr():0}"); + + float left = AlfarHeimkall.Remaining(player); + Print($"Heimkall: {(left <= 0f ? "READY" : (left / 60f).ToString("0.0") + " min left")} " + + $"(cooldown now {AlfarHeimkall.CooldownSeconds() / 60f:0} min)"); + + bool se = player.GetSEMan().HaveStatusEffect(SE_AlfarStats.EffectName.GetStableHashCode()); + Print($"passive status effect: {(se ? "on" : "OFF")}"); + } + + private static void Print(string text) + { + Console.instance.Print("[Alfar] " + text); + Jotunn.Logger.LogInfo("[Alfar] " + text); + } + } + + public class AlfarResetCommand : ConsoleCommand + { + public override string Name => "alfarreset"; + public override string Help => "[DEBUG] Clears the Alfar's Heimkall timer and every power cooldown."; + + public override void Run(string[] args) + { + Player player = Player.m_localPlayer; + if (player == null) return; + + AlfarHeimkall.ResetTimer(player); + AlfarHeimkall.InvulnerableUntil = 0f; + AlfarPowers.ResetCooldowns(player); + Console.instance.Print("[Alfar] Heimkall timer and power cooldowns cleared."); + } + } + + public class AlfarEitrCommand : ConsoleCommand + { + public override string Name => "alfareitr"; + public override string Help => "[DEBUG] alfareitr - sets the Alfr's current eitr."; + + public override void Run(string[] args) + { + Player player = Player.m_localPlayer; + if (player == null || args.Length == 0) { Console.instance.Print("alfareitr "); return; } + + float target; + if (args[0].ToLower() == "full") target = player.GetMaxEitr(); + else if (!float.TryParse(args[0], System.Globalization.NumberStyles.Float, + System.Globalization.CultureInfo.InvariantCulture, out target)) + { + Console.instance.Print("alfareitr "); + return; + } + + target = Mathf.Clamp(target, 0f, player.GetMaxEitr()); + float delta = target - player.GetEitr(); + if (delta > 0f) player.AddEitr(delta); + else if (delta < 0f) AlfarEitr.Spend(player, -delta); + + Console.instance.Print($"[Alfar] eitr = {player.GetEitr():0.0}/{player.GetMaxEitr():0}"); + } + } + + public class AlfarHpCommand : ConsoleCommand + { + public override string Name => "alfarhp"; + public override string Help => "[DEBUG] alfarhp - sets the current health, to test the lethal-blow case."; + + public override void Run(string[] args) + { + Player player = Player.m_localPlayer; + if (player == null || args.Length == 0) { Console.instance.Print("alfarhp "); return; } + + if (!float.TryParse(args[0], System.Globalization.NumberStyles.Float, + System.Globalization.CultureInfo.InvariantCulture, out float hp)) + { + Console.instance.Print("alfarhp "); + return; + } + + player.SetHealth(Mathf.Clamp(hp, 1f, player.GetMaxHealth())); + Console.instance.Print($"[Alfar] health = {player.GetHealth():0}/{player.GetMaxHealth():0}"); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarConfig.cs b/JotunnModStub/Alfar/AlfarConfig.cs new file mode 100644 index 0000000..1769a1a --- /dev/null +++ b/JotunnModStub/Alfar/AlfarConfig.cs @@ -0,0 +1,159 @@ +using BepInEx.Configuration; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Every number the Alfar use. Nothing numeric lives in the logic files (guide 3.4), and every + /// value here is a STARTING value: Alfar_Progettazione.txt sec. 19 says they will all be + /// corrected in play. + /// + /// Only the look is bound so far. The shield, the powers and the base add their own sections as + /// they are written. + /// + public static class AlfarConfig + { + /// + /// Written into m_customData["Race"] and the ZDO. Chosen once and never changed: renaming it + /// later leaves every saved Alfar character unrecognised and back to human (the Brandr + /// lesson, design doc sec. 2). + /// + public const string RaceId = "Alfar"; + + // ─── Look ──────────────────────────────────────────────────────────── + + /// The tint written into _SkinColor. Ash grey: low saturation, a hair cool. + public static ConfigEntry SkinColor; + + /// + /// Height against a normal Viking: +5%, design doc sec. 7.1. Applied to the Visual child's Y, + /// never the root (RaceEyeHeight explains why). + /// + public static ConfigEntry HeightScale; + + /// + /// Width and depth: "barely visibly thinner", about -8%. Together with HeightScale this is a + /// NON-UNIFORM scale, which is where held weapons and the first-person camera tend to look + /// squashed - doc sec. 7.2. If it does, raise this toward 1 before touching anything else. + /// + public static ConfigEntry WidthScale; + + /// + /// 1 is the Sverm's size, which is what the design asked to try first ("se non va li + /// allarghiamo"). Raise it to enlarge the eyes: 1.6 is roughly a grey from the films. + /// + public static ConfigEntry EyeSizeMultiplier; + + // The eye geometry is the Sverm's, unchanged (SvermVisuals): offsets are metres in the head + // bone's OWN frame, so they land on the same part of the face at any body scale. + public const float EyeSeparation = 0.032f; + public const float EyeForward = 0.081f; + public const float EyeHeight = 0.181f; + public const float EyeSize = 0.062f; + + // ─── Eitr: diet, shield, soft fall ─────────────────────────────────── + + /// + /// What each food adds to the maximum eitr besides its own: min(hp, stamina) times this. + /// 1 is the design (sec. 3): native eitr plus the lower of hp and stamina. + /// + public static ConfigEntry DietMultiplier; + + /// + /// Eitr spent per point of damage. 1:1, FIXED, for ever (sec. 4.1): progression comes from + /// the food raising the pool, not from a better rate. + /// + public static ConfigEntry ShieldRate; + + /// Lightning and spirit cost this many times the rate (sec. 5.1: the double cost). + public static ConfigEntry ConductiveMultiplier; + + /// + /// Falls cost nothing while there is any eitr (sec. 4.5: soft fall). Off, a fall is shielded + /// like any other blow. + /// + public static ConfigEntry SoftFall; + + /// + /// The fastest an Alfr falls while there is eitr, in metres per second. The vanilla Feather + /// Cape caps at 5; a little under that reads as floating. + /// + public static ConfigEntry FeatherFallSpeed; + + // ─── Heimkall: the death that costs a wait ─────────────────────────── + + /// Minutes before a second Heimkall is possible, before Yagluth (sec. 6). + public static ConfigEntry HeimkallMinutes; + + /// The same, once Yagluth is down. + public static ConfigEntry HeimkallMinutesAfterYagluth; + + /// The same, once Fader is down. + public static ConfigEntry HeimkallMinutesAfterFader; + + /// + /// Seconds of invulnerability on arrival, so a lethal blow does not simply repeat at the + /// bed. Without it a burning or drowning death would loop. + /// + public static ConfigEntry HeimkallInvulnerableSeconds; + + public static void Bind(ConfigFile config) + { + const string heimkall = "Alfar - Heimkall"; + + HeimkallMinutes = config.Bind(heimkall, "Cooldown Minutes", 20f, + new ConfigDescription("Minutes between two Heimkalls (the lethal-blow teleport to the bed). Inside this wait, a lethal blow kills normally.", + new AcceptableValueRange(0f, 120f))); + + HeimkallMinutesAfterYagluth = config.Bind(heimkall, "Cooldown Minutes After Yagluth", 15f, + new ConfigDescription("The cooldown once Yagluth is defeated.", + new AcceptableValueRange(0f, 120f))); + + HeimkallMinutesAfterFader = config.Bind(heimkall, "Cooldown Minutes After Fader", 10f, + new ConfigDescription("The cooldown once Fader is defeated.", + new AcceptableValueRange(0f, 120f))); + + HeimkallInvulnerableSeconds = config.Bind(heimkall, "Invulnerable Seconds", 5f, + new ConfigDescription("Seconds nothing can hurt the Alfr after arriving.", + new AcceptableValueRange(0f, 30f))); + + const string eitr = "Alfar - Eitr"; + + DietMultiplier = config.Bind(eitr, "Diet Multiplier", 1f, + new ConfigDescription("Each food adds its native eitr plus min(hp, stamina) times this to the maximum eitr.", + new AcceptableValueRange(0f, 3f))); + + ShieldRate = config.Bind(eitr, "Shield Rate", 1f, + new ConfigDescription("Eitr spent per point of damage absorbed (1 = 1:1).", + new AcceptableValueRange(0.1f, 5f))); + + ConductiveMultiplier = config.Bind(eitr, "Lightning And Spirit Multiplier", 2f, + new ConfigDescription("Lightning and spirit damage cost this many times the shield rate.", + new AcceptableValueRange(1f, 5f))); + + SoftFall = config.Bind(eitr, "Soft Fall", true, + new ConfigDescription("Falling does no damage, and is slowed, while the Alfr has any eitr.")); + + FeatherFallSpeed = config.Bind(eitr, "Feather Fall Speed", 4f, + new ConfigDescription("Maximum falling speed (m/s) while the Alfr has eitr. Lower floats more.", + new AcceptableValueRange(1f, 20f))); + + const string look = "Alfar - Look"; + + SkinColor = config.Bind(look, "Skin Color", new Color(0.86f, 0.88f, 0.88f, 1f), + new ConfigDescription("How light the ash-grey skin is. The skin texture itself is made grey; this only sets its brightness.")); + + HeightScale = config.Bind(look, "Height Scale", 1.05f, + new ConfigDescription("Body height against a normal Viking (1.05 = +5%).", + new AcceptableValueRange(0.8f, 1.3f))); + + WidthScale = config.Bind(look, "Width Scale", 0.92f, + new ConfigDescription("Body width and depth against a normal Viking (0.92 = 8% thinner).", + new AcceptableValueRange(0.7f, 1.2f))); + + EyeSizeMultiplier = config.Bind(look, "Eye Size Multiplier", 0.8f, + new ConfigDescription("1 = the Sverm's eye size; 0.8 is slightly smaller. Raise to enlarge the black eyes.", + new AcceptableValueRange(0.5f, 3f))); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarConstructs.cs b/JotunnModStub/Alfar/AlfarConstructs.cs new file mode 100644 index 0000000..80fe2a5 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarConstructs.cs @@ -0,0 +1,397 @@ +using System.Collections.Generic; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The three constructs, the Alfar's only troops (Alfar_Progettazione.txt sec. 8.5): + /// + /// Neistvordr a Surtling: hp 60 and a shield of 60 (the vanilla Surtling has 20), fire thrower + /// Steinvordr the StoneGolem: hp 800, the tank, ONE per Nexus + /// Eldingvordr a smaller Abomination at half its hp, which fires a lightning sphere every 8 s + /// + /// Everything that makes them the Alfar's is done by what is added, not by rewriting attacks: + /// AlfarMark turns whatever they deal into lightning and keeps it off friends and buildings, + /// AlfarCreatureShield gives them a shield that returns by itself, and RaisedThrall gives them + /// the follow and stay orders every other race's troops already have. + /// + /// They are NOT repaired and do not heal: the damage to the body is permanent. RaisedThrall's + /// sentinel regeneration (SkeletonSentryBehaviour) is therefore left off, and the creature's own + /// slow vanilla regeneration is switched off too. + /// + public static class AlfarConstructs + { + public const string Neistvordr = "AlfarNeistvordr"; + public const string Steinvordr = "AlfarSteinvordr"; + public const string Eldingvordr = "AlfarEldingvordr"; + + public const string SphereProjectile = "AlfarLightningSphere"; + public const string SphereWeapon = "AlfarSphereAttack"; + + public class Kind + { + public string PrefabName; + public string Display; + public string Source; + public float Health; // 0 = keep the vanilla creature's + public float HealthFactor; // applied after Health when Health is 0 + public float Scale; // 1 = the vanilla size + } + + public static readonly Kind[] Roster = + { + new Kind { PrefabName = Neistvordr, Display = "$rov_creature_alfar_neistvordr_name", Source = "Surtling", Health = 60f, Scale = 1f }, + new Kind { PrefabName = Steinvordr, Display = "$rov_creature_alfar_steinvordr_name", Source = "StoneGolem", Health = 0f, HealthFactor = 1f, Scale = 0.6f }, + new Kind { PrefabName = Eldingvordr, Display = "$rov_creature_alfar_eldingvordr_name", Source = "Abomination", Health = 0f, HealthFactor = 0.5f, Scale = 0.4f }, + }; + + public static Kind Find(string prefabName) + { + foreach (Kind kind in Roster) if (kind.PrefabName == prefabName) return kind; + return null; + } + + // ─── Registration ──────────────────────────────────────────────────── + + public static void Register() + { + // The sphere first: the Eldingvordr's weapon needs it. + bool sphere = RegisterSphere(); + + foreach (Kind kind in Roster) + { + if (kind.PrefabName == Eldingvordr && !sphere) + { + Jotunn.Logger.LogWarning("[Alfar] No lightning sphere: the Eldingvordr keeps the Abomination's melee."); + } + RegisterOne(kind, sphere); + } + } + + private static void RegisterOne(Kind kind, bool sphere) + { + GameObject source = PrefabManager.Cache.GetPrefab(kind.Source); + if (source == null) + { + Jotunn.Logger.LogWarning($"[Alfar] No '{kind.Source}' to build {kind.Display} from."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(kind.PrefabName, source); + if (prefab == null) return; + + Character character = prefab.GetComponent(); + if (character != null) + { + character.m_name = kind.Display; + character.m_faction = Character.Faction.Players; + if (kind.Health > 0f) character.m_health = kind.Health; + else character.m_health *= kind.HealthFactor; + + // The damage to the body is permanent: no slow regeneration either. + character.m_regenAllHPTime = 0f; + } + + if (!Mathf.Approximately(kind.Scale, 1f)) + { + prefab.transform.localScale = Vector3.one * kind.Scale; + ZNetView nview = prefab.GetComponent(); + if (nview != null) nview.m_syncInitialScale = true; + } + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = AlfarNexusConfig.ConstructLeash.Value; + + MonsterAI monster = prefab.GetComponent(); + if (monster != null) + { + // The vanilla creatures attack player-built objects. Ours never touch a building. + monster.m_attackPlayerObjects = false; + monster.m_alertRange = AlfarNexusConfig.ConstructAlertRange.Value; + monster.m_maxChaseDistance = AlfarNexusConfig.ConstructAlertRange.Value; + } + + // A construct that dropped Coal, a Surtling core or a trophy would be a loot farm. + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + if (kind.PrefabName == Eldingvordr && sphere) GiveSphereWeapon(prefab); + if (kind.PrefabName == Neistvordr) BlueFlames(prefab); + else Tint(prefab, new Color(0.85f, 0.52f, 0.2f, 1f)); + + AlfarMark mark = prefab.AddComponent(); + mark.Role = "construct"; + + // What a destroyed construct gives back: the METAL it was built from, and nothing else - the + // crystals and the refined eitr are spent for good (design sec. 8.5). + AlfarRefund refund = prefab.AddComponent(); + refund.Item = kind.PrefabName == Neistvordr ? "Bronze" : kind.PrefabName == Eldingvordr ? "Iron" : "BlackMetal"; + refund.Amount = kind.PrefabName == Neistvordr ? AlfarNexusConfig.NeistMetal.Value + : kind.PrefabName == Eldingvordr ? AlfarNexusConfig.EldingMetal.Value + : AlfarNexusConfig.SteinMetal.Value; + + AlfarCreatureShield shield = prefab.AddComponent(); + shield.MaxShield = character != null ? character.m_health : 0f; + shield.Shield = shield.MaxShield; + + RaisedThrall thrall = prefab.AddComponent(); + thrall.m_kind = kind.PrefabName; + thrall.m_commandingRace = AlfarConfig.RaceId; + thrall.m_maxFollowers = -1; // the cap is the Nexus's, per type, counted at the Nexus + thrall.m_witherSeconds = AlfarNexusConfig.WitherSeconds.Value; + thrall.m_homeCheckRange = AlfarNexusConfig.NexusRadius.Value; + thrall.m_refusalMessage = "$rov_msg_thrall_refusal_alfar"; + + PrefabManager.Instance.AddPrefab(prefab); + Jotunn.Logger.LogInfo($"[Alfar] Registered '{kind.PrefabName}' from '{kind.Source}'."); + } + + // ─── The lightning sphere ──────────────────────────────────────────── + + /// + /// The Eldingvordr's shot: a sphere that bursts in a small area, hurts only enemies, and never + /// touches a building (doc sec. 8.5 and 16B V12). Cloned from the Dverger ice projectile, the + /// clean base the probe found: an area burst and NO lingering effect spawned on impact (the + /// fire one drops a fire field and also spawns on buildings). + /// + private static bool RegisterSphere() + { + GameObject source = PrefabManager.Cache.GetPrefab("DvergerStaffIce_projectile"); + if (source == null) + { + Jotunn.Logger.LogWarning("[Alfar] DvergerStaffIce_projectile not found: no lightning sphere."); + return false; + } + + GameObject projectile = PrefabManager.Instance.CreateClonedPrefab(SphereProjectile, source); + if (projectile == null) return false; + + Projectile settings = projectile.GetComponent(); + if (settings == null) return false; + + settings.m_gravity = 0f; + settings.m_ttl = 4f; + settings.m_aoe = 3f; + settings.m_aoeSkipWearNTear = true; + settings.m_hitFriendly = false; + settings.m_noDamageFriendly = true; + settings.m_hitOwner = false; + settings.m_statusEffect = ""; + + Tint(projectile, new Color(0.55f, 0.85f, 1f, 1f)); + PrefabManager.Instance.AddPrefab(projectile); + + // The weapon that fires it: the Surtling's own fireball weapon, because a creature that + // shoots needs an item with a projectile attack, and that is the one that exists. + GameObject surtling = PrefabManager.Cache.GetPrefab("Surtling"); + Humanoid surtlingHumanoid = surtling != null ? surtling.GetComponent() : null; + GameObject fireball = surtlingHumanoid != null && surtlingHumanoid.m_defaultItems != null && + surtlingHumanoid.m_defaultItems.Length > 0 + ? surtlingHumanoid.m_defaultItems[0] + : null; + if (fireball == null) + { + Jotunn.Logger.LogWarning("[Alfar] The Surtling's fireball weapon was not found: no sphere weapon."); + return false; + } + + GameObject weapon = PrefabManager.Instance.CreateClonedPrefab(SphereWeapon, fireball); + if (weapon == null) return false; + + ItemDrop drop = weapon.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = "$rov_item_alfar_sphere_name"; + + // One shot every eight seconds (design): the AI waits this long between uses. + shared.m_aiAttackInterval = AlfarNexusConfig.SphereIntervalSeconds.Value; + shared.m_aiAttackRange = AlfarNexusConfig.SphereRange.Value; + shared.m_aiAttackRangeMin = 4f; + + HitData.DamageTypes damage = default(HitData.DamageTypes); + damage.m_lightning = AlfarNexusConfig.SphereDamage.Value; + shared.m_damages = damage; + + if (shared.m_attack != null) + { + shared.m_attack.m_attackProjectile = projectile; + // The Abomination's right hand: where the sphere leaves from. + shared.m_attack.m_attackOriginJoint = "r.hand"; + } + + ItemManager.Instance.AddItem(new CustomItem(weapon, fixReference: false)); + return true; + } + + private static void GiveSphereWeapon(GameObject prefab) + { + Humanoid humanoid = prefab.GetComponent(); + GameObject weapon = PrefabManager.Instance.GetPrefab(SphereWeapon); + if (humanoid == null || weapon == null) return; + + humanoid.m_defaultItems = new[] { weapon }; + humanoid.m_randomWeapon = new GameObject[0]; + humanoid.m_randomArmor = new GameObject[0]; + humanoid.m_randomShield = new GameObject[0]; + humanoid.m_randomSets = new Humanoid.ItemSet[0]; + } + + // ─── Colour ────────────────────────────────────────────────────────── + + /// + /// A tint on every mesh, through renderer.materials (an instanced copy) and NEVER .material or + /// sharedMaterial: the vanilla creature uses the same asset and must stay as it is (guide 3.5). + /// This is a recolour and not a retexture: a true repaint of the golem and the Abomination is + /// still to do (test file, phase 6). + /// + public static void Tint(GameObject prefab, Color color) + { + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + if (renderer is ParticleSystemRenderer || renderer is TrailRenderer || renderer is LineRenderer) continue; + + Material[] materials = renderer.materials; + foreach (Material material in materials) + { + if (material == null) continue; + if (material.HasProperty("_Color")) material.color = color; + if (material.HasProperty("_EmissionColor")) + { + material.SetColor("_EmissionColor", color * 0.08f); + material.EnableKeyword("_EMISSION"); + } + } + renderer.materials = materials; + } + + foreach (Light light in prefab.GetComponentsInChildren(true)) light.color = color; + } + + /// + /// The Surtling is made of particles and lights, not textures, and the vanilla prefab ALREADY + /// carries blue variants of its flames, switched off (probe, doc 16C P2): turn those on, turn + /// the red ones off, and recolour the glow of the body and the point light. + /// + private static void BlueFlames(GameObject prefab) + { + foreach (Transform child in prefab.GetComponentsInChildren(true)) + { + if (child.name == "flames_world_BLUE") child.gameObject.SetActive(true); + else if (child.name == "flames" || child.name == "flames_world" || child.name == "flames_world_Purple") + { + child.gameObject.SetActive(false); + } + } + + Color blue = new Color(0.25f, 0.55f, 1f, 1f); + foreach (Light light in prefab.GetComponentsInChildren(true)) light.color = blue; + + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + Material[] materials = renderer.materials; + foreach (Material material in materials) + { + if (material != null && material.HasProperty("_EmissionColor")) + { + // The vanilla emission is white-hot (73): keep the strength, change the hue. + material.SetColor("_EmissionColor", new Color(0.25f, 0.55f, 1f, 1f) * 30f); + } + } + renderer.materials = materials; + } + } + + // ─── Counting and spawning (called by the Nexus) ───────────────────── + + /// + /// A destroyed construct drops the metal it cost, on the ground where it fell. Only a DEATH: + /// a zone unloading destroys the object too and must not pay anyone (the same rule as the + /// Butler's payload). + /// + public class AlfarRefund : MonoBehaviour + { + public string Item = ""; + public int Amount; + } + + [HarmonyLib.HarmonyPatch(typeof(Character), "OnDeath")] + public static class Alfar_Refund_Patch + { + public static void Postfix(Character __instance) + { + AlfarRefund refund = __instance != null ? __instance.GetComponent() : null; + if (refund == null || refund.Amount <= 0 || ObjectDB.instance == null) return; + + GameObject prefab = ObjectDB.instance.GetItemPrefab(refund.Item); + ItemDrop template = prefab != null ? prefab.GetComponent() : null; + if (template == null || template.m_itemData == null) return; + + int left = refund.Amount; + int max = Mathf.Max(1, template.m_itemData.m_shared.m_maxStackSize); + Vector3 at = __instance.transform.position + Vector3.up * 0.5f; + + while (left > 0) + { + int stack = Mathf.Min(left, max); + ItemDrop.ItemData clone = template.m_itemData.Clone(); + clone.m_dropPrefab = prefab; + ItemDrop.DropItem(clone, stack, at + Random.insideUnitSphere * 0.3f, Quaternion.identity); + left -= stack; + } + refund.Amount = 0; // once only + } + } + + public static int CountAlive(Vector3 anchor, string prefabName) + { + int count = 0; + foreach (RaisedThrall thrall in RaisedThrall.BoundTo(anchor)) + { + if (thrall != null && thrall.Kind == prefabName) count++; + } + return count; + } + + public static bool Spawn(Vector3 anchor, string prefabName) + { + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Alfar] No '{prefabName}' in ZNetScene: it cannot be built."); + return false; + } + + Vector3 where = SpawnSpot(anchor); + GameObject spawned = Object.Instantiate(prefab, where, Quaternion.Euler(0f, Random.Range(0, 360), 0f)); + RaisedThrall thrall = spawned != null ? spawned.GetComponent() : null; + if (thrall != null) thrall.Bind(anchor); + return spawned != null; + } + + /// A free spot on a ring around the Nexus, on the ground, or due south as a last resort. + public static Vector3 SpawnSpot(Vector3 centre) + { + const float radius = 3.5f; + int obstacleMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "vehicle"); + float start = Random.Range(0f, 360f); + + for (int i = 0; i < 12; i++) + { + float angle = (start + i * 30f) * Mathf.Deg2Rad; + Vector3 candidate = centre + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * radius; + if (ZoneSystem.instance != null) candidate.y = ZoneSystem.instance.GetGroundHeight(candidate); + if (Physics.CheckSphere(candidate + Vector3.up * 1.5f, 1f, obstacleMask)) continue; + return candidate + Vector3.up * 0.3f; + } + + Vector3 fallback = centre + new Vector3(0f, 0f, -radius); + if (ZoneSystem.instance != null) fallback.y = ZoneSystem.instance.GetGroundHeight(fallback); + return fallback + Vector3.up * 0.3f; + } + } +} diff --git a/JotunnModStub/Alfar/AlfarDroneAI.cs b/JotunnModStub/Alfar/AlfarDroneAI.cs new file mode 100644 index 0000000..59d8fea --- /dev/null +++ b/JotunnModStub/Alfar/AlfarDroneAI.cs @@ -0,0 +1,1950 @@ +using System.Collections.Generic; +using System.Text; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Alfar drone's own head (Alfar_Progettazione.txt sec. 9): a FORK of the Butler's BoneServantAI, + /// kept as a separate class so nothing that ships with the Skeleton, Skadi or Sverm can be broken + /// from here. What it keeps: the movement, the payload in the ZDO, the three families of stations, + /// the burn protection and the one-stage rule. What it changes: ONE drone does both trades; chests + /// are read the other way round (the sigil marks the ones NOT to touch); stations are fed only from + /// the entry chest, wood only from the wood chest; the product goes back to the entry chest and is + /// SORTED from there into the chest that already holds the same thing; and three jobs are new - + /// repair, farming (with the replant rule) and sorting. + /// + /// The Bone Servant's own head, as it was written: everything it does is here; vanilla's MonsterAI + /// never runs on it. + /// + /// HOW IT MOVES, which was the one open question in the design and is answered here rather than in + /// the doc. Three candidates were on the table: a ghost follow-target, pinning m_patrolPoint the way + /// RaisedThrall does, and calling BaseAI.MoveTo directly. The IL settled it: + /// + /// - BaseAI has NO Update and NO FixedUpdate. UpdateAI(dt) is driven centrally by + /// MonoUpdaters.FixedUpdate over BaseAI.Instances, and that list is maintained by OnEnable / + /// OnDisable. So "disable the AI and drive MoveTo yourself" kills the only thing that would + /// call anything: a disabled BaseAI is not ticked at all. That candidate is dead. + /// - BaseAI.UpdateAI itself does almost nothing - IsOwner, UpdateTakeoffLanding, + /// UpdateRegeneration - so skipping it costs a flying check we do not need and a regeneration + /// we already have from SkeletonSentryBehaviour. + /// + /// So: a PREFIX on MonsterAI.UpdateAI that hands the tick to this class and returns false. The + /// servant keeps its place in the central tick, keeps vanilla pathing through BaseAI.MoveTo, and + /// vanilla's own AI - targeting, fleeing, wandering, attacking - never executes a single line. That + /// is also why the servant cannot fight: not because its weapon was taken (it was), but because the + /// code that would swing it is never reached. + /// + /// MoveTo(dt, point, dist, run) is private, hence the cached MethodInfo. It returns TRUE on arrival + /// (read in the IL: DistanceXZ under the threshold calls StopMoving and returns 1), which is the + /// whole arrival test - no distance maths of our own. + /// + /// THE PAYLOAD IS VIRTUAL. The servant has no inventory. Every station's input RPC takes a STRING, + /// so what it carries is a list of prefab names and counts in its own ZDO, which survives saving, + /// zone reload and - the case that matters - a change of owner mid-job in multiplayer. The one + /// thing this costs is that the goods do not exist as objects while in transit, so they have to be + /// put back into the world by hand if the servant dies holding them. That is , + /// and it is the reason nothing here can quietly delete a player's ore. + /// + public class AlfarDroneAI : MonoBehaviour + { + // ─── ZDO keys ──────────────────────────────────────────────────────── + public const string KeyAnchor = "RoV_alfarAnchor"; + public const string KeyOrphanAt = "RoV_alfarOrphanAt"; + public const string KeyLoad = "RoV_alfarLoad"; + public const string KeySource = "RoV_alfarSource"; + public const string KeyTarget = "RoV_alfarTarget"; + public const string KeyStatus = "RoV_alfarStatus"; + public const string KeyDest = "RoV_alfarDest"; + + /// Every drone alive in the loaded zones: the repairs look at each other through it. + public static readonly List All = new List(); + + /// Written into a STATION's ZDO: the chest whose material is in it right now, so the + /// product goes home to where the raw came from even after a reload, and even if a different + /// client collects it. + public const string KeyFedBy = "RoV_alfarFedBy"; + + // ─── numbers that are not worth a config entry ─────────────────────── + private const float PlanInterval = 1.5f; + + /// + /// How close is close enough. Measured to the piece's ORIGIN, which on a furnace or a kiln sits + /// inside a metre or so of solid collider - so anything tight enough to look like hugging the + /// thing is a distance the servant can never actually reach, and it would time out and put a + /// perfectly good station in the penalty box. Two and a half metres is roughly where a player + /// stands to use one. + /// + private const float ArriveDistance = 2.5f; + + private const float CollectRadius = 3.5f; + private const float JobTimeout = 25f; + private const float PenaltySeconds = 180f; + + /// Set aside briefly when a job was reached but achieved nothing. Without this, a job + /// that arrives and finds nothing to do is re-planned identically on the next tick and the + /// servant stands there deciding the same thing forever. + private const float ShortPenaltySeconds = 20f; + private const float FleeSeconds = 6f; + private const float WitherSeconds = 30f; + private const float HomeCheckRange = 25f; + + /// A cooking slot inside this many seconds of burning outranks everything else. Twelve + /// seconds is a walk of about twenty metres with room to spare, which is the whole radius. + private const float SpoilPanicSeconds = 12f; + + /// How long a station may sit unserved before its wait starts outweighing distance. + /// This is what stops a furnace at the edge of the circle from starving while the servant + /// shuttles between two closer ones. + private const float WaitToMetres = 0.25f; + + private const int PayloadCap = 120; + + private static readonly System.Reflection.MethodInfo MoveToMethod = + AccessTools.Method(typeof(BaseAI), "MoveTo", + new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) }); + + private static readonly System.Reflection.FieldInfo AllPiecesField = + AccessTools.Field(typeof(Piece), "s_allPieces"); + + private static readonly System.Reflection.MethodInfo ContainerSaveMethod = + AccessTools.Method(typeof(Container), "Save"); + + private static int s_itemMask = -1; + + /// Which stations this one serves. Set on the prefab at registration, so it travels + /// with every instance the table raises. + public ButlerFamily m_family = ButlerFamily.Forge; + + /// + /// Whether this one stands and fights instead of walking home when trouble comes. Off for the + /// Bone Servants, which are pacifists by decision; on for the Sverm's Seeker Workers, which + /// keep the forge AND defend the nest. See . + /// + public bool m_fightsBack = false; + + /// + /// How close to the anchor counts as home, and how far past the configured radius it works. + /// 2.5 and 0 for a table. A Sverm nest is metres of collider that grows with its stage, so + /// SvermWorkerBehaviour sets both to the nest's measured edge - otherwise an idle worker would + /// spend its life walking into the trunk, and the work circle would be mostly nest. + /// + public float m_homeDistance = 2.5f; + public float m_radiusBonus = 0f; + + /// For a servant that fights back: how close an enemy has to be to stop the work, how + /// often that is asked, and how long the fight holds after the last sign of one. + private const float FightRange = 12f; + private const float FightScanInterval = 1f; + private const float FightLinger = 5f; + + private float m_nextFightScan; + private float m_fightUntil; + + private ZNetView m_nview; + private Character m_character; + private MonsterAI m_ai; + + private readonly object[] m_moveArgs = new object[4]; + private readonly List m_payload = new List(); + private readonly Dictionary m_penalties = new Dictionary(); + private readonly Dictionary m_idleSince = new Dictionary(); + + private readonly List m_stations = new List(); + private readonly List m_chests = new List(); // the storage chests + private Container m_entry; // the entry chest + private Container m_wood; // the wood-to-burn chest + private readonly List m_damaged = new List(); + + // Farming: where the last harvest was, and what to put back there. + private Vector3? m_farmSpot; + private Quaternion m_farmRot; + private PlantInfo m_farmInfo; + private float m_farmReadyAt; + + // Sorting: what was chosen at the entry chest and where it is going. + private string m_sortItem; + private ZDOID m_sortDest; + private float m_scannedAt = -99f; + + private Job m_job; + private float m_nextPlan; + private float m_jobDeadline; + private float m_fleeUntil; + private string m_status = ""; + + private class Load + { + public string Name; + public int Count; + } + + private class Job + { + public string Kind; // load | fuel | collect | deposit | drop + public ZDOID Target; + public Vector3 Point; + public bool Hurry; + public string Label; + public ZDOID Claim; // the one target other drones must leave alone + } + + // ================================================================ life + + private void Awake() + { + m_nview = GetComponent(); + m_character = GetComponent(); + m_ai = GetComponent(); + + All.Add(this); + ReadPayload(); + } + + private void OnDestroy() + { + All.Remove(this); + + // Only a DEATH scatters the load. A zone unloading destroys this object too, and there the + // payload must stay in the ZDO where it will be read again on the way back in - dropping it + // would mint a copy every time the player walked away. + if (m_character != null && m_character.IsDead()) DropPayload(); + } + + /// Called by the table the moment it raises one. + public void Bind(Vector3 anchor) + { + if (m_nview == null || !m_nview.IsValid()) return; + + m_nview.GetZDO().Set(KeyAnchor, anchor); + + if (m_ai != null) m_ai.MakeTame(); + if (m_character != null) m_character.SetTamed(true); + } + + public Vector3? Anchor + { + get + { + if (m_nview == null || !m_nview.IsValid()) return null; + + Vector3 anchor = m_nview.GetZDO().GetVec3(KeyAnchor, Vector3.zero); + return anchor == Vector3.zero ? (Vector3?)null : anchor; + } + } + + public bool IsBoundTo(Vector3 anchor) + { + Vector3? own = Anchor; + return own != null && Vector3.SqrMagnitude(own.Value - anchor) < 0.25f; + } + + /// The one line the table's hover shows. Read from the ZDO so a client that does not + /// own the servant still sees what it is doing. + public string Status + { + get + { + if (m_nview == null || !m_nview.IsValid()) return m_status; + return m_nview.GetZDO().GetString(KeyStatus, m_status); + } + } + + private void SetStatus(string text) + { + if (text == m_status) return; + + m_status = text; + if (m_nview != null && m_nview.IsValid() && m_nview.IsOwner()) + { + m_nview.GetZDO().Set(KeyStatus, text); + } + } + + /// Hit by something: stop working and walk home. It never fights back - there is + /// nothing in this class that could. A servant that fights back ignores this: vanilla already + /// holds the attacker as its target (MonsterAI.OnDamaged calls SetTarget, read off the IL), and + /// gives it the tick on the next frame. + public void NoteDamage() + { + if (m_fightsBack) return; + + m_fleeUntil = Time.time + FleeSeconds; + m_job = null; + } + + /// + /// True while vanilla's MonsterAI should have the tick instead of the work - only ever for a + /// servant that fights back, and only on the client that runs it. + /// + /// VANILLA DOES THE FIGHTING, this only decides when. Two things start a fight: a target the + /// MonsterAI already holds - which covers being hit, see NoteDamage - and an enemy inside + /// FightRange, found with BaseAI.FindClosestEnemy. That one is a static sweep of distance and + /// IsEnemy with no line of sight (IL), which is why the range is short. Either holds the fight + /// for FightLinger seconds, so the worker does not flicker between swinging and walking to the + /// chest on alternate ticks. + /// + /// The job is dropped, not the payload: whatever it was carrying stays in the ZDO, and the + /// first plan after the fight carries it on to where it was going. + /// + public bool HandsToVanilla() + { + if (!m_fightsBack || m_ai == null || m_character == null || m_character.IsDead()) return false; + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false; + + Character target = m_ai.GetTargetCreature(); + if (target != null && !target.IsDead()) + { + m_fightUntil = Time.time + FightLinger; + } + else if (Time.time >= m_nextFightScan) + { + m_nextFightScan = Time.time + FightScanInterval; + if (BaseAI.FindClosestEnemy(m_character, transform.position, FightRange) != null) + { + m_fightUntil = Time.time + FightLinger; + } + } + + if (Time.time >= m_fightUntil) return false; + + m_job = null; + m_nextPlan = 0f; // the fight moved it; plan afresh the moment it hands back + SetStatus("Fighting."); + return true; + } + + // ================================================================ the tick + + /// Everything. Returns what MonsterAI.UpdateAI would have returned. + public bool Tick(float dt) + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false; + if (m_character == null || m_character.IsDead()) return false; + + if (TickWither()) return true; + + if (Time.time < m_fleeUntil) + { + SetStatus("Driven off."); + GoHome(dt); + return true; + } + + if (Time.time >= m_nextPlan) + { + m_nextPlan = Time.time + PlanInterval; + Plan(); + } + + Execute(dt); + return true; + } + + /// + /// The table is gone: start the clock, and stop when it runs out. Same shape as RaisedThrall's, + /// and deliberately only asked near home - further out the table's zone is simply not loaded, so + /// "nothing there" would be a lie. + /// + private bool TickWither() + { + Vector3? anchor = Anchor; + if (anchor == null || ZNet.instance == null) return false; + + long stamp = m_nview.GetZDO().GetLong(KeyOrphanAt, 0L); + + if (stamp == 0L) + { + if (Vector3.SqrMagnitude(transform.position - anchor.Value) > + HomeCheckRange * HomeCheckRange) return false; + if (RaisedThrall.StationStandsAt(anchor.Value)) return false; + + m_nview.GetZDO().Set(KeyOrphanAt, ZNet.instance.GetTime().Ticks); + return false; + } + + if (RaisedThrall.StationStandsAt(anchor.Value)) + { + m_nview.GetZDO().Set(KeyOrphanAt, 0L); + return false; + } + + double elapsed = (ZNet.instance.GetTime() - new System.DateTime(stamp)).TotalSeconds; + if (elapsed < WitherSeconds) return false; + + HitData hit = new HitData(); + hit.m_damage.m_damage = 1E+10f; + hit.m_hitType = HitData.HitType.Undefined; + m_character.ApplyDamage(hit, true, false); + return true; + } + + // ================================================================ planning + + private void Plan() + { + Vector3? anchor = Anchor; + if (anchor == null) { m_job = null; return; } + + Scan(anchor.Value); + ExpirePenalties(); + + // A harvest is in progress: wait for the drops to land, then gather them and replant. + if (m_farmSpot != null) + { + m_job = Time.time < m_farmReadyAt + ? new Job { Kind = "wait", Point = transform.position, Label = "Waiting" } + : new Job { Kind = "farm_finish", Point = m_farmSpot.Value, Label = "Gathering" }; + return; + } + + if (m_payload.Count > 0) { m_job = PlanDelivery(anchor.Value); return; } + + // The forge has no clock: a smelter holds its ore indefinitely and puts its own output on + // the floor, so PlanRescue would ask a question whose answer is always no. The smith is a + // four-state machine and the cook is a five-state one, and that is the whole of the + // simplification the split bought. + // REFUEL BEFORE LOAD, and that order is the whole of the blast furnace fix. FreeSlots goes + // back above zero the instant a furnace eats one ore, so while there is scrap left in any + // chest PlanLoad always has an answer and PlanFuel, sitting behind it, never got a turn - + // the furnace was topped up forever and burned down to nothing. Fuel cannot starve loading + // in return, because FuelWanted is zero for a station with no work: an empty furnace asks + // for no coal, gets filled, and only then becomes worth stoking. + // One drone does both trades, so the burn protection is always on. Stations first, then the + // base: repairs, the fields, and last the tidying of the entry chest. + Job job = PlanRescue(); + job = job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad(); + job = job ?? PlanRepair(anchor.Value) ?? PlanFarm(anchor.Value) ?? PlanSort(); + + if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target)) + { + m_jobDeadline = Time.time + JobTimeout; + } + if (m_job != null && !ReferenceEquals(m_job, job)) Release(m_job.Claim); + if (job != null) Claim(job.Claim); + m_job = job; + } + + /// + /// Everything within the radius, once every planning tick. Piece.s_allPieces is the cheap way in + /// - it is the list the game already keeps of every built piece - so there is no OverlapSphere + /// and no guessing at layer masks for the part that runs constantly. + /// + private void Scan(Vector3 anchor) + { + if (Time.time - m_scannedAt < PlanInterval * 0.5f) return; + m_scannedAt = Time.time; + + m_stations.Clear(); + m_chests.Clear(); + m_damaged.Clear(); + m_entry = null; + m_wood = null; + + List pieces = AllPiecesField != null ? AllPiecesField.GetValue(null) as List : null; + if (pieces == null) return; + + float radius = AlfarNexusConfig.NexusRadius.Value + m_radiusBonus; + float radiusSq = radius * radius; + + for (int i = 0; i < pieces.Count; i++) + { + Piece piece = pieces[i]; + if (piece == null) continue; + if (Vector3.SqrMagnitude(piece.transform.position - anchor) > radiusSq) continue; + + // A station of the other trade is not this servant's business, but it is still not a + // chest - hence the continue either way. + // Both trades: the drone serves the smelters AND the kitchens. + ButlerStation station = ButlerStation.From(piece.gameObject); + if (station != null) + { + m_stations.Add(station); + continue; + } + + // Every chest in reach is the drone's, EXCEPT one holding the sigil. The two special + // chests are told apart by prefab name. + Container container = piece.GetComponent(); + if (container != null && !IsMarkedOff(container)) + { + string chestName = Utils.GetPrefabName(piece.gameObject); + if (chestName == AlfarChests.EntryName) m_entry = container; + else if (chestName == AlfarChests.WoodName) m_wood = container; + else m_chests.Add(container); + } + + // Anything damaged is for the drones to mend, towers and chests and walls alike. + WearNTear wear = piece.GetComponent(); + if (wear != null && wear.GetHealthPercentage() < 0.999f) m_damaged.Add(wear); + } + } + + /// + /// The sigil is INVERTED from the Butler's: it marks the chests the drones must NOT look at. A + /// chest in use by a player is left alone too. The sigil itself is never counted as material and + /// never carried away - see TakeFrom. + /// + private static bool IsMarkedOff(Container container) + { + if (container == null || container.IsInUse()) return true; + + Inventory inventory = container.GetInventory(); + if (inventory == null) return true; + + string sigil = SigilSharedName(); + return !string.IsNullOrEmpty(sigil) && inventory.CountItems(sigil) > 0; + } + + private static string s_sigilShared; + private static string s_sigilFor; + + /// Inventory.CountItems matches on the SHARED name ($item_...), not on the prefab name + /// the stations use, so the configured prefab is resolved once into the other kind of name. + private static string SigilSharedName() + { + string wanted = AlfarSigil.PrefabName; + if (s_sigilFor == wanted) return s_sigilShared; + + s_sigilFor = wanted; + s_sigilShared = null; + + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(wanted) : null; + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null) + { + s_sigilShared = drop.m_itemData.m_shared.m_name; + } + else + { + Jotunn.Logger.LogWarning($"[AlfarDrone] No item '{wanted}' to use as the sigil; " + + "no chest can be marked until that name is right."); + } + + return s_sigilShared; + } + + // ---------------------------------------------------------------- the five states + + /// 1. SAVE. A slot about to burn beats everything, and it is the only job it runs to. + private Job PlanRescue() + { + ButlerStation best = null; + float soonest = SpoilPanicSeconds; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.HasOutput) continue; // nothing pullable yet, panic changes nothing + + float left = station.SecondsToSpoil; + if (left >= soonest) continue; + + soonest = left; + best = station; + } + + if (best == null) return null; + + return new Job + { + Kind = "collect", + Target = best.Id, + Claim = best.Id, + Point = best.Position, + Hurry = true, + Label = "Saving the food", + }; + } + + /// 2. COLLECT. Anything finished, and anything already lying under a station. + private Job PlanCollect() + { + ButlerStation best = null; + float bestScore = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.HasOutput && !HasDropsNear(station.Position)) continue; + + float score = Vector3.Distance(transform.position, station.Position); + if (score >= bestScore) continue; + + bestScore = score; + best = station; + } + + if (best == null) return null; + + return new Job + { + Kind = "collect", + Target = best.Id, + Claim = best.Id, + Point = best.Position, + Label = "Collecting", + }; + } + + /// + /// 4. LOAD. Urgency, then distance - and the urgency of a station with nothing wrong with it is + /// how long it has been waiting. A metre of walking is worth four seconds of a station standing + /// idle, so the far furnace wins eventually instead of never. + /// + private Job PlanLoad() + { + ButlerStation best = null; + string bestItem = null; + Container bestChest = null; + float bestScore = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.Operable || station.FreeSlots <= 0) continue; + + Container chest; + string item = FindMaterialFor(station, out chest); + if (item == null) { m_idleSince.Remove(station.Id); continue; } + + float waited = NoteIdle(station.Id); + float score = Vector3.Distance(transform.position, chest.transform.position) + + Vector3.Distance(chest.transform.position, station.Position) - + waited * WaitToMetres; + + if (score >= bestScore) continue; + + bestScore = score; + best = station; + bestItem = item; + bestChest = chest; + } + + if (best == null) return null; + + // The chest first - the station is where the payload goes afterwards, and PlanDelivery + // works that out from the target written on the load. + return new Job + { + Kind = "load", + Target = ZdoOf(bestChest), + Claim = best.Id, + Point = bestChest.transform.position, + Label = "Fetching " + bestItem, + }; + } + + /// + /// 3. REFUEL. Only stations that actually have something to work on. + /// + /// Scored by the walk, the same way PlanLoad is, and for a reason that only appeared once this + /// moved up the list: taking the first station in scan order was harmless while refuelling was + /// the job of last resort, but ahead of loading it lets one furnace at the edge of the circle + /// hold the servant while a cold one two metres away waits. + /// + private Job PlanFuel() + { + Container bestChest = null; + string bestFuel = null; + float bestScore = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.Operable) continue; + + int wanted = station.FuelWanted; + if (wanted <= 0) continue; + + string fuel = station.FuelPrefab; + if (string.IsNullOrEmpty(fuel)) continue; + + Container chest = FindChestWith(fuel); + if (chest == null) continue; + + float score = Vector3.Distance(transform.position, chest.transform.position) + + Vector3.Distance(chest.transform.position, station.Position); + if (score >= bestScore) continue; + + bestScore = score; + bestChest = chest; + bestFuel = fuel; + } + + if (bestChest == null) return null; + + return new Job + { + Kind = "fuel", + Target = ZdoOf(bestChest), + Point = bestChest.transform.position, + Label = "Fetching " + bestFuel, + }; + } + + /// Where the load in hand is going: on to its station, or back into a chest. + private Job PlanDelivery(Vector3 anchor) + { + // A sorting trip has a destination chosen at the entry chest: take it there. + ZDOID dest = m_nview.GetZDO().GetZDOID(KeyDest); + if (dest != ZDOID.None) + { + Container destination = ContainerById(dest); + if (destination != null && !IsMarkedOff(destination) && !IsPenalised(dest) && HasRoomFor(destination)) + { + return new Job + { + Kind = "deposit", + Target = dest, + Point = destination.transform.position, + Label = "Sorting " + Describe(), + }; + } + m_nview.GetZDO().Set(KeyDest, ZDOID.None); + } + + ZDOID target = m_nview.GetZDO().GetZDOID(KeyTarget); + if (target != ZDOID.None) + { + // NO FreeSlots CHECK HERE, and that was the first bug found in play: fuel does not go + // into a slot. A furnace filled to m_maxOre with copper has FreeSlots 0 and still wants + // coal, so gating the delivery on free slots sent the servant back to the chest with + // the coal it had just fetched - and then PlanFuel sent it out for the same coal again, + // forever. AcceptsAnything already asks the right question of both doors. + ButlerStation station = StationById(target); + if (station != null && station.Alive && station.Operable && AcceptsAnything(station)) + { + return new Job + { + Kind = "deposit_station", + Target = target, + Point = station.Position, + Label = "Loading " + Describe(), + }; + } + + // The station is gone, full or cold. The goods are ours to put back, not to hold. + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + } + + Container chest = ChestForProduct(); + if (chest != null) + { + return new Job + { + Kind = "deposit", + Target = ZdoOf(chest), + Point = chest.transform.position, + Label = "Storing " + Describe(), + }; + } + + // Every sealed chest is full - but a chest is not the only place a thing can go. A station + // that BURNS what is in hand is a destination too, and for the smith it is usually the + // right one: the charcoal kiln releases its whole batch in one go (verified in the IL - + // UpdateSmelter only calls SpawnProcessed once the ore queue empties), which is exactly the + // delivery a nearly full chest cannot absorb, and the coal it makes is what the furnace + // beside it is waiting for. Offering the load to a consumer before giving up is what turns + // "nowhere to put 20x Coal" into a full blast furnace. + // + // It comes AFTER the chest and not before, so a product still goes home to the chest that + // paid for it whenever there is room; this is the step before the floor, not instead of + // storing. + ButlerStation consumer = StationWanting(); + if (consumer != null) + { + return new Job + { + Kind = "deposit_station", + Target = consumer.Id, + Point = consumer.Position, + Label = "Loading " + Describe(), + }; + } + + // Nothing will take it. Beside the table it goes: a stalled chain is worse than a tidy + // floor, and nothing may vanish (sec. 7.3). + return new Job + { + Kind = "drop", + Target = ZDOID.None, + Point = anchor, + Label = "Nowhere to put " + Describe(), + }; + } + + /// The nearest station that will take something out of the payload, as material or as + /// fuel. No FreeSlots check, for the reason spelled out above the KeyTarget branch: fuel does + /// not go into a slot, and AcceptsAnything already asks the right question of both doors. + private ButlerStation StationWanting() + { + ButlerStation best = null; + float bestDistance = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.Operable || !AcceptsAnything(station)) continue; + + float distance = Vector3.Distance(transform.position, station.Position); + if (distance >= bestDistance) continue; + + bestDistance = distance; + best = station; + } + + return best; + } + + // ================================================================ execution + + private void Execute(float dt) + { + if (m_job == null) + { + SetStatus(m_stations.Count == 0 ? "Nothing to serve." : "Nothing to do."); + GoHome(dt); + return; + } + + SetStatus(m_job.Label); + + if (!MoveToPoint(dt, m_job.Point, ArriveDistance, m_job.Hurry)) + { + // Doors do not open for pathfinding. A target it cannot reach goes into the penalty box + // and the servant gets on with something it can do. + if (Time.time > m_jobDeadline) + { + Penalise(m_job.Target); + Jotunn.Logger.LogInfo($"[AlfarDrone] Could not reach {m_job.Kind} target; " + + "setting it aside for a few minutes."); + m_job = null; + m_nextPlan = 0f; + } + return; + } + + bool achieved; + switch (m_job.Kind) + { + case "load": achieved = DoLoad(); break; + case "fuel": achieved = DoFuel(); break; + case "collect": achieved = DoCollect(); break; + case "deposit_station": achieved = DoDepositStation(); break; + case "deposit": achieved = DoDeposit(); break; + case "drop": DropPayload(); achieved = true; break; + case "wait": achieved = true; break; + case "repair": achieved = DoRepair(); break; + case "farm": achieved = DoFarm(); break; + case "farm_finish": achieved = DoFarmFinish(); break; + case "sortfetch": achieved = DoSortFetch(); break; + default: achieved = true; break; + } + + // Arrived and nothing happened: the world moved while it walked. Set that target aside for + // twenty seconds so the next plan picks something else instead of re-deciding the same + // errand on every tick. + if (!achieved) PenaliseShort(m_job.Target); + + m_job = null; + m_nextPlan = 0f; // arriving changes the world; re-plan on the next tick rather than in 1.5 s + } + + /// At the chest: take what the chosen station will eat, and remember where it came from. + private bool DoLoad() + { + Container chest = ContainerById(m_job.Target); + if (chest == null) return false; + + // The station is chosen again here rather than carried on the job, because the walk took + // time and the world may have moved on. + ButlerStation station = null; + string item = null; + + foreach (ButlerStation candidate in m_stations) + { + if (!candidate.Alive || !candidate.Operable || candidate.FreeSlots <= 0) continue; + if (IsPenalised(candidate.Id)) continue; + + string found = FirstAccepted(candidate, chest); + if (found == null) continue; + + station = candidate; + item = found; + break; + } + + if (station == null || item == null) return false; + + int taken = TakeFrom(chest, item, station.FreeSlots); + if (taken <= 0) return false; + + AddToPayload(item, taken); + m_nview.GetZDO().Set(KeySource, ZdoOf(chest)); + m_nview.GetZDO().Set(KeyTarget, station.Id); + WritePayload(); + return true; + } + + /// At the chest, for fuel. Same shape as DoLoad, and kept separate because fuel goes in + /// through a different door and is never the thing being processed. + private bool DoFuel() + { + Container chest = ContainerById(m_job.Target); + if (chest == null) return false; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || !station.Operable || IsPenalised(station.Id)) continue; + + int wanted = station.FuelWanted; + string fuel = station.FuelPrefab; + if (wanted <= 0 || string.IsNullOrEmpty(fuel)) continue; + + int taken = TakeFrom(chest, fuel, wanted); + if (taken <= 0) continue; + + AddToPayload(fuel, taken); + m_nview.GetZDO().Set(KeySource, ZdoOf(chest)); + m_nview.GetZDO().Set(KeyTarget, station.Id); + WritePayload(); + return true; + } + + return false; + } + + /// + /// At a station with something finished. Pull first, sweep second - and the sweep is the only + /// place the servant ever picks anything up off the ground, which is what keeps it from tidying + /// away things the player left lying about on purpose. + /// + /// THE ORDER IS THE POINT, and it used to be the other way round. Sweeping first meant every + /// visit collected what the LAST visit had thrown on the floor and then threw a fresh one down; + /// since Plan() hands the servant to PlanDelivery the moment it is carrying anything, it walked + /// off to the chest the instant the sweep landed and abandoned the item it had just pulled. + /// While a hearth kept working there was therefore always exactly one cooked meat lying on the + /// ground - the "loses one per batch, whether that is two or five" the testers reported. + /// + /// The loop is the other half of it. RPC_RemoveDoneItem empties ONE slot per call, so a hearth + /// with five done slots needs five calls; one per visit turned one batch into five round trips + /// to the chest. It runs against OutputPulls rather than against HasOutput alone because the + /// fermenter's Ready survives its own tap for the length of the animation. + /// + private bool DoCollect() + { + ButlerStation station = StationById(m_job.Target); + if (station == null || !station.Alive) return false; + + bool pulled = false; + for (int i = 0; i < station.OutputPulls && station.HasOutput; i++) + { + station.PullOutput(transform.position); + pulled = true; + } + + int before = PayloadCount(); + SweepDrops(station.Position); + bool swept = PayloadCount() > before; + + if (swept) + { + // The product belongs to whoever fed the station. If nothing was written there - the + // player loaded it by hand - it goes to the nearest sealed chest instead, which is the + // "yes, it collects your work too" decision paying its own way. + ZDOID fedBy = station.Nview.GetZDO().GetZDOID(KeyFedBy); + m_nview.GetZDO().Set(KeySource, fedBy); + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + WritePayload(); + } + + return swept || pulled; + } + + /// At the station, with raw material in hand. + private bool DoDepositStation() + { + ButlerStation station = StationById(m_job.Target); + if (station == null || !station.Alive || !station.Operable) return false; + + bool loadedAny = false; + + for (int i = m_payload.Count - 1; i >= 0; i--) + { + Load load = m_payload[i]; + + while (load.Count > 0 && station.FreeSlots > 0 && station.Accepts(load.Name)) + { + station.Add(load.Name); + load.Count--; + loadedAny = true; + } + + // Fuel goes in through its own door, and only for as long as it is wanted. + if (load.Count > 0 && load.Name == station.FuelPrefab) + { + int wanted = station.FuelWanted; + while (load.Count > 0 && wanted > 0) + { + station.AddFuel(); + load.Count--; + wanted--; + loadedAny = true; + } + } + + if (load.Count <= 0) m_payload.RemoveAt(i); + } + + if (loadedAny) + { + // Whoever fed it, gets it back. + ZDOID source = m_nview.GetZDO().GetZDOID(KeySource); + if (source != ZDOID.None && station.Nview.IsValid()) + { + if (!station.Nview.IsOwner()) station.Nview.ClaimOwnership(); + station.Nview.GetZDO().Set(KeyFedBy, source); + } + } + + if (m_payload.Count == 0) m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + WritePayload(); + return loadedAny; + } + + /// At a chest, with the finished goods. + private bool DoDeposit() + { + Container chest = ContainerById(m_job.Target); + if (chest == null) return false; + + ZNetView nview = chest.GetComponent(); + if (nview == null || !nview.IsValid()) return false; + if (!nview.IsOwner()) nview.ClaimOwnership(); + + Inventory inventory = chest.GetInventory(); + if (inventory == null) return false; + + bool wrote = false; + + for (int i = m_payload.Count - 1; i >= 0; i--) + { + Load load = m_payload[i]; + + GameObject prefab = ObjectDB.instance != null + ? ObjectDB.instance.GetItemPrefab(load.Name) + : null; + if (prefab == null) continue; + + // One at a time: it stacks correctly, it stops exactly when the chest is full, and the + // counts are small enough that being tidy costs nothing. + while (load.Count > 0 && inventory.CanAddItem(prefab, 1) && inventory.AddItem(prefab, 1)) + { + load.Count--; + wrote = true; + } + + if (load.Count <= 0) m_payload.RemoveAt(i); + } + + if (wrote && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(chest, null); + WritePayload(); + + // Still holding something: that chest is full, so do not choose it again on the next pass. + if (m_payload.Count > 0) Penalise(m_job.Target); + else m_nview.GetZDO().Set(KeyDest, ZDOID.None); + return wrote; + } + + // ================================================================ claims + + // Two drones must not take the same station or chest in the same moment. The Butler forbids a + // second table nearby; with N drones to a Nexus that is impossible, so the choice is made + // visible between them: a target is CLAIMED by the drone that picked it for a short while. This + // is the local-client form of the dispatcher the design asks for; two clients owning two + // drones still cannot see each other's claims (doc 17.14). + private static readonly Dictionary> s_claims = + new Dictionary>(); + private const float ClaimSeconds = 30f; + + private bool ClaimedByOther(ZDOID id) + { + if (id == ZDOID.None) return false; + KeyValuePair claim; + if (!s_claims.TryGetValue(id, out claim)) return false; + + if (claim.Key == null || Time.time >= claim.Value) { s_claims.Remove(id); return false; } + return claim.Key != this; + } + + private void Claim(ZDOID id) + { + if (id != ZDOID.None) s_claims[id] = new KeyValuePair(this, Time.time + ClaimSeconds); + } + + private void Release(ZDOID id) + { + KeyValuePair claim; + if (id != ZDOID.None && s_claims.TryGetValue(id, out claim) && claim.Key == this) s_claims.Remove(id); + } + + // ================================================================ repair + + /// + /// Anything damaged in the base, and any other drone that is hurt. Free, like the hammer. NOT the + /// constructs: their damage is permanent by design (they are Characters and not pieces, and + /// they are not drones, so they never come up here). + /// + private Job PlanRepair(Vector3 anchor) + { + WearNTear bestPiece = null; + AlfarDroneAI bestDrone = null; + float bestDistance = float.MaxValue; + + foreach (WearNTear wear in m_damaged) + { + if (wear == null) continue; + ZDOID id = ZdoOf(wear); + if (IsPenalised(id) || ClaimedByOther(id)) continue; + + float distance = Vector3.Distance(transform.position, wear.transform.position); + if (distance >= bestDistance) continue; + bestDistance = distance; + bestPiece = wear; + } + + foreach (AlfarDroneAI other in All) + { + if (other == null || other == this || other.m_character == null || other.m_character.IsDead()) continue; + if (other.m_character.GetHealth() >= other.m_character.GetMaxHealth() - 0.5f) continue; + if (Vector3.Distance(other.transform.position, anchor) > AlfarNexusConfig.NexusRadius.Value) continue; + + ZDOID id = ZdoOf(other); + if (IsPenalised(id) || ClaimedByOther(id)) continue; + + float distance = Vector3.Distance(transform.position, other.transform.position); + if (distance >= bestDistance) continue; + bestDistance = distance; + bestDrone = other; + bestPiece = null; + } + + if (bestPiece != null) + { + ZDOID id = ZdoOf(bestPiece); + return new Job { Kind = "repair", Target = id, Claim = id, Point = bestPiece.transform.position, Label = "Repairing" }; + } + if (bestDrone != null) + { + ZDOID id = ZdoOf(bestDrone); + return new Job { Kind = "repair", Target = id, Claim = id, Point = bestDrone.transform.position, Label = "Mending a drone" }; + } + return null; + } + + private bool DoRepair() + { + if (ZNetScene.instance == null) return false; + + GameObject go = ZNetScene.instance.FindInstance(m_job.Target); + if (go == null) return false; + + WearNTear wear = go.GetComponent(); + if (wear != null) return wear.Repair(); + + Character character = go.GetComponent(); + if (character != null && !character.IsDead() && go.GetComponent() != null) + { + character.Heal(character.GetMaxHealth(), true); + return true; + } + return false; + } + + // ================================================================ farming + + private class PlantInfo + { + public GameObject Sapling; // the piece that grows the plant + public string Item; // the item that piece costs, and so the item to put back + } + + // pickable prefab name -> the sapling that grows it and the item that sapling costs + private static readonly Dictionary s_plants = new Dictionary(); + private static bool s_plantsBuilt; + private static float s_pickScanAt = -99f; + private static readonly List s_pickables = new List(); + private static readonly System.Reflection.FieldInfo PickedField = AccessTools.Field(typeof(Pickable), "m_picked"); + + /// + /// Built from the game, not from a list: every Plant in ZNetScene names the pickable it grows + /// into and costs one of an item through its Piece. The drone ONLY works plants it can put back + /// (rule R2): it never harvests something it could not replant. + /// + private static void BuildPlants() + { + if (s_plantsBuilt || ZNetScene.instance == null) return; + s_plantsBuilt = true; + + foreach (GameObject prefab in ZNetScene.instance.m_prefabs) + { + if (prefab == null) continue; + + Plant plant = prefab.GetComponent(); + Piece piece = prefab.GetComponent(); + if (plant == null || piece == null || plant.m_grownPrefabs == null) continue; + if (piece.m_resources == null || piece.m_resources.Length == 0 || piece.m_resources[0].m_resItem == null) continue; + + string item = piece.m_resources[0].m_resItem.gameObject.name; + foreach (GameObject grown in plant.m_grownPrefabs) + { + if (grown != null && !s_plants.ContainsKey(grown.name)) + { + s_plants[grown.name] = new PlantInfo { Sapling = prefab, Item = item }; + } + } + } + Jotunn.Logger.LogInfo($"[AlfarDrone] {s_plants.Count} replantable crops known."); + } + + private static void RefreshPickables() + { + if (Time.time - s_pickScanAt < 4f) return; + s_pickScanAt = Time.time; + + s_pickables.Clear(); + s_pickables.AddRange(Object.FindObjectsByType(FindObjectsSortMode.None)); + } + + private static bool IsPicked(Pickable pickable) + { + return PickedField != null && (bool)PickedField.GetValue(pickable); + } + + /// Does picking it give back the item the sapling costs? + private static bool Yields(Pickable pickable, string item) + { + if (pickable.m_itemPrefab != null && pickable.m_itemPrefab.name == item) return true; + + if (pickable.m_extraDrops != null && pickable.m_extraDrops.m_drops != null) + { + foreach (DropTable.DropData drop in pickable.m_extraDrops.m_drops) + { + if (drop.m_item != null && drop.m_item.name == item) return true; + } + } + return false; + } + + private static string[] s_wild; + private static bool IsWildTarget(string prefabName) + { + if (s_wild == null) s_wild = AlfarNexusConfig.WildPickables.Value.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries); + foreach (string part in s_wild) + { + if (prefabName.IndexOf(part.Trim(), System.StringComparison.OrdinalIgnoreCase) >= 0) return true; + } + return false; + } + + /// + /// FARMING, with the iron rule (doc 9.4): a cultivated plant is harvested only if the drone can + /// replant one of what it gives; the replant is made RIGHT AWAY, in the SAME place, out of what + /// was just picked, and the rest is stored. Wild mushrooms, berry bushes and flowers on the list + /// are picked and NOT replanted (they grow back by themselves, and trees are never touched). + /// + private Job PlanFarm(Vector3 anchor) + { + BuildPlants(); + RefreshPickables(); + + float radius = AlfarNexusConfig.NexusRadius.Value; + Pickable best = null; + PlantInfo bestInfo = null; + float bestDistance = float.MaxValue; + + foreach (Pickable pickable in s_pickables) + { + if (pickable == null || !pickable.gameObject.activeInHierarchy) continue; + if (Vector3.Distance(pickable.transform.position, anchor) > radius) continue; + if (IsPicked(pickable)) continue; + + ZDOID id = ZdoOf(pickable); + if (id == ZDOID.None || IsPenalised(id) || ClaimedByOther(id)) continue; + + string name = Utils.GetPrefabName(pickable.gameObject); + PlantInfo info = null; + + if (pickable.m_respawnTimeMinutes > 0f) + { + if (!IsWildTarget(name)) continue; // wild and regrowing: only the listed ones + } + else + { + if (!s_plants.TryGetValue(name, out info) || !Yields(pickable, info.Item)) continue; + } + + float distance = Vector3.Distance(transform.position, pickable.transform.position); + if (distance >= bestDistance) continue; + + bestDistance = distance; + best = pickable; + bestInfo = info; + } + + if (best == null) return null; + + m_farmInfo = bestInfo; + ZDOID target = ZdoOf(best); + return new Job { Kind = "farm", Target = target, Claim = target, Point = best.transform.position, Label = "Harvesting" }; + } + + private bool DoFarm() + { + if (ZNetScene.instance == null) return false; + + GameObject go = ZNetScene.instance.FindInstance(m_job.Target); + Pickable pickable = go != null ? go.GetComponent() : null; + if (pickable == null || IsPicked(pickable)) return false; + + Humanoid hands = m_character as Humanoid; + if (hands == null) return false; + + Vector3 spot = pickable.transform.position; + Quaternion rot = pickable.transform.rotation; + + if (!pickable.Interact(hands, false, false)) return false; + + m_farmSpot = spot; + m_farmRot = rot; + m_farmReadyAt = Time.time + 0.8f; // the drops need a moment to land + return true; + } + + private bool DoFarmFinish() + { + Vector3? spot = m_farmSpot; + PlantInfo info = m_farmInfo; + m_farmSpot = null; + m_farmInfo = null; + if (spot == null) return false; + + SweepDrops(spot.Value); + + if (info != null) + { + // R6: the replant comes OUT OF what was just picked, never out of anyone's stock. + bool have = false; + foreach (Load load in m_payload) + { + if (load.Name == info.Item && load.Count > 0) { load.Count--; have = true; break; } + } + m_payload.RemoveAll(l => l.Count <= 0); + WritePayload(); + + if (have && info.Sapling != null) + { + Object.Instantiate(info.Sapling, spot.Value, m_farmRot); + } + else + { + Jotunn.Logger.LogWarning($"[AlfarDrone] Harvested a crop but found no '{info.Item}' to put back."); + } + } + + m_nview.GetZDO().Set(KeySource, ZDOID.None); + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + return true; + } + + // ================================================================ sorting + + private bool AnyStationAccepts(string prefabName) + { + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || !station.Operable) continue; + if (station.Accepts(prefabName) || prefabName == station.FuelPrefab) return true; + } + return false; + } + + /// The storage chest that already holds this item and has room; else the first EMPTY one. + private Container DestinationFor(string prefabName) + { + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null; + if (prefab == null) return null; + + Container firstEmpty = null; + foreach (Container chest in m_chests) + { + if (chest == null || chest.IsInUse()) continue; + + ZDOID id = ZdoOf(chest); + if (IsPenalised(id) || ClaimedByOther(id)) continue; + + Inventory inventory = chest.GetInventory(); + if (inventory == null || !inventory.CanAddItem(prefab, 1)) continue; + + if (inventory.GetAllItems().Count == 0) + { + if (firstEmpty == null) firstEmpty = chest; + continue; + } + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == prefabName) return chest; + } + } + return firstEmpty; + } + + /// + /// Tidying the entry chest, last of all. What a station will take is the WORK QUEUE and stays; the + /// rest (and any wood, which is stock unless it is in the wood chest) goes to the chest that + /// already holds the same thing, or to an empty one. With nowhere to go it stays where it is. + /// + private Job PlanSort() + { + if (m_entry == null || m_entry.IsInUse()) return null; + + ZDOID entryId = ZdoOf(m_entry); + if (IsPenalised(entryId)) return null; + + Inventory inventory = m_entry.GetInventory(); + if (inventory == null) return null; + + string sigil = AlfarSigil.PrefabName; + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item == null || item.m_dropPrefab == null) continue; + + string name = item.m_dropPrefab.name; + if (name == sigil) continue; + if (!IsWood(name) && AnyStationAccepts(name)) continue; + + Container destination = DestinationFor(name); + if (destination == null) continue; + + m_sortItem = name; + m_sortDest = ZdoOf(destination); + return new Job + { + Kind = "sortfetch", + Target = entryId, + Claim = m_sortDest, + Point = m_entry.transform.position, + Label = "Sorting " + name, + }; + } + return null; + } + + private bool DoSortFetch() + { + if (m_sortItem == null || m_sortDest == ZDOID.None) return false; + + Container entry = ContainerById(m_job.Target); + if (entry == null) return false; + + int taken = TakeFrom(entry, m_sortItem, 40); + if (taken <= 0) return false; + + AddToPayload(m_sortItem, taken); + m_nview.GetZDO().Set(KeyDest, m_sortDest); + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + WritePayload(); + return true; + } + + // ================================================================ moving + + /// Vanilla pathing, through the private MoveTo. True the moment it has arrived. + private bool MoveToPoint(float dt, Vector3 point, float distance, bool run) + { + if (m_ai == null || MoveToMethod == null) return true; // cannot walk: act in place + + m_moveArgs[0] = dt; + m_moveArgs[1] = point; + m_moveArgs[2] = distance; + m_moveArgs[3] = run; + + return (bool)MoveToMethod.Invoke(m_ai, m_moveArgs); + } + + private void GoHome(float dt) + { + Vector3? anchor = Anchor; + if (anchor == null) + { + if (m_ai != null) m_ai.StopMoving(); + return; + } + + MoveToPoint(dt, anchor.Value, m_homeDistance, false); + } + + // ================================================================ the ground + + private static int ItemMask() + { + if (s_itemMask >= 0) return s_itemMask; + + int mask = LayerMask.GetMask("item"); + s_itemMask = mask != 0 ? mask : ~0; + return s_itemMask; + } + + private bool HasDropsNear(Vector3 point) + { + Collider[] hits = Physics.OverlapSphere(point, CollectRadius, ItemMask()); + foreach (Collider hit in hits) + { + if (hit == null) continue; + ItemDrop drop = hit.GetComponentInParent(); + if (drop != null && drop.m_itemData != null) return true; + } + return false; + } + + /// + /// Picks up everything lying around a station. The drop is destroyed and its contents become + /// entries in the virtual payload, which is the same road the smelter's bars, the oven's bread + /// and the fermenter's bottles all arrive by - one pickup routine for three families. + /// + private void SweepDrops(Vector3 point) + { + Collider[] hits = Physics.OverlapSphere(point, CollectRadius, ItemMask()); + + foreach (Collider hit in hits) + { + if (hit == null) continue; + if (PayloadCount() >= PayloadCap) return; + + ItemDrop drop = hit.GetComponentInParent(); + if (drop == null || drop.m_itemData == null) continue; + + ZNetView nview = drop.GetComponent(); + if (nview == null || !nview.IsValid()) continue; + if (!nview.IsOwner()) nview.ClaimOwnership(); + + string name = drop.m_itemData.m_dropPrefab != null + ? drop.m_itemData.m_dropPrefab.name + : Utils.GetPrefabName(drop.gameObject); + if (string.IsNullOrEmpty(name)) continue; + + AddToPayload(name, Mathf.Max(1, drop.m_itemData.m_stack)); + if (ZNetScene.instance != null) ZNetScene.instance.Destroy(drop.gameObject); + } + } + + /// + /// Puts the virtual load back into the world as real objects. Called when the servant dies and + /// when there is nowhere left to put anything - the two ends of the same promise, which is that + /// nothing the player owns is ever deleted by this feature. + /// + public void DropPayload() + { + if (m_payload.Count == 0) return; + if (ObjectDB.instance == null) { m_payload.Clear(); return; } + + Vector3 at = transform.position + Vector3.up * 0.4f; + + foreach (Load load in m_payload) + { + GameObject prefab = ObjectDB.instance.GetItemPrefab(load.Name); + ItemDrop template = prefab != null ? prefab.GetComponent() : null; + if (template == null || template.m_itemData == null) continue; + + int left = load.Count; + int max = Mathf.Max(1, template.m_itemData.m_shared.m_maxStackSize); + + while (left > 0) + { + int stack = Mathf.Min(left, max); + + // ItemDrop.DropItem instantiates item.m_dropPrefab - a clone off a raw ObjectDB + // prefab does not carry that (see AswidBloodPotions.MakeFood for the same fix). + // Without this, dropping a payload throws instantiating null and never clears + // it, so the same broken load is retried - and crashes - on every AI tick after. + ItemDrop.ItemData clone = template.m_itemData.Clone(); + clone.m_dropPrefab = prefab; + + ItemDrop.DropItem(clone, stack, + at + Random.insideUnitSphere * 0.3f, Quaternion.identity); + left -= stack; + } + } + + m_payload.Clear(); + WritePayload(); + } + + // ================================================================ chests + + /// + /// Takes up to of a prefab out of a chest. The sigil is skipped by name, + /// which is the one thing in here that must never be got wrong: carrying it off would unmark the + /// chest halfway through a job. + /// + private int TakeFrom(Container chest, string prefabName, int want) + { + if (chest == null || want <= 0) return 0; + if (prefabName == AlfarSigil.PrefabName) return 0; + + ZNetView nview = chest.GetComponent(); + if (nview == null || !nview.IsValid()) return 0; + if (!nview.IsOwner()) nview.ClaimOwnership(); + + Inventory inventory = chest.GetInventory(); + if (inventory == null) return 0; + + List matches = new List(); + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item == null || item.m_dropPrefab == null) continue; + if (item.m_dropPrefab.name != prefabName) continue; + matches.Add(item); + } + + int taken = 0; + foreach (ItemDrop.ItemData item in matches) + { + if (taken >= want) break; + + int amount = Mathf.Min(item.m_stack, want - taken); + if (amount <= 0) continue; + + inventory.RemoveItem(item, amount); + taken += amount; + } + + if (taken > 0 && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(chest, null); + return taken; + } + + // The wood that may be burnt. Only the wood chest's wood is ever consumed: the same wood in the + // entry chest is stock to be sorted, never fuel or charcoal. + private static readonly HashSet s_woodFamily = new HashSet + { + "Wood", "FineWood", "RoundLog", "ElderBark", "YggdrasilWood", "Blackwood", + }; + + private static bool IsWood(string prefabName) => s_woodFamily.Contains(prefabName); + + /// + /// The first thing a station will take, and the chest it is in: raw material from the ENTRY chest + /// (never its wood), and wood only from the WOOD chest. + /// + private string FindMaterialFor(ButlerStation station, out Container chest) + { + foreach (Container candidate in new[] { m_entry, m_wood }) + { + if (candidate == null || candidate.IsInUse()) continue; + + string item = FirstAccepted(station, candidate); + if (item == null) continue; + + chest = candidate; + return item; + } + + chest = null; + return null; + } + + private string FirstAccepted(ButlerStation station, Container chest) + { + Inventory inventory = chest != null ? chest.GetInventory() : null; + if (inventory == null) return null; + + bool woodChest = chest == m_wood; + string sigil = AlfarSigil.PrefabName; + string fuel = station.FuelPrefab; + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item == null || item.m_dropPrefab == null) continue; + + string name = item.m_dropPrefab.name; + if (name == sigil) continue; + if (name == fuel) continue; // fuel has its own errand + if (IsWood(name) != woodChest) continue; // wood from the wood chest, the rest from the entry + if (!station.Accepts(name)) continue; + + return name; + } + + return null; + } + + /// Fuel: wood-type fuel from the wood chest, anything else (coal) from the entry chest. + private Container FindChestWith(string prefabName) + { + Container chest = IsWood(prefabName) ? m_wood : m_entry; + if (chest == null || chest.IsInUse()) return null; + + Inventory inventory = chest.GetInventory(); + if (inventory == null) return null; + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == prefabName) return chest; + } + return null; + } + + /// + /// Where the finished goods go: back to the ENTRY chest, which is both the inbox and the outbox; + /// they are sorted from there. If it is full, the nearest storage chest with room. + /// + private Container ChestForProduct() + { + if (m_entry != null && !m_entry.IsInUse() && !IsPenalised(ZdoOf(m_entry)) && HasRoomFor(m_entry)) return m_entry; + + Container best = null; + float bestDistance = float.MaxValue; + + foreach (Container chest in m_chests) + { + if (chest == null || chest.IsInUse()) continue; + if (IsPenalised(ZdoOf(chest))) continue; + if (!HasRoomFor(chest)) continue; + + float distance = Vector3.Distance(transform.position, chest.transform.position); + if (distance >= bestDistance) continue; + + bestDistance = distance; + best = chest; + } + + return best; + } + + private bool HasRoomFor(Container chest) + { + Inventory inventory = chest != null ? chest.GetInventory() : null; + if (inventory == null || ObjectDB.instance == null) return false; + + foreach (Load load in m_payload) + { + GameObject prefab = ObjectDB.instance.GetItemPrefab(load.Name); + if (prefab != null && inventory.CanAddItem(prefab, 1)) return true; + } + + return false; + } + + // ================================================================ payload + + private bool AcceptsAnything(ButlerStation station) + { + foreach (Load load in m_payload) + { + if (station.Accepts(load.Name)) return true; + if (load.Name == station.FuelPrefab && station.FuelWanted > 0) return true; + } + return false; + } + + private void AddToPayload(string name, int count) + { + if (string.IsNullOrEmpty(name) || count <= 0) return; + + foreach (Load load in m_payload) + { + if (load.Name != name) continue; + load.Count += count; + WritePayload(); + return; + } + + m_payload.Add(new Load { Name = name, Count = count }); + WritePayload(); + } + + private int PayloadCount() + { + int total = 0; + foreach (Load load in m_payload) total += load.Count; + return total; + } + + private string Describe() + { + if (m_payload.Count == 0) return "nothing"; + if (m_payload.Count == 1) return m_payload[0].Count + "x " + m_payload[0].Name; + + return PayloadCount() + " items"; + } + + /// "Copper:8;Coal:12". Small, readable in a ZDO dump, and enough to survive a handover + /// mid-job - which is the whole reason the payload lives in the ZDO instead of in this class. + private void WritePayload() + { + if (m_nview == null || !m_nview.IsValid()) return; + + StringBuilder builder = new StringBuilder(); + foreach (Load load in m_payload) + { + if (load.Count <= 0) continue; + if (builder.Length > 0) builder.Append(';'); + builder.Append(load.Name).Append(':').Append(load.Count); + } + + m_nview.GetZDO().Set(KeyLoad, builder.ToString()); + } + + private void ReadPayload() + { + m_payload.Clear(); + if (m_nview == null || !m_nview.IsValid()) return; + + string raw = m_nview.GetZDO().GetString(KeyLoad, ""); + if (string.IsNullOrEmpty(raw)) return; + + foreach (string entry in raw.Split(';')) + { + if (string.IsNullOrEmpty(entry)) continue; + + int split = entry.LastIndexOf(':'); + if (split <= 0) continue; + + int count; + if (!int.TryParse(entry.Substring(split + 1), out count) || count <= 0) continue; + + m_payload.Add(new Load { Name = entry.Substring(0, split), Count = count }); + } + } + + // ================================================================ small change + + private static ZDOID ZdoOf(Component component) + { + ZNetView nview = component != null ? component.GetComponent() : null; + return nview != null && nview.IsValid() ? nview.GetZDO().m_uid : ZDOID.None; + } + + private Container ContainerById(ZDOID id) + { + if (id == ZDOID.None || ZNetScene.instance == null) return null; + + GameObject go = ZNetScene.instance.FindInstance(id); + return go != null ? go.GetComponent() : null; + } + + private ButlerStation StationById(ZDOID id) + { + foreach (ButlerStation station in m_stations) + { + if (station.Id == id) return station; + } + + if (id == ZDOID.None || ZNetScene.instance == null) return null; + + GameObject go = ZNetScene.instance.FindInstance(id); + return go != null ? ButlerStation.From(go) : null; + } + + private void Penalise(ZDOID id) + { + if (id == ZDOID.None) return; + m_penalties[id] = Time.time + PenaltySeconds; + } + + /// Never shortens a penalty already running: a target set aside for three minutes + /// because it could not be reached must not be let back in after twenty seconds. + private void PenaliseShort(ZDOID id) + { + if (id == ZDOID.None) return; + + float until; + float wanted = Time.time + ShortPenaltySeconds; + if (m_penalties.TryGetValue(id, out until) && until > wanted) return; + + m_penalties[id] = wanted; + } + + private bool IsPenalised(ZDOID id) + { + float until; + return m_penalties.TryGetValue(id, out until) && Time.time < until; + } + + private void ExpirePenalties() + { + if (m_penalties.Count == 0) return; + + List done = null; + foreach (KeyValuePair entry in m_penalties) + { + if (Time.time < entry.Value) continue; + if (done == null) done = new List(); + done.Add(entry.Key); + } + + if (done == null) return; + foreach (ZDOID id in done) m_penalties.Remove(id); + } + + /// Seconds this station has been waiting with work available. + private float NoteIdle(ZDOID id) + { + float since; + if (!m_idleSince.TryGetValue(id, out since)) + { + m_idleSince[id] = Time.time; + return 0f; + } + + return Time.time - since; + } + } + + /// + /// The whole of the servant's mind, in one prefix. + /// + /// Returning false skips MonsterAI.UpdateAI entirely - targeting, alerting, fleeing, wandering and + /// attacking with it - so the servant is peaceful by construction rather than by having its weapon + /// confiscated. __result is legitimate here and not the old PlacePiece trap: that one threw because + /// the patched method was VOID. This one returns bool, which is exactly what a prefix may write. + /// + /// Bound positionally (__0) so a parameter rename in a future patch cannot stop the mod from + /// applying its patches at startup. + /// + [HarmonyPatch(typeof(MonsterAI), "UpdateAI")] + public static class AlfarDroneUpdateAIPatch + { + public static bool Prefix(MonsterAI __instance, float __0, ref bool __result) + { + if (__instance == null) return true; + + AlfarDroneAI servant = __instance.GetComponent(); + if (servant == null) return true; + + // The one way back into vanilla: a servant that fights back hands over the whole tick for + // as long as there is a fight. Always false for the Bone Servants themselves. + if (servant.HandsToVanilla()) return true; + + __result = servant.Tick(__0); + return false; + } + } + + /// Hit and it walks home. The same postfix shape the sentry's regeneration uses, on the + /// same method, which is a shape known to work in this project. + [HarmonyPatch(typeof(Character), "Damage")] + public static class AlfarDroneDamagePatch + { + public static void Postfix(Character __instance) + { + if (__instance == null) return; + + AlfarDroneAI servant = __instance.GetComponent(); + if (servant != null) servant.NoteDamage(); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarDrones.cs b/JotunnModStub/Alfar/AlfarDrones.cs new file mode 100644 index 0000000..7cef524 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarDrones.cs @@ -0,0 +1,365 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The LJOSVAETTIR, the Alfar's drones (Alfar_Progettazione.txt sec. 9): a Deathsquito without legs, + /// stinger or buzz, bronze, with blue light. One kind of drone does every job (the work itself is + /// AlfarDroneWork); the only thing apart is the GRAFVAETTIR, the same creature thrown like a + /// grenade to dig the precious ores around a point for two minutes and then vanish. + /// + /// What a drone is by itself: 25 hp and a shield of 25, tamed, tied to its Ljoskjarne, and able to + /// defend itself with a lightning zap of 1 damage every two seconds. It never attacks anything + /// outside the Nexus's radius and never goes after anything: it is a worker, not a soldier. + /// + /// The Deathsquito is ONE skinned mesh with one material (probe, doc 16C P1): the legs are bones, so + /// they are hidden by scaling the bones to zero, and the blue is an emission on a bronze body, not + /// separate eyes and wings - a true repaint is still to do. + /// + public static class AlfarDrones + { + public const string DroneName = "AlfarDrone"; + public const string MinerName = "AlfarGrafvaettir"; + public const string ZapWeapon = "AlfarDroneZap"; + + private static readonly Color Bronze = new Color(1f, 0.62f, 0.25f, 1f); + private static readonly Color ElectricBlue = new Color(0.25f, 0.65f, 1f, 1f); + + public static void Register() + { + GameObject source = PrefabManager.Cache.GetPrefab("Deathsquito"); + if (source == null) + { + Jotunn.Logger.LogWarning("[Alfar] No 'Deathsquito' to build the drones from."); + return; + } + + bool zap = RegisterZap(source); + RegisterOne(source, DroneName, "$rov_creature_alfar_drone_name", zap, miner: false); + RegisterOne(source, MinerName, "$rov_creature_alfar_grafvaettir_name", zap, miner: true); + } + + /// The Deathsquito's sting turned into a zap: 1 lightning, every two seconds. + private static bool RegisterZap(GameObject deathsquito) + { + Humanoid humanoid = deathsquito.GetComponent(); + GameObject sting = humanoid != null && humanoid.m_defaultItems != null && humanoid.m_defaultItems.Length > 0 + ? humanoid.m_defaultItems[0] + : null; + if (sting == null) return false; + + GameObject weapon = PrefabManager.Instance.CreateClonedPrefab(ZapWeapon, sting); + if (weapon == null) return false; + + ItemDrop drop = weapon.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = "$rov_item_alfar_zap_name"; + + HitData.DamageTypes damage = default(HitData.DamageTypes); + damage.m_lightning = AlfarNexusConfig.DroneZapDamage.Value; + shared.m_damages = damage; + shared.m_aiAttackInterval = AlfarNexusConfig.DroneZapInterval.Value; + + ItemManager.Instance.AddItem(new CustomItem(weapon, fixReference: false)); + return true; + } + + private static void RegisterOne(GameObject source, string prefabName, string display, bool zap, bool miner) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source); + if (prefab == null) return; + + Character character = prefab.GetComponent(); + if (character != null) + { + character.m_name = display; + character.m_faction = Character.Faction.Players; + character.m_health = AlfarNexusConfig.DroneHealth.Value; + } + + Humanoid humanoid = prefab.GetComponent(); + if (humanoid != null) + { + GameObject weapon = zap ? PrefabManager.Instance.GetPrefab(ZapWeapon) : null; + // A miner does not fight at all; the worker only defends itself. + humanoid.m_defaultItems = !miner && weapon != null ? new[] { weapon } : new GameObject[0]; + humanoid.m_randomWeapon = new GameObject[0]; + humanoid.m_randomArmor = new GameObject[0]; + humanoid.m_randomShield = new GameObject[0]; + humanoid.m_randomSets = new Humanoid.ItemSet[0]; + } + + MonsterAI monster = prefab.GetComponent(); + if (monster != null) + { + monster.m_attackPlayerObjects = false; + monster.m_alertRange = AlfarNexusConfig.NexusRadius.Value; + monster.m_maxChaseDistance = AlfarNexusConfig.NexusRadius.Value; + } + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = 5f; + + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + // The buzz: the continuous sound child, and the flying loop effect. + foreach (Transform child in prefab.GetComponentsInChildren(true)) + { + if (child != null && child.name == "SFX") Object.DestroyImmediate(child.gameObject); + } + if (character != null) character.m_flyingContinuousEffect = new EffectList { m_effectPrefabs = new EffectList.EffectData[0] }; + + HideLegs(prefab); + Look(prefab); + prefab.AddComponent(); + + AlfarMark mark = prefab.AddComponent(); + mark.Role = miner ? "miner" : "drone"; + + AlfarCreatureShield shield = prefab.AddComponent(); + shield.MaxShield = AlfarNexusConfig.DroneHealth.Value; + shield.Shield = shield.MaxShield; + + if (miner) + { + // The mining drone has no anchor and no leash: it lives two minutes and vanishes. + prefab.AddComponent(); + } + else + { + // The worker is NOT a RaisedThrall: that brings the follow command on E, and a drone + // that can be walked out of the base stops working (the Butler's reasoning, Butler 9). + // AlfarDroneAI keeps its own anchor to the Nexus and its own wither. + AlfarDroneAI work = prefab.AddComponent(); + work.m_fightsBack = true; // it defends itself with the zap + work.m_homeDistance = 4f; + } + + PrefabManager.Instance.AddPrefab(prefab); + Jotunn.Logger.LogInfo($"[Alfar] Registered '{prefabName}'."); + } + + /// + /// No legs: the mesh is one skinned body, so the leg bones are scaled to zero and take their + /// part of the mesh with them. The stinger has no bone of its own and is left (doc 16C P1). + /// + private static void HideLegs(GameObject prefab) + { + foreach (Transform bone in prefab.GetComponentsInChildren(true)) + { + string n = bone.name; + if (n == "L.leg1" || n == "R.leg1") bone.localScale = Vector3.zero; + } + } + + private static void Look(GameObject prefab) + { + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + Material[] materials = renderer.materials; + foreach (Material material in materials) + { + if (material == null) continue; + if (material.HasProperty("_Color")) material.color = Bronze; + if (material.HasProperty("_EmissionColor")) + { + material.SetColor("_EmissionColor", ElectricBlue * 0.15f); + material.EnableKeyword("_EMISSION"); + } + } + renderer.materials = materials; + } + foreach (Light light in prefab.GetComponentsInChildren(true)) light.color = ElectricBlue; + } + + /// + /// The same look, applied to the LIVE body at spawn and re-applied after the animator every + /// frame for the bones: edits made on the registered clone may not reach the instance, and the + /// animator can write the leg scale back. + /// + public class AlfarDroneLook : MonoBehaviour + { + private Transform[] legs; + + private void Awake() + { + var list = new System.Collections.Generic.List(); + foreach (Transform bone in GetComponentsInChildren(true)) + { + if (bone.name == "L.leg1" || bone.name == "R.leg1") list.Add(bone); + } + legs = list.ToArray(); + Look(gameObject); + } + + private void LateUpdate() + { + foreach (Transform leg in legs) if (leg != null) leg.localScale = Vector3.zero; + } + } + + // ─── Counting and spawning ─────────────────────────────────────────── + + public static int CountAlive(Vector3 anchor) + { + int count = 0; + foreach (AlfarDroneAI drone in AlfarDroneAI.All) + { + if (drone != null && drone.IsBoundTo(anchor)) count++; + } + return count; + } + + public static bool Spawn(Vector3 anchor) + { + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(DroneName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Alfar] No '{DroneName}' in ZNetScene: no drone can be made."); + return false; + } + + Vector3 where = AlfarConstructs.SpawnSpot(anchor) + Vector3.up * 1.5f; + GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity); + AlfarDroneAI work = spawned != null ? spawned.GetComponent() : null; + if (work != null) work.Bind(anchor); + return spawned != null; + } + } + + /// + /// A MINING DRONE: thrown to a point, it digs the precious ores around that point for a fixed time + /// and then vanishes (design sec. 9.3). It takes over its own AI tick like the Butler's servants do + /// (a prefix on MonsterAI.UpdateAI), flies to the nearest deposit on the list and strikes it with + /// pickaxe damage at a tool tier high enough for any of them. The ore falls where it stands. + /// + /// Whatever it breaks is on the list in AlfarMiner.Deposits; a name list in the config so a + /// wrong or missing name is a config edit, not a rebuild. + /// + public class AlfarMiner : MonoBehaviour + { + public Vector3 Centre; + public float Radius = 12f; + public float LiveSeconds = 120f; + + private float born; + private float nextStrike; + private Component target; + + private static readonly System.Reflection.MethodInfo MoveToMethod = + AccessTools.Method(typeof(BaseAI), "MoveTo", new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) }); + + private void Start() + { + born = Time.time; + } + + public bool Tick(MonsterAI ai, float dt) + { + if (Time.time - born >= LiveSeconds) + { + ZNetView nview = GetComponent(); + if (nview != null && nview.IsValid() && nview.IsOwner()) ZNetScene.instance.Destroy(gameObject); + return true; + } + + if (target == null || !target.gameObject.activeInHierarchy) target = FindDeposit(); + if (target == null) { ai.StopMoving(); return true; } + + Vector3 point = target.transform.position; + float distance = Vector3.Distance(transform.position, point); + + if (distance > 3.5f) + { + if (MoveToMethod != null) MoveToMethod.Invoke(ai, new object[] { dt, point + Vector3.up * 1.5f, 2f, true }); + return true; + } + + ai.StopMoving(); + if (Time.time < nextStrike) return true; + nextStrike = Time.time + 1f; + Strike(target); + return true; + } + + private static string[] names; + private static string[] Deposits => names ?? (names = AlfarNexusConfig.MinerDeposits.Value.Split( + new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries)); + + private bool IsPrecious(string prefabName) + { + foreach (string wanted in Deposits) + { + if (prefabName.IndexOf(wanted.Trim(), System.StringComparison.OrdinalIgnoreCase) >= 0) return true; + } + return false; + } + + private Component FindDeposit() + { + Component best = null; + float bestDistance = float.MaxValue; + foreach (Collider collider in Physics.OverlapSphere(Centre, Radius, ~0, QueryTriggerInteraction.Ignore)) + { + Component deposit = collider.GetComponentInParent(); + if (deposit == null) deposit = collider.GetComponentInParent(); + if (deposit == null) deposit = collider.GetComponentInParent(); + if (deposit == null) continue; + + string prefabName = Utils.GetPrefabName(deposit.gameObject); + if (!IsPrecious(prefabName)) continue; + + float distance = Vector3.Distance(transform.position, deposit.transform.position); + if (distance < bestDistance) { best = deposit; bestDistance = distance; } + } + return best; + } + + private void Strike(Component deposit) + { + IDestructible destructible = deposit as IDestructible; + if (destructible == null) return; + + HitData hit = new HitData(); + hit.m_damage.m_pickaxe = AlfarNexusConfig.MinerDamage.Value; + hit.m_toolTier = 100; + hit.m_dodgeable = false; + hit.m_blockable = false; + hit.m_point = deposit.transform.position; + hit.m_dir = (deposit.transform.position - transform.position).normalized; + + // MineRock5 picks the piece of the rock to hurt from the collider that was hit. + Collider collider = deposit.GetComponentInChildren(); + if (collider != null) + { + hit.m_hitCollider = collider; + hit.m_point = collider.bounds.center; + } + + destructible.Damage(hit); + } + + [HarmonyPatch(typeof(MonsterAI), "UpdateAI")] + public static class Alfar_Miner_UpdateAI_Patch + { + public static bool Prefix(MonsterAI __instance, float __0, ref bool __result) + { + if (__instance == null) return true; + AlfarMiner miner = __instance.GetComponent(); + if (miner == null) return true; + + __result = miner.Tick(__instance, __0); + return false; + } + } + } +} diff --git a/JotunnModStub/Alfar/AlfarEitr.cs b/JotunnModStub/Alfar/AlfarEitr.cs new file mode 100644 index 0000000..5d79655 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarEitr.cs @@ -0,0 +1,166 @@ +using System.Reflection; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Alfar's one resource (Alfar_Progettazione.txt sec. 3, 4 and 5.1): food becomes eitr, and + /// eitr is the shield. + /// + /// Every signature and call order here was read from assembly_valheim.dll (doc sec. 16B V1-V4), + /// not remembered: + /// - Character.ApplyDamage is the single final stage for direct hits, burning and poison + /// ticks AND falls, so one prefix on it covers all three; + /// - Player.RPC_UseEitr spends eitr and arms the vanilla regeneration delay, which is the + /// only brake the shield has - writing m_eitr by hand would skip the delay; + /// - Player.GetTotalFoodValue is what UpdateFood hands to SetMaxEitr. + /// + public static class AlfarEitr + { + private static readonly MethodInfo UseEitrRpc = + AccessTools.Method(typeof(Player), "RPC_UseEitr", new[] { typeof(long), typeof(float) }); + + /// + /// Spends eitr WITHOUT Game.m_eitrRate scaling, so the rate is exactly the configured one. + /// UseEitr would multiply by the world modifier first; the RPC does not, and it is what + /// arms the regeneration delay (V3). + /// + public static void Spend(Player player, float amount) + { + if (player == null || amount <= 0f) return; + + if (UseEitrRpc == null) + { + Jotunn.Logger.LogWarning("[Alfar] Player.RPC_UseEitr not found: the shield cannot spend eitr."); + return; + } + UseEitrRpc.Invoke(player, new object[] { 0L, amount }); + } + + // ─── Diet ──────────────────────────────────────────────────────────── + + /// + /// Each food adds min(hp, stamina) to the maximum eitr, on top of the eitr it already has. + /// Clarified by the user: the minimum is between hp and stamina ONLY, so a plain cooked + /// meat (40 / 30 / 0) is worth +30 eitr and a balanced food is better than a lopsided one. + /// + /// Locally only: GetTotalFoodValue is the owner's own bookkeeping. Positional parameters + /// (guide 5.16): __0 hp, __1 stamina, __2 eitr. + /// + [HarmonyPatch(typeof(Player), "GetTotalFoodValue")] + public static class Alfar_FoodValue_Patch + { + public static void Postfix(Player __instance, ref float __2) + { + if (__instance == null || !AlfarVisuals.IsAlfarPlayer(__instance)) return; + + float bonus = 0f; + foreach (Player.Food food in __instance.GetFoods()) + { + bonus += Mathf.Min(food.m_health, food.m_stamina); + } + + __2 += bonus * AlfarConfig.DietMultiplier.Value; + } + } + + // ─── Shield and soft fall ──────────────────────────────────────────── + + /// + /// Blows land on the eitr first, 1 for 1. + /// + /// - No cooldown: the shield absorbs for as long as one point of eitr remains. + /// - Lightning and spirit cost double (the cost, not the damage: DamageModifier.Weak is a + /// flat +50% and cannot be made to double anything). + /// - A blow bigger than the pool is shared out: the eitr takes the share it can, the body + /// takes the rest. + /// - Drowning and the edge of the world skip the shield altogether; falls are free while + /// there is eitr and shielded like anything else once there is none left. + /// + /// The prefix edits the HitData and lets ApplyDamage run: with nothing left in it, + /// ApplyDamage returns at once ("took no damage"). Positional parameters, and the argument + /// types are in the attribute so the patch binds to the real overload (guide 5.16). + /// + [HarmonyPatch(typeof(Character), "ApplyDamage", + new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })] + public static class Alfar_ApplyDamage_Patch + { + public static void Prefix(Character __instance, HitData __0) + { + Player player = __instance as Player; + if (player == null || __0 == null) return; + if (!AlfarVisuals.IsAlfarPlayer(player)) return; + + // The shield belongs to whoever owns the body: ApplyDamage runs on the owner, and a + // remote copy must not spend eitr it does not hold. + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + // The same early exits ApplyDamage has: nothing to absorb, nothing to spend. + if (player.IsDead() || player.IsTeleporting() || player.InCutscene() || player.InGodMode()) return; + + // Just arrived by Heimkall: nothing hurts for a few seconds, or a burning death would + // simply repeat at the bed. + if (Time.time < AlfarHeimkall.InvulnerableUntil) + { + __0.m_damage = default(HitData.DamageTypes); + return; + } + + // In the archon form the pool IS the defence: it takes every blow, drowning and the + // edge of the world included, and the eitr is already spent (AlfarArchon). + if (AlfarArchon.Active) + { + AlfarArchon.Absorb(player, __0); + return; + } + + HitData.HitType type = __0.m_hitType; + if (type == HitData.HitType.Drowning || type == HitData.HitType.EdgeOfWorld) return; + + float available = player.GetEitr(); + + if (type == HitData.HitType.Fall && AlfarConfig.SoftFall.Value) + { + // Soft fall: free while there is eitr, a normal fall once there is none. + if (available > 0f) __0.m_damage = default(HitData.DamageTypes); + return; + } + + float cost = Cost(__0.m_damage); + if (cost <= 0f || available <= 0f) return; + + if (available >= cost) + { + Spend(player, cost); + __0.m_damage = default(HitData.DamageTypes); + return; + } + + // Shared out: the eitr absorbs the fraction it can pay for, the body takes the rest. + float covered = available / cost; + HitData.DamageTypes remaining = __0.m_damage; + remaining.Modify(1f - covered); + __0.m_damage = remaining; + Spend(player, available); + } + + /// + /// The eitr a blow costs. Every damage type that wounds a person counts; chop and + /// pickaxe are tool damage (trees, rocks) and do not. Lightning and spirit are doubled. + /// + private static float Cost(HitData.DamageTypes damage) + { + float rate = AlfarConfig.ShieldRate.Value; + float conductive = AlfarConfig.ConductiveMultiplier.Value; + + float ordinary = damage.m_damage + damage.m_blunt + damage.m_slash + damage.m_pierce + + damage.m_fire + damage.m_frost + damage.m_poison; + float double_ = damage.m_lightning + damage.m_spirit; + + return (ordinary + double_ * conductive) * rate; + } + } + } +} diff --git a/JotunnModStub/Alfar/AlfarHeimkall.cs b/JotunnModStub/Alfar/AlfarHeimkall.cs new file mode 100644 index 0000000..49a7dc4 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarHeimkall.cs @@ -0,0 +1,171 @@ +using System.Globalization; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// HEIMKALL: a lethal blow does not kill an Alfr, it sends them to their bed with one hit point + /// (Alfar_Progettazione.txt sec. 6). Then a wait: 20 minutes, 15 after Yagluth, 10 after Fader. + /// Inside the wait a lethal blow kills like it does anyone. + /// + /// HOW IT AVOIDS DEATH (read from the IL, doc sec. 16B V5): + /// Character.ApplyDamage ends with the health at zero, and the death itself is not decided + /// there but in Character.CheckDeath, which Character.CustomFixedUpdate calls on its next step. + /// So a POSTFIX on ApplyDamage that puts one hit point back, the same frame, means the check + /// finds a living body and there is no death routine, no tomb, no skill loss, no message. + /// + /// The timer lives in m_customData as a world-time stamp, so it survives a logout. + /// + public static class AlfarHeimkall + { + private const string TimerKey = "Alfar_HeimkallAt"; + + /// Time.time until which nothing may hurt the local Alfr (the arrival grace). + public static float InvulnerableUntil; + + // ─── The timer ─────────────────────────────────────────────────────── + + /// The cooldown for the current boss progress, in seconds. + public static float CooldownSeconds() + { + int state = BossProgressionManager.GetCurrentProgressionState(); + float minutes = state >= 8 ? AlfarConfig.HeimkallMinutesAfterFader.Value + : state >= 6 ? AlfarConfig.HeimkallMinutesAfterYagluth.Value + : AlfarConfig.HeimkallMinutes.Value; + return minutes * 60f; + } + + /// Seconds left before the next Heimkall; 0 when it is ready. + public static float Remaining(Player player) + { + if (player == null || player.m_customData == null || ZNet.instance == null) return 0f; + if (!player.m_customData.TryGetValue(TimerKey, out string stamp)) return 0f; + if (!double.TryParse(stamp, NumberStyles.Float, CultureInfo.InvariantCulture, out double at)) return 0f; + + double elapsed = ZNet.instance.GetTimeSeconds() - at; + + // A stamp from a different world (its clock is another clock) reads as the future, or as + // a wait longer than any cooldown. Either way the timer is not this world's: ready. + float cooldown = CooldownSeconds(); + if (elapsed < 0d || elapsed > 1e9) return 0f; + + return Mathf.Max(0f, cooldown - (float)elapsed); + } + + public static bool IsReady(Player player) => Remaining(player) <= 0f; + + public static void StartTimer(Player player) + { + if (player == null || ZNet.instance == null) return; + player.m_customData[TimerKey] = + ZNet.instance.GetTimeSeconds().ToString("R", CultureInfo.InvariantCulture); + } + + public static void ResetTimer(Player player) + { + if (player != null && player.m_customData != null) player.m_customData.Remove(TimerKey); + AlfarStatusEffects.ClearTimer("heimkall"); + } + + private static float nextIconSync; + + /// + /// Keeps the on-screen Heimkall countdown honest: status effects are not saved, so after a + /// reload the wait is put back on screen with what is really left of it, and removed when over. + /// + public static void SyncIcon(Player player) + { + if (Time.time < nextIconSync) return; + nextIconSync = Time.time + 2f; + + float left = Remaining(player); + bool shown = AlfarStatusEffects.HasTimer("heimkall"); + if (left > 0f && !shown) AlfarStatusEffects.ShowTimer("heimkall", left); + else if (left <= 0f && shown) AlfarStatusEffects.ClearTimer("heimkall"); + } + + // ─── The call home ─────────────────────────────────────────────────── + + /// + /// Teleports to the bed (or the world spawn when there is none) at one hit point, clears what + /// was killing the body, and starts the wait. Returns false when it is not ready. + /// + public static bool TryTrigger(Player player, string reason, bool force = false) + { + // force: the archon form ends with a Heimkall that it already paid for at the start. + if (player == null || (!force && !IsReady(player))) return false; + + bool bed; + Vector3 destination = FindDestination(out bed); + + // distantTeleport tells Valheim to stream the destination zone in first. Anything past a + // couple of zone-widths needs it. + bool distant = Vector3.Distance(player.transform.position, destination) > 100f; + bool teleported = player.TeleportTo(destination, player.transform.rotation, distant); + + // Whether or not the teleport was accepted (it refuses for two seconds after another + // one), the body must not die this frame. + player.SetHealth(1f); + + // What was killing the body goes with it: burning, poison, the cold, being wet. Cleared + // before the passive is put back, since RemoveAll takes that too. + player.GetSEMan().RemoveAllStatusEffects(true); + AlfarStatusEffects.Ensure(player); + + InvulnerableUntil = Time.time + AlfarConfig.HeimkallInvulnerableSeconds.Value; + StartTimer(player); + AlfarStatusEffects.ShowTimer("heimkall", CooldownSeconds()); + + Jotunn.Logger.LogInfo($"[Alfar] Heimkall ({reason}): teleported={teleported} to {destination}; " + + $"next in {CooldownSeconds() / 60f:0} min."); + player.Message(MessageHud.MessageType.Center, ModText.Get(bed ? "rov_msg_alfar_heimkall" : "rov_msg_alfar_heimkall_nobed")); + return true; + } + + /// + /// The bed the player set, else the world's original spawn. A bed point already has its height; + /// the world spawn is stored with a placeholder height (50), so its ground is worked out from the + /// world generator, which answers even when the zone there is not loaded yet - the first version + /// stood the Alfr at 50.5 m in the air or inside a hill. A bed counts only after the player has + /// SET it (sleeping in it, or interacting with it); an unused bed is not a spawn point. + /// + private static Vector3 FindDestination(out bool bed) + { + PlayerProfile profile = Game.instance != null ? Game.instance.GetPlayerProfile() : null; + + bed = profile != null && profile.HaveCustomSpawnPoint(); + if (bed) return profile.GetCustomSpawnPoint() + Vector3.up * 0.5f; + + Vector3 point = PlayerProfile.m_originalSpawnPoint; + if (WorldGenerator.instance != null) + { + float ground = WorldGenerator.instance.GetHeight(point.x, point.z); + point.y = Mathf.Max(ground, 30f) + 1f; // 30 is the sea level: never under the water + } + return point; + } + + // ─── The patch ─────────────────────────────────────────────────────── + + /// + /// After the blow has landed: if it left the body at zero, call it home instead. The shield + /// prefix has already taken what it could, so this only fires for the blow the eitr could + /// not cover (or a fall at eitr zero, a drowning, the edge of the world). + /// + [HarmonyPatch(typeof(Character), "ApplyDamage", + new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })] + public static class Alfar_Heimkall_Patch + { + public static void Postfix(Character __instance) + { + Player player = __instance as Player; + if (player == null || player != Player.m_localPlayer) return; + if (!AlfarVisuals.IsAlfarPlayer(player)) return; + if (player.IsDead() || player.GetHealth() > 0f) return; + + TryTrigger(player, "lethal blow"); + } + } + } +} diff --git a/JotunnModStub/Alfar/AlfarLevitation.cs b/JotunnModStub/Alfar/AlfarLevitation.cs new file mode 100644 index 0000000..77f6b9d --- /dev/null +++ b/JotunnModStub/Alfar/AlfarLevitation.cs @@ -0,0 +1,120 @@ +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// LEVITATION (Alfar_Progettazione.txt sec. 4.6): in the air, hold the jump key and the Alfr rises + /// slowly, burning eitr slowly. Let go and the soft fall takes over. + /// + /// There is no hover in vanilla. This pushes the rigidbody's vertical speed up toward a small + /// target while the key is held, and nothing else: no horizontal speed is added, so it is a way + /// over a ledge or out of a pit and not flight (the pool of an early Alfr lasts about half a + /// minute of it). + /// + /// It runs on the owner's FixedUpdate, where the rigidbody is read, and the position syncs like + /// any other movement. The eitr is spent in small batches, not every physics step: each spend arms + /// the regeneration delay and goes through an RPC call. + /// + public static class AlfarLevitation + { + // A short moment in the air before it starts, so a normal jump (a tap) is just a jump. + private const float AirDelay = 0.2f; + private const float SpendInterval = 0.25f; + + private static float airTime; + private static float owed; + private static float nextSpend; + + public static bool Rising { get; private set; } + + [HarmonyPatch(typeof(Player), "FixedUpdate")] + public static class Alfar_Levitation_Patch + { + public static void Postfix(Player __instance) + { + if (__instance == null || __instance != Player.m_localPlayer) return; + if (!AlfarVisuals.IsAlfarPlayer(__instance) || __instance.IsDead()) { Reset(); return; } + + // THE ARCHON FLIES for as long as the form lasts: it hovers where it is, climbs while + // jump is held and sinks while crouch is held. The eitr is already gone, so nothing is + // spent. Horizontal movement stays the normal controls. + if (AlfarArchon.Active) + { + Rigidbody flyer = Traverse.Create(__instance).Field("m_body").GetValue(); + if (flyer != null) + { + float speed = AlfarPowerConfig.LevitationRise.Value * 2f; + float target = 0f; + if (Time.time - AlfarArchon.StartedAt < 0.6f) target = 4f; // lift off + else if (RaceInput.Allowed && JumpHeld()) target = speed; + else if (RaceInput.Allowed && ZInput.GetButton("Crouch")) target = -speed; + + Vector3 velocity = flyer.linearVelocity; + velocity.y = Mathf.Lerp(velocity.y, target, 0.25f); + flyer.linearVelocity = velocity; + } + Traverse.Create(__instance).Field("m_maxAirAltitude").SetValue(__instance.transform.position.y); + Rising = true; + return; + } + + bool wants = RaceInput.Allowed && JumpHeld(); + bool airborne = !__instance.IsOnGround() && !__instance.IsSwimming() && !__instance.IsAttached() && + !__instance.IsFlying(); + + airTime = airborne ? airTime + Time.fixedDeltaTime : 0f; + + float cost = AlfarPowerConfig.LevitationCostPerSecond.Value; + bool canPay = AlfarArchon.Active || __instance.GetEitr() > 0f; + + if (!wants || !airborne || airTime < AirDelay || !canPay) + { + Rising = false; + FlushSpend(__instance); + return; + } + + Rising = true; + + Rigidbody body = Traverse.Create(__instance).Field("m_body").GetValue(); + if (body != null) + { + Vector3 velocity = body.linearVelocity; + velocity.y = Mathf.Lerp(velocity.y, AlfarPowerConfig.LevitationRise.Value, 0.25f); + body.linearVelocity = velocity; + } + + // Rising resets the fall: the point of the soft fall is that the way down starts at + // the top, and a long climb must not count as a long drop at eitr zero. + Traverse.Create(__instance).Field("m_maxAirAltitude").SetValue(__instance.transform.position.y); + + // In the archon form the eitr is already gone and the pool pays for nothing here. + if (!AlfarArchon.Active) owed += cost * Time.fixedDeltaTime; + if (Time.time >= nextSpend) FlushSpend(__instance); + } + } + + private static bool JumpHeld() + { + // ZInput's "Jump" covers the space bar and the pad's jump button alike, and respects the + // controls the player picked in the settings. + return ZInput.GetButton("Jump"); + } + + private static void FlushSpend(Player player) + { + nextSpend = Time.time + SpendInterval; + if (owed <= 0f) return; + AlfarEitr.Spend(player, owed); + owed = 0f; + } + + private static void Reset() + { + airTime = 0f; + owed = 0f; + Rising = false; + } + } +} diff --git a/JotunnModStub/Alfar/AlfarLjosgard.cs b/JotunnModStub/Alfar/AlfarLjosgard.cs new file mode 100644 index 0000000..e70c5cb --- /dev/null +++ b/JotunnModStub/Alfar/AlfarLjosgard.cs @@ -0,0 +1,108 @@ +using System.Collections.Generic; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The LJOSGARD, the garden of light (Alfar_Progettazione.txt sec. 8.6 and 12): the module of the + /// Nexus that mixes the two mushrooms of the Mistlands into SAP, very slowly. + /// + /// It is a clone of the stone furnace with its recipe turned: MAGECAP is the "ore" and JOTUN PUFFS + /// the "fuel", one of each per sap, so mixing the two is exactly what a smelter already does with + /// its two inputs. Being a Smelter it needs no new code to be served: the drones feed it (a + /// Smelter-family station) and carry the sap away, and the refinery (vanilla, sap as fuel and soft + /// tissue as ore) is served by them too. Output falls where a furnace's does. + /// + public static class AlfarLjosgard + { + public const string PieceName = "AlfarLjosgard"; + public const string PieceDisplay = "$rov_piece_alfar_ljosgard_name"; + + public static void Register() + { + GameObject source = PrefabManager.Cache.GetPrefab("smelter"); + ItemDrop magecap = PrefabManager.Cache.GetPrefab("MushroomMagecap"); + ItemDrop puffs = PrefabManager.Cache.GetPrefab("MushroomJotunPuffs"); + ItemDrop sap = PrefabManager.Cache.GetPrefab("Sap"); + + if (source == null || magecap == null || puffs == null || sap == null) + { + Jotunn.Logger.LogWarning("[Alfar] The Ljosgard needs the 'smelter' piece and the Magecap, Jotun Puffs and Sap items: not registered."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, source); + if (prefab == null) return; + + // The furnace's heat and its fire: the Ljosgard is cool to the touch (guide 5.1). + AswidBloodRefinery.StripOffensive(prefab, "Ljosgard"); + + Smelter smelter = prefab.GetComponent(); + if (smelter == null) + { + Jotunn.Logger.LogWarning("[Alfar] The cloned smelter has no Smelter component: no Ljosgard."); + return; + } + + smelter.m_name = PieceDisplay; + smelter.m_conversion = new List + { + new Smelter.ItemConversion { m_from = magecap, m_to = sap }, + }; + smelter.m_fuelItem = puffs; + smelter.m_fuelPerProduct = 1; + smelter.m_maxOre = AlfarNexusConfig.GardCapacity.Value; + smelter.m_maxFuel = AlfarNexusConfig.GardCapacity.Value; + smelter.m_secPerProduct = AlfarNexusConfig.GardSecondsPerSap.Value; + smelter.m_requiresRoof = false; + smelter.m_spawnStack = false; + smelter.m_windmill = null; + + AlfarConstructs.Tint(prefab, new Color(0.55f, 0.85f, 0.7f, 1f)); + + Piece piece = prefab.GetComponent(); + if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The cloned smelter has no Piece."); return; } + + piece.m_craftingStation = null; + piece.m_name = PieceDisplay; + piece.m_description = "$rov_piece_alfar_ljosgard_desc"; + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = PieceDisplay, + Description = "$rov_piece_alfar_ljosgard_desc", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = piece.m_icon, + Requirements = new[] + { + new RequirementConfig("Bronze", AlfarNexusConfig.GardBronze.Value, 0, true), + new RequirementConfig("MushroomJotunPuffs", AlfarNexusConfig.GardMushrooms.Value, 0, true), + new RequirementConfig("MushroomMagecap", AlfarNexusConfig.GardMushrooms.Value, 0, true), + }, + })); + + // One per Ljoskjarne, inside its reach, and only for the Alfar. + PieceDensityLimit.Register(PieceName, AlfarNexusConfig.NexusRadius.Value, 1, "rov_msg_build_limit_alfar_ljosgard"); + PieceDensityLimit.RegisterGate(PieceName, (player, position) => + { + if (!AlfarRace.IsLocalAlfar()) + { + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar")); + return false; + } + if (AlfarNexusBehaviour.Covering(position) == null) + { + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_gard_needs_nexus")); + return false; + } + return true; + }); + + AlfarPieces.Extra.Add(PieceName); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarMark.cs b/JotunnModStub/Alfar/AlfarMark.cs new file mode 100644 index 0000000..2bfc3ae --- /dev/null +++ b/JotunnModStub/Alfar/AlfarMark.cs @@ -0,0 +1,149 @@ +using System.Collections.Generic; +using System.Reflection; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Marks a creature or a piece as one of the Alfar's own: a construct, a drone or a tower. + /// + /// What the mark does is decided in ONE place, the patches below, instead of editing every attack + /// of every cloned creature (Alfar_Progettazione.txt sec. 8.5 and 16C P4): + /// - everything the marked thing deals becomes LIGHTNING, with the same total; chop and pickaxe + /// are tool damage and are dropped; + /// - it never hurts an ally; + /// - it never hurts a building, a tree or a rock. + /// Intercepting the hit covers melee, projectiles and area attacks alike, whatever the vanilla + /// creature does with its weapons. + /// + public class AlfarMark : MonoBehaviour + { + /// "drone", "construct" or "tower": only for logs and the status command. + public string Role = ""; + + /// The attacker's mark, or null when the hit is not from one of ours. + public static AlfarMark Of(HitData hit) + { + if (hit == null) return null; + Character attacker = hit.GetAttacker(); + return attacker != null ? attacker.GetComponent() : null; + } + + /// All the damage that can wound a person, moved into lightning. Chop and pickaxe go. + public static void ConvertToLightning(HitData hit) + { + HitData.DamageTypes d = hit.m_damage; + float total = d.m_damage + d.m_blunt + d.m_slash + d.m_pierce + d.m_fire + d.m_frost + + d.m_poison + d.m_spirit + d.m_lightning; + + HitData.DamageTypes converted = default(HitData.DamageTypes); + converted.m_lightning = total; + hit.m_damage = converted; + } + } + + /// The blows of an Alfar creature: lightning only, and never on a friend. + [HarmonyPatch(typeof(Character), "Damage")] + public static class AlfarMark_CharacterDamage_Patch + { + public static bool Prefix(Character __instance, HitData __0) + { + AlfarMark mark = AlfarMark.Of(__0); + if (mark == null) return true; + + Character attacker = __0.GetAttacker(); + if (__instance == attacker) return false; + + // Nobody on our side is ever hurt by us: players, their tames, the other constructs. + if (!BaseAI.IsEnemy(attacker, __instance)) return false; + + AlfarMark.ConvertToLightning(__0); + return true; + } + } + + /// + /// Buildings, trees and rocks take nothing from the Alfar's creatures: the golem that razed its + /// owner's base would be a bug. One prefix on every kind of thing that can be struck. + /// + [HarmonyPatch] + public static class AlfarMark_StructureDamage_Patch + { + public static IEnumerable TargetMethods() + { + System.Type[] types = + { + typeof(WearNTear), typeof(Destructible), typeof(MineRock5), typeof(MineRock), + typeof(TreeBase), typeof(TreeLog), + }; + + foreach (System.Type type in types) + { + MethodBase method = AccessTools.Method(type, "Damage", new[] { typeof(HitData) }); + if (method != null) yield return method; + else Jotunn.Logger.LogWarning($"[Alfar] {type.Name}.Damage(HitData) not found: that structure is not protected from the Alfar's creatures."); + } + } + + public static bool Prefix(HitData __0) + { + return AlfarMark.Of(__0) == null; + } + } + + /// + /// A shield equal to the creature's health that comes back by itself: 1% of it per second once it + /// has gone five seconds without being hit (design sec. 8.5 and 9.6). Health does NOT come back: + /// the damage to the body is permanent, which is why a construct is rebuilt and not repaired. + /// + /// Its own absorption and not SE_Shield: the blow arrives at ApplyDamage, and what is left after + /// the shield is what reaches the health (the same stage the Alfr's own eitr shield uses). + /// + public class AlfarCreatureShield : MonoBehaviour + { + public float MaxShield; + public float Shield; + public float RegenPerSecondFraction = 0.01f; + public float QuietSeconds = 5f; + + private float lastHit = -999f; + + private void Awake() + { + if (Shield <= 0f) Shield = MaxShield; + } + + private void Update() + { + if (Shield >= MaxShield || Time.time - lastHit < QuietSeconds) return; + Shield = Mathf.Min(MaxShield, Shield + MaxShield * RegenPerSecondFraction * Time.deltaTime); + } + + public void Absorb(HitData hit) + { + float total = hit.m_damage.GetTotalDamage(); + if (total <= 0f) return; + + lastHit = Time.time; + float absorbed = Mathf.Min(Shield, total); + Shield -= absorbed; + + HitData.DamageTypes rest = hit.m_damage; + rest.Modify((total - absorbed) / total); + hit.m_damage = rest; + } + + [HarmonyPatch(typeof(Character), "ApplyDamage", + new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })] + public static class Alfar_CreatureShield_Patch + { + public static void Prefix(Character __instance, HitData __0) + { + if (__0 == null || __instance is Player) return; + AlfarCreatureShield shield = __instance.GetComponent(); + if (shield != null) shield.Absorb(__0); + } + } + } +} diff --git a/JotunnModStub/Alfar/AlfarMiners.cs b/JotunnModStub/Alfar/AlfarMiners.cs new file mode 100644 index 0000000..59b3b22 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarMiners.cs @@ -0,0 +1,104 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// GRAFVAETTIR, the mining grenade (Alfar_Progettazione.txt sec. 9.3): unlocked at Eikthyr, thrown + /// like a grenade at a point; five drones dig the precious ores around it for two minutes and + /// vanish. The ore falls where it stands, and nothing else limits it but its cost (eitr, a little + /// stone and flint) and a five minute wait. + /// + /// The thrown part is only the spawn; the digging is AlfarMiner on the drones themselves. + /// + public static class AlfarMiners + { + private static float readyAt; + + public static void Tick(Player player) + { + // Nothing to tick per frame: the miners run themselves. Kept so the power loop treats + // every power the same way. + } + + public static void Throw(Player player) + { + if (Time.time < readyAt) return; + + Transform aim = GameCamera.instance != null ? GameCamera.instance.transform : player.transform; + Vector3 origin = aim.position; + Vector3 direction = aim.forward; + float range = AlfarPowerConfig.GrafRange.Value; + + Vector3 point = origin + direction * range; + foreach (RaycastHit hit in Physics.RaycastAll(origin, direction, range, ~0, QueryTriggerInteraction.Ignore)) + { + if (hit.collider.GetComponentInParent() == player) continue; + if (Vector3.Distance(origin, hit.point) < Vector3.Distance(origin, point)) point = hit.point; + } + + // The price: a little eitr, a little stone, a little flint. + string stone = SharedName("Stone"); + string flint = SharedName("Flint"); + int needStone = AlfarPowerConfig.GrafStone.Value; + int needFlint = AlfarPowerConfig.GrafFlint.Value; + float eitr = AlfarPowerConfig.GrafEitr.Value; + + Inventory inventory = player.GetInventory(); + if (inventory.CountItems(stone, -1, false) < needStone || inventory.CountItems(flint, -1, false) < needFlint) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_graf_materials", needStone, needFlint)); + return; + } + if (player.GetEitr() < eitr) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_no_eitr")); + return; + } + + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(AlfarDrones.MinerName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Alfar] No '{AlfarDrones.MinerName}' in ZNetScene: the mining drones cannot be thrown."); + return; + } + + inventory.RemoveItem(stone, needStone, -1, false); + inventory.RemoveItem(flint, needFlint, -1, false); + AlfarEitr.Spend(player, eitr); + readyAt = Time.time + AlfarPowerConfig.GrafCooldown.Value; + AlfarStatusEffects.ShowTimer("graf", AlfarPowerConfig.GrafCooldown.Value); + + int count = AlfarPowerConfig.GrafCount.Value; + for (int i = 0; i < count; i++) + { + Vector2 offset = Random.insideUnitCircle * 1.5f; + Vector3 where = point + new Vector3(offset.x, 1.5f + i * 0.2f, offset.y); + GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity); + + AlfarMiner miner = spawned.GetComponent(); + if (miner != null) + { + miner.Centre = point; + miner.Radius = AlfarPowerConfig.GrafRadius.Value; + miner.LiveSeconds = AlfarPowerConfig.GrafSeconds.Value; + } + + // Tame at once so nothing flees them and they flee nothing; no anchor, no leash. + MonsterAI ai = spawned.GetComponent(); + Character character = spawned.GetComponent(); + if (ai != null) ai.MakeTame(); + if (character != null) character.SetTamed(true); + } + + AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", point); + Jotunn.Logger.LogInfo($"[Alfar] Grafvaettir thrown: {count} at {point}."); + } + + private static string SharedName(string prefabName) + { + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null; + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + return drop != null ? drop.m_itemData.m_shared.m_name : prefabName; + } + } +} diff --git a/JotunnModStub/Alfar/AlfarNexus.cs b/JotunnModStub/Alfar/AlfarNexus.cs new file mode 100644 index 0000000..8ba5ac9 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarNexus.cs @@ -0,0 +1,576 @@ +using System.Collections.Generic; +using System.Text; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The LJOSKJARNE, the Alfar's Nexus (Alfar_Progettazione.txt sec. 8): the one piece the whole + /// base hangs from. It makes the drones and the constructs, it keeps the crystals, and the towers + /// and the drones only work inside its radius. One per 1.6 km2 like the other races' stations. + /// + /// ONE INTERACTION POINT (guide 4.7): E opens the vanilla merchant window with a row per product + /// (AlfarNexusStore), the way the Trol's war totem and the Dvergar's contract bank do. The first + /// version stepped through the products with Shift+E, which gave trouble in other races' tests, and + /// the player asked for the store. The prices are not coins: they come out of the pack, and the + /// row's tooltip lists them with how many exist and how many are allowed. + /// + /// Everything is paid from the player's inventory. The crystals the Nexus makes (after the + /// Kristallvigsla) pile up inside it, a beehive's way - slowly, to a cap, and it stops when full + /// until somebody collects - and "collect" moves them to the pack. + /// + public static class AlfarNexus + { + public const string PieceName = "AlfarNexus"; + public const string PieceDisplay = "$rov_piece_alfar_nexus_name"; + + public static void Register() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_cartographytable"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Alfar] Could not clone piece_cartographytable; the Ljoskjarne is not registered."); + return; + } + + // The MapTable trap (Butler 4.1): MapTable is Interactable AND Hoverable and takes the E + // key before our Switch sees it. Everything goes except what makes it a building. + foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren(true)) + { + if (behaviour == null) continue; + if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue; + Object.DestroyImmediate(behaviour); + } + + AlfarConstructs.Tint(prefab, new Color(0.62f, 0.8f, 1f, 1f)); + + AlfarNexusBehaviour nexus = prefab.AddComponent(); + nexus.m_switch = prefab.AddComponent(); + nexus.m_switch.m_name = PieceDisplay; + + // A Trader with an empty catalogue: StoreGui needs one to open at all, and the rows are drawn + // by AlfarNexusStore. Disabled and with every list filled, for the reasons the Trol's totem + // spells out (Trader.Update and Start assume an animator and a look-at rig that a nucleus + // does not have, and an unfilled list sends Trader.Interact into a null Say). + Trader trader = prefab.GetComponent() ?? prefab.AddComponent(); + trader.m_name = PieceDisplay; + trader.enabled = false; + trader.m_items = new List(); + trader.m_useItems = new List(); + trader.m_randomTalk = new List(); + trader.m_randomGreets = new List(); + trader.m_randomGoodbye = new List(); + trader.m_randomStartTrade = new List(); + trader.m_randomBuy = new List(); + trader.m_randomSell = new List(); + trader.m_randomGiveItemNo = new List(); + trader.m_randomUseItemAlreadyRecieved = new List(); + trader.m_randomTalkConditionals = new List(); + + Sprite icon = BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore"); + + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + piece.m_craftingStation = null; + piece.m_resources = new Piece.Requirement[0]; + piece.m_name = PieceDisplay; + piece.m_canBeRemoved = true; + piece.m_groundPiece = false; + piece.m_groundOnly = false; + piece.m_icon = icon; + + Piece template = PrefabManager.Cache.GetPrefab("piece_workbench"); + if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect; + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = PieceDisplay, + Description = "$rov_piece_alfar_nexus_desc", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = icon, + Requirements = new[] + { + new RequirementConfig("Bronze", AlfarNexusConfig.NexusBronze.Value, 0, true), + new RequirementConfig("Stone", AlfarNexusConfig.NexusStone.Value, 0, true), + }, + })); + + PieceDensityLimit.Register(PieceName, PieceDensityLimit.RadiusForArea(AlfarNexusConfig.NexusDensityKm2.Value), + 1, "rov_msg_build_limit_alfar_nexus"); + PieceDensityLimit.RegisterGate(PieceName, (player, position) => + { + if (AlfarRace.IsLocalAlfar()) return true; + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar")); + return false; + }); + } + + public static Sprite BorrowIcon(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(prefabName); + Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null + ? drop.m_itemData.m_shared.m_icons + : null; + return icons != null && icons.Length > 0 ? icons[0] : null; + } + + /// Teaches the player the Alfar's pieces: a piece registered after the learning pass does not reach its table alone (guide 4.4). + public static void EnsureKnown(Player player) + { + if (player == null || !AlfarVisuals.IsAlfarPlayer(player)) return; + + Traverse traverse = Traverse.Create(player); + foreach (string name in AlfarPieces.AllNames()) + { + GameObject prefab = PrefabManager.Instance.GetPrefab(name); + Piece piece = prefab != null ? prefab.GetComponent() : null; + if (piece != null) traverse.Method("AddKnownPiece", piece).GetValue(); + } + traverse.Method("UpdateAvailablePiecesList").GetValue(); + } + } + + /// The names of every piece the Alfar can build, in one place for the lock and for learning. + public static class AlfarPieces + { + public static readonly List Extra = new List(); + + public static IEnumerable AllNames() + { + yield return AlfarNexus.PieceName; + foreach (string name in Extra) yield return name; + } + } + + [HarmonyPatch(typeof(Player), "OnSpawned")] + public static class AlfarKnownPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + AlfarNexus.EnsureKnown(__instance); + } + } + + public class AlfarNexusBehaviour : MonoBehaviour + { + public Switch m_switch; + + public static readonly List All = new List(); + + private const string KeySelected = "RoV_alfarSel"; + private const string KeyUpgrade = "RoV_alfarUp"; + private const string KeyCrystals = "RoV_alfarCr"; + private const string KeyCrystalAt = "RoV_alfarCrAt"; + + public enum Product { Drone = 0, Neistvordr = 1, Eldingvordr = 2, Steinvordr = 3, Upgrade = 4, Collect = 5 } + private static readonly int ProductCount = System.Enum.GetValues(typeof(Product)).Length; + + private ZNetView m_nview; + + private void Awake() + { + m_nview = GetComponent(); + All.Add(this); + RaisedThrall.RegisterStation(transform); + + if (m_switch != null) + { + m_switch.m_onUse = OnUse; + m_switch.m_onHover = Hover; + } + } + + private void OnDestroy() + { + All.Remove(this); + RaisedThrall.UnregisterStation(transform); + } + + /// The nearest Ljoskjarne whose radius covers the point, or null. + public static AlfarNexusBehaviour Covering(Vector3 point) + { + AlfarNexusBehaviour best = null; + float bestDistance = float.MaxValue; + foreach (AlfarNexusBehaviour nexus in All) + { + if (nexus == null) continue; + float distance = Vector3.Distance(nexus.transform.position, point); + if (distance <= AlfarNexusConfig.NexusRadius.Value && distance < bestDistance) + { + best = nexus; + bestDistance = distance; + } + } + return best; + } + + // ─── State ─────────────────────────────────────────────────────────── + + private bool Upgraded => m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetInt(KeyUpgrade, 0) == 1; + public int Crystals => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyCrystals, 0) : 0; + + private Product Selected + { + get + { + int value = m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeySelected, 0) : 0; + return (Product)Mathf.Clamp(value, 0, ProductCount - 1); + } + } + + private bool Available(Product product) + { + bool constructsOpen = Upgraded && BossProgressionManager.GetCurrentProgressionState() >= AlfarNexusConfig.ConstructState; + switch (product) + { + case Product.Drone: return true; + case Product.Neistvordr: + case Product.Eldingvordr: + case Product.Steinvordr: return constructsOpen; + case Product.Upgrade: return !Upgraded; + case Product.Collect: return Upgraded; + } + return false; + } + + // ─── Crystals: a beehive's way ─────────────────────────────────────── + + /// + /// One crystal per Time Factor beehive-intervals of WORLD time, up to the cap, and nothing while + /// full: the clock restarts when somebody collects, like the honey. Only the owner counts. + /// The beehive's own interval is read, not copied (guide 3.2) - and only the INTERVAL, not its + /// daylight rule: the Alfar have no light mechanic (doc sec. 8.6). + /// + private void Update() + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner() || !Upgraded || ZNet.instance == null) return; + + ZDO zdo = m_nview.GetZDO(); + int cap = AlfarNexusConfig.CrystalCap.Value; + int stored = zdo.GetInt(KeyCrystals, 0); + double now = ZNet.instance.GetTimeSeconds(); + + if (stored >= cap) { zdo.Set(KeyCrystalAt, now.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); return; } + + string stamp = zdo.GetString(KeyCrystalAt, ""); + if (!double.TryParse(stamp, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double at)) + { + zdo.Set(KeyCrystalAt, now.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + return; + } + + float interval = CrystalInterval(); + int made = Mathf.FloorToInt((float)((now - at) / interval)); + if (made <= 0) return; + + stored = Mathf.Min(cap, stored + made); + zdo.Set(KeyCrystals, stored); + zdo.Set(KeyCrystalAt, (at + made * interval).ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + } + + /// Seconds per crystal: Time Factor times a vanilla beehive's seconds per honey. + public static float CrystalInterval() + { + Beehive hive = TrentaConfig.FindVanillaBeehive(); + float honey = hive != null && hive.m_secPerUnit > 0f ? hive.m_secPerUnit : 1200f; + return honey * AlfarNexusConfig.CrystalTimeFactor.Value; + } + + // ─── Costs ─────────────────────────────────────────────────────────── + + private struct Cost + { + public string Item; + public int Amount; + public Cost(string item, int amount) { Item = item; Amount = amount; } + } + + private static List CostOf(Product product) + { + switch (product) + { + case Product.Drone: + return new List { new Cost("Bronze", AlfarNexusConfig.DroneBronze.Value) }; + case Product.Neistvordr: + return new List + { + new Cost("Bronze", AlfarNexusConfig.NeistMetal.Value), + new Cost("Crystal", AlfarNexusConfig.NeistCrystal.Value), + new Cost("Eitr", AlfarNexusConfig.NeistEitr.Value), + }; + case Product.Eldingvordr: + return new List + { + new Cost("Iron", AlfarNexusConfig.EldingMetal.Value), + new Cost("Crystal", AlfarNexusConfig.EldingCrystal.Value), + new Cost("Eitr", AlfarNexusConfig.EldingEitr.Value), + }; + case Product.Steinvordr: + return new List + { + new Cost("BlackMetal", AlfarNexusConfig.SteinMetal.Value), + new Cost("Crystal", AlfarNexusConfig.SteinCrystal.Value), + new Cost("Eitr", AlfarNexusConfig.SteinEitr.Value), + }; + case Product.Upgrade: + return new List { new Cost("Crystal", AlfarNexusConfig.UpgradeCrystals.Value) }; + } + return new List(); + } + + private static string SharedName(string prefabName) + { + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null; + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + return drop != null ? drop.m_itemData.m_shared.m_name : prefabName; + } + + private static bool CanPay(Player player, List costs) + { + foreach (Cost cost in costs) + { + if (cost.Amount <= 0) continue; + if (player.GetInventory().CountItems(SharedName(cost.Item), -1, false) < cost.Amount) return false; + } + return true; + } + + private static void Pay(Player player, List costs) + { + foreach (Cost cost in costs) + { + if (cost.Amount > 0) player.GetInventory().RemoveItem(SharedName(cost.Item), cost.Amount, -1, false); + } + } + + private static string CostText(List costs) + { + var parts = new List(); + foreach (Cost cost in costs) + { + if (cost.Amount > 0) parts.Add($"{cost.Amount} {Localization.instance.Localize(SharedName(cost.Item))}"); + } + return parts.Count == 0 ? "-" : string.Join(", ", parts); + } + + // ─── Counts and caps ───────────────────────────────────────────────── + + private int AliveOf(Product product) + { + Vector3 anchor = transform.position; + switch (product) + { + case Product.Drone: return AlfarDrones.CountAlive(anchor); + case Product.Neistvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Neistvordr); + case Product.Eldingvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Eldingvordr); + case Product.Steinvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Steinvordr); + } + return 0; + } + + private static int CapOf(Product product) + { + switch (product) + { + case Product.Drone: return AlfarNexusConfig.DroneCap.Value; + case Product.Neistvordr: return AlfarNexusConfig.NeistCap.Value; + case Product.Eldingvordr: return AlfarNexusConfig.EldingCap.Value; + case Product.Steinvordr: return AlfarNexusConfig.SteinCap.Value; + } + return int.MaxValue; + } + + private static string NameOf(Product product) => ModText.Get("rov_alfar_product_" + product.ToString().ToLowerInvariant()); + + // ─── Interaction ───────────────────────────────────────────────────── + + private string Hover() + { + var sb = new StringBuilder(); + sb.AppendLine(Localization.instance.Localize(AlfarNexus.PieceDisplay)); + sb.AppendLine($"[$KEY_Use] {ModText.Get("rov_alfar_nexus_open")}"); + + if (Upgraded) sb.AppendLine(ModText.Get("rov_alfar_nexus_crystals", Crystals, AlfarNexusConfig.CrystalCap.Value)); + else sb.AppendLine(ModText.Get("rov_alfar_nexus_no_upgrade")); + + return Localization.instance.Localize(sb.ToString()); + } + + private bool OnUse(Switch sw, Humanoid user, ItemDrop.ItemData item) + { + Player player = user as Player; + if (player == null || m_nview == null || !m_nview.IsValid()) return false; + + if (!AlfarVisuals.IsAlfarPlayer(player)) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar")); + return item != null; + } + + // Holding something is not a way to use the nucleus: it only opens the store. + if (item != null) + { + player.Message(MessageHud.MessageType.Center, "$msg_wontwork"); + return true; + } + + Trader trader = GetComponent(); + if (trader == null || StoreGui.instance == null) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_no_store")); + return false; + } + + // The store reads the nucleus back out of StoreGui's own m_trader when it repaints. + StoreGui.instance.Show(trader); + return true; + } + + // ─── What the store window uses ────────────────────────────────────── + + /// The products on offer right now, in the order the rows are drawn. + public List OnOffer() + { + var list = new List(); + foreach (Product product in System.Enum.GetValues(typeof(Product))) + { + if (Available(product)) list.Add(product); + } + return list; + } + + /// Builds a product from the row the player clicked. Every check Build makes still applies. + public void BuildFromStore(Product product) + { + Player player = Player.m_localPlayer; + if (player == null || m_nview == null || !m_nview.IsValid() || !Available(product)) return; + + m_nview.ClaimOwnership(); + Build(player, product); + } + + /// The short number on a row: the metal (or the crystals of the upgrade) it costs. + public static string PriceShort(Product product) + { + foreach (Cost cost in CostOf(product)) + { + if (cost.Amount > 0) return cost.Amount.ToString(); + } + return "-"; + } + + /// The full terms for the row's tooltip: the price, how many exist, how many are allowed. + public string Terms(Product product) + { + var sb = new StringBuilder(); + sb.AppendLine(CostText(CostOf(product))); + + int cap = CapOf(product); + if (cap != int.MaxValue) sb.AppendLine(ModText.Get("rov_alfar_store_count", AliveOf(product), cap)); + if (product == Product.Collect) sb.AppendLine(ModText.Get("rov_alfar_nexus_crystals", Crystals, AlfarNexusConfig.CrystalCap.Value)); + + sb.Append(ModText.Get("rov_alfar_store_terms")); + return sb.ToString(); + } + + public static string ProductName(Product product) => NameOf(product); + + private void Build(Player player, Product product) + { + List costs = CostOf(product); + + if (product == Product.Collect) + { + Collect(player); + return; + } + + if (AliveOf(product) >= CapOf(product)) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_cap")); + return; + } + + if (!CanPay(player, costs)) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_cannot_pay", CostText(costs))); + return; + } + + bool done; + switch (product) + { + case Product.Drone: done = AlfarDrones.Spawn(transform.position); break; + case Product.Neistvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Neistvordr); break; + case Product.Eldingvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Eldingvordr); break; + case Product.Steinvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Steinvordr); break; + case Product.Upgrade: done = true; break; + default: done = false; break; + } + if (!done) return; + + Pay(player, costs); + + if (product == Product.Upgrade) + { + ZDO zdo = m_nview.GetZDO(); + zdo.Set(KeyUpgrade, 1); + zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_upgraded")); + } + else + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_built", NameOf(product))); + } + } + + private void Collect(Player player) + { + int stored = Crystals; + if (stored <= 0) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_no_crystals")); + return; + } + + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab("Crystal") : null; + if (prefab == null) return; + + // Whatever fits goes in the pack; the rest stays in the Nexus. + int taken = 0; + for (int i = 0; i < stored; i++) + { + if (!player.GetInventory().CanAddItem(prefab, 1)) break; + if (!player.GetInventory().AddItem(prefab, 1)) break; + taken++; + } + + if (taken > 0) + { + ZDO zdo = m_nview.GetZDO(); + zdo.Set(KeyCrystals, stored - taken); + // Collecting restarts the clock, like emptying a hive. + zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + } + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_collected", taken)); + } + + /// Crystals a drone may carry away from the Nexus, and the call that does it (used by the drone's work). + public int TakeCrystals(int wanted) + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return 0; + int stored = Crystals; + int taken = Mathf.Min(stored, wanted); + if (taken <= 0) return 0; + ZDO zdo = m_nview.GetZDO(); + zdo.Set(KeyCrystals, stored - taken); + zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + return taken; + } + } +} diff --git a/JotunnModStub/Alfar/AlfarNexusConfig.cs b/JotunnModStub/Alfar/AlfarNexusConfig.cs new file mode 100644 index 0000000..59c4020 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarNexusConfig.cs @@ -0,0 +1,144 @@ +using BepInEx.Configuration; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The numbers of the Alfar's base: the Nexus, its drones, the constructs, the towers and the + /// crystals (Alfar_Progettazione.txt sec. 8, 9 and 19). All starting values, all to be corrected + /// in play, none in the logic files. + /// + public static class AlfarNexusConfig + { + // The progression state the constructs open at (BossProgressionManager: 6 = Yagluth down). + public const int ConstructState = 6; + + // ─── The Nexus ─────────────────────────────────────────────────────── + public static ConfigEntry NexusRadius; + public static ConfigEntry NexusDensityKm2; + public static ConfigEntry NexusBronze; + public static ConfigEntry NexusStone; + + // ─── Drones ────────────────────────────────────────────────────────── + public static ConfigEntry DroneBronze; + public static ConfigEntry DroneCap; + public static ConfigEntry DroneHealth; + public static ConfigEntry DroneZapDamage; + public static ConfigEntry DroneZapInterval; + + // ─── Mining drones ─────────────────────────────────────────────────── + public static ConfigEntry MinerDeposits; + public static ConfigEntry MinerDamage; + public static ConfigEntry WildPickables; + + // ─── Constructs ────────────────────────────────────────────────────── + public static ConfigEntry NeistMetal; + public static ConfigEntry NeistCrystal; + public static ConfigEntry NeistEitr; + public static ConfigEntry NeistCap; + + public static ConfigEntry EldingMetal; + public static ConfigEntry EldingCrystal; + public static ConfigEntry EldingEitr; + public static ConfigEntry EldingCap; + + public static ConfigEntry SteinMetal; + public static ConfigEntry SteinCrystal; + public static ConfigEntry SteinEitr; + public static ConfigEntry SteinCap; + + public static ConfigEntry ConstructLeash; + public static ConfigEntry ConstructAlertRange; + public static ConfigEntry WitherSeconds; + + public static ConfigEntry SphereDamage; + public static ConfigEntry SphereIntervalSeconds; + public static ConfigEntry SphereRange; + + // ─── Crystals ──────────────────────────────────────────────────────── + public static ConfigEntry UpgradeCrystals; + public static ConfigEntry CrystalCap; + public static ConfigEntry CrystalTimeFactor; + + // ─── Towers ────────────────────────────────────────────────────────── + public static ConfigEntry TowerBronze; + public static ConfigEntry TowerCrystal; + public static ConfigEntry TowerHealthFactor; + public static ConfigEntry TowerDamage; + public static ConfigEntry TowerScale; + + // ─── Ljosgard (sap) and chests ─────────────────────────────────────── + public static ConfigEntry GardBronze; + public static ConfigEntry GardMushrooms; + public static ConfigEntry GardSecondsPerSap; + public static ConfigEntry GardCapacity; + public static ConfigEntry ChestEyes; + + public static void Bind(ConfigFile config) + { + const string nexus = "Alfar - Nexus"; + NexusRadius = config.Bind(nexus, "Radius", 40f, new ConfigDescription("Metres around a Ljoskjarne where its drones work and its towers run.", new AcceptableValueRange(10f, 150f))); + NexusDensityKm2 = config.Bind(nexus, "Density Km2", 1.6f, new ConfigDescription("At most one Ljoskjarne per this many square kilometres.", new AcceptableValueRange(0.1f, 20f))); + NexusBronze = config.Bind(nexus, "Bronze Cost", 40, new ConfigDescription("Bronze to build a Ljoskjarne.", new AcceptableValueRange(0, 500))); + NexusStone = config.Bind(nexus, "Stone Cost", 30, new ConfigDescription("Stone to build a Ljoskjarne.", new AcceptableValueRange(0, 500))); + + const string drone = "Alfar - Drones"; + DroneBronze = config.Bind(drone, "Bronze Cost", 8, new ConfigDescription("Bronze for each Ljosvaettir.", new AcceptableValueRange(0, 200))); + DroneCap = config.Bind(drone, "Cap Per Nexus", 6, new ConfigDescription("Most drones one Ljoskjarne keeps.", new AcceptableValueRange(0, 50))); + DroneHealth = config.Bind(drone, "Health", 25f, new ConfigDescription("A drone's health and shield (a Deathsquito has 10).", new AcceptableValueRange(1f, 1000f))); + DroneZapDamage = config.Bind(drone, "Zap Damage", 1f, new ConfigDescription("Lightning damage of a drone's defensive zap.", new AcceptableValueRange(0f, 100f))); + DroneZapInterval = config.Bind(drone, "Zap Interval", 2f, new ConfigDescription("Seconds between a drone's zaps.", new AcceptableValueRange(0.2f, 30f))); + + MinerDeposits = config.Bind(drone, "Mining Targets", "MineRock_Copper,MineRock_Tin,MineRock_Iron,silvervein,rock3_silver,giant_brain", + new ConfigDescription("Comma separated parts of prefab names the mining drones dig (case does not matter). Soft tissue comes from giant_brain.")); + MinerDamage = config.Bind(drone, "Mining Damage", 40f, new ConfigDescription("Pickaxe damage each mining drone does per second to a deposit.", new AcceptableValueRange(1f, 1000f))); + + WildPickables = config.Bind(drone, "Wild Plants Harvested", "Pickable_Mushroom,Pickable_Dandelion,Pickable_Thistle,RaspberryBush,BlueberryBush,CloudberryBush", + new ConfigDescription("Comma separated parts of prefab names of WILD plants the drones pick without replanting (mushrooms, berry bushes, flowers). Trees are never touched. Cultivated crops are always replanted.")); + + const string construct = "Alfar - Constructs"; + NeistMetal = config.Bind(construct, "Neistvordr Bronze", 20, new ConfigDescription("Bronze for a Neistvordr.", new AcceptableValueRange(0, 500))); + NeistCrystal = config.Bind(construct, "Neistvordr Crystal", 3, new ConfigDescription("Crystals for a Neistvordr.", new AcceptableValueRange(0, 50))); + NeistEitr = config.Bind(construct, "Neistvordr Refined Eitr", 3, new ConfigDescription("Refined eitr for a Neistvordr.", new AcceptableValueRange(0, 50))); + NeistCap = config.Bind(construct, "Neistvordr Cap", 4, new ConfigDescription("Most Neistvordr one Ljoskjarne keeps.", new AcceptableValueRange(0, 50))); + + EldingMetal = config.Bind(construct, "Eldingvordr Iron", 20, new ConfigDescription("Iron for an Eldingvordr.", new AcceptableValueRange(0, 500))); + EldingCrystal = config.Bind(construct, "Eldingvordr Crystal", 5, new ConfigDescription("Crystals for an Eldingvordr.", new AcceptableValueRange(0, 50))); + EldingEitr = config.Bind(construct, "Eldingvordr Refined Eitr", 4, new ConfigDescription("Refined eitr for an Eldingvordr.", new AcceptableValueRange(0, 50))); + EldingCap = config.Bind(construct, "Eldingvordr Cap", 4, new ConfigDescription("Most Eldingvordr one Ljoskjarne keeps.", new AcceptableValueRange(0, 50))); + + SteinMetal = config.Bind(construct, "Steinvordr Black Metal", 20, new ConfigDescription("Black metal for a Steinvordr.", new AcceptableValueRange(0, 500))); + SteinCrystal = config.Bind(construct, "Steinvordr Crystal", 8, new ConfigDescription("Crystals for a Steinvordr.", new AcceptableValueRange(0, 50))); + SteinEitr = config.Bind(construct, "Steinvordr Refined Eitr", 6, new ConfigDescription("Refined eitr for a Steinvordr.", new AcceptableValueRange(0, 50))); + SteinCap = config.Bind(construct, "Steinvordr Cap", 1, new ConfigDescription("Most Steinvordr one Ljoskjarne keeps.", new AcceptableValueRange(0, 50))); + + ConstructLeash = config.Bind(construct, "Leash Range", 12f, new ConfigDescription("How far a construct wanders from its Ljoskjarne when not following.", new AcceptableValueRange(2f, 80f))); + ConstructAlertRange = config.Bind(construct, "Alert Range", 25f, new ConfigDescription("How far a construct notices and chases enemies.", new AcceptableValueRange(5f, 100f))); + WitherSeconds = config.Bind(construct, "Wither Seconds", 60f, new ConfigDescription("How long creatures last after their Ljoskjarne falls.", new AcceptableValueRange(0f, 600f))); + + SphereDamage = config.Bind(construct, "Sphere Damage", 80f, new ConfigDescription("Lightning damage of the Eldingvordr's sphere.", new AcceptableValueRange(1f, 1000f))); + SphereIntervalSeconds = config.Bind(construct, "Sphere Interval", 8f, new ConfigDescription("Seconds between the Eldingvordr's shots.", new AcceptableValueRange(0.5f, 60f))); + SphereRange = config.Bind(construct, "Sphere Range", 30f, new ConfigDescription("How far the Eldingvordr shoots.", new AcceptableValueRange(5f, 80f))); + + const string crystal = "Alfar - Crystals"; + UpgradeCrystals = config.Bind(crystal, "Upgrade Cost", 20, new ConfigDescription("Crystals the player must find for the Kristallvigsla.", new AcceptableValueRange(0, 200))); + CrystalCap = config.Bind(crystal, "Stored Cap", 20, new ConfigDescription("Most crystals the Ljoskjarne holds before it stops making them.", new AcceptableValueRange(1, 200))); + CrystalTimeFactor = config.Bind(crystal, "Time Factor", 2f, new ConfigDescription("A crystal takes this many times a vanilla beehive's time for one honey.", new AcceptableValueRange(0.1f, 20f))); + + const string tower = "Alfar - Towers"; + TowerBronze = config.Bind(tower, "Bronze Cost", 25, new ConfigDescription("Bronze for a Prismavard.", new AcceptableValueRange(0, 500))); + TowerCrystal = config.Bind(tower, "Crystal Cost", 2, new ConfigDescription("Crystals for a Prismavard.", new AcceptableValueRange(0, 50))); + TowerHealthFactor = config.Bind(tower, "Health Factor", 0.5f, new ConfigDescription("A Prismavard's health against the charred ballista's 400.", new AcceptableValueRange(0.05f, 3f))); + TowerDamage = config.Bind(tower, "Bolt Damage", 40f, new ConfigDescription("Lightning damage of a Prismavard's bolt.", new AcceptableValueRange(1f, 1000f))); + TowerScale = config.Bind(tower, "Scale", 0.6f, new ConfigDescription("Size of a Prismavard against the charred ballista.", new AcceptableValueRange(0.2f, 2f))); + + const string gard = "Alfar - Ljosgard"; + GardBronze = config.Bind(gard, "Bronze Cost", 40, new ConfigDescription("Bronze for a Ljosgard.", new AcceptableValueRange(0, 500))); + GardMushrooms = config.Bind(gard, "Mushrooms Cost", 10, new ConfigDescription("Jotun Puffs AND Magecap, this many of each, to build a Ljosgard.", new AcceptableValueRange(0, 100))); + GardSecondsPerSap = config.Bind(gard, "Seconds Per Sap", 600f, new ConfigDescription("Seconds to turn one Jotun Puffs and one Magecap into a Sap.", new AcceptableValueRange(10f, 7200f))); + GardCapacity = config.Bind(gard, "Sap Capacity", 10, new ConfigDescription("Sap the Ljosgard holds before it stops.", new AcceptableValueRange(1, 200))); + + ChestEyes = config.Bind(gard, "Chest Greydwarf Eyes", 3, new ConfigDescription("Greydwarf eyes in the price of the entry chest and the wood chest.", new AcceptableValueRange(0, 50))); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarNexusStore.cs b/JotunnModStub/Alfar/AlfarNexusStore.cs new file mode 100644 index 0000000..4b17cc1 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarNexusStore.cs @@ -0,0 +1,171 @@ +using System.Collections.Generic; +using HarmonyLib; +using TMPro; +using UnityEngine; +using UnityEngine.UI; + +namespace RacesOfValheim +{ + /// + /// The Ljoskjarne's window: the merchant's own store with a column of products in it - the drone, + /// the three constructs, the crystal upgrade, and the crystals to collect. + /// + /// It is the Trol war totem's window (TrolTotemStore) cloned for another trader, and for the same + /// reasons: same three patch points (Awake to build, FillList to repaint, Hide to clear), same trick + /// of instantiating StoreGui.m_listElement for the rows. The empty-catalogue guard that keeps vanilla + /// FillList from throwing is already on every trader with no wares (StoreGuiEmptyCatalogueGuardPatch), + /// so this one needs none of its own. + /// + /// What is different from the totem: a row's price is a number out of the pack and not coins, so the + /// short figure on the row is the metal or the crystals, and the tooltip carries the whole price. + /// + public static class AlfarNexusStore + { + private static RectTransform _list; + private static readonly List _rows = new List(); + + public static AlfarNexusBehaviour ActiveNexus(StoreGui gui) + { + Trader trader = FactionMerchantRuntime.GetActiveTrader(gui); + return trader != null ? trader.GetComponent() : null; + } + + // ─── build ─────────────────────────────────────────────────────────── + + public static void Create(StoreGui gui) + { + if (gui == null || gui.m_listRoot == null || _list != null) return; + + GameObject clone = Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent); + clone.name = "AlfarProductList"; + _list = clone.GetComponent(); + _list.anchoredPosition = gui.m_listRoot.anchoredPosition; + + // The clone carries whatever rows the vanilla list held at Awake: it starts empty. + foreach (Transform child in _list) Object.Destroy(child.gameObject); + _list.gameObject.SetActive(false); + } + + public static void Clear() + { + foreach (GameObject row in _rows) if (row != null) Object.Destroy(row); + _rows.Clear(); + if (_list != null) _list.gameObject.SetActive(false); + } + + // ─── fill ──────────────────────────────────────────────────────────── + + public static void Refresh(StoreGui gui) + { + Clear(); + + AlfarNexusBehaviour nexus = ActiveNexus(gui); + if (nexus == null) return; // an ordinary merchant: not ours + + if (_list == null) + { + Jotunn.Logger.LogWarning("[Alfar] The Ljoskjarne's column was never built (did the patch on StoreGui.Awake fail?)."); + return; + } + + _list.gameObject.SetActive(true); + + int row = 0; + foreach (AlfarNexusBehaviour.Product product in nexus.OnOffer()) + { + BuildRow(gui, nexus, product, row++); + } + + float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue(); + _list.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, Mathf.Max(baseSize, row * gui.m_itemSpacing)); + } + + private static string IconOf(AlfarNexusBehaviour.Product product) + { + switch (product) + { + case AlfarNexusBehaviour.Product.Drone: return "TrophyDeathsquito"; + case AlfarNexusBehaviour.Product.Neistvordr: return "TrophySurtling"; + case AlfarNexusBehaviour.Product.Eldingvordr: return "TrophyAbomination"; + case AlfarNexusBehaviour.Product.Steinvordr: return "TrophySGolem"; + default: return "Crystal"; + } + } + + private static void BuildRow(StoreGui gui, AlfarNexusBehaviour nexus, AlfarNexusBehaviour.Product product, int rowIndex) + { + GameObject element = Object.Instantiate(gui.m_listElement, _list); + element.SetActive(true); + + RectTransform rt = (RectTransform)element.transform; + float offset = (_list.rect.width - rt.rect.width) / 2f; + rt.anchoredPosition = new Vector2(offset, rowIndex * -gui.m_itemSpacing - offset); + + Sprite icon = Icon(IconOf(product)); + Image iconImage = element.transform.Find("icon").GetComponent(); + if (icon != null) iconImage.sprite = icon; + + string name = AlfarNexusBehaviour.ProductName(product); + element.transform.Find("name").GetComponent().text = Localization.instance.Localize(name); + + TMP_Text price = FindDescendant(element.transform, "price"); + if (price != null) price.text = AlfarNexusBehaviour.PriceShort(product); + + // The coin that sits beside the number on a vanilla row is the wrong picture here. + foreach (Image image in element.GetComponentsInChildren(true)) + { + if (image != null && image.gameObject.name.ToLowerInvariant().Contains("coin")) image.gameObject.SetActive(false); + } + + UITooltip tooltip = element.GetComponent(); + if (tooltip != null) tooltip.Set(Localization.instance.Localize(name), nexus.Terms(product), gui.m_tooltipAnchor, default(Vector2)); + + AlfarNexusBehaviour.Product chosen = product; + element.GetComponent