diff --git a/.claude/launch.json b/.claude/launch.json deleted file mode 100644 index a0517b3..0000000 --- a/.claude/launch.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "version": "0.0.1", - "configurations": [ - { - "name": "nandor-museum", - "runtimeExecutable": "npm", - "runtimeArgs": [ - "--prefix", - "C:/Users/FERDINANDO/Desktop/JotunnModStub-master/NandorMuseum", - "run", - "dev" - ], - "port": 5190 - }, - { - "name": "nandor-museum-build", - "runtimeExecutable": "npm", - "runtimeArgs": [ - "--prefix", - "C:/Users/FERDINANDO/Desktop/JotunnModStub-master/NandorMuseum", - "run", - "preview" - ], - "port": 5191 - } - ] -} \ No newline at end of file diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index dfdb8b7..0000000 --- a/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -*.sh text eol=lf diff --git a/.gitignore b/.gitignore index e1a2a2e..f7973c2 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,4 @@ Thumbs.db *.lnk # How to setup Configuration Manager -CONFIGURATION-MANAGER-HOWTO.md -# Written by scripts/publish.* on a Release build from the root README; never edit or commit it. -/JotunnModStub/Package/README.md +CONFIGURATION-MANAGER-HOWTO.md \ No newline at end of file diff --git a/JotunnModStub/Alfar/AlfarArchon.cs b/JotunnModStub/Alfar/AlfarArchon.cs deleted file mode 100644 index 079d7a6..0000000 --- a/JotunnModStub/Alfar/AlfarArchon.cs +++ /dev/null @@ -1,179 +0,0 @@ -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; - // The pulse fires on its own while the form lasts, so it earns what an aura does: - // a tenth of a hit per second, once per pulse that struck something. - if (AlfarPowers.Pulse(player, AlfarPowerConfig.ArchonPulseRadius.Value, AlfarPowerConfig.ArchonPulseDamage.Value)) - FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, 0.1f * AlfarPowerConfig.ArchonPulseInterval.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/AlfarChestGlow.cs b/JotunnModStub/Alfar/AlfarChestGlow.cs deleted file mode 100644 index dc529ff..0000000 --- a/JotunnModStub/Alfar/AlfarChestGlow.cs +++ /dev/null @@ -1,79 +0,0 @@ -using UnityEngine; - -namespace RacesOfValheim -{ - /// - /// The light on the two Alfar chests, which says whether the drones have work there: the fire - /// chest's grate burns while it holds wood they may burn, the entry chest's inlay shines while it - /// holds anything but the sigil. Every client asks its own copy of the inventory, which Container - /// keeps in step with the ZDO, so nothing travels over the network for it. - /// - public class AlfarChestGlow : MonoBehaviour - { - public Renderer[] Glows; - public ParticleSystem Embers; - public Color GlowColor; - public bool WoodOnly; - - private Container m_container; - private Material m_lit; - private Material m_cold; - private bool? m_shown; - private float m_nextCheck; - - private void Awake() - { - m_container = GetComponent(); - if (Glows == null || Glows.Length == 0 || Glows[0] == null) return; - - m_cold = Glows[0].sharedMaterial; - m_lit = new Material(m_cold) { name = m_cold.name + "_lit" }; - m_lit.color = Color.black; - m_lit.EnableKeyword("_EMISSION"); - m_lit.SetColor("_EmissionColor", GlowColor); - } - - private void Update() - { - if (Time.time < m_nextCheck) return; - m_nextCheck = Time.time + 1f; - - bool lit = HasWork(); - if (m_shown == lit) return; - m_shown = lit; - - if (m_lit != null) - { - foreach (Renderer glow in Glows) - { - if (glow != null) glow.sharedMaterial = lit ? m_lit : m_cold; - } - } - if (Embers != null) - { - if (lit) Embers.Play(true); - else Embers.Stop(true, ParticleSystemStopBehavior.StopEmitting); - } - } - - private bool HasWork() - { - Inventory inventory = m_container != null ? m_container.GetInventory() : null; - if (inventory == null) return false; - - foreach (ItemDrop.ItemData item in inventory.GetAllItems()) - { - if (item == null || item.m_dropPrefab == null) continue; - - string name = item.m_dropPrefab.name; - if (WoodOnly ? AlfarDroneAI.IsWood(name) : name != AlfarSigil.PrefabName) return true; - } - return false; - } - - private void OnDestroy() - { - if (m_lit != null) Destroy(m_lit); - } - } -} diff --git a/JotunnModStub/Alfar/AlfarChests.cs b/JotunnModStub/Alfar/AlfarChests.cs deleted file mode 100644 index 9efa86a..0000000 --- a/JotunnModStub/Alfar/AlfarChests.cs +++ /dev/null @@ -1,148 +0,0 @@ -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", - "$rov_hover_alfar_inngangskista", new Color(0.62f, 0.80f, 1f, 1f), - AlfarInputChest.Build, "AlfarInputChest_icon.png"); - RegisterOne(WoodName, "$rov_piece_alfar_eldividarkista_name", "$rov_piece_alfar_eldividarkista_desc", - "$rov_hover_alfar_eldividarkista", new Color(0.85f, 0.62f, 0.36f, 1f), - AlfarFireChest.Build, "AlfarFireChest_icon.png"); - } - - private static void RegisterOne(string pieceName, string display, string description, string hoverName, Color tint, - System.Func build, string iconResource) - { - 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)); - - // The hover and the chest window say what the chest is for, not only its name. - Container container = prefab.GetComponent(); - if (container != null) container.m_name = hoverName; - - 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; - - // Each chest has a body of its own; the tint stays as the fallback if it cannot be built. - Sprite icon = piece.m_icon; - if (!build(prefab)) AlfarConstructs.Tint(prefab, tint); - else icon = IconFrom(iconResource) ?? icon; - - PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig - { - Name = display, - Description = description, - PieceTable = PieceTables.Hammer, - Category = PieceCategories.Crafting, - Icon = 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); - } - - internal static Sprite IconFrom(string resource) - { - Texture2D texture = PieceLook.LoadTexture(resource); - if (texture == null) return null; - return Sprite.Create(texture, new Rect(0f, 0f, texture.width, texture.height), new Vector2(0.5f, 0.5f)); - } - } -} diff --git a/JotunnModStub/Alfar/AlfarCommands.cs b/JotunnModStub/Alfar/AlfarCommands.cs deleted file mode 100644 index a0f4785..0000000 --- a/JotunnModStub/Alfar/AlfarCommands.cs +++ /dev/null @@ -1,110 +0,0 @@ -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 deleted file mode 100644 index 558c0a7..0000000 --- a/JotunnModStub/Alfar/AlfarConfig.cs +++ /dev/null @@ -1,168 +0,0 @@ -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; - - /// - /// Scales the almond eyes (EyeExtent). The default 0.8 is the tuned grey look; raise it for - /// bigger eyes. - /// - public static ConfigEntry EyeSizeMultiplier; - - // A grey's eyes, on the Sverm's eye spot: offsets are metres in the head bone's OWN frame - // at human scale, so they land on the same part of the face at any body scale. - // Pushed apart and forward of the Sverm's, because an almond this wide would otherwise - // meet its twin over the nose and sink into the cheek. - public const float EyeSeparation = 0.037f; - public const float EyeForward = 0.090f; - public const float EyeHeight = 0.183f; - - // Full width, height and depth of one eye in metres at Eye Size Multiplier 1. The saved - // default of 0.8 makes that 50 x 28 x 18 mm. - public static readonly Vector3 EyeExtent = new Vector3(0.0625f, 0.035f, 0.0225f); - - // Degrees. Slant raises the outer corner; wrap turns each eye out toward its temple. - public const float EyeSlant = 22f; - public const float EyeWrap = 20f; - - // ─── 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("Scales the black almond eyes. 0.8 is the default look; raise it for bigger eyes.", - new AcceptableValueRange(0.5f, 3f))); - } - } -} diff --git a/JotunnModStub/Alfar/AlfarConstructs.cs b/JotunnModStub/Alfar/AlfarConstructs.cs deleted file mode 100644 index 80fe2a5..0000000 --- a/JotunnModStub/Alfar/AlfarConstructs.cs +++ /dev/null @@ -1,397 +0,0 @@ -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 deleted file mode 100644 index b319ceb..0000000 --- a/JotunnModStub/Alfar/AlfarDroneAI.cs +++ /dev/null @@ -1,2317 +0,0 @@ -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"; - - // What the drone last said: a counter every client watches, the text key and the item. - // Each client builds the line in its own language, so only the token travels. - public const string KeySaySeq = "RoV_alfarSaySeq"; - public const string KeySayKey = "RoV_alfarSayKey"; - public const string KeySayItem = "RoV_alfarSayItem"; - public const string KeySayStation = "RoV_alfarSayStation"; - - /// 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 bool m_fighting; - - 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; - - // Speech: the last line this client showed, and when to look for a new one. - private int m_heardSeq; - private float m_nextListen; - private float m_nextKilnCheck; - - 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(); - - // A line said before this object loaded is old news: do not replay it on a zone reload. - if (m_nview != null && m_nview.IsValid()) m_heardSeq = m_nview.GetZDO().GetInt(KeySaySeq, 0); - } - - private void Update() - { - if (Time.time < m_nextListen) return; - m_nextListen = Time.time + 0.5f; - Listen(); - } - - 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; - - // A tamed MonsterAI with no patrol point and no follow target never drops its target for - // distance (UpdateTarget, IL): only after 30 s unsensed or 60 s without a swing. The drone - // hears far, so an enemy that ran off kept "being sensed" and held the tick for vanilla. - // Past the leash it is no longer this drone's fight. - Character target = m_ai.GetTargetCreature(); - if (target != null && !target.IsDead() && !InFightReach(target)) - { - m_ai.MakeTame(); - target = null; - } - - if (target != null && !target.IsDead()) - { - m_fightUntil = Time.time + FightLinger; - } - else if (Time.time >= m_nextFightScan) - { - m_nextFightScan = Time.time + FightScanInterval; - // FindClosestEnemy takes its first match at ANY distance (it only compares against - // maxDistance once it holds one), so with a deer anywhere in the loaded zones it never - // returned null and vanilla kept the tick: the drone idled about instead of working. - Character enemy = BaseAI.FindClosestEnemy(m_character, transform.position, FightRange); - if (enemy != null && Vector3.Distance(enemy.transform.position, transform.position) <= FightRange) - { - m_fightUntil = Time.time + FightLinger; - } - } - - if (Time.time >= m_fightUntil) - { - // The fight is over: clear what vanilla still holds (target, alert), or the next - // GetTargetCreature hands the tick straight back to it. MakeTame is the public door - // that nulls both targets and the alert in one call; the drone is tamed already. - if (m_fighting) { m_fighting = false; m_ai.MakeTame(); } - return false; - } - - m_fighting = true; - m_job = null; - m_nextPlan = 0f; // the fight moved it; plan afresh the moment it hands back - SetStatus("Fighting."); - return true; - } - - /// Close to the drone, and not past the edge of the base it works. - private bool InFightReach(Character enemy) - { - Vector3 at = enemy.transform.position; - if (Vector3.Distance(at, transform.position) > FightRange * 2f) return false; - - Vector3? anchor = Anchor; - float leash = AlfarNexusConfig.NexusRadius.Value + m_radiusBonus + FightRange; - return anchor == null || Vector3.Distance(at, anchor.Value) <= leash; - } - - // ================================================================ 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(); - CheckIdleKiln(); - - // A harvest is in progress: wait for the drops to land, then gather them and replant. - Job job; - if (m_farmSpot != null) - { - 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" }; - } - // A delivery is a job like any other and gets its own clock. It used to return early here - // and inherit the load's deadline: a slow trip, or a fight on the way, left it already late, - // so it timed out on the first tick, was planned again, timed out again, every frame - the - // drone froze with wood in hand next to the kiln (10790 timeouts in one player's log). - else if (m_payload.Count > 0) job = PlanDelivery(anchor.Value); - else job = PlanWork(anchor.Value); - - 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; - } - - private Job PlanWork(Vector3 anchor) - { - - // 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(); - return job ?? PlanRepair(anchor) ?? PlanFarm(anchor) ?? PlanSort(); - } - - /// - /// 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 = ApproachPoint(best), - 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 = ApproachPoint(best), - 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. - // A station it could not reach is in the penalty box: asking it again straight away - // is the same failed trip. - bool unreachable = IsPenalised(target); - ButlerStation station = StationById(target); - if (station != null && station.Alive && station.Operable && AcceptsAnything(station) && !unreachable) - { - return new Job - { - Kind = "deposit_station", - Target = target, - Point = ApproachPoint(station), - 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); - - // Out of reach, the load goes back where it came from: the Eldividarkista's wood stays - // fuel instead of landing in the entry chest and being sorted away into storage. - Container source = unreachable ? ContainerById(m_nview.GetZDO().GetZDOID(KeySource)) : null; - if (source != null && !IsMarkedOff(source) && !IsPenalised(ZdoOf(source)) && HasRoomFor(source)) - { - return new Job - { - Kind = "deposit", - Target = ZdoOf(source), - Point = source.transform.position, - Label = "Storing " + Describe(), - }; - } - } - - 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 = ApproachPoint(consumer), - 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; - bool spoke = false; - 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)) - { - if (!spoke) spoke = Say("rov_msg_alfar_drone_sort_keep", name, KeepRepeatSeconds); - continue; - } - - Container destination = DestinationFor(name); - if (destination == null) - { - if (!spoke) spoke = Say("rov_msg_alfar_drone_sort_nowhere", name, NowhereRepeatSeconds); - 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; - } - - // ================================================================ speech - - /// When each item may be mentioned again, shared by every drone on this client, so - /// five drones looking at the same stone say it once and not five times. - private static readonly Dictionary s_nextMention = new Dictionary(); - private const float NowhereRepeatSeconds = 300f; - private const float KeepRepeatSeconds = 1800f; - private const float SpeechRange = 40f; - - /// Owner side: says the line once per cooldown per item, by writing it into the ZDO - /// where every client in range picks it up. Returns whether it spoke, so one plan says one - /// line and the bubbles do not overwrite each other. - private bool Say(string key, string item, float repeatSeconds, string station = "") - { - string mention = key + "|" + item; - float next; - if (s_nextMention.TryGetValue(mention, out next) && Time.time < next) return false; - s_nextMention[mention] = Time.time + repeatSeconds; - - ZDO zdo = m_nview.GetZDO(); - zdo.Set(KeySayKey, key); - zdo.Set(KeySayItem, item); - zdo.Set(KeySayStation, station); - zdo.Set(KeySaySeq, zdo.GetInt(KeySaySeq, 0) + 1); - return true; - } - - /// Every client: a new line in the ZDO goes over the drone's head, the way vanilla's - /// NPCs talk, and into the chat window, for players close enough to care. - private void Listen() - { - if (m_nview == null || !m_nview.IsValid()) return; - - ZDO zdo = m_nview.GetZDO(); - int seq = zdo.GetInt(KeySaySeq, 0); - if (seq == m_heardSeq) return; - m_heardSeq = seq; - - Player player = Player.m_localPlayer; - if (player == null || Chat.instance == null) return; - if (Vector3.Distance(player.transform.position, transform.position) > SpeechRange) return; - - string item = zdo.GetString(KeySayItem, ""); - GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(item) : null; - ItemDrop drop = prefab != null ? prefab.GetComponent() : null; - string itemName = drop != null ? drop.m_itemData.m_shared.m_name : item; - - string text = ModText.Get(zdo.GetString(KeySayKey, ""), itemName, - "$rov_piece_alfar_inngangskista_name", "$rov_piece_alfar_eldividarkista_name", - zdo.GetString(KeySayStation, "")); - string speaker = m_character != null ? Localization.instance.Localize(m_character.m_name) : ""; - - Chat.instance.SetNpcText(gameObject, Vector3.up * 1.5f, SpeechRange, 8f, speaker, text, false); - Chat.instance.AddString(speaker, text, Talker.Type.Normal); - } - - /// - /// The mistake players make with the kiln: the wood is in a plain chest (vanilla even calls - /// one "Wood chest"), and only the Eldividarkista's wood is ever burnt. A station that takes - /// wood, standing idle with nothing for it in the Eldividarkista while the right wood sits in - /// another chest, gets a line explaining that. Every 30 s is plenty for something the player - /// fixes by hand. - /// - private void CheckIdleKiln() - { - if (Time.time < m_nextKilnCheck) return; - m_nextKilnCheck = Time.time + 30f; - - foreach (ButlerStation station in m_stations) - { - if (!station.Alive || !station.Operable || station.HasWork || station.FreeSlots <= 0) continue; - if (m_wood != null && FirstAccepted(station, m_wood) != null) continue; - - string misplaced = WoodElsewhereFor(station); - if (misplaced == null) continue; - - // The station's own name token, so every language says "kiln" the game's way. - Piece piece = station.Behaviour.GetComponent(); - string stationName = piece != null ? piece.m_name : ""; - if (Say("rov_msg_alfar_drone_kiln_wood", misplaced, NowhereRepeatSeconds, stationName)) return; - } - } - - /// Wood the station would take, lying in the entry chest or a storage chest. - private string WoodElsewhereFor(ButlerStation station) - { - if (m_entry != null) - { - string found = WoodIn(m_entry, station); - if (found != null) return found; - } - foreach (Container chest in m_chests) - { - string found = WoodIn(chest, station); - if (found != null) return found; - } - return null; - } - - private static string WoodIn(Container chest, ButlerStation station) - { - Inventory inventory = chest != null ? chest.GetInventory() : null; - if (inventory == null) return null; - - foreach (ItemDrop.ItemData item in inventory.GetAllItems()) - { - if (item == null || item.m_dropPrefab == null) continue; - string name = item.m_dropPrefab.name; - if (IsWood(name) && station.Accepts(name)) return 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. - /// F8 readout: what each worker within 60 m is doing and what vanilla still holds, and - /// for the nearest one, why each thing in the entry chest is (or is not) being sorted. - public static void DebugReport(Player player) - { - var lines = new List(); - AlfarDroneAI nearest = null; - float nearestDistance = 60f; - - foreach (AlfarDroneAI drone in All) - { - if (drone == null || drone.m_ai == null) continue; - float distance = Vector3.Distance(drone.transform.position, player.transform.position); - if (distance > 60f) continue; - if (distance < nearestDistance) { nearestDistance = distance; nearest = drone; } - - Character target = drone.m_ai.GetTargetCreature(); - string targetText = target != null - ? $"{Utils.GetPrefabName(target.gameObject)} {Vector3.Distance(target.transform.position, drone.transform.position):0}m" - : "none"; - lines.Add($"[RoV drone] {distance:0}m: '{drone.Status}' job {(drone.m_job != null ? drone.m_job.Kind : "none")} " + - $"carry {drone.PayloadCount()} fight {drone.m_fighting} vanilla target {targetText} " + - $"alerted {drone.m_ai.IsAlerted()} flying {drone.m_character.IsFlying()} owner {drone.m_nview.IsOwner()}"); - - // The other half of what holds a fight: the 12 m sweep, and how long the linger has left. - Character near = BaseAI.FindClosestEnemy(drone.m_character, drone.transform.position, FightRange); - string nearText = near != null - ? $"{Utils.GetPrefabName(near.gameObject)} {Vector3.Distance(near.transform.position, drone.transform.position):0}m" - : "none"; - lines.Add($"[RoV drone] fight left {Mathf.Max(0f, drone.m_fightUntil - Time.time):0.0}s, " + - $"closest enemy {nearText}, in reach {(target != null && drone.InFightReach(target))}"); - } - - if (nearest == null) lines.Add("[RoV drone] no worker drone within 60m"); - else - { - lines.AddRange(nearest.SortReport()); - lines.AddRange(nearest.StationReport()); - } - - foreach (string line in lines) - { - Debug.Log(line); - player.Message(MessageHud.MessageType.TopLeft, line); - } - } - - /// Why a station is (or is not) fed: what the last scan saw, the wood chest, and every - /// smelter, hearth or fermenter within the radius - and the ones just past it, by how much. - private IEnumerable StationReport() - { - Vector3? anchor = Anchor; - if (anchor == null) { yield return "[RoV station] no anchor"; yield break; } - - float radius = AlfarNexusConfig.NexusRadius.Value + m_radiusBonus; - yield return $"[RoV station] anchor {Vector3.Distance(transform.position, anchor.Value):0}m from drone, " + - $"radius {radius:0}, scanned {Time.time - m_scannedAt:0}s ago, {m_stations.Count} stations, {m_chests.Count} chests"; - - if (m_wood == null) yield return "[RoV station] no Eldividarkista in range (or it is open, or holds the sigil)"; - else - { - var wood = new List(); - Inventory inventory = m_wood.GetInventory(); - if (inventory != null) - { - foreach (ItemDrop.ItemData item in inventory.GetAllItems()) - { - wood.Add(item.m_dropPrefab != null ? $"{item.m_dropPrefab.name}x{item.m_stack}" : $"{item.m_shared.m_name}(no prefab)"); - } - } - yield return $"[RoV station] Eldividarkista {Vector3.Distance(m_wood.transform.position, anchor.Value):0}m from anchor, " + - $"open {m_wood.IsInUse()}, penalty {IsPenalised(ZdoOf(m_wood))}, holds [{string.Join(", ", wood.ToArray())}]"; - } - - foreach (ButlerStation station in m_stations) - { - if (!station.Alive) { yield return "[RoV station] (a station that is gone)"; continue; } - - Container chest; - string material = FindMaterialFor(station, out chest); - string from = material == null ? "nothing" : $"{material} from {(chest == m_wood ? "Eldividarkista" : "entry")}"; - yield return $"[RoV station] {Utils.GetPrefabName(station.Behaviour.gameObject)} " + - $"{Vector3.Distance(station.Position, anchor.Value):0}m: operable {station.Operable} free {station.FreeSlots} " + - $"work {station.HasWork} wood {station.Accepts("Wood")} penalty {IsPenalised(station.Id)} " + - $"claimed {ClaimedByOther(station.Id)} fuel {station.FuelPrefab ?? "-"}/{station.FuelWanted} | load: {from}"; - } - - // A station the scan cannot see because it stands past the edge. - List pieces = AllPiecesField != null ? AllPiecesField.GetValue(null) as List : null; - if (pieces == null) yield break; - foreach (Piece piece in pieces) - { - if (piece == null) continue; - float distance = Vector3.Distance(piece.transform.position, anchor.Value); - if (distance <= radius || distance > radius + 15f) continue; - if (ButlerStation.From(piece.gameObject) == null) continue; - yield return $"[RoV station] {Utils.GetPrefabName(piece.gameObject)} {distance:0}m: OUTSIDE the radius by {distance - radius:0.0}m"; - } - } - - private IEnumerable SortReport() - { - if (m_entry == null) { yield return "[RoV sort] no entry chest in range"; yield break; } - if (m_entry.IsInUse()) yield return "[RoV sort] entry chest is open"; - if (IsPenalised(ZdoOf(m_entry))) yield return "[RoV sort] entry chest is set aside (penalty)"; - - Inventory inventory = m_entry.GetInventory(); - if (inventory == null) yield break; - - var seen = new HashSet(); - foreach (ItemDrop.ItemData item in inventory.GetAllItems()) - { - if (item == null) continue; - if (item.m_dropPrefab == null) { yield return $"[RoV sort] {item.m_shared.m_name}: no drop prefab"; continue; } - - string name = item.m_dropPrefab.name; - if (!seen.Add(name)) continue; - - string verdict; - if (name == AlfarSigil.PrefabName) verdict = "sigil, stays"; - else if (!IsWood(name) && AnyStationAccepts(name)) verdict = "a station takes it, stays as work"; - else - { - Container destination = DestinationFor(name); - verdict = destination != null - ? $"goes to chest at {Vector3.Distance(destination.transform.position, m_entry.transform.position):0}m" - : $"nowhere: no storage chest holds it and none is empty ({m_chests.Count} chests)"; - } - yield return $"[RoV sort] {name}: {verdict}"; - } - } - - /// - /// Where the drone flies to serve a station: beside it, a metre past its colliders on the side - /// the drone comes from. Vanilla lifts a flyer's goal to m_flyAltitudeMin over the ground under - /// it (BaseAI.MoveTo, IL), and under a charcoal kiln's origin that is inside the dome: the drone - /// pressed against the stone, never came within ArriveDistance, and the kiln went into the - /// penalty box (snakey's log, "Could not reach collect target"). Beside it is open air, and it - /// stays under a roof indoors, where aiming over the top would not. The loading and the sweep - /// still work from the station's own position. - /// - private Vector3 ApproachPoint(ButlerStation station) - { - Vector3 centre = station.Position; - bool any = false; - Bounds bounds = new Bounds(centre, Vector3.zero); - foreach (Collider collider in station.Behaviour.GetComponentsInChildren()) - { - if (collider == null || !collider.enabled || collider.isTrigger) continue; - if (any) bounds.Encapsulate(collider.bounds); - else { bounds = collider.bounds; any = true; } - } - if (!any) return centre; - - Vector3 away = transform.position - bounds.center; - away.y = 0f; - if (away.sqrMagnitude < 0.01f) away = station.Transform.forward; - float reach = Mathf.Max(bounds.extents.x, bounds.extents.z) + 1f; - - Vector3 point = bounds.center + away.normalized * reach; - point.y = centre.y; - return point; - } - - 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", - }; - - internal 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 deleted file mode 100644 index 669d0c0..0000000 --- a/JotunnModStub/Alfar/AlfarDrones.cs +++ /dev/null @@ -1,710 +0,0 @@ -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; - // A flyer's MoveTo lifts its goal to m_flyAltitudeMin above whatever solid is under it, - // the rock top included: at the vanilla height the miners hovered over a deposit out of - // reach and never struck. - if (ai != null && miner) { ai.m_flyAltitudeMin = 0.5f; ai.m_flyAltitudeMax = 2f; } - - 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; - - // The job lives in the drone's ZDO, not only in these fields: Valheim destroys a creature - // when its zone unloads and builds a fresh one when the zone comes back, and the fresh - // one had a zero Centre, so it searched around the world origin and stood idle. The - // birth time is network time, so a rebuilt drone does not get a new two minutes either. - private static readonly int CentreKey = "rov_graf_centre".GetStableHashCode(); - private static readonly int RadiusKey = "rov_graf_radius".GetStableHashCode(); - private static readonly int LifeKey = "rov_graf_life".GetStableHashCode(); - private static readonly int BornKey = "rov_graf_born".GetStableHashCode(); - - private const float Reach = 4f; - - private bool loaded; - private double bornAt; - private float nextStrike; - private Component target; - private float lastDistance = -1f; - private int strikes; - private string lastHit = "none"; - - public static readonly List All = new List(); - - private void OnEnable() { All.Add(this); } - private void OnDisable() { All.Remove(this); } - - private static readonly System.Reflection.MethodInfo MoveToMethod = - AccessTools.Method(typeof(BaseAI), "MoveTo", new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) }); - - private static double Now => ZNet.instance != null ? ZNet.instance.GetTimeSeconds() : Time.time; - - /// Called by the throw right after the drone is made: the job, into the ZDO. - public void Assign(Vector3 centre, float radius, float liveSeconds) - { - Centre = centre; - Radius = radius; - LiveSeconds = liveSeconds; - bornAt = Now; - loaded = true; - - ZNetView nview = GetComponent(); - if (nview == null || !nview.IsValid()) return; - ZDO zdo = nview.GetZDO(); - zdo.Set(CentreKey, centre); - zdo.Set(RadiusKey, radius); - zdo.Set(LifeKey, liveSeconds); - zdo.Set(BornKey, (long)(bornAt * 1000.0)); - } - - /// - /// A drone rebuilt from its ZDO reads its job back. One with no job at all (thrown by an - /// older build) digs around where it stands, which is where it was thrown. - /// - private void Load() - { - loaded = true; - ZNetView nview = GetComponent(); - ZDO zdo = nview != null && nview.IsValid() ? nview.GetZDO() : null; - long born = zdo != null ? zdo.GetLong(BornKey, 0L) : 0L; - if (born == 0L) - { - Centre = transform.position; - bornAt = Now; - return; - } - Centre = zdo.GetVec3(CentreKey, transform.position); - Radius = zdo.GetFloat(RadiusKey, Radius); - LiveSeconds = zdo.GetFloat(LifeKey, LiveSeconds); - bornAt = born / 1000.0; - } - - public bool Tick(MonsterAI ai, float dt) - { - if (!loaded) Load(); - - if (Now - bornAt >= LiveSeconds) - { - ZNetView nview = GetComponent(); - if (nview != null && nview.IsValid() && nview.IsOwner()) ZNetScene.instance.Destroy(gameObject); - return true; - } - - // A deposit another drone just broke is still there until the end of the frame, with a - // dead network view: drop it and look again. - if (target == null || !target.gameObject.activeInHierarchy || !Live(target)) target = FindDeposit(); - Vector3 point = Vector3.zero; - Collider area = target != null ? NearestArea(target, out point) : null; - if (area == null) { target = null; ai.StopMoving(); return true; } - - // Measured to the closest point of the rock, not to its root: a copper deposit's root - // sits at its base inside the mesh, so a drone aiming there stopped on top of the rock - // and never came within reach. - float distance = Vector3.Distance(transform.position, point); - lastDistance = distance; - - if (distance > Reach) - { - 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, area, point); - strikes++; - return true; - } - - private static string[] names; - private static string namesSource; - - // Read again when the config line changes, so an edit in game counts without a restart. - private static string[] Deposits - { - get - { - string value = AlfarNexusConfig.MinerDeposits.Value; - if (names == null || namesSource != value) - { - namesSource = value; - names = value.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries); - } - return names; - } - } - - private static 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 = DepositOf(collider); - if (deposit == null) continue; - - if (!Live(deposit)) continue; - string prefabName = DepositName(deposit); - if (!IsPrecious(prefabName)) continue; - - float distance = Vector3.Distance(transform.position, deposit.transform.position); - if (distance < bestDistance) { best = deposit; bestDistance = distance; } - } - return best; - } - - /// - /// The live hit area of the deposit closest to the drone, and the closest point on it. - /// MineRock and MineRock5 only take a hit on one of their own areas; a MineRock with an area - /// root (tin) keeps its base model collider apart, and a hit on that one is thrown away. - /// Broken areas are switched off, so only active colliders count. - /// - private Collider NearestArea(Component deposit, out Vector3 point) - { - point = Vector3.zero; - MineRock rock = deposit as MineRock; - GameObject root = rock != null && rock.m_areaRoot != null ? rock.m_areaRoot : deposit.gameObject; - - Collider best = null; - float bestDistance = float.MaxValue; - foreach (Collider collider in root.GetComponentsInChildren()) - { - if (collider == null || !collider.enabled) continue; - Vector3 closest = collider.bounds.ClosestPoint(transform.position); - float distance = Vector3.Distance(transform.position, closest); - if (distance < bestDistance) { best = collider; bestDistance = distance; point = closest; } - } - return best; - } - - private void Strike(Component deposit, Collider area, Vector3 point) - { - IDestructible destructible = deposit as IDestructible; - if (destructible == null) { lastHit = $"{deposit.GetType().Name} is not IDestructible"; 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_hitCollider = area; - hit.m_point = point; - hit.m_dir = (area.bounds.center - transform.position).normalized; - // Vanilla MineRock (tin) reads the attacker's ZDOID for its hit effects without a null - // check: a hit with no attacker throws before the area can break. - hit.SetAttacker(GetComponent()); - - // Overwritten by the patches below at each step the hit gets through. Vanilla runs the - // RPC on this machine at once when we own the deposit, so `striking` is still set then. - lastHit = "Damage not entered"; - striking = this; - rpcRan = false; - try - { - destructible.Damage(hit); - - // The F8 readout showed the hit entering Damage with every gate open and this - // machine owning the deposit, and the RPC handler never running: the routed call - // left for the network instead of being handled here. When we own the deposit, - // call its own handler directly - the same resistance, tier and break logic, only - // without the routing. - if (!rpcRan && OwnsDeposit(deposit)) StrikeDirect(deposit, area, hit); - } - finally { striking = null; } - } - - private static bool rpcRan; - - private static readonly System.Reflection.MethodInfo DestructibleRpc = AccessTools.Method(typeof(Destructible), "RPC_Damage"); - private static readonly System.Reflection.MethodInfo MineRockRpc = AccessTools.Method(typeof(MineRock), "RPC_Hit"); - private static readonly System.Reflection.MethodInfo MineRockArea = AccessTools.Method(typeof(MineRock), "GetAreaIndex"); - private static readonly System.Reflection.MethodInfo MineRock5Rpc = AccessTools.Method(typeof(MineRock5), "RPC_Damage"); - private static readonly System.Reflection.MethodInfo MineRock5Area = AccessTools.Method(typeof(MineRock5), "GetAreaIndex"); - private static readonly System.Reflection.FieldInfo RpcIdField = AccessTools.Field(typeof(ZRoutedRpc), "m_id"); - - private static bool OwnsDeposit(Component deposit) - { - ZNetView nview = deposit.GetComponent(); - return nview != null && nview.IsValid() && nview.IsOwner(); - } - - private void StrikeDirect(Component deposit, Collider area, HitData hit) - { - long sender = ZDOMan.GetSessionID(); - string entry = lastHit; - try - { - if (deposit is Destructible && DestructibleRpc != null) - { - DestructibleRpc.Invoke(deposit, new object[] { sender, hit }); - } - else if (deposit is MineRock && MineRockRpc != null && MineRockArea != null) - { - int index = (int)MineRockArea.Invoke(deposit, new object[] { area }); - if (index < 0) { lastHit = "direct: collider is not a MineRock area"; return; } - MineRockRpc.Invoke(deposit, new object[] { sender, hit, index }); - } - else if (deposit is MineRock5 && MineRock5Rpc != null && MineRock5Area != null) - { - int index = (int)MineRock5Area.Invoke(deposit, new object[] { area }); - if (index < 0) { lastHit = "direct: collider is not a MineRock5 area"; return; } - MineRock5Rpc.Invoke(deposit, new object[] { sender, hit, index }); - } - else - { - lastHit = $"direct: no handler for {deposit.GetType().Name}"; - return; - } - lastHit = $"direct, {lastHit} | before: {entry}"; - } - catch (System.Exception ex) - { - System.Exception inner = ex.InnerException ?? ex; - lastHit = $"direct failed: {inner.GetType().Name}: {inner.Message}"; - Jotunn.Logger.LogWarning($"[Alfar] Grafvaettir direct hit failed: {inner}"); - } - } - - // ─── F8 diagnostics: what each hit did on arrival ────────────────────── - - private static AlfarMiner striking; - - private static AlfarMiner MinerOf(HitData hit) - { - if (striking != null) return striking; - Character attacker = hit != null ? hit.GetAttacker() : null; - return attacker != null ? attacker.GetComponent() : null; - } - - private static readonly System.Reflection.FieldInfo FirstFrameField = AccessTools.Field(typeof(Destructible), "m_firstFrame"); - - /// The gates in front of the RPC: whose deposit it is and whether the view is live. - private static void RecordEntry(Component deposit, string extra) - { - if (striking == null) return; - ZNetView nview = deposit.GetComponent(); - bool valid = nview != null && nview.IsValid(); - long owner = valid ? nview.GetZDO().GetOwner() : -1L; - long me = ZDOMan.GetSessionID(); - Character attacker = striking.GetComponent(); - object rpcId = RpcIdField != null && ZRoutedRpc.instance != null ? RpcIdField.GetValue(ZRoutedRpc.instance) : null; - striking.lastHit = $"Damage entered{extra} valid={valid} owner={owner} session={me} rpcId={rpcId} " + - $"attackerZdo={(attacker != null ? attacker.GetZDOID().ToString() : "none")}, no RPC"; - } - - [HarmonyPatch(typeof(Destructible), nameof(Destructible.Damage))] - public static class Alfar_Miner_DestructibleEnter_Patch - { - public static void Prefix(Destructible __instance) - { - object first = FirstFrameField != null ? FirstFrameField.GetValue(__instance) : null; - RecordEntry(__instance, $" firstFrame={first}"); - } - } - - [HarmonyPatch(typeof(MineRock), nameof(MineRock.Damage))] - public static class Alfar_Miner_MineRockEnter_Patch - { - public static void Prefix(MineRock __instance) => RecordEntry(__instance, ""); - } - - [HarmonyPatch(typeof(MineRock5), nameof(MineRock5.Damage))] - public static class Alfar_Miner_MineRock5Enter_Patch - { - public static void Prefix(MineRock5 __instance) => RecordEntry(__instance, ""); - } - - private static void Record(HitData hit, string kind, float before, float after, int minTier) - { - AlfarMiner miner = MinerOf(hit); - if (miner == null) return; - if (miner == striking) rpcRan = true; - miner.lastHit = $"{kind} hp {before:0.#}->{after:0.#} dmg {hit.GetTotalDamage():0.#} " + - $"pick {hit.m_damage.m_pickaxe:0.#} tier {hit.m_toolTier}/{minTier}"; - } - - [HarmonyPatch(typeof(Destructible), "RPC_Damage")] - public static class Alfar_Miner_DestructibleHit_Patch - { - private static float Health(Destructible d) - { - ZNetView nview = d.GetComponent(); - return nview != null && nview.IsValid() ? nview.GetZDO().GetFloat(ZDOVars.s_health, d.m_health) : -1f; - } - - public static void Prefix(Destructible __instance, HitData hit, out float __state) - { - __state = MinerOf(hit) != null ? Health(__instance) : -1f; - } - - public static void Postfix(Destructible __instance, HitData hit, float __state) - { - if (MinerOf(hit) == null) return; - Record(hit, "Destructible", __state, Health(__instance), __instance.m_minToolTier); - } - } - - [HarmonyPatch(typeof(MineRock), "RPC_Hit")] - public static class Alfar_Miner_MineRockHit_Patch - { - private static float Health(MineRock rock, int area) - { - ZNetView nview = rock.GetComponent(); - return nview != null && nview.IsValid() ? nview.GetZDO().GetFloat("Health" + area, rock.GetHealth()) : -1f; - } - - public static void Prefix(MineRock __instance, HitData hit, int hitAreaIndex, out float __state) - { - __state = MinerOf(hit) != null ? Health(__instance, hitAreaIndex) : -1f; - } - - public static void Postfix(MineRock __instance, HitData hit, int hitAreaIndex, float __state) - { - if (MinerOf(hit) == null) return; - Record(hit, $"MineRock area {hitAreaIndex}", __state, Health(__instance, hitAreaIndex), __instance.m_minToolTier); - } - } - - [HarmonyPatch(typeof(MineRock5), "DamageArea")] - public static class Alfar_Miner_MineRock5Hit_Patch - { - public static void Postfix(MineRock5 __instance, int hitAreaIndex, HitData hit, bool __result) - { - if (MinerOf(hit) == null) return; - Record(hit, $"MineRock5 area {hitAreaIndex} damaged={__result}", -1f, -1f, __instance.m_minToolTier); - } - } - - private static bool Live(Component deposit) - { - ZNetView nview = deposit.GetComponent(); - return nview != null && nview.IsValid(); - } - - /// - /// The deposit's prefab name, read from its ZDO. Not from the GameObject: MineRock5 renames - /// its own object to "___MineRock5 m_meshFilter" in Awake, so a broken copper vein - /// (rock4_copper_frac) never matched the list and the drones stopped after the first blow. - /// - private static string DepositName(Component deposit) - { - ZNetView nview = deposit.GetComponent(); - if (nview != null && nview.IsValid() && ZNetScene.instance != null) - { - GameObject prefab = ZNetScene.instance.GetPrefab(nview.GetZDO().GetPrefab()); - if (prefab != null) return prefab.name; - } - return Utils.GetPrefabName(deposit.gameObject); - } - - private static Component DepositOf(Collider collider) - { - Component deposit = collider.GetComponentInParent(); - if (deposit == null) deposit = collider.GetComponentInParent(); - if (deposit == null) deposit = collider.GetComponentInParent(); - return deposit; - } - - /// - /// F8 readout: what the camera looks at (is it a deposit, of which kind, on the list?) and - /// what each live miner is doing (its target, how far, how many strikes). - /// - public static void DebugReport(Player player) - { - var lines = new List(); - Transform aim = GameCamera.instance != null ? GameCamera.instance.transform : player.transform; - if (Physics.Raycast(aim.position, aim.forward, out RaycastHit hit, 50f, ~0, QueryTriggerInteraction.Ignore)) - { - Component deposit = DepositOf(hit.collider); - string prefabName = deposit != null ? DepositName(deposit) : Utils.GetPrefabName(hit.collider.transform.root.gameObject); - lines.Add($"[RoV graf] look: {hit.collider.name} on {prefabName} " + - (deposit != null ? $"{deposit.GetType().Name} listed={IsPrecious(prefabName)}" : "not a deposit")); - } - else lines.Add("[RoV graf] look: nothing within 50m"); - - foreach (AlfarMiner miner in All) - { - if (miner == null) continue; - string targetName = miner.target != null ? DepositName(miner.target) : "none"; - lines.Add($"[RoV graf] miner {Vector3.Distance(miner.transform.position, player.transform.position):0}m away: " + - $"target {targetName} dist {miner.lastDistance:0.0} strikes {miner.strikes} " + - $"age {Now - miner.bornAt:0}s centre {miner.Centre} r {miner.Radius:0} | last hit: {miner.lastHit}"); - } - - foreach (string line in lines) - { - Debug.Log(line); - player.Message(MessageHud.MessageType.TopLeft, line); - } - } - - [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 deleted file mode 100644 index 5d79655..0000000 --- a/JotunnModStub/Alfar/AlfarEitr.cs +++ /dev/null @@ -1,166 +0,0 @@ -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/AlfarFireChest.cs b/JotunnModStub/Alfar/AlfarFireChest.cs deleted file mode 100644 index ffff98a..0000000 --- a/JotunnModStub/Alfar/AlfarFireChest.cs +++ /dev/null @@ -1,166 +0,0 @@ -using System.Collections.Generic; -using Jotunn.Managers; -using UnityEngine; - -namespace RacesOfValheim -{ - /// - /// The Eldividarkista's own body. Players kept mistaking a plain "Wood chest" for it, so it must - /// not look like any chest they can build: the box and lid are the Mistlands dvergr crate (a prop - /// nobody can place), repainted as blackened iron with an aged-bronze frame - /// (scripts/paint_fire_chest.py), with an iron grate on the front. - /// - /// Behind the grate the fire shows only while the chest holds wood the drones may burn: a dark - /// grate means empty. No light source, on purpose - a base full of chests must not glow. - /// - public static class AlfarFireChest - { - private const string CrateName = "dvergrprops_crate"; - private const string EmbersSource = "fx_Torch_Carried"; - - // The crate is a 1.02 m cube, stretched into a chest about the size of the vanilla one: - // 1.6 m wide, 0.8 m deep. Its front face (+z, away from the lid's hinge) ends up here. - private static readonly Vector3 Stretch = new Vector3(1.6f, 1f, 0.8f); - private const float FrontZ = 0.515f * 0.8f; - private const float LidY = 0.81f; - private const float GrateWidth = 0.62f * 1.6f; - private const int GrateGaps = 10; - private const float GrateHeight = 0.36f; - private const float GrateY = 0.42f; - - private static readonly Color Ember = new Color(1f, 0.42f, 0.1f); - - /// Swaps the cloned wood chest's meshes for the fire chest. False leaves the wood - /// chest's look in place, with a warning, rather than an invisible chest. - public static bool Build(GameObject prefab) - { - GameObject crate = PrefabManager.Cache.GetPrefab(CrateName); - Transform crateNew = crate != null ? crate.transform.Find("new") : null; - Transform visual = prefab.transform.Find("New"); - if (crateNew == null || crateNew.childCount < 3 || visual == null) - { - Jotunn.Logger.LogWarning("[Alfar] No dvergr crate to build the Eldividarkista from; it keeps the wood chest's look."); - return false; - } - - // The wood chest's box, lids and LOD group go; "New" itself stays, because WearNTear - // switches it as the piece's healthy look. - for (int i = visual.childCount - 1; i >= 0; i--) Object.DestroyImmediate(visual.GetChild(i).gameObject); - LODGroup lod = visual.GetComponent(); - if (lod != null) Object.DestroyImmediate(lod); - - // The crate's high meshes, in the order the prefab keeps them: box, contents, lid. The - // contents are the glowing dvergr cargo and stay behind. - GameObject body = Object.Instantiate(crateNew.GetChild(0).gameObject, visual, false); - body.name = "body"; - body.transform.localScale = Vector3.Scale(body.transform.localScale, Stretch); - GameObject lidClosed = Object.Instantiate(crateNew.GetChild(2).gameObject, visual, false); - lidClosed.name = "lid_closed"; - lidClosed.transform.localScale = Vector3.Scale(lidClosed.transform.localScale, Stretch); - - // The open lid: the closed one turned up 100 degrees about its back edge. - GameObject lidOpen = Object.Instantiate(lidClosed, visual, false); - lidOpen.name = "lid_open"; - foreach (Collider collider in lidOpen.GetComponentsInChildren(true)) Object.DestroyImmediate(collider); - Vector3 hinge = new Vector3(0f, LidY, -FrontZ); - Quaternion turn = Quaternion.Euler(-100f, 0f, 0f); - lidOpen.transform.localPosition = hinge + turn * (lidClosed.transform.localPosition - hinge); - lidOpen.transform.localRotation = turn * lidClosed.transform.localRotation; - lidOpen.SetActive(false); - - Container container = prefab.GetComponent(); - if (container != null) - { - container.m_open = lidOpen; - container.m_closed = lidClosed; - } - - // Only a retextured material is a copy; without the paint, writing to it would change every - // dvergr crate in the Mistlands too. - Texture2D paint = PieceLook.LoadTexture("AlfarFireChest_d.png"); - if (paint != null) PieceLook.Retexture(visual, new Dictionary { { "Crate_d", paint } }); - Material iron = paint != null ? body.GetComponent()?.sharedMaterial : null; - if (iron != null) - { - // The crate's normal map is wood planks; on plates it would draw seams that are not there. - if (iron.HasProperty("_BumpMap")) iron.SetTexture("_BumpMap", null); - if (iron.HasProperty("_Metallic")) iron.SetFloat("_Metallic", 0.6f); - if (iron.HasProperty("_Glossiness")) iron.SetFloat("_Glossiness", 0.45f); - } - - Transform grate = BuildGrate(visual, iron, out Renderer glow); - ParticleSystem embers = AddEmbers(grate); - - AlfarChestGlow look = prefab.AddComponent(); - look.Glows = new[] { glow }; - look.Embers = embers; - look.GlowColor = Ember * 2f; - look.WoodOnly = true; - return true; - } - - /// The grate: a glowing plate just off the front face, a frame and bars in front of it. - private static Transform BuildGrate(Transform visual, Material iron, out Renderer glow) - { - Transform grate = new GameObject("grate").transform; - grate.SetParent(visual, false); - grate.gameObject.layer = visual.gameObject.layer; - - Material bars = iron != null ? new Material(iron) { name = "AlfarFireChest_bars" } : null; - if (bars != null) - { - bars.SetTexture("_MainTex", null); - bars.color = new Color(0.16f, 0.15f, 0.15f); - } - - glow = Block(grate, "glow", new Vector3(0f, GrateY, FrontZ + 0.005f), new Vector3(GrateWidth, GrateHeight, 0.01f), bars).GetComponent(); - - const float frame = 0.035f; - foreach (float x in new[] { -GrateWidth / 2f, GrateWidth / 2f }) - Block(grate, "frame", new Vector3(x, GrateY, FrontZ + 0.02f), new Vector3(frame, GrateHeight + frame, 0.04f), bars); - foreach (float y in new[] { GrateY - GrateHeight / 2f, GrateY + GrateHeight / 2f }) - Block(grate, "frame", new Vector3(0f, y, FrontZ + 0.02f), new Vector3(GrateWidth + frame, frame, 0.04f), bars); - - for (int i = 1; i < GrateGaps; i++) - { - float x = -GrateWidth / 2f + GrateWidth * i / GrateGaps; - Block(grate, "bar", new Vector3(x, GrateY, FrontZ + 0.02f), new Vector3(0.022f, GrateHeight, 0.03f), bars); - } - Block(grate, "bar", new Vector3(0f, GrateY, FrontZ + 0.022f), new Vector3(GrateWidth, 0.022f, 0.03f), bars); - - return grate; - } - - /// A plain box with no collider, for trim the borrowed meshes do not have. - internal static GameObject Block(Transform parent, string name, Vector3 position, Vector3 size, Material material) - { - GameObject block = GameObject.CreatePrimitive(PrimitiveType.Cube); - Object.DestroyImmediate(block.GetComponent()); - block.name = name; - block.layer = parent.gameObject.layer; - block.transform.SetParent(parent, false); - block.transform.localPosition = position; - block.transform.localScale = size; - if (material != null) block.GetComponent().sharedMaterial = material; - return block; - } - - /// The carried torch's embers, rising off the top of the grate. - private static ParticleSystem AddEmbers(Transform grate) - { - GameObject torch = PrefabManager.Cache.GetPrefab(EmbersSource); - Transform source = torch != null ? torch.transform.Find("Embers") : null; - if (source == null) - { - Jotunn.Logger.LogWarning("[Alfar] No torch embers for the Eldividarkista; its grate glows without sparks."); - return null; - } - - GameObject embers = Object.Instantiate(source.gameObject, grate, false); - embers.name = "embers"; - embers.transform.localPosition = new Vector3(0f, GrateY + GrateHeight / 2f, FrontZ + 0.05f); - embers.transform.localRotation = Quaternion.identity; - return embers.GetComponent(); - } - } -} diff --git a/JotunnModStub/Alfar/AlfarHeimkall.cs b/JotunnModStub/Alfar/AlfarHeimkall.cs deleted file mode 100644 index 49a7dc4..0000000 --- a/JotunnModStub/Alfar/AlfarHeimkall.cs +++ /dev/null @@ -1,171 +0,0 @@ -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/AlfarInputChest.cs b/JotunnModStub/Alfar/AlfarInputChest.cs deleted file mode 100644 index 6f4ea39..0000000 --- a/JotunnModStub/Alfar/AlfarInputChest.cs +++ /dev/null @@ -1,137 +0,0 @@ -using System.Collections.Generic; -using Jotunn.Managers; -using UnityEngine; - -namespace RacesOfValheim -{ - /// - /// The Inngangskista's own body, the cold twin of : the dvergr loot - /// chest of the Mistlands towns (seen, never built), its panels repainted navy steel - /// (scripts/paint_input_chest.py) and its copper trim turned silver. A cyan line set into the - /// lid shines while the chest holds anything for the drones, and goes dark once they have - /// emptied it. - /// - public static class AlfarInputChest - { - private const string SourceName = "TreasureChest_dvergrtown"; - - // The town chest is placed at 1.2 and its meshes at 1.5 on top: 1.66 m wide, a vanilla chest's size. - private const float SourceScale = 1.2f; - private const float MeshScale = 1.5f * SourceScale; - private const float LidTop = 0.48f * MeshScale; - private const float LidHalfX = 0.42f * MeshScale; - private const float LidHalfZ = 0.24f * MeshScale; - private const float InlayInset = 0.10f; - private const float InlayWidth = 0.03f; - - private static readonly Color Trim = new Color(0.9f, 0.95f, 1f); - private static readonly Color Inlay = new Color(0.35f, 0.9f, 1f); - - /// Swaps the cloned wood chest's meshes for the input chest. False leaves the wood - /// chest's look in place, with a warning. - public static bool Build(GameObject prefab) - { - GameObject source = PrefabManager.Cache.GetPrefab(SourceName); - Transform sourceNew = source != null ? source.transform.Find("New") : null; - Transform box = sourceNew != null ? sourceNew.Find("stonechest") : null; - Transform closed = sourceNew != null ? sourceNew.Find("stonechesttop_closed") : null; - Transform open = sourceNew != null ? sourceNew.Find("stonechesttop_open") : null; - Transform visual = prefab.transform.Find("New"); - if (box == null || closed == null || open == null || visual == null) - { - Jotunn.Logger.LogWarning("[Alfar] No dvergr chest to build the Inngangskista from; it keeps the wood chest's look."); - return false; - } - - for (int i = visual.childCount - 1; i >= 0; i--) Object.DestroyImmediate(visual.GetChild(i).gameObject); - LODGroup lod = visual.GetComponent(); - if (lod != null) Object.DestroyImmediate(lod); - - GameObject body = Copy(box, visual, "body"); - GameObject lidClosed = Copy(closed, visual, "lid_closed"); - GameObject lidOpen = Copy(open, visual, "lid_open"); - lidOpen.SetActive(false); - - Container container = prefab.GetComponent(); - if (container != null) - { - container.m_open = lidOpen; - container.m_closed = lidClosed; - } - - Texture2D paint = PieceLook.LoadTexture("AlfarInputChest_d.png"); - if (paint == null) return true; // the dvergr chest as it is: still not a vanilla chest - PieceLook.Retexture(visual, new Dictionary { { "dvergrchestWorn_d", paint } }); - - // The trim shares the anvil's texture, so it is recoloured on a copy instead; the panels' - // material is already a copy from Retexture. - var copies = new Dictionary(); - Material panel = null; - foreach (Renderer renderer in visual.GetComponentsInChildren(true)) - { - Material[] materials = renderer.sharedMaterials; - for (int i = 0; i < materials.Length; i++) - { - Material material = materials[i]; - if (material == null) continue; - if (material.name.EndsWith("_rov")) { panel = panel ?? material; continue; } - if (!material.name.StartsWith("dvergr_metal_furnmiture")) continue; - - if (!copies.TryGetValue(material, out Material trim)) - { - trim = new Material(material) { name = material.name + "_rov" }; - trim.color = Trim; - if (trim.HasProperty("_MetalColor")) trim.SetColor("_MetalColor", Trim); - copies[material] = trim; - } - materials[i] = trim; - } - renderer.sharedMaterials = materials; - } - - AlfarChestGlow look = prefab.AddComponent(); - look.Glows = BuildInlay(lidClosed.transform, panel); - look.GlowColor = Inlay * 1.6f; - look.WoodOnly = false; - return true; - } - - /// A copy of one of the town chest's parts, at the town chest's size and on the piece layer. - private static GameObject Copy(Transform part, Transform parent, string name) - { - GameObject copy = Object.Instantiate(part.gameObject, parent, false); - copy.name = name; - copy.transform.localPosition = part.localPosition * SourceScale; - copy.transform.localScale = part.localScale * SourceScale; - foreach (Transform t in copy.GetComponentsInChildren(true)) t.gameObject.layer = parent.gameObject.layer; - return copy; - } - - /// The cyan line on the lid: four thin strips just above it, inset from the edge. They - /// hang off the closed lid, so they go with it when the chest opens. The lid is scaled, so the - /// sizes are divided back out of it. - private static Renderer[] BuildInlay(Transform lid, Material panel) - { - Material cold = panel != null ? new Material(panel) { name = "AlfarInputChest_inlay" } : null; - if (cold != null) - { - cold.SetTexture("_MainTex", null); - cold.color = new Color(0.08f, 0.12f, 0.16f); - } - - float k = 1f / lid.localScale.x; - float x = LidHalfX - InlayInset, z = LidHalfZ - InlayInset, y = LidTop + 0.004f; - var strips = new List(); - foreach (float side in new[] { -z, z }) - strips.Add(Strip(lid, new Vector3(0f, y, side) * k, new Vector3(2f * x + InlayWidth, 0.01f, InlayWidth) * k, cold)); - foreach (float side in new[] { -x, x }) - strips.Add(Strip(lid, new Vector3(side, y, 0f) * k, new Vector3(InlayWidth, 0.01f, 2f * z) * k, cold)); - return strips.ToArray(); - } - - private static Renderer Strip(Transform lid, Vector3 position, Vector3 size, Material material) - { - return AlfarFireChest.Block(lid, "inlay", position, size, material).GetComponent(); - } - } -} diff --git a/JotunnModStub/Alfar/AlfarLevitation.cs b/JotunnModStub/Alfar/AlfarLevitation.cs deleted file mode 100644 index 206c8c7..0000000 --- a/JotunnModStub/Alfar/AlfarLevitation.cs +++ /dev/null @@ -1,126 +0,0 @@ -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 && CrouchHeld()) 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() - { - // "Jump" is the keyboard binding only; the pad's button is a separate "JoyJump", read - // the way PlayerController reads it, kept off while a radial menu has the pad. - return ZInput.GetButton("Jump") || (ZInput.GetButton("JoyJump") && !Hud.InRadial()); - } - - private static bool CrouchHeld() - { - // Same split as jump: PlayerController ORs "Crouch" with "JoyCrouch". - return ZInput.GetButton("Crouch") || (ZInput.GetButton("JoyCrouch") && !Hud.InRadial()); - } - - 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 deleted file mode 100644 index e70c5cb..0000000 --- a/JotunnModStub/Alfar/AlfarLjosgard.cs +++ /dev/null @@ -1,108 +0,0 @@ -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 deleted file mode 100644 index 2bfc3ae..0000000 --- a/JotunnModStub/Alfar/AlfarMark.cs +++ /dev/null @@ -1,149 +0,0 @@ -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 deleted file mode 100644 index b2c5a95..0000000 --- a/JotunnModStub/Alfar/AlfarMiners.cs +++ /dev/null @@ -1,103 +0,0 @@ -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) - { - player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_graf_cooldown", Mathf.CeilToInt(readyAt - Time.time))); - 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.Assign(point, AlfarPowerConfig.GrafRadius.Value, 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 deleted file mode 100644 index 26024f5..0000000 --- a/JotunnModStub/Alfar/AlfarNexus.cs +++ /dev/null @@ -1,578 +0,0 @@ -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); - } - - // The floating pyramid; the blue table stays as the fallback if it cannot be built. - bool pyramid = AlfarNexusLook.Build(prefab); - if (!pyramid) 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 = (pyramid ? AlfarChests.IconFrom("AlfarNexus_icon.png") : null) ?? 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 deleted file mode 100644 index 84ffd4c..0000000 --- a/JotunnModStub/Alfar/AlfarNexusConfig.cs +++ /dev/null @@ -1,149 +0,0 @@ -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))); - - // Copper deposits are rock4_copper (and rock4_copper_frac once hit), crypt scrap is mudpile; - // the first default missed both, so a config still holding it is moved to the new one. - const string oldTargets = "MineRock_Copper,MineRock_Tin,MineRock_Iron,silvervein,rock3_silver,giant_brain"; - const string targets = "rock4_copper,MineRock_Copper,MineRock_Tin,MineRock_Iron,mudpile,silvervein,rock3_silver,giant_brain"; - MinerDeposits = config.Bind(drone, "Mining Targets", targets, - new ConfigDescription("Comma separated parts of prefab names the mining drones dig (case does not matter). Soft tissue comes from giant_brain.")); - if (MinerDeposits.Value == oldTargets) MinerDeposits.Value = targets; - 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/AlfarNexusLook.cs b/JotunnModStub/Alfar/AlfarNexusLook.cs deleted file mode 100644 index 34c1fe7..0000000 --- a/JotunnModStub/Alfar/AlfarNexusLook.cs +++ /dev/null @@ -1,217 +0,0 @@ -using Jotunn.Managers; -using UnityEngine; - -namespace RacesOfValheim -{ - /// - /// The Ljoskjarne's body: a stone pyramid, 2 m to a side and 2 m tall, floating 0.8 m above the - /// ground. Dark steel carved with Valheim's own runes (the Ashlands rune tile's glyphs, laid out by - /// scripts/paint_nexus.py), and a cyan seam down the middle of each face. - /// - /// The seam is painted into the faces' glow map, not built. Bars standing on the faces, lit or - /// unlit, lost part of their length to the face on whichever side looked one way in the world, - /// as the pyramid turned; a line in the face's own pixels has nothing to hide behind. - /// - /// Only the look moves. The piece keeps one still collider from the ground up, so building on it, - /// support, hovering and the E key behave as before; the pyramid bobs and turns on each client by - /// itself, nothing over the network. The seam breathes, and burns brighter while crystals wait. - /// - public static class AlfarNexusLook - { - private const float Height = 2f; - private const float HalfBase = 1f; - private const float Lift = 0.8f; - private const string SourceMaterialPrefab = "piece_cartographytable"; - private const string EmbersSource = "fx_Torch_Carried"; - - private static readonly Color Seam = new Color(0.35f, 0.75f, 1f); - - /// Strips the cartography table's body and puts the pyramid in its place. False leaves - /// the table, with a warning, so the Nexus is never invisible. - public static bool Build(GameObject prefab) - { - Texture2D face = PieceLook.LoadTexture("AlfarNexus_face.png"); - Texture2D glow = PieceLook.LoadTexture("AlfarNexus_glow.png"); - Texture2D bumps = PieceLook.LoadTexture("AlfarNexus_n.png", true); - Renderer tableRenderer = prefab.transform.Find("new/high")?.GetComponent(); - if (face == null || glow == null || tableRenderer == null || tableRenderer.sharedMaterial == null) - { - Jotunn.Logger.LogWarning("[Alfar] Could not build the Ljoskjarne's pyramid; it keeps the cartography table's look."); - return false; - } - - Material stone = new Material(tableRenderer.sharedMaterial) { name = "AlfarNexus_stone" }; - stone.color = Color.white; - stone.SetTexture("_MainTex", face); - // Forged, not polished: the plate's own grain in the normal map, and a dull sheen. - stone.SetTexture("_BumpMap", bumps); - if (bumps != null) stone.EnableKeyword("_NORMALMAP"); - else stone.DisableKeyword("_NORMALMAP"); - if (stone.HasProperty("_MetallicGlossMap")) stone.SetTexture("_MetallicGlossMap", null); - if (stone.HasProperty("_Metallic")) stone.SetFloat("_Metallic", 0.6f); - if (stone.HasProperty("_Glossiness")) stone.SetFloat("_Glossiness", 0.3f); - // Custom/Piece samples its noise in world space unless told the object moves, as boats and - // carts do; on a turning pyramid the blotches would slide across the faces. - stone.EnableKeyword("_MOVEABLEOBJECT_ON"); - if (stone.HasProperty("_MoveableObject")) stone.SetFloat("_MoveableObject", 1f); - stone.SetTexture("_EmissionMap", glow); - stone.EnableKeyword("_EMISSION"); - stone.SetColor("_EmissionColor", Seam); - - // The table goes whole: its meshes, its damage states, its fragments and its four colliders. - for (int i = prefab.transform.childCount - 1; i >= 0; i--) - Object.DestroyImmediate(prefab.transform.GetChild(i).gameObject); - WearNTear wear = prefab.GetComponent(); - if (wear != null) - { - wear.m_new = null; - wear.m_worn = null; - wear.m_broken = null; - wear.m_fragmentRoots = new GameObject[0]; - } - - // One still collider, from the ground to the tip, a little inside the faces. - GameObject solid = new GameObject("collider") { layer = prefab.layer }; - solid.transform.SetParent(prefab.transform, false); - BoxCollider box = solid.AddComponent(); - box.center = new Vector3(0f, (Lift + Height) / 2f, 0f); - box.size = new Vector3(HalfBase * 1.4f, Lift + Height, HalfBase * 1.4f); - - Transform floating = new GameObject("float").transform; - floating.SetParent(prefab.transform, false); - floating.gameObject.layer = prefab.layer; - - MeshRenderer pyramid = Part(floating, "pyramid", PyramidMesh(), stone).GetComponent(); - - NexusLook look = prefab.AddComponent(); - look.Float = floating; - look.SeamRenderer = pyramid; - look.Motes = AddMotes(prefab.transform); - return true; - } - - private static GameObject Part(Transform parent, string name, Mesh mesh, Material material) - { - GameObject part = new GameObject(name) { layer = parent.gameObject.layer }; - part.transform.SetParent(parent, false); - part.AddComponent().sharedMesh = mesh; - part.AddComponent().sharedMaterial = material; - return part; - } - - private static Vector3 Apex => new Vector3(0f, Lift + Height, 0f); - - private static Vector3[] BaseCorners => new[] - { - new Vector3(-HalfBase, Lift, -HalfBase), new Vector3(HalfBase, Lift, -HalfBase), - new Vector3(HalfBase, Lift, HalfBase), new Vector3(-HalfBase, Lift, HalfBase), - }; - - /// Four faces, each with its own three corners so the shading stays flat and every face - /// shows the whole carving (u along the base, v = 1 at the tip), and the underside. - private static Mesh PyramidMesh() - { - Vector3[] c = BaseCorners; - var vertices = new Vector3[16]; - var uvs = new Vector2[16]; - var triangles = new int[18]; - for (int i = 0; i < 4; i++) - { - // Wound clockwise seen from outside, which is Unity's front face. - vertices[i * 3] = c[(i + 1) % 4]; - vertices[i * 3 + 1] = c[i]; - vertices[i * 3 + 2] = Apex; - uvs[i * 3] = new Vector2(1f, 0f); - uvs[i * 3 + 1] = new Vector2(0f, 0f); - uvs[i * 3 + 2] = new Vector2(0.5f, 1f); - triangles[i * 3] = i * 3; - triangles[i * 3 + 1] = i * 3 + 1; - triangles[i * 3 + 2] = i * 3 + 2; - } - for (int i = 0; i < 4; i++) { vertices[12 + i] = c[i]; uvs[12 + i] = new Vector2(0.1f, 0.02f); } - int[] under = { 12, 13, 14, 12, 14, 15 }; - System.Array.Copy(under, 0, triangles, 12, 6); - - Mesh mesh = new Mesh { name = "AlfarNexus_pyramid", vertices = vertices, uv = uvs, triangles = triangles }; - mesh.RecalculateNormals(); - mesh.RecalculateBounds(); - return mesh; - } - - /// A few cyan motes drifting up from the ground under it: the torch's embers, recoloured, - /// spread over the pyramid's shadow and slowed down. - private static ParticleSystem AddMotes(Transform root) - { - GameObject torch = PrefabManager.Cache.GetPrefab(EmbersSource); - Transform source = torch != null ? torch.transform.Find("Embers") : null; - if (source == null) return null; - - GameObject motes = Object.Instantiate(source.gameObject, root, false); - motes.name = "motes"; - motes.transform.localPosition = new Vector3(0f, 0.05f, 0f); - motes.transform.localRotation = Quaternion.identity; - PieceLook.Rehue(motes.transform, Seam * 2f); - - ParticleSystem particles = motes.GetComponent(); - if (particles != null) - { - ParticleSystem.ShapeModule shape = particles.shape; - shape.enabled = true; - shape.shapeType = ParticleSystemShapeType.Circle; - shape.radius = HalfBase; - shape.rotation = new Vector3(-90f, 0f, 0f); - ParticleSystem.MainModule main = particles.main; - main.simulationSpeed = 0.5f; - } - return particles; - } - - /// The motion and the seam's light, per client. - public class NexusLook : MonoBehaviour - { - public Transform Float; - public Renderer SeamRenderer; - public ParticleSystem Motes; - - private const float BobHeight = 0.08f; - private const float BobSeconds = 4.5f; - private const float TurnSeconds = 40f; - private const float BreathSeconds = 3.5f; - - private AlfarNexusBehaviour m_nexus; - private Material m_seam; - private float m_phase; - private float m_ready; // eases between 0 (no crystals) and 1, so the brightening is not a jump - - private void Awake() - { - m_nexus = GetComponent(); - if (SeamRenderer != null) m_seam = SeamRenderer.material; // this one's own copy, to animate - // Two Nexuses side by side must not bob in step. - m_phase = (Mathf.Abs(transform.position.x * 0.37f + transform.position.z * 0.71f)) % 10f; - } - - private void Update() - { - float t = Time.time + m_phase; - if (Float != null) - { - Float.localPosition = new Vector3(0f, Mathf.Sin(t * 2f * Mathf.PI / BobSeconds) * BobHeight, 0f); - Float.localRotation = Quaternion.Euler(0f, t * 360f / TurnSeconds, 0f); - } - - if (m_seam == null) return; - bool ready = m_nexus != null && m_nexus.Crystals > 0; - m_ready = Mathf.MoveTowards(m_ready, ready ? 1f : 0f, Time.deltaTime * 0.5f); - float breath = 0.75f + 0.25f * Mathf.Sin(t * 2f * Mathf.PI / BreathSeconds); - Color glow = Seam * breath * Mathf.Lerp(1f, 2.2f, m_ready); - m_seam.SetColor("_EmissionColor", glow); - } - - private void OnDestroy() - { - if (m_seam != null) Destroy(m_seam); - } - } - } -} diff --git a/JotunnModStub/Alfar/AlfarNexusStore.cs b/JotunnModStub/Alfar/AlfarNexusStore.cs deleted file mode 100644 index 4b17cc1..0000000 --- a/JotunnModStub/Alfar/AlfarNexusStore.cs +++ /dev/null @@ -1,171 +0,0 @@ -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