Compare commits

..

No commits in common. "localisation" and "fix-skadi-fader-moder-attack-overlap" have entirely different histories.

298 changed files with 3892 additions and 49379 deletions

View file

@ -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
}
]
}

1
.gitattributes vendored
View file

@ -1 +0,0 @@
*.sh text eol=lf

4
.gitignore vendored
View file

@ -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

View file

@ -1,179 +0,0 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>True for any player in range: the form is read off the ZDO, not local state.</summary>
public static bool IsArchon(Player player)
{
if (player == null) return false;
ZNetView nview = player.GetComponent<ZNetView>();
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<ZNetView>();
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 ─────────────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
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}).");
}
/// <summary>The cooldown Ljosstorm and Geisli wait in the form, instead of costing eitr.</summary>
public static float FreePowerCooldown => AlfarPowerConfig.ArchonFreePowerCooldown.Value;
/// <summary>
/// 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".
/// </summary>
[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;
}
}
/// <summary>Clears the state without teleporting (used by the reset command).</summary>
public static void ForceClear(Player player)
{
Active = false;
Pool = 0f;
if (player != null) Publish(player, false);
AlfarStatusEffects.ClearTimer("archon");
}
}
}

View file

@ -1,79 +0,0 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
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<Container>();
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);
}
}
}

View file

@ -1,148 +0,0 @@
using System.Collections.Generic;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
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<ItemDrop>();
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) },
}));
}
}
/// <summary>
/// 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.
/// </summary>
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<GameObject, bool> build, string iconResource)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("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<RequirementConfig>();
Piece vanilla = source.GetComponent<Piece>();
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<Container>();
if (container != null) container.m_name = hoverName;
Piece piece = prefab.GetComponent<Piece>();
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));
}
}
}

View file

@ -1,110 +0,0 @@
using Jotunn.Entities;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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 <n|full|0> sets the eitr pool: a number, "full", or 0
/// alfarhp <n> sets the current health, to try the lethal-blow case without dying
/// </summary>
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 <number|full|0> - 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 <number|full|0>"); 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 <number|full|0>");
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 <number> - 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 <number>"); return; }
if (!float.TryParse(args[0], System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out float hp))
{
Console.instance.Print("alfarhp <number>");
return;
}
player.SetHealth(Mathf.Clamp(hp, 1f, player.GetMaxHealth()));
Console.instance.Print($"[Alfar] health = {player.GetHealth():0}/{player.GetMaxHealth():0}");
}
}
}

View file

@ -1,168 +0,0 @@
using BepInEx.Configuration;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class AlfarConfig
{
/// <summary>
/// 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).
/// </summary>
public const string RaceId = "Alfar";
// ─── Look ────────────────────────────────────────────────────────────
/// <summary>The tint written into _SkinColor. Ash grey: low saturation, a hair cool.</summary>
public static ConfigEntry<Color> SkinColor;
/// <summary>
/// Height against a normal Viking: +5%, design doc sec. 7.1. Applied to the Visual child's Y,
/// never the root (RaceEyeHeight explains why).
/// </summary>
public static ConfigEntry<float> HeightScale;
/// <summary>
/// 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.
/// </summary>
public static ConfigEntry<float> WidthScale;
/// <summary>
/// Scales the almond eyes (EyeExtent). The default 0.8 is the tuned grey look; raise it for
/// bigger eyes.
/// </summary>
public static ConfigEntry<float> 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 ───────────────────────────────────
/// <summary>
/// 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.
/// </summary>
public static ConfigEntry<float> DietMultiplier;
/// <summary>
/// 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.
/// </summary>
public static ConfigEntry<float> ShieldRate;
/// <summary>Lightning and spirit cost this many times the rate (sec. 5.1: the double cost).</summary>
public static ConfigEntry<float> ConductiveMultiplier;
/// <summary>
/// Falls cost nothing while there is any eitr (sec. 4.5: soft fall). Off, a fall is shielded
/// like any other blow.
/// </summary>
public static ConfigEntry<bool> SoftFall;
/// <summary>
/// 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.
/// </summary>
public static ConfigEntry<float> FeatherFallSpeed;
// ─── Heimkall: the death that costs a wait ───────────────────────────
/// <summary>Minutes before a second Heimkall is possible, before Yagluth (sec. 6).</summary>
public static ConfigEntry<float> HeimkallMinutes;
/// <summary>The same, once Yagluth is down.</summary>
public static ConfigEntry<float> HeimkallMinutesAfterYagluth;
/// <summary>The same, once Fader is down.</summary>
public static ConfigEntry<float> HeimkallMinutesAfterFader;
/// <summary>
/// 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.
/// </summary>
public static ConfigEntry<float> 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<float>(0f, 120f)));
HeimkallMinutesAfterYagluth = config.Bind(heimkall, "Cooldown Minutes After Yagluth", 15f,
new ConfigDescription("The cooldown once Yagluth is defeated.",
new AcceptableValueRange<float>(0f, 120f)));
HeimkallMinutesAfterFader = config.Bind(heimkall, "Cooldown Minutes After Fader", 10f,
new ConfigDescription("The cooldown once Fader is defeated.",
new AcceptableValueRange<float>(0f, 120f)));
HeimkallInvulnerableSeconds = config.Bind(heimkall, "Invulnerable Seconds", 5f,
new ConfigDescription("Seconds nothing can hurt the Alfr after arriving.",
new AcceptableValueRange<float>(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<float>(0f, 3f)));
ShieldRate = config.Bind(eitr, "Shield Rate", 1f,
new ConfigDescription("Eitr spent per point of damage absorbed (1 = 1:1).",
new AcceptableValueRange<float>(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<float>(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<float>(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<float>(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<float>(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<float>(0.5f, 3f)));
}
}
}

View file

@ -1,397 +0,0 @@
using System.Collections.Generic;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
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<GameObject>(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<Character>();
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<ZNetView>();
if (nview != null) nview.m_syncInitialScale = true;
}
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = AlfarNexusConfig.ConstructLeash.Value;
MonsterAI monster = prefab.GetComponent<MonsterAI>();
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<CharacterDrop>(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<AlfarMark>();
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<AlfarRefund>();
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<AlfarCreatureShield>();
shield.MaxShield = character != null ? character.m_health : 0f;
shield.Shield = shield.MaxShield;
RaisedThrall thrall = prefab.AddComponent<RaisedThrall>();
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 ────────────────────────────────────────────
/// <summary>
/// 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).
/// </summary>
private static bool RegisterSphere()
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("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<Projectile>();
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<GameObject>("Surtling");
Humanoid surtlingHumanoid = surtling != null ? surtling.GetComponent<Humanoid>() : 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<ItemDrop>();
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<Humanoid>();
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 ──────────────────────────────────────────────────────────
/// <summary>
/// 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).
/// </summary>
public static void Tint(GameObject prefab, Color color)
{
foreach (Renderer renderer in prefab.GetComponentsInChildren<Renderer>(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<Light>(true)) light.color = color;
}
/// <summary>
/// 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.
/// </summary>
private static void BlueFlames(GameObject prefab)
{
foreach (Transform child in prefab.GetComponentsInChildren<Transform>(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<Light>(true)) light.color = blue;
foreach (Renderer renderer in prefab.GetComponentsInChildren<SkinnedMeshRenderer>(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) ─────────────────────
/// <summary>
/// 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).
/// </summary>
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<AlfarRefund>() : null;
if (refund == null || refund.Amount <= 0 || ObjectDB.instance == null) return;
GameObject prefab = ObjectDB.instance.GetItemPrefab(refund.Item);
ItemDrop template = prefab != null ? prefab.GetComponent<ItemDrop>() : 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<RaisedThrall>() : null;
if (thrall != null) thrall.Bind(anchor);
return spawned != null;
}
/// <summary>A free spot on a ring around the Nexus, on the ground, or due south as a last resort.</summary>
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;
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,710 +0,0 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
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<GameObject>("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);
}
/// <summary>The Deathsquito's sting turned into a zap: 1 lightning, every two seconds.</summary>
private static bool RegisterZap(GameObject deathsquito)
{
Humanoid humanoid = deathsquito.GetComponent<Humanoid>();
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<ItemDrop>();
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<Character>();
if (character != null)
{
character.m_name = display;
character.m_faction = Character.Faction.Players;
character.m_health = AlfarNexusConfig.DroneHealth.Value;
}
Humanoid humanoid = prefab.GetComponent<Humanoid>();
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<MonsterAI>();
if (monster != null)
{
monster.m_attackPlayerObjects = false;
monster.m_alertRange = AlfarNexusConfig.NexusRadius.Value;
monster.m_maxChaseDistance = AlfarNexusConfig.NexusRadius.Value;
}
BaseAI ai = prefab.GetComponent<BaseAI>();
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<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
// The buzz: the continuous sound child, and the flying loop effect.
foreach (Transform child in prefab.GetComponentsInChildren<Transform>(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<AlfarDroneLook>();
AlfarMark mark = prefab.AddComponent<AlfarMark>();
mark.Role = miner ? "miner" : "drone";
AlfarCreatureShield shield = prefab.AddComponent<AlfarCreatureShield>();
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<AlfarMiner>();
}
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<AlfarDroneAI>();
work.m_fightsBack = true; // it defends itself with the zap
work.m_homeDistance = 4f;
}
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Alfar] Registered '{prefabName}'.");
}
/// <summary>
/// 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).
/// </summary>
private static void HideLegs(GameObject prefab)
{
foreach (Transform bone in prefab.GetComponentsInChildren<Transform>(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<SkinnedMeshRenderer>(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<Light>(true)) light.color = ElectricBlue;
}
/// <summary>
/// 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.
/// </summary>
public class AlfarDroneLook : MonoBehaviour
{
private Transform[] legs;
private void Awake()
{
var list = new System.Collections.Generic.List<Transform>();
foreach (Transform bone in GetComponentsInChildren<Transform>(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<AlfarDroneAI>() : null;
if (work != null) work.Bind(anchor);
return spawned != null;
}
}
/// <summary>
/// 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.
/// </summary>
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<AlfarMiner> All = new List<AlfarMiner>();
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;
/// <summary>Called by the throw right after the drone is made: the job, into the ZDO.</summary>
public void Assign(Vector3 centre, float radius, float liveSeconds)
{
Centre = centre;
Radius = radius;
LiveSeconds = liveSeconds;
bornAt = Now;
loaded = true;
ZNetView nview = GetComponent<ZNetView>();
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));
}
/// <summary>
/// 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.
/// </summary>
private void Load()
{
loaded = true;
ZNetView nview = GetComponent<ZNetView>();
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<ZNetView>();
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;
}
/// <summary>
/// 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.
/// </summary>
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<Collider>())
{
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<Character>());
// 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<ZNetView>();
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<AlfarMiner>() : null;
}
private static readonly System.Reflection.FieldInfo FirstFrameField = AccessTools.Field(typeof(Destructible), "m_firstFrame");
/// <summary>The gates in front of the RPC: whose deposit it is and whether the view is live.</summary>
private static void RecordEntry(Component deposit, string extra)
{
if (striking == null) return;
ZNetView nview = deposit.GetComponent<ZNetView>();
bool valid = nview != null && nview.IsValid();
long owner = valid ? nview.GetZDO().GetOwner() : -1L;
long me = ZDOMan.GetSessionID();
Character attacker = striking.GetComponent<Character>();
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<ZNetView>();
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<ZNetView>();
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<ZNetView>();
return nview != null && nview.IsValid();
}
/// <summary>
/// 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.
/// </summary>
private static string DepositName(Component deposit)
{
ZNetView nview = deposit.GetComponent<ZNetView>();
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<MineRock5>();
if (deposit == null) deposit = collider.GetComponentInParent<MineRock>();
if (deposit == null) deposit = collider.GetComponentInParent<Destructible>();
return deposit;
}
/// <summary>
/// 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).
/// </summary>
public static void DebugReport(Player player)
{
var lines = new List<string>();
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<AlfarMiner>();
if (miner == null) return true;
__result = miner.Tick(__instance, __0);
return false;
}
}
}
}

View file

@ -1,166 +0,0 @@
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class AlfarEitr
{
private static readonly MethodInfo UseEitrRpc =
AccessTools.Method(typeof(Player), "RPC_UseEitr", new[] { typeof(long), typeof(float) });
/// <summary>
/// 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).
/// </summary>
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 ────────────────────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
[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 ────────────────────────────────────────────
/// <summary>
/// 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).
/// </summary>
[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<ZNetView>();
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);
}
/// <summary>
/// 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.
/// </summary>
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;
}
}
}
}

View file

@ -1,166 +0,0 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
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);
/// <summary>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.</summary>
public static bool Build(GameObject prefab)
{
GameObject crate = PrefabManager.Cache.GetPrefab<GameObject>(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<LODGroup>();
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<Collider>(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<Container>();
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<string, Texture> { { "Crate_d", paint } });
Material iron = paint != null ? body.GetComponent<MeshRenderer>()?.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<AlfarChestGlow>();
look.Glows = new[] { glow };
look.Embers = embers;
look.GlowColor = Ember * 2f;
look.WoodOnly = true;
return true;
}
/// <summary>The grate: a glowing plate just off the front face, a frame and bars in front of it.</summary>
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<Renderer>();
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;
}
/// <summary>A plain box with no collider, for trim the borrowed meshes do not have.</summary>
internal static GameObject Block(Transform parent, string name, Vector3 position, Vector3 size, Material material)
{
GameObject block = GameObject.CreatePrimitive(PrimitiveType.Cube);
Object.DestroyImmediate(block.GetComponent<Collider>());
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<Renderer>().sharedMaterial = material;
return block;
}
/// <summary>The carried torch's embers, rising off the top of the grate.</summary>
private static ParticleSystem AddEmbers(Transform grate)
{
GameObject torch = PrefabManager.Cache.GetPrefab<GameObject>(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<ParticleSystem>();
}
}
}

View file

@ -1,171 +0,0 @@
using System.Globalization;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class AlfarHeimkall
{
private const string TimerKey = "Alfar_HeimkallAt";
/// <summary>Time.time until which nothing may hurt the local Alfr (the arrival grace).</summary>
public static float InvulnerableUntil;
// ─── The timer ───────────────────────────────────────────────────────
/// <summary>The cooldown for the current boss progress, in seconds.</summary>
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;
}
/// <summary>Seconds left before the next Heimkall; 0 when it is ready.</summary>
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;
/// <summary>
/// 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.
/// </summary>
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 ───────────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>
/// 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.
/// </summary>
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 ───────────────────────────────────────────────────────
/// <summary>
/// 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).
/// </summary>
[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");
}
}
}
}

View file

@ -1,137 +0,0 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Inngangskista's own body, the cold twin of <see cref="AlfarFireChest"/>: 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.
/// </summary>
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);
/// <summary>Swaps the cloned wood chest's meshes for the input chest. False leaves the wood
/// chest's look in place, with a warning.</summary>
public static bool Build(GameObject prefab)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(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<LODGroup>();
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<Container>();
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<string, Texture> { { "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, Material>();
Material panel = null;
foreach (Renderer renderer in visual.GetComponentsInChildren<Renderer>(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<AlfarChestGlow>();
look.Glows = BuildInlay(lidClosed.transform, panel);
look.GlowColor = Inlay * 1.6f;
look.WoodOnly = false;
return true;
}
/// <summary>A copy of one of the town chest's parts, at the town chest's size and on the piece layer.</summary>
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<Transform>(true)) t.gameObject.layer = parent.gameObject.layer;
return copy;
}
/// <summary>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.</summary>
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<Renderer>();
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<Renderer>();
}
}
}

View file

@ -1,126 +0,0 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
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<Rigidbody>();
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<Rigidbody>();
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;
}
}
}

View file

@ -1,108 +0,0 @@
using System.Collections.Generic;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
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<GameObject>("smelter");
ItemDrop magecap = PrefabManager.Cache.GetPrefab<ItemDrop>("MushroomMagecap");
ItemDrop puffs = PrefabManager.Cache.GetPrefab<ItemDrop>("MushroomJotunPuffs");
ItemDrop sap = PrefabManager.Cache.GetPrefab<ItemDrop>("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<Smelter>();
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<Smelter.ItemConversion>
{
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<Piece>();
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);
}
}
}

View file

@ -1,149 +0,0 @@
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public class AlfarMark : MonoBehaviour
{
/// <summary>"drone", "construct" or "tower": only for logs and the status command.</summary>
public string Role = "";
/// <summary>The attacker's mark, or null when the hit is not from one of ours.</summary>
public static AlfarMark Of(HitData hit)
{
if (hit == null) return null;
Character attacker = hit.GetAttacker();
return attacker != null ? attacker.GetComponent<AlfarMark>() : null;
}
/// <summary>All the damage that can wound a person, moved into lightning. Chop and pickaxe go.</summary>
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;
}
}
/// <summary>The blows of an Alfar creature: lightning only, and never on a friend.</summary>
[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;
}
}
/// <summary>
/// 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.
/// </summary>
[HarmonyPatch]
public static class AlfarMark_StructureDamage_Patch
{
public static IEnumerable<MethodBase> 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;
}
}
/// <summary>
/// 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).
/// </summary>
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<AlfarCreatureShield>();
if (shield != null) shield.Absorb(__0);
}
}
}
}

View file

@ -1,103 +0,0 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
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>() == 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<AlfarMiner>();
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<MonsterAI>();
Character character = spawned.GetComponent<Character>();
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<ItemDrop>() : null;
return drop != null ? drop.m_itemData.m_shared.m_name : prefabName;
}
}
}

View file

@ -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
{
/// <summary>
/// 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.
/// </summary>
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<MonoBehaviour>(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<AlfarNexusBehaviour>();
nexus.m_switch = prefab.AddComponent<Switch>();
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<Trader>() ?? prefab.AddComponent<Trader>();
trader.m_name = PieceDisplay;
trader.enabled = false;
trader.m_items = new List<Trader.TradeItem>();
trader.m_useItems = new List<Trader.TraderUseItem>();
trader.m_randomTalk = new List<string>();
trader.m_randomGreets = new List<string>();
trader.m_randomGoodbye = new List<string>();
trader.m_randomStartTrade = new List<string>();
trader.m_randomBuy = new List<string>();
trader.m_randomSell = new List<string>();
trader.m_randomGiveItemNo = new List<string>();
trader.m_randomUseItemAlreadyRecieved = new List<string>();
trader.m_randomTalkConditionals = new List<Trader.ConditionalDialog>();
Sprite icon = (pyramid ? AlfarChests.IconFrom("AlfarNexus_icon.png") : null) ?? BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore");
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
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>("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<ItemDrop>(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;
}
/// <summary>Teaches the player the Alfar's pieces: a piece registered after the learning pass does not reach its table alone (guide 4.4).</summary>
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<Piece>() : null;
if (piece != null) traverse.Method("AddKnownPiece", piece).GetValue();
}
traverse.Method("UpdateAvailablePiecesList").GetValue();
}
}
/// <summary>The names of every piece the Alfar can build, in one place for the lock and for learning.</summary>
public static class AlfarPieces
{
public static readonly List<string> Extra = new List<string>();
public static IEnumerable<string> 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<AlfarNexusBehaviour> All = new List<AlfarNexusBehaviour>();
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<ZNetView>();
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);
}
/// <summary>The nearest Ljoskjarne whose radius covers the point, or null.</summary>
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 ───────────────────────────────────────
/// <summary>
/// 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).
/// </summary>
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));
}
/// <summary>Seconds per crystal: Time Factor times a vanilla beehive's seconds per honey.</summary>
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<Cost> CostOf(Product product)
{
switch (product)
{
case Product.Drone:
return new List<Cost> { new Cost("Bronze", AlfarNexusConfig.DroneBronze.Value) };
case Product.Neistvordr:
return new List<Cost>
{
new Cost("Bronze", AlfarNexusConfig.NeistMetal.Value),
new Cost("Crystal", AlfarNexusConfig.NeistCrystal.Value),
new Cost("Eitr", AlfarNexusConfig.NeistEitr.Value),
};
case Product.Eldingvordr:
return new List<Cost>
{
new Cost("Iron", AlfarNexusConfig.EldingMetal.Value),
new Cost("Crystal", AlfarNexusConfig.EldingCrystal.Value),
new Cost("Eitr", AlfarNexusConfig.EldingEitr.Value),
};
case Product.Steinvordr:
return new List<Cost>
{
new Cost("BlackMetal", AlfarNexusConfig.SteinMetal.Value),
new Cost("Crystal", AlfarNexusConfig.SteinCrystal.Value),
new Cost("Eitr", AlfarNexusConfig.SteinEitr.Value),
};
case Product.Upgrade:
return new List<Cost> { new Cost("Crystal", AlfarNexusConfig.UpgradeCrystals.Value) };
}
return new List<Cost>();
}
private static string SharedName(string prefabName)
{
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null;
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
return drop != null ? drop.m_itemData.m_shared.m_name : prefabName;
}
private static bool CanPay(Player player, List<Cost> 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<Cost> 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<Cost> costs)
{
var parts = new List<string>();
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($"[<color=yellow><b>$KEY_Use</b></color>] {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<Trader>();
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 ──────────────────────────────────────
/// <summary>The products on offer right now, in the order the rows are drawn.</summary>
public List<Product> OnOffer()
{
var list = new List<Product>();
foreach (Product product in System.Enum.GetValues(typeof(Product)))
{
if (Available(product)) list.Add(product);
}
return list;
}
/// <summary>Builds a product from the row the player clicked. Every check Build makes still applies.</summary>
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);
}
/// <summary>The short number on a row: the metal (or the crystals of the upgrade) it costs.</summary>
public static string PriceShort(Product product)
{
foreach (Cost cost in CostOf(product))
{
if (cost.Amount > 0) return cost.Amount.ToString();
}
return "-";
}
/// <summary>The full terms for the row's tooltip: the price, how many exist, how many are allowed.</summary>
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<Cost> 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));
}
/// <summary>Crystals a drone may carry away from the Nexus, and the call that does it (used by the drone's work).</summary>
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;
}
}
}

View file

@ -1,149 +0,0 @@
using BepInEx.Configuration;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
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<float> NexusRadius;
public static ConfigEntry<float> NexusDensityKm2;
public static ConfigEntry<int> NexusBronze;
public static ConfigEntry<int> NexusStone;
// ─── Drones ──────────────────────────────────────────────────────────
public static ConfigEntry<int> DroneBronze;
public static ConfigEntry<int> DroneCap;
public static ConfigEntry<float> DroneHealth;
public static ConfigEntry<float> DroneZapDamage;
public static ConfigEntry<float> DroneZapInterval;
// ─── Mining drones ───────────────────────────────────────────────────
public static ConfigEntry<string> MinerDeposits;
public static ConfigEntry<float> MinerDamage;
public static ConfigEntry<string> WildPickables;
// ─── Constructs ──────────────────────────────────────────────────────
public static ConfigEntry<int> NeistMetal;
public static ConfigEntry<int> NeistCrystal;
public static ConfigEntry<int> NeistEitr;
public static ConfigEntry<int> NeistCap;
public static ConfigEntry<int> EldingMetal;
public static ConfigEntry<int> EldingCrystal;
public static ConfigEntry<int> EldingEitr;
public static ConfigEntry<int> EldingCap;
public static ConfigEntry<int> SteinMetal;
public static ConfigEntry<int> SteinCrystal;
public static ConfigEntry<int> SteinEitr;
public static ConfigEntry<int> SteinCap;
public static ConfigEntry<float> ConstructLeash;
public static ConfigEntry<float> ConstructAlertRange;
public static ConfigEntry<float> WitherSeconds;
public static ConfigEntry<float> SphereDamage;
public static ConfigEntry<float> SphereIntervalSeconds;
public static ConfigEntry<float> SphereRange;
// ─── Crystals ────────────────────────────────────────────────────────
public static ConfigEntry<int> UpgradeCrystals;
public static ConfigEntry<int> CrystalCap;
public static ConfigEntry<float> CrystalTimeFactor;
// ─── Towers ──────────────────────────────────────────────────────────
public static ConfigEntry<int> TowerBronze;
public static ConfigEntry<int> TowerCrystal;
public static ConfigEntry<float> TowerHealthFactor;
public static ConfigEntry<float> TowerDamage;
public static ConfigEntry<float> TowerScale;
// ─── Ljosgard (sap) and chests ───────────────────────────────────────
public static ConfigEntry<int> GardBronze;
public static ConfigEntry<int> GardMushrooms;
public static ConfigEntry<float> GardSecondsPerSap;
public static ConfigEntry<int> GardCapacity;
public static ConfigEntry<int> 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<float>(10f, 150f)));
NexusDensityKm2 = config.Bind(nexus, "Density Km2", 1.6f, new ConfigDescription("At most one Ljoskjarne per this many square kilometres.", new AcceptableValueRange<float>(0.1f, 20f)));
NexusBronze = config.Bind(nexus, "Bronze Cost", 40, new ConfigDescription("Bronze to build a Ljoskjarne.", new AcceptableValueRange<int>(0, 500)));
NexusStone = config.Bind(nexus, "Stone Cost", 30, new ConfigDescription("Stone to build a Ljoskjarne.", new AcceptableValueRange<int>(0, 500)));
const string drone = "Alfar - Drones";
DroneBronze = config.Bind(drone, "Bronze Cost", 8, new ConfigDescription("Bronze for each Ljosvaettir.", new AcceptableValueRange<int>(0, 200)));
DroneCap = config.Bind(drone, "Cap Per Nexus", 6, new ConfigDescription("Most drones one Ljoskjarne keeps.", new AcceptableValueRange<int>(0, 50)));
DroneHealth = config.Bind(drone, "Health", 25f, new ConfigDescription("A drone's health and shield (a Deathsquito has 10).", new AcceptableValueRange<float>(1f, 1000f)));
DroneZapDamage = config.Bind(drone, "Zap Damage", 1f, new ConfigDescription("Lightning damage of a drone's defensive zap.", new AcceptableValueRange<float>(0f, 100f)));
DroneZapInterval = config.Bind(drone, "Zap Interval", 2f, new ConfigDescription("Seconds between a drone's zaps.", new AcceptableValueRange<float>(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<float>(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<int>(0, 500)));
NeistCrystal = config.Bind(construct, "Neistvordr Crystal", 3, new ConfigDescription("Crystals for a Neistvordr.", new AcceptableValueRange<int>(0, 50)));
NeistEitr = config.Bind(construct, "Neistvordr Refined Eitr", 3, new ConfigDescription("Refined eitr for a Neistvordr.", new AcceptableValueRange<int>(0, 50)));
NeistCap = config.Bind(construct, "Neistvordr Cap", 4, new ConfigDescription("Most Neistvordr one Ljoskjarne keeps.", new AcceptableValueRange<int>(0, 50)));
EldingMetal = config.Bind(construct, "Eldingvordr Iron", 20, new ConfigDescription("Iron for an Eldingvordr.", new AcceptableValueRange<int>(0, 500)));
EldingCrystal = config.Bind(construct, "Eldingvordr Crystal", 5, new ConfigDescription("Crystals for an Eldingvordr.", new AcceptableValueRange<int>(0, 50)));
EldingEitr = config.Bind(construct, "Eldingvordr Refined Eitr", 4, new ConfigDescription("Refined eitr for an Eldingvordr.", new AcceptableValueRange<int>(0, 50)));
EldingCap = config.Bind(construct, "Eldingvordr Cap", 4, new ConfigDescription("Most Eldingvordr one Ljoskjarne keeps.", new AcceptableValueRange<int>(0, 50)));
SteinMetal = config.Bind(construct, "Steinvordr Black Metal", 20, new ConfigDescription("Black metal for a Steinvordr.", new AcceptableValueRange<int>(0, 500)));
SteinCrystal = config.Bind(construct, "Steinvordr Crystal", 8, new ConfigDescription("Crystals for a Steinvordr.", new AcceptableValueRange<int>(0, 50)));
SteinEitr = config.Bind(construct, "Steinvordr Refined Eitr", 6, new ConfigDescription("Refined eitr for a Steinvordr.", new AcceptableValueRange<int>(0, 50)));
SteinCap = config.Bind(construct, "Steinvordr Cap", 1, new ConfigDescription("Most Steinvordr one Ljoskjarne keeps.", new AcceptableValueRange<int>(0, 50)));
ConstructLeash = config.Bind(construct, "Leash Range", 12f, new ConfigDescription("How far a construct wanders from its Ljoskjarne when not following.", new AcceptableValueRange<float>(2f, 80f)));
ConstructAlertRange = config.Bind(construct, "Alert Range", 25f, new ConfigDescription("How far a construct notices and chases enemies.", new AcceptableValueRange<float>(5f, 100f)));
WitherSeconds = config.Bind(construct, "Wither Seconds", 60f, new ConfigDescription("How long creatures last after their Ljoskjarne falls.", new AcceptableValueRange<float>(0f, 600f)));
SphereDamage = config.Bind(construct, "Sphere Damage", 80f, new ConfigDescription("Lightning damage of the Eldingvordr's sphere.", new AcceptableValueRange<float>(1f, 1000f)));
SphereIntervalSeconds = config.Bind(construct, "Sphere Interval", 8f, new ConfigDescription("Seconds between the Eldingvordr's shots.", new AcceptableValueRange<float>(0.5f, 60f)));
SphereRange = config.Bind(construct, "Sphere Range", 30f, new ConfigDescription("How far the Eldingvordr shoots.", new AcceptableValueRange<float>(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<int>(0, 200)));
CrystalCap = config.Bind(crystal, "Stored Cap", 20, new ConfigDescription("Most crystals the Ljoskjarne holds before it stops making them.", new AcceptableValueRange<int>(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<float>(0.1f, 20f)));
const string tower = "Alfar - Towers";
TowerBronze = config.Bind(tower, "Bronze Cost", 25, new ConfigDescription("Bronze for a Prismavard.", new AcceptableValueRange<int>(0, 500)));
TowerCrystal = config.Bind(tower, "Crystal Cost", 2, new ConfigDescription("Crystals for a Prismavard.", new AcceptableValueRange<int>(0, 50)));
TowerHealthFactor = config.Bind(tower, "Health Factor", 0.5f, new ConfigDescription("A Prismavard's health against the charred ballista's 400.", new AcceptableValueRange<float>(0.05f, 3f)));
TowerDamage = config.Bind(tower, "Bolt Damage", 40f, new ConfigDescription("Lightning damage of a Prismavard's bolt.", new AcceptableValueRange<float>(1f, 1000f)));
TowerScale = config.Bind(tower, "Scale", 0.6f, new ConfigDescription("Size of a Prismavard against the charred ballista.", new AcceptableValueRange<float>(0.2f, 2f)));
const string gard = "Alfar - Ljosgard";
GardBronze = config.Bind(gard, "Bronze Cost", 40, new ConfigDescription("Bronze for a Ljosgard.", new AcceptableValueRange<int>(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<int>(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<float>(10f, 7200f)));
GardCapacity = config.Bind(gard, "Sap Capacity", 10, new ConfigDescription("Sap the Ljosgard holds before it stops.", new AcceptableValueRange<int>(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<int>(0, 50)));
}
}
}

View file

@ -1,217 +0,0 @@
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
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);
/// <summary>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.</summary>
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<Renderer>();
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<WearNTear>();
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<BoxCollider>();
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<MeshRenderer>();
NexusLook look = prefab.AddComponent<NexusLook>();
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<MeshFilter>().sharedMesh = mesh;
part.AddComponent<MeshRenderer>().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),
};
/// <summary>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.</summary>
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;
}
/// <summary>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.</summary>
private static ParticleSystem AddMotes(Transform root)
{
GameObject torch = PrefabManager.Cache.GetPrefab<GameObject>(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<ParticleSystem>();
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;
}
/// <summary>The motion and the seam's light, per client.</summary>
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<AlfarNexusBehaviour>();
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);
}
}
}
}

View file

@ -1,171 +0,0 @@
using System.Collections.Generic;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class AlfarNexusStore
{
private static RectTransform _list;
private static readonly List<GameObject> _rows = new List<GameObject>();
public static AlfarNexusBehaviour ActiveNexus(StoreGui gui)
{
Trader trader = FactionMerchantRuntime.GetActiveTrader(gui);
return trader != null ? trader.GetComponent<AlfarNexusBehaviour>() : 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<RectTransform>();
_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<float>();
_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<Image>();
if (icon != null) iconImage.sprite = icon;
string name = AlfarNexusBehaviour.ProductName(product);
element.transform.Find("name").GetComponent<TMP_Text>().text = Localization.instance.Localize(name);
TMP_Text price = FindDescendant<TMP_Text>(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<Image>(true))
{
if (image != null && image.gameObject.name.ToLowerInvariant().Contains("coin")) image.gameObject.SetActive(false);
}
UITooltip tooltip = element.GetComponent<UITooltip>();
if (tooltip != null) tooltip.Set(Localization.instance.Localize(name), nexus.Terms(product), gui.m_tooltipAnchor, default(Vector2));
AlfarNexusBehaviour.Product chosen = product;
element.GetComponent<Button>().onClick.AddListener(() =>
{
nexus.BuildFromStore(chosen);
Traverse.Create(gui).Method("FillList").GetValue(); // repaints the column
});
_rows.Add(element);
}
// ─── helpers ─────────────────────────────────────────────────────────
private static Sprite Icon(string prefabName)
{
ItemDrop drop = Jotunn.Managers.PrefabManager.Cache.GetPrefab<ItemDrop>(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;
}
private static T FindDescendant<T>(Transform root, string childName) where T : Component
{
foreach (T candidate in root.GetComponentsInChildren<T>(true))
{
if (candidate.gameObject.name == childName) return candidate;
}
return null;
}
}
[HarmonyPatch(typeof(StoreGui), "Awake")]
public static class AlfarNexusStoreSetupPatch
{
public static void Postfix(StoreGui __instance) => AlfarNexusStore.Create(__instance);
}
[HarmonyPatch(typeof(StoreGui), "FillList")]
public static class AlfarNexusStoreFillPatch
{
public static void Postfix(StoreGui __instance) => AlfarNexusStore.Refresh(__instance);
}
[HarmonyPatch(typeof(StoreGui), "Hide")]
public static class AlfarNexusStoreHidePatch
{
public static void Postfix() => AlfarNexusStore.Clear();
}
}

View file

@ -1,180 +0,0 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The hooks that keep an Alfr looking like one. Only the look so far; the shield, the death
/// timer and the powers add their own patches as they are written.
/// </summary>
public static class AlfarPatches
{
/// <summary>
/// The only thing that actually colours a player.
///
/// SetSkinColor followed by UpdateColors does nothing, because UpdateColors is what REBUILDS
/// the body material from Valheim's own values and throws any earlier write away
/// (DvergarPatches documents the dead end). Writing _SkinColor here, after it has run, is the
/// only order that survives.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
public static class Alfar_UpdateColors_Patch
{
public static void Postfix(VisEquipment __instance)
{
if (__instance == null || __instance.m_bodyModel == null) return;
Player player = __instance.GetComponent<Player>();
if (player == null || !AlfarVisuals.IsAlfarPlayer(player)) return;
AlfarVisuals.ApplyGreyTexture(__instance, true);
Material material = __instance.m_bodyModel.material;
if (material != null && material.HasProperty("_SkinColor"))
{
material.SetColor("_SkinColor", AlfarVisuals.SkinFor(player));
}
}
}
/// <summary>
/// Hair and beard never attach to an Alfr. Every equipment change makes the game write the
/// profile's hair back (Humanoid.SetupVisEquipment), and ApplyHairless only clears it on its
/// 0.5s pass, so players saw the hair flash in for a moment. Zeroing the hash here, where
/// VisEquipment spawns the model, means it never appears. Covers remote players too, since
/// their visuals go through the same call.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "SetHairEquipped")]
public static class Alfar_SetHairEquipped_Patch
{
public static void Prefix(VisEquipment __instance, ref int hash)
{
if (hash != 0 && IsAlfarVis(__instance)) hash = 0;
}
}
[HarmonyPatch(typeof(VisEquipment), "SetBeardEquipped")]
public static class Alfar_SetBeardEquipped_Patch
{
public static void Prefix(VisEquipment __instance, ref int hash)
{
if (hash != 0 && IsAlfarVis(__instance)) hash = 0;
}
}
private static bool IsAlfarVis(VisEquipment vis)
{
Player player = vis.GetComponent<Player>();
return player != null && AlfarVisuals.IsAlfarPlayer(player);
}
/// <summary>
/// The character preview on the main menu is a Player too, with the saved race in its custom data
/// and no ZNetView. Its Update may never run, so a small driver on it keeps the look: skin, hair,
/// scale and eyes, twice a second, for as long as the preview exists. The existing menu hook only
/// pushes ONE colour refresh and knows nothing of eyes or texture.
/// </summary>
public class AlfarPreviewDriver : MonoBehaviour
{
private Player player;
private float next;
private void Awake() { player = GetComponent<Player>(); }
private void Update()
{
if (player == null || Time.time < next) return;
next = Time.time + 0.5f;
bool isAlfar = AlfarVisuals.IsAlfarPlayer(player);
AlfarVisuals.ApplyScale(player, isAlfar);
AlfarVisuals.ApplyEyes(player);
if (isAlfar) AlfarVisuals.ApplyHairless(player);
AlfarVisuals.SyncSkin(player, isAlfar);
}
}
public static void AttachPreviewDriver(FejdStartup instance)
{
Player preview = instance.GetType()
.GetMethod("GetPreviewPlayer",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Public)
?.Invoke(instance, null) as Player;
if (preview != null && preview.GetComponent<AlfarPreviewDriver>() == null)
{
preview.gameObject.AddComponent<AlfarPreviewDriver>();
}
}
[HarmonyPatch(typeof(FejdStartup), "SetupCharacterPreview")]
public static class Alfar_Preview_Setup_Patch
{
[HarmonyPriority(Priority.Last)]
public static void Postfix(FejdStartup __instance) => AttachPreviewDriver(__instance);
}
[HarmonyPatch(typeof(FejdStartup), "SetSelectedProfile")]
public static class Alfar_Preview_Profile_Patch
{
[HarmonyPriority(Priority.Last)]
public static void Postfix(FejdStartup __instance) => AttachPreviewDriver(__instance);
}
/// <summary>
/// Scale every frame, the cosmetics on a throttle.
///
/// On Player.Update because that is the one place body scale survives: the Trol's postfix
/// forces every other player's visual back to 1 on the same frame, so a scale written
/// anywhere else is simply overwritten. RaceScale keeps the two from undoing each other.
/// This runs for every player in range, not just the local one, so other clients see an
/// Alfr as one.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class Alfar_PlayerUpdate_Patch
{
private static readonly Dictionary<Player, float> nextCosmeticPass = new Dictionary<Player, float>();
private const float CosmeticInterval = 0.5f;
public static void Postfix(Player __instance)
{
if (__instance == null) return;
bool isAlfar = AlfarVisuals.IsAlfarPlayer(__instance);
AlfarVisuals.ApplyScale(__instance, isAlfar);
// The passive carrier belongs to the local body only; status effects are re-added
// because they do not survive a reload or a death.
if (__instance == Player.m_localPlayer)
{
if (isAlfar && !__instance.IsDead())
{
AlfarStatusEffects.Ensure(__instance);
AlfarPowers.Tick(__instance);
}
else
{
AlfarStatusEffects.Remove(__instance);
if (AlfarArchon.Active) AlfarArchon.ForceClear(__instance);
}
}
if (!nextCosmeticPass.TryGetValue(__instance, out float due) || Time.time >= due)
{
nextCosmeticPass[__instance] = Time.time + CosmeticInterval;
// Unconditional, like the other races': the eyes have to be able to remove
// themselves from whoever stops being an Alfr, and they cannot do that from
// behind an `if (isAlfar)`.
AlfarVisuals.ApplyEyes(__instance);
AlfarVisuals.ApplyArchonGlow(__instance);
if (isAlfar) AlfarVisuals.ApplyHairless(__instance);
AlfarVisuals.SyncSkin(__instance, isAlfar);
}
}
}
}
}

View file

@ -1,170 +0,0 @@
using BepInEx.Configuration;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The numbers and the keys of the Alfar's powers (Alfar_Progettazione.txt sec. 13 and 19.6).
/// Every value is a STARTING value to be corrected in play. Nothing numeric lives in the logic.
///
/// Keys follow the mod's habit: letters the other races also use (G, H, I, J, K, O, U), because a
/// character has exactly one race, so the same letter never means two things at once.
/// </summary>
public static class AlfarPowerConfig
{
// Progression states a power unlocks at (BossProgressionManager: 2 Eikthyr ... 8 Fader).
public const int SkridState = 2;
public const int GrafvaettirState = 2;
public const int UtsogState = 3;
public const int KallState = 4;
public const int LjosstormState = 5;
public const int GeisliState = 6;
public const int KyrrState = 7;
public const int SameiningState = 8;
// ─── Keys ────────────────────────────────────────────────────────────
public static ConfigEntry<KeyboardShortcut> SkridKey;
public static ConfigEntry<KeyboardShortcut> GrafvaettirKey;
public static ConfigEntry<KeyboardShortcut> KallKey;
public static ConfigEntry<KeyboardShortcut> LjosstormKey;
public static ConfigEntry<KeyboardShortcut> GeisliKey;
public static ConfigEntry<KeyboardShortcut> KyrrKey;
public static ConfigEntry<KeyboardShortcut> SameiningKey;
// ─── Skrid: the blink ────────────────────────────────────────────────
public static ConfigEntry<float> SkridDistance;
public static ConfigEntry<float> SkridCost;
public static ConfigEntry<float> SkridCooldown;
// ─── Utsog: damage dealt comes back as eitr ──────────────────────────
public static ConfigEntry<float> UtsogPercent;
// ─── Kall: telekinesis ───────────────────────────────────────────────
public static ConfigEntry<float> KallRadius;
public static ConfigEntry<float> KallSpeed;
public static ConfigEntry<float> KallCost;
public static ConfigEntry<float> KallCooldown;
// ─── Ljosstorm: the psionic storm ────────────────────────────────────
public static ConfigEntry<float> StormRange;
public static ConfigEntry<float> StormRadius;
public static ConfigEntry<float> StormSeconds;
public static ConfigEntry<float> StormDps;
public static ConfigEntry<float> StormCost;
public static ConfigEntry<float> StormCooldown;
// ─── Geisli: the beam ────────────────────────────────────────────────
public static ConfigEntry<float> BeamRange;
public static ConfigEntry<float> BeamDps;
public static ConfigEntry<float> BeamCostPerSecond;
public static ConfigEntry<float> BeamMaxSeconds;
public static ConfigEntry<float> BeamCooldown;
// ─── Kyrr: stasis ────────────────────────────────────────────────────
public static ConfigEntry<float> StasisRange;
public static ConfigEntry<float> StasisSeconds;
public static ConfigEntry<float> StasisBossSeconds;
public static ConfigEntry<float> StasisCost;
public static ConfigEntry<float> StasisCooldown;
// ─── Sameining: the archon ───────────────────────────────────────────
public static ConfigEntry<float> ArchonThreshold;
public static ConfigEntry<float> ArchonSeconds;
public static ConfigEntry<float> ArchonScale;
public static ConfigEntry<float> ArchonSpeedBonus;
public static ConfigEntry<float> ArchonPoolPerEitr;
public static ConfigEntry<float> ArchonPulseRadius;
public static ConfigEntry<float> ArchonPulseDamage;
public static ConfigEntry<float> ArchonPulseInterval;
public static ConfigEntry<float> ArchonFreePowerCooldown;
public static ConfigEntry<Color> ArchonColor;
// ─── Grafvaettir: the mining grenade ─────────────────────────────────
public static ConfigEntry<float> GrafRange;
public static ConfigEntry<float> GrafRadius;
public static ConfigEntry<float> GrafSeconds;
public static ConfigEntry<int> GrafCount;
public static ConfigEntry<float> GrafEitr;
public static ConfigEntry<int> GrafStone;
public static ConfigEntry<int> GrafFlint;
public static ConfigEntry<float> GrafCooldown;
// ─── Levitation ──────────────────────────────────────────────────────
public static ConfigEntry<float> LevitationRise;
public static ConfigEntry<float> LevitationCostPerSecond;
public static void Bind(ConfigFile config)
{
const string keys = "Alfar - Keybinds";
SkridKey = config.Bind(keys, "Skrid (Blink)", new KeyboardShortcut(KeyCode.G));
GrafvaettirKey = config.Bind(keys, "Grafvaettir (Mining Drones)", new KeyboardShortcut(KeyCode.H));
KallKey = config.Bind(keys, "Kall (Telekinesis)", new KeyboardShortcut(KeyCode.J));
LjosstormKey = config.Bind(keys, "Ljosstorm (Psionic Storm)", new KeyboardShortcut(KeyCode.K));
GeisliKey = config.Bind(keys, "Geisli (Beam, hold)", new KeyboardShortcut(KeyCode.O));
KyrrKey = config.Bind(keys, "Kyrr (Stasis)", new KeyboardShortcut(KeyCode.U));
SameiningKey = config.Bind(keys, "Sameining (Archon)", new KeyboardShortcut(KeyCode.I));
const string skrid = "Alfar - Skrid";
SkridDistance = config.Bind(skrid, "Distance", 8f, new ConfigDescription("Blink length in metres.", new AcceptableValueRange<float>(1f, 30f)));
SkridCost = config.Bind(skrid, "Eitr Cost", 10f, new ConfigDescription("Eitr spent per blink.", new AcceptableValueRange<float>(0f, 200f)));
SkridCooldown = config.Bind(skrid, "Cooldown", 3f, new ConfigDescription("Seconds between blinks.", new AcceptableValueRange<float>(0f, 120f)));
const string utsog = "Alfar - Utsog";
UtsogPercent = config.Bind(utsog, "Return Percent", 15f, new ConfigDescription("Percent of the damage you deal that comes back as eitr.", new AcceptableValueRange<float>(0f, 100f)));
const string kall = "Alfar - Kall";
KallRadius = config.Bind(kall, "Radius", 15f, new ConfigDescription("Metres around you whose dropped items are pulled in.", new AcceptableValueRange<float>(1f, 60f)));
KallSpeed = config.Bind(kall, "Pull Speed", 12f, new ConfigDescription("Speed items fly toward you, in metres per second.", new AcceptableValueRange<float>(1f, 40f)));
KallCost = config.Bind(kall, "Eitr Cost", 5f, new ConfigDescription("Eitr spent per pull.", new AcceptableValueRange<float>(0f, 200f)));
KallCooldown = config.Bind(kall, "Cooldown", 2f, new ConfigDescription("Seconds between pulls.", new AcceptableValueRange<float>(0f, 120f)));
const string storm = "Alfar - Ljosstorm";
StormRange = config.Bind(storm, "Range", 30f, new ConfigDescription("How far you can place the storm.", new AcceptableValueRange<float>(5f, 80f)));
StormRadius = config.Bind(storm, "Radius", 6f, new ConfigDescription("Radius of the storm in metres.", new AcceptableValueRange<float>(1f, 30f)));
StormSeconds = config.Bind(storm, "Duration", 6f, new ConfigDescription("Seconds the storm lasts.", new AcceptableValueRange<float>(1f, 60f)));
StormDps = config.Bind(storm, "Damage Per Second", 20f, new ConfigDescription("Lightning damage per second to each enemy inside.", new AcceptableValueRange<float>(1f, 500f)));
StormCost = config.Bind(storm, "Eitr Cost", 40f, new ConfigDescription("Eitr spent per cast.", new AcceptableValueRange<float>(0f, 400f)));
StormCooldown = config.Bind(storm, "Cooldown", 20f, new ConfigDescription("Seconds between casts.", new AcceptableValueRange<float>(0f, 300f)));
const string beam = "Alfar - Geisli";
BeamRange = config.Bind(beam, "Range", 30f, new ConfigDescription("Beam length in metres.", new AcceptableValueRange<float>(5f, 80f)));
BeamDps = config.Bind(beam, "Damage Per Second", 35f, new ConfigDescription("Lightning damage per second to the target.", new AcceptableValueRange<float>(1f, 500f)));
BeamCostPerSecond = config.Bind(beam, "Eitr Per Second", 8f, new ConfigDescription("Eitr burned each second the beam is held.", new AcceptableValueRange<float>(0f, 100f)));
BeamMaxSeconds = config.Bind(beam, "Max Continuous Seconds", 8f, new ConfigDescription("The beam cuts off after this long.", new AcceptableValueRange<float>(1f, 60f)));
BeamCooldown = config.Bind(beam, "Cooldown After Release", 2f, new ConfigDescription("Seconds before the beam can start again.", new AcceptableValueRange<float>(0f, 60f)));
const string stasis = "Alfar - Kyrr";
StasisRange = config.Bind(stasis, "Range", 25f, new ConfigDescription("How far the stasis reaches.", new AcceptableValueRange<float>(5f, 80f)));
StasisSeconds = config.Bind(stasis, "Seconds", 4f, new ConfigDescription("How long an ordinary enemy is held.", new AcceptableValueRange<float>(0.5f, 30f)));
StasisBossSeconds = config.Bind(stasis, "Boss Seconds", 1.5f, new ConfigDescription("How long a boss is held.", new AcceptableValueRange<float>(0.5f, 30f)));
StasisCost = config.Bind(stasis, "Eitr Cost", 50f, new ConfigDescription("Eitr spent per cast.", new AcceptableValueRange<float>(0f, 400f)));
StasisCooldown = config.Bind(stasis, "Cooldown", 45f, new ConfigDescription("Seconds between casts.", new AcceptableValueRange<float>(0f, 600f)));
const string archon = "Alfar - Sameining";
ArchonThreshold = config.Bind(archon, "Activation Threshold", 0.75f, new ConfigDescription("Fraction of the maximum eitr needed to begin. All of it is spent.", new AcceptableValueRange<float>(0f, 1f)));
ArchonSeconds = config.Bind(archon, "Duration", 180f, new ConfigDescription("Seconds the form lasts at most.", new AcceptableValueRange<float>(5f, 900f)));
ArchonScale = config.Bind(archon, "Scale", 1.5f, new ConfigDescription("Body size multiplier in the form.", new AcceptableValueRange<float>(1f, 3f)));
ArchonSpeedBonus = config.Bind(archon, "Speed Bonus", 0.2f, new ConfigDescription("Movement speed bonus in the form (0.2 = +20%).", new AcceptableValueRange<float>(0f, 1f)));
ArchonPoolPerEitr = config.Bind(archon, "Pool Per Eitr", 3f, new ConfigDescription("Points of protection per point of eitr spent to enter.", new AcceptableValueRange<float>(0.1f, 20f)));
ArchonPulseRadius = config.Bind(archon, "Pulse Radius", 4f, new ConfigDescription("Radius of the psionic pulse around you.", new AcceptableValueRange<float>(1f, 20f)));
ArchonPulseDamage = config.Bind(archon, "Pulse Damage", 60f, new ConfigDescription("Lightning damage of each pulse.", new AcceptableValueRange<float>(1f, 1000f)));
ArchonPulseInterval = config.Bind(archon, "Pulse Interval", 1f, new ConfigDescription("Seconds between pulses.", new AcceptableValueRange<float>(0.2f, 10f)));
ArchonFreePowerCooldown = config.Bind(archon, "Free Power Cooldown", 5f, new ConfigDescription("In the form, Ljosstorm and Geisli cost no eitr but wait this long.", new AcceptableValueRange<float>(0f, 60f)));
ArchonColor = config.Bind(archon, "Glow Color", new Color(0.55f, 0.85f, 1f, 1f), new ConfigDescription("Skin and light colour while in the form."));
const string graf = "Alfar - Grafvaettir";
GrafRange = config.Bind(graf, "Throw Range", 25f, new ConfigDescription("How far the drones can be thrown.", new AcceptableValueRange<float>(5f, 80f)));
GrafRadius = config.Bind(graf, "Dig Radius", 12f, new ConfigDescription("Radius around the landing point where they dig.", new AcceptableValueRange<float>(2f, 60f)));
GrafSeconds = config.Bind(graf, "Duration", 120f, new ConfigDescription("Seconds the drones dig before vanishing.", new AcceptableValueRange<float>(5f, 900f)));
GrafCount = config.Bind(graf, "Drones Per Throw", 5, new ConfigDescription("How many mining drones one throw makes.", new AcceptableValueRange<int>(1, 30)));
GrafEitr = config.Bind(graf, "Eitr Cost", 25f, new ConfigDescription("Eitr spent per throw.", new AcceptableValueRange<float>(0f, 400f)));
GrafStone = config.Bind(graf, "Stone Cost", 10, new ConfigDescription("Stone spent per throw.", new AcceptableValueRange<int>(0, 200)));
GrafFlint = config.Bind(graf, "Flint Cost", 5, new ConfigDescription("Flint spent per throw.", new AcceptableValueRange<int>(0, 200)));
GrafCooldown = config.Bind(graf, "Cooldown", 300f, new ConfigDescription("Seconds between throws; keep it well above the duration or they are permanent.", new AcceptableValueRange<float>(0f, 3600f)));
const string lev = "Alfar - Levitation";
LevitationRise = config.Bind(lev, "Rise Speed", 2f, new ConfigDescription("Climb speed (m/s) while the jump key is held in the air.", new AcceptableValueRange<float>(0.2f, 10f)));
LevitationCostPerSecond = config.Bind(lev, "Eitr Per Second", 2f, new ConfigDescription("Eitr burned each second of levitation.", new AcceptableValueRange<float>(0f, 50f)));
}
}
}

View file

@ -1,687 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Alfar's powers (Alfar_Progettazione.txt sec. 13): caster tools, one per boss from Eikthyr.
///
/// Skrid Eikthyr blink
/// Grafvaettir Eikthyr mining drones thrown like a grenade (AlfarMiners)
/// Utsog Elder damage dealt returns as eitr (passive, below)
/// Kall Bonemass telekinesis
/// Ljosstorm Moder psionic storm on the ground
/// Geisli Yagluth continuous beam (hold the key)
/// Kyrr Queen stasis
/// Sameining Fader the archon (AlfarArchon)
///
/// Every power costs eitr from the SAME pool as the shield, which is the whole tension of the race
/// (doc sec. 4.4). Eitr is spent through AlfarEitr.Spend so the vanilla regeneration delay arms.
/// </summary>
public static class AlfarPowers
{
private static readonly Dictionary<string, float> cooldownUntil = new Dictionary<string, float>();
public static void ResetCooldowns(Player player)
{
cooldownUntil.Clear();
StopBeam();
AlfarArchon.ForceClear(player);
foreach (string id in AlfarStatusEffects.TimerIds) AlfarStatusEffects.ClearTimer(id);
}
private static bool Ready(string id) => !cooldownUntil.TryGetValue(id, out float until) || Time.time >= until;
private static void StartCooldown(string id, float seconds)
{
cooldownUntil[id] = Time.time + seconds;
AlfarStatusEffects.ShowTimer(id, seconds);
}
private static bool Unlocked(int need) => BossProgressionManager.GetCurrentProgressionState() >= need;
/// <summary>
/// The eitr a power costs: nothing for Ljosstorm and Geisli inside the archon form.
/// </summary>
private static float CostOf(float cost, bool freeInArchon) =>
freeInArchon && AlfarArchon.Active ? 0f : cost;
private static float CooldownOf(float cooldown, bool freeInArchon) =>
freeInArchon && AlfarArchon.Active ? AlfarArchon.FreePowerCooldown : cooldown;
/// <summary>Pays for a power, or says so and returns false.</summary>
private static bool Pay(Player player, float cost)
{
if (cost <= 0f) return true;
if (player.GetEitr() < cost)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_no_eitr"));
return false;
}
AlfarEitr.Spend(player, cost);
return true;
}
// ─── The loop ────────────────────────────────────────────────────────
/// <summary>Called every frame for the LOCAL Alfr, from the Player.Update postfix.</summary>
public static void Tick(Player player)
{
AlfarArchon.Tick(player);
AlfarHeimkall.SyncIcon(player);
AlfarMiners.Tick(player);
TickBeam(player);
if (!RaceInput.Allowed || player.IsDead()) return;
if (Unlocked(AlfarPowerConfig.SkridState) && AlfarPowerConfig.SkridKey.Value.IsDownIgnoringHeldKeys()) Skrid(player);
if (Unlocked(AlfarPowerConfig.GrafvaettirState) && AlfarPowerConfig.GrafvaettirKey.Value.IsDownIgnoringHeldKeys()) AlfarMiners.Throw(player);
if (Unlocked(AlfarPowerConfig.KallState) && AlfarPowerConfig.KallKey.Value.IsDownIgnoringHeldKeys()) Kall(player);
if (Unlocked(AlfarPowerConfig.LjosstormState) && AlfarPowerConfig.LjosstormKey.Value.IsDownIgnoringHeldKeys()) Ljosstorm(player);
if (Unlocked(AlfarPowerConfig.KyrrState) && AlfarPowerConfig.KyrrKey.Value.IsDownIgnoringHeldKeys()) Kyrr(player);
if (Unlocked(AlfarPowerConfig.SameiningState) && AlfarPowerConfig.SameiningKey.Value.IsDownIgnoringHeldKeys()) AlfarArchon.TryActivate(player);
}
// ─── Aim ─────────────────────────────────────────────────────────────
private static Transform AimTransform(Player player)
{
return GameCamera.instance != null ? GameCamera.instance.transform : player.transform;
}
/// <summary>
/// What the crosshair is on: the first thing the ray hits that is not the Alfr, with the
/// character under it if there is one. Triggers are ignored. With nothing hit, the point is at
/// the end of the range.
/// </summary>
private static bool Aim(Player player, float range, out Vector3 point, out Character target)
{
Transform aim = AimTransform(player);
Vector3 origin = aim.position;
Vector3 direction = aim.forward;
target = null;
point = origin + direction * range;
RaycastHit[] hits = Physics.RaycastAll(origin, direction, range, ~0, QueryTriggerInteraction.Ignore);
System.Array.Sort(hits, (a, b) => a.distance.CompareTo(b.distance));
foreach (RaycastHit hit in hits)
{
if (hit.collider == null) continue;
if (hit.collider.GetComponentInParent<Player>() == player) continue;
point = hit.point;
target = hit.collider.GetComponentInParent<Character>();
return true;
}
return false;
}
private static bool IsHostile(Player player, Character other)
{
return other != null && other != player && !other.IsDead() && !other.IsTamed() &&
BaseAI.IsEnemy(player, other);
}
// ─── Damage ──────────────────────────────────────────────────────────
/// <summary>
/// One lightning strike on a character. Not blockable and not dodgeable: a power that can be
/// blocked is a weapon, and these are not.
/// </summary>
public static void Strike(Player attacker, Character target, float lightning, Vector3 point)
{
if (target == null || lightning <= 0f) return;
HitData hit = new HitData();
hit.m_damage.m_lightning = lightning;
hit.m_point = point;
hit.m_dir = (target.transform.position - attacker.transform.position).normalized;
hit.m_dodgeable = false;
hit.m_blockable = false;
hit.m_hitType = HitData.HitType.PlayerHit;
hit.SetAttacker(attacker);
target.Damage(hit);
}
/// <summary>A pulse of lightning on every hostile creature within a radius of the Alfr.</summary>
/// <returns>True if it struck at least one creature.</returns>
public static bool Pulse(Player player, float radius, float damage)
{
bool struck = false;
foreach (Character character in CharactersIn(player.transform.position, radius))
{
if (!IsHostile(player, character)) continue;
Strike(player, character, damage, character.GetCenterPoint());
struck = true;
}
return struck;
}
private static IEnumerable<Character> CharactersIn(Vector3 center, float radius)
{
var seen = new HashSet<Character>();
foreach (Collider collider in Physics.OverlapSphere(center, radius, ~0, QueryTriggerInteraction.Ignore))
{
Character character = collider.GetComponentInParent<Character>();
if (character != null && seen.Add(character)) yield return character;
}
}
// ─── Skrid: blink ────────────────────────────────────────────────────
private static void Skrid(Player player)
{
if (!Ready("skrid")) return;
Transform aim = AimTransform(player);
Vector3 origin = player.transform.position + Vector3.up * 1.0f;
Vector3 direction = aim.forward;
float distance = AlfarPowerConfig.SkridDistance.Value;
// Stop short of whatever is in the way, so the blink never ends inside a wall.
Vector3 destination = origin + direction * distance;
if (NearestHit(player, origin, direction, distance, out RaycastHit wall))
{
destination = wall.point - direction * 0.6f;
}
// Back down to the player's own height: the origin was at the chest. The floor is found
// with a short ray down from the landing point, never with GetSolidHeight: that one casts
// from 1000 m up, so under any roof (a crypt, a cave, a house) it returned the roof and
// put the Alfr on top of it. A flat 1 m drop also sank the feet under the floor when the
// blink was aimed at it.
const float FloorSearch = 3f;
if (NearestHit(player, destination, Vector3.down, FloorSearch, out RaycastHit floor))
{
destination.y = floor.point.y + 0.05f;
}
else if (player.InInterior())
{
// No floor under the landing point inside a dungeon: it would end in the void the
// dungeon floats in. Cancel before paying.
return;
}
else
{
destination.y -= 1.0f;
if (ZoneSystem.instance != null)
{
// Terrain only, so a roof overhead is never mistaken for the ground.
float ground = ZoneSystem.instance.GetGroundHeight(destination);
if (destination.y < ground) destination.y = ground + 0.1f;
}
}
if (!Pay(player, AlfarPowerConfig.SkridCost.Value)) return;
Teleport(player, destination);
StartCooldown("skrid", AlfarPowerConfig.SkridCooldown.Value);
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", origin);
}
/// <summary>The nearest solid hit along a ray, skipping the caster's own colliders.</summary>
private static bool NearestHit(Player player, Vector3 origin, Vector3 direction, float distance, out RaycastHit nearest)
{
nearest = default;
bool found = false;
foreach (RaycastHit hit in Physics.RaycastAll(origin, direction, distance, ~0, QueryTriggerInteraction.Ignore))
{
if (hit.collider.GetComponentInParent<Player>() == player) continue;
if (!found || hit.distance < nearest.distance)
{
nearest = hit;
found = true;
}
}
return found;
}
/// <summary>
/// Moves the body without the teleport fade: the rigidbody is repositioned and its velocity
/// zeroed, and the fall tracker is reset so a blink up a cliff does not count as a fall.
/// </summary>
private static void Teleport(Player player, Vector3 destination)
{
Rigidbody body = Traverse.Create(player).Field("m_body").GetValue<Rigidbody>();
player.transform.position = destination;
if (body != null)
{
body.position = destination;
body.linearVelocity = Vector3.zero;
}
Traverse.Create(player).Field("m_maxAirAltitude").SetValue(destination.y);
}
// ─── Utsog: damage dealt returns as eitr ─────────────────────────────
/// <summary>
/// After a blow lands on something that is not a player: if the local Alfr struck it, a share
/// of the damage comes back as eitr. Runs only where the victim is owned, which is here for
/// anything this client owns (singleplayer and the host in practice): a monster owned by
/// another client feeds no eitr. Known limit, doc sec. 17.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Alfar_Utsog_Patch
{
public static void Postfix(Character __instance, HitData __0)
{
if (__instance == null || __0 == null || __instance is Player) return;
Player local = Player.m_localPlayer;
if (local == null || __0.GetAttacker() != local) return;
if (!AlfarVisuals.IsAlfarPlayer(local) || !Unlocked(AlfarPowerConfig.UtsogState)) return;
if (__instance.IsTamed()) return;
float returned = __0.GetTotalDamage() * AlfarPowerConfig.UtsogPercent.Value / 100f;
if (returned > 0f) local.AddEitr(returned);
}
}
// ─── Kall: telekinesis ───────────────────────────────────────────────
private static void Kall(Player player)
{
if (!Ready("kall")) return;
if (!Pay(player, AlfarPowerConfig.KallCost.Value)) return;
Vector3 target = player.GetCenterPoint();
int pulled = 0;
var seen = new HashSet<ItemDrop>();
foreach (Collider collider in Physics.OverlapSphere(player.transform.position, AlfarPowerConfig.KallRadius.Value,
~0, QueryTriggerInteraction.Ignore))
{
ItemDrop item = collider.GetComponentInParent<ItemDrop>();
if (item == null || !seen.Add(item)) continue;
Rigidbody body = item.GetComponent<Rigidbody>();
ZNetView nview = item.GetComponent<ZNetView>();
if (body == null || nview == null || !nview.IsValid()) continue;
// The item's physics belong to whoever owns it; take it so the pull is not undone.
nview.ClaimOwnership();
Vector3 direction = (target - item.transform.position).normalized;
body.WakeUp();
body.linearVelocity = direction * AlfarPowerConfig.KallSpeed.Value;
pulled++;
}
StartCooldown("kall", AlfarPowerConfig.KallCooldown.Value);
Jotunn.Logger.LogInfo($"[Alfar] Kall pulled {pulled} item(s).");
}
// ─── Ljosstorm: the psionic storm ────────────────────────────────────
private static void Ljosstorm(Player player)
{
if (!Ready("storm")) return;
float cost = CostOf(AlfarPowerConfig.StormCost.Value, true);
if (!Pay(player, cost)) return;
Aim(player, AlfarPowerConfig.StormRange.Value, out Vector3 point, out Character _);
GameObject storm = new GameObject("AlfarStorm");
storm.transform.position = point;
AlfarStormZone zone = storm.AddComponent<AlfarStormZone>();
zone.Owner = player;
zone.Radius = AlfarPowerConfig.StormRadius.Value;
zone.Seconds = AlfarPowerConfig.StormSeconds.Value;
zone.DamagePerSecond = AlfarPowerConfig.StormDps.Value;
StartCooldown("storm", CooldownOf(AlfarPowerConfig.StormCooldown.Value, true));
}
// ─── Geisli: the beam ────────────────────────────────────────────────
/// <summary>
/// The pad's way to hold the beam. Every pad button is taken in vanilla's Classic layout, so,
/// like Skadi's Cold Spell, the beam borrows the secondary attack: bare-handed, or in the
/// archon form, which has no weapons anyway. The radial entry only gives a single press,
/// which cannot hold a beam.
/// </summary>
private static bool PadBeamHeld(Player player) =>
!RaceInput.RadialOpen && RaceInput.PadAttackHeld(2) &&
(AlfarArchon.Active || RaceInput.EmptyHanded(player));
/// <summary>
/// Swallows the unarmed secondary (the kick) while the pad's secondary attack is the beam,
/// the same way SkadiAttackPatch does for the Cold Spell.
/// </summary>
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Alfar_GeisliPadKick_Patch
{
public static bool Prefix(Humanoid __instance, bool secondaryAttack, ref bool __result)
{
if (!secondaryAttack || __instance != Player.m_localPlayer) return true;
Player player = (Player)__instance;
if (!AlfarVisuals.IsAlfarPlayer(player) || !Unlocked(AlfarPowerConfig.GeisliState)) return true;
if (!PadBeamHeld(player)) return true;
__result = false;
return false;
}
}
private static LineRenderer beamLine;
private static readonly List<LineRenderer> beamArcs = new List<LineRenderer>();
private static GameObject beamFx;
private static bool beamOn;
private static float beamStarted;
private static float beamNextTick;
private static float beamNextAnim;
private static float beamNextArcs;
/// <summary>
/// The beam leaves the RIGHT HAND, raised with the palm open: the borrowed "gpower" gesture (the
/// arms-raised cast the other races use too, with the real Guardian Power swallowed for a moment),
/// repeated while the key is held so the arm stays up. A quiet electric hum comes from the
/// vanilla lightning staff's charge effect hung on the hand, turned down, and a few jagged arcs
/// flicker round the line.
/// </summary>
private static void TickBeam(Player player)
{
bool wanted = RaceInput.Allowed && !player.IsDead() && Unlocked(AlfarPowerConfig.GeisliState) &&
(AlfarPowerConfig.GeisliKey.Value.IsPressedIgnoringHeldKeys() || PadBeamHeld(player));
if (!wanted)
{
if (beamOn) StopBeam(startCooldown: true);
return;
}
if (!beamOn)
{
if (!Ready("beam")) return;
if (player.GetEitr() <= 0f && !AlfarArchon.Active) { Pay(player, 1f); return; }
beamOn = true;
beamStarted = Time.time;
beamNextTick = Time.time;
beamNextAnim = 0f;
StartBeamFx(player);
}
if (Time.time - beamStarted > AlfarPowerConfig.BeamMaxSeconds.Value) { StopBeam(startCooldown: true); return; }
if (Time.time >= beamNextAnim)
{
beamNextAnim = Time.time + 1.6f;
RaiseHand(player);
}
Transform aim = AimTransform(player);
Transform hand = AlfarVisuals.RightHand(player);
Vector3 start = hand != null ? hand.position : player.GetEyePoint() + Vector3.down * 0.35f + aim.forward * 0.5f;
Aim(player, AlfarPowerConfig.BeamRange.Value, out Vector3 end, out Character target);
DrawBeam(start, end);
if (Time.time < beamNextTick) return;
const float tick = 0.2f;
beamNextTick = Time.time + tick;
float cost = CostOf(AlfarPowerConfig.BeamCostPerSecond.Value * tick, true);
if (cost > 0f)
{
if (player.GetEitr() < cost) { StopBeam(startCooldown: true); return; }
AlfarEitr.Spend(player, cost);
}
if (IsHostile(player, target))
{
Strike(player, target, AlfarPowerConfig.BeamDps.Value * tick, end);
FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, tick); // a full hit per second on target
}
}
private static void RaiseHand(Player player)
{
ZSyncAnimation animation = player.GetComponent<ZSyncAnimation>();
if (animation == null) return;
RaceInput.SuppressGuardianPowerBriefly(3f);
animation.SetTrigger("gpower");
}
private static void StartBeamFx(Player player)
{
Transform hand = AlfarVisuals.RightHand(player);
if (hand == null || ZNetScene.instance == null) return;
GameObject prefab = ZNetScene.instance.GetPrefab("fx_lightningstaff_charge");
if (prefab == null) return;
beamFx = Object.Instantiate(prefab, hand.position, hand.rotation, hand);
// Not too loud: a hum, not a thunderclap.
foreach (AudioSource source in beamFx.GetComponentsInChildren<AudioSource>(true))
{
source.volume *= 0.35f;
}
}
private static LineRenderer NewLine(string name, float width)
{
GameObject go = new GameObject(name);
LineRenderer line = go.AddComponent<LineRenderer>();
line.material = new Material(Shader.Find("Sprites/Default"));
line.startWidth = width;
line.endWidth = width * 0.5f;
line.useWorldSpace = true;
return line;
}
private static void DrawBeam(Vector3 start, Vector3 end)
{
Color color = AlfarPowerConfig.ArchonColor.Value;
if (beamLine == null)
{
beamLine = NewLine("AlfarBeam", 0.12f);
beamLine.positionCount = 2;
}
beamLine.startColor = color;
beamLine.endColor = new Color(color.r, color.g, color.b, 0.4f);
beamLine.SetPosition(0, start);
beamLine.SetPosition(1, end);
// A few jagged arcs round the line, redrawn about twenty times a second.
if (beamArcs.Count == 0)
{
for (int i = 0; i < 3; i++)
{
LineRenderer arc = NewLine("AlfarBeamArc" + i, 0.04f);
arc.positionCount = 9;
beamArcs.Add(arc);
}
}
if (Time.time >= beamNextArcs)
{
beamNextArcs = Time.time + 0.05f;
Vector3 direction = end - start;
foreach (LineRenderer arc in beamArcs)
{
arc.startColor = new Color(1f, 1f, 1f, 0.9f);
arc.endColor = new Color(color.r, color.g, color.b, 0.2f);
for (int i = 0; i < arc.positionCount; i++)
{
float t = i / (float)(arc.positionCount - 1);
Vector3 point = start + direction * t;
if (i > 0 && i < arc.positionCount - 1) point += Random.insideUnitSphere * 0.35f;
arc.SetPosition(i, point);
}
}
}
}
private static void StopBeam(bool startCooldown = false)
{
if (beamLine != null) { Object.Destroy(beamLine.gameObject); beamLine = null; }
foreach (LineRenderer arc in beamArcs) if (arc != null) Object.Destroy(arc.gameObject);
beamArcs.Clear();
if (beamFx != null) { Object.Destroy(beamFx); beamFx = null; }
if (beamOn && startCooldown) StartCooldown("beam", CooldownOf(AlfarPowerConfig.BeamCooldown.Value, true));
beamOn = false;
}
// ─── Kyrr: stasis ────────────────────────────────────────────────────
private static void Kyrr(Player player)
{
if (!Ready("kyrr")) return;
Transform aim = AimTransform(player);
Character best = null;
float bestDistance = float.MaxValue;
foreach (RaycastHit hit in Physics.SphereCastAll(aim.position, 0.8f, aim.forward,
AlfarPowerConfig.StasisRange.Value, ~0, QueryTriggerInteraction.Ignore))
{
Character character = hit.collider.GetComponentInParent<Character>();
if (!IsHostile(player, character) || hit.distance >= bestDistance) continue;
best = character;
bestDistance = hit.distance;
}
if (best == null) return;
if (!Pay(player, AlfarPowerConfig.StasisCost.Value)) return;
float seconds = best.IsBoss() ? AlfarPowerConfig.StasisBossSeconds.Value : AlfarPowerConfig.StasisSeconds.Value;
AlfarStasis.Apply(best, seconds);
StartCooldown("kyrr", AlfarPowerConfig.StasisCooldown.Value);
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", best.GetCenterPoint());
}
}
/// <summary>A storm on the ground that strikes every hostile creature inside it, twice a second.</summary>
public class AlfarStormZone : MonoBehaviour
{
public Player Owner;
public float Radius;
public float Seconds;
public float DamagePerSecond;
private float born;
private float nextTick;
private Light glow;
private void Start()
{
born = Time.time;
glow = gameObject.AddComponent<Light>();
glow.color = AlfarPowerConfig.ArchonColor.Value;
glow.range = Radius * 1.5f;
glow.intensity = 2f;
}
private void Update()
{
if (Owner == null || Time.time - born >= Seconds) { Destroy(gameObject); return; }
if (Time.time < nextTick) return;
const float tick = 0.5f;
nextTick = Time.time + tick;
bool struck = false;
foreach (Collider collider in Physics.OverlapSphere(transform.position, Radius, ~0, QueryTriggerInteraction.Ignore))
{
Character character = collider.GetComponentInParent<Character>();
if (character == null || character == Owner || character.IsDead() || character.IsTamed()) continue;
if (!BaseAI.IsEnemy(Owner, character)) continue;
AlfarPowers.Strike(Owner, character, DamagePerSecond * tick, character.GetCenterPoint());
struck = true;
}
// Once per tick, not per creature: a full hit per second the storm strikes something.
if (struck && Owner == Player.m_localPlayer) FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, tick);
Vector2 offset = Random.insideUnitCircle * Radius;
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", transform.position + new Vector3(offset.x, 0f, offset.y));
}
}
/// <summary>
/// Holds a creature still and untouchable for a few seconds (Kyrr). Frozen means the AI is off, the
/// animator stopped and the body locked; untouchable is the prefix at the bottom, which cancels
/// every blow on a creature that carries this. Everything is put back when it runs out.
/// </summary>
public class AlfarStasis : MonoBehaviour
{
private float until;
private Animator animator;
private float animatorSpeed;
private MonoBehaviour ai;
private Rigidbody body;
private RigidbodyConstraints constraints;
public static void Apply(Character target, float seconds)
{
AlfarStasis existing = target.GetComponent<AlfarStasis>();
if (existing != null) { existing.until = Time.time + seconds; return; }
ZNetView nview = target.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.ClaimOwnership();
AlfarStasis stasis = target.gameObject.AddComponent<AlfarStasis>();
stasis.until = Time.time + seconds;
}
private void Awake()
{
animator = GetComponentInChildren<Animator>();
if (animator != null) { animatorSpeed = animator.speed; animator.speed = 0f; }
ai = GetComponent<BaseAI>();
if (ai != null) ai.enabled = false;
body = GetComponent<Rigidbody>();
if (body != null)
{
constraints = body.constraints;
body.linearVelocity = Vector3.zero;
body.constraints = RigidbodyConstraints.FreezeAll;
}
}
private void Update()
{
if (Time.time >= until) Destroy(this);
}
private void OnDestroy()
{
if (animator != null) animator.speed = animatorSpeed;
if (ai != null) ai.enabled = true;
if (body != null) body.constraints = constraints;
}
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Alfar_Stasis_Patch
{
public static void Prefix(Character __instance, HitData __0)
{
if (__0 != null && __instance != null && __instance.GetComponent<AlfarStasis>() != null)
{
__0.m_damage = default(HitData.DamageTypes);
}
}
}
}
/// <summary>Spawns a vanilla effect prefab by name, and says nothing if the name is not there.</summary>
public static class AlfarFx
{
public static void Spawn(string prefabName, Vector3 position)
{
if (ZNetScene.instance == null) return;
GameObject prefab = ZNetScene.instance.GetPrefab(prefabName);
if (prefab == null) return;
Object.Instantiate(prefab, position, Quaternion.identity);
}
}
}

View file

@ -1,434 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Alfar probe: reads the live prefabs the design leans on, because Mono.Cecil only shows
/// field NAMES and never the values baked into a prefab (Alfar_Progettazione.txt, sec. 16B V11).
///
/// Nothing here instantiates a prefab, so no AI or Awake logic runs. Everything goes to the
/// BepInEx log under an [AlfarProbe] prefix; the console only says it finished.
///
/// alfarprobe EVERYTHING: every default target, the lightning table, and who
/// references Softtissue and Crystal
/// alfarprobe <prefab> just that prefab (names are the manifest's, case sensitive)
/// alfarprobe lightning just the table of how every creature takes lightning damage
///
/// WHAT EACH TARGET ANSWERS, so the log can be read against the design rather than around it:
/// Deathsquito are the legs and stinger separate objects (they are meant to be removed),
/// where the buzz lives, which materials the eyes and wings use
/// Surtling whether it is particles and lights or textures (decides how to recolour it)
/// StoneGolem attacks, area attacks, hp: the numbers the construct copies
/// Abomination whether it is a Humanoid with item attacks, and its hp and damage
/// piece_Charred_Balista whether it is a Piece with WearNTear and a Turret, and what it
/// needs to be built (sec. 8.6: it may only be the ballista a camp spawns)
/// ancient_skull what it is (MineRock5, Destructible...) and what it drops (soft tissue?)
/// eitrrefinery its conversion list: what really turns sap into refined eitr
/// Beehive m_secPerUnit and m_maxHoney, which the crystal timer is defined from
/// Dverger staffs the projectile the Abomination's sphere will be cloned from
/// </summary>
public class AlfarProbeCommand : ConsoleCommand
{
public override string Name => "alfarprobe";
public override string Help =>
"[DEBUG] alfarprobe [prefab|lightning] - logs the live prefab data the Alfar design needs " +
"(hierarchy, components, drops, attacks, lightning resistances) to the BepInEx log.";
private static readonly string[] DefaultTargets =
{
"Deathsquito", "Deathsquito_sting",
"Surtling", "StoneGolem", "Abomination",
"piece_Charred_Balista", "ancient_skull", "giant_skull",
"eitrrefinery", "Beehive", "piece_beehive", "piece_sapcollector",
"giant_skull_frac", "rock4_forest_frac", "giant_brain", "giant_brain_frac",
"DvergerStaffFire_fireball_projectile", "DvergerStaffIce_projectile",
"Pickable_Mushroom_Magecap", "Pickable_Mushroom_JotunPuffs", "sapling_magecap",
};
// Components whose public fields are worth printing in full. Anything else is only listed by name.
private static readonly HashSet<string> Interesting = new HashSet<string>
{
"Character", "Humanoid", "MonsterAI", "BaseAI", "CharacterDrop", "Tameable",
"Piece", "WearNTear", "Turret", "ZNetView",
"Destructible", "MineRock5", "MineRock", "DropOnDestroyed", "Pickable", "Plant",
"Beehive", "Smelter", "CookingStation", "Fermenter", "Container",
"Projectile", "Aoe", "ItemDrop", "ZSyncAnimation", "CharacterAnimEvent",
};
// For these the private fields are printed as well, because the interesting data (default
// items, attack timings) is private. Only fields declared on the type itself, to skip noise.
private static readonly HashSet<string> WithPrivate = new HashSet<string>
{
"Humanoid", "MonsterAI", "BaseAI", "Character",
};
public override void Run(string[] args)
{
if (args.Length > 0 && args[0].ToLower() == "lightning")
{
DumpLightningTable();
Console.instance.Print("[AlfarProbe] lightning table written to the BepInEx log.");
return;
}
if (args.Length > 1 && args[0].ToLower() == "whodrops")
{
WhoDrops(args[1]);
Console.instance.Print($"[AlfarProbe] whodrops {args[1]} written to the BepInEx log.");
return;
}
string[] targets = args.Length > 0 ? args : DefaultTargets;
foreach (string name in targets)
{
DumpPrefab(name);
}
if (args.Length == 0)
{
// The no-argument form is the WHOLE probe in one go: every default prefab, the
// lightning table, and who references soft tissue and crystals (the two drops the
// design could not place from the prefabs alone).
DumpLightningTable();
WhoDrops("Softtissue");
WhoDrops("Crystal");
}
Console.instance.Print($"[AlfarProbe] done, {targets.Length} prefab(s). Read BepInEx/LogOutput.log.");
}
private static void Log(string line) => Jotunn.Logger.LogInfo("[AlfarProbe] " + line);
private static GameObject Find(string name)
{
GameObject found = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(name) : null;
if (found != null) return found;
return PrefabManager.Cache.GetPrefab<GameObject>(name);
}
// ─── One prefab ──────────────────────────────────────────────────────
private static void DumpPrefab(string name)
{
GameObject prefab = Find(name);
Log($"==================== {name} ====================");
if (prefab == null)
{
Log("NOT FOUND by ZNetScene or the prefab cache. Check the spelling against the manifest, " +
"and note an _res/ prefab may not be registered at all (Alfar doc sec. 8.6).");
return;
}
Log($"root '{prefab.name}' scale={prefab.transform.localScale}");
DumpHierarchy(prefab.transform, "", 0);
foreach (Component component in prefab.GetComponentsInChildren<Component>(true))
{
if (component == null) continue;
string typeName = component.GetType().Name;
if (!Interesting.Contains(typeName)) continue;
Log($"--- {typeName} on '{PathOf(component.transform, prefab.transform)}'");
DumpFields(component, WithPrivate.Contains(typeName));
}
DumpDefaultItems(prefab);
}
private static void DumpHierarchy(Transform node, string indent, int depth)
{
if (depth > 9) { Log($"{indent}... (deeper than 9 levels)"); return; }
var parts = new List<string>();
foreach (Component c in node.GetComponents<Component>())
{
if (c == null || c is Transform) continue;
parts.Add(c.GetType().Name);
}
string pos = node.localPosition == Vector3.zero ? "" : $" pos={node.localPosition}";
string scale = node.localScale == Vector3.one ? "" : $" scale={node.localScale}";
Log($"{indent}{node.name}{(node.gameObject.activeSelf ? "" : " [INACTIVE]")}{pos}{scale}" +
(parts.Count > 0 ? " <" + string.Join(", ", parts) + ">" : ""));
Renderer renderer = node.GetComponent<Renderer>();
if (renderer != null)
{
foreach (Material m in renderer.sharedMaterials)
{
if (m == null) continue;
Log($"{indent} material '{m.name}' shader='{(m.shader != null ? m.shader.name : "null")}'" +
$" color={(m.HasProperty("_Color") ? m.GetColor("_Color").ToString() : "-")}" +
$" emission={(m.HasProperty("_EmissionColor") ? m.GetColor("_EmissionColor").ToString() : "-")}");
}
}
foreach (Transform child in node)
{
DumpHierarchy(child, indent + " ", depth + 1);
}
}
// ─── Generic field reader ────────────────────────────────────────────
private static void DumpFields(object target, bool includePrivate)
{
Type type = target.GetType();
// The first probe printed only the fields DECLARED on Humanoid and MonsterAI and so never
// showed Character's (hp, faction, flying, damage modifiers) or BaseAI's. Walk up the
// chain and print the public fields of every base too, private ones only on the leaf.
for (Type level = type; level != null && level != typeof(MonoBehaviour) && level != typeof(Behaviour); level = level.BaseType)
{
bool leaf = level == type;
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly;
if (includePrivate && leaf) flags |= BindingFlags.NonPublic;
if (!leaf) Log($" -- inherited from {level.Name}");
DumpLevel(target, level, flags);
}
}
private static void DumpLevel(object target, Type type, BindingFlags flags)
{
foreach (FieldInfo field in type.GetFields(flags))
{
// Runtime state, not prefab data: nothing there to learn and lots of it.
if (field.FieldType == typeof(ZNetView) && field.IsPrivate) continue;
object value;
try { value = field.GetValue(target); }
catch (Exception) { continue; }
string text = Describe(value, 0);
if (text == null) continue;
Log($" {field.Name} = {text}");
}
}
/// <summary>
/// A short readable form of a field value, or null when it is not worth a line (null, empty,
/// zero). Objects are shown by name only: this is a probe, not a serialiser.
/// </summary>
private static string Describe(object value, int depth)
{
if (value == null) return null;
if (value is UnityEngine.Object unityObject)
{
return unityObject == null ? null : $"'{unityObject.name}' ({unityObject.GetType().Name})";
}
if (value is string s) return s.Length == 0 ? null : "'" + s + "'";
Type t = value.GetType();
if (t.IsEnum) return value.ToString();
if (t.IsPrimitive)
{
if (value is bool b) return b ? "true" : "false";
string number = value.ToString();
return number == "0" ? null : number;
}
if (value is Vector2 || value is Vector3 || value is Color || value is Quaternion || value is Vector4)
{
return value.ToString();
}
if (depth >= 2) return $"({t.Name})";
if (value is IList list)
{
if (list.Count == 0) return null;
var items = new List<string>();
foreach (object item in list.Cast<object>().Take(24))
{
string d = Describe(item, depth + 1);
if (d != null) items.Add(d);
}
return $"[{list.Count}] " + string.Join("; ", items);
}
// A plain struct or class: print the fields that carry something.
var inner = new List<string>();
foreach (FieldInfo f in t.GetFields(BindingFlags.Instance | BindingFlags.Public))
{
object fv;
try { fv = f.GetValue(value); }
catch (Exception) { continue; }
string d = Describe(fv, depth + 1);
if (d != null) inner.Add($"{f.Name}={d}");
}
return inner.Count == 0 ? null : "{" + string.Join(", ", inner) + "}";
}
// ─── What a creature actually attacks with ───────────────────────────
private static void DumpDefaultItems(GameObject prefab)
{
Humanoid humanoid = prefab.GetComponent<Humanoid>();
if (humanoid == null) return;
Log("--- DEFAULT ITEMS (Humanoid.m_defaultItems / m_randomWeapon / m_unarmedWeapon)");
var items = new List<GameObject>();
AddAll(items, Read<GameObject[]>(humanoid, "m_defaultItems"));
AddAll(items, Read<GameObject[]>(humanoid, "m_randomWeapon"));
ItemDrop unarmed = Read<ItemDrop>(humanoid, "m_unarmedWeapon");
if (unarmed != null) items.Add(unarmed.gameObject);
// The StoneGolem carries its weapons in random SETS (Spike, Sledge), which the first probe
// never looked at: m_defaultItems was empty and it said "none".
IList sets = Read<IList>(humanoid, "m_randomSets");
if (sets != null)
{
foreach (object set in sets)
{
GameObject[] setItems = Read<GameObject[]>(set, "m_items");
AddAll(items, setItems);
}
}
if (items.Count == 0) { Log(" (none)"); return; }
foreach (GameObject item in items.Distinct())
{
ItemDrop drop = item.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) continue;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
Log($" weapon '{item.name}' ({shared.m_name}) damages={shared.m_damages}");
LogAttack("primary", shared.m_attack);
LogAttack("secondary", shared.m_secondaryAttack);
}
}
private static void LogAttack(string label, Attack attack)
{
if (attack == null) return;
Log($" {label}: {Describe(attack, 0)}");
}
private static T Read<T>(object target, string field) where T : class
{
FieldInfo info = target.GetType().GetField(field,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
return info != null ? info.GetValue(target) as T : null;
}
private static void AddAll(List<GameObject> into, GameObject[] source)
{
if (source == null) return;
foreach (GameObject go in source) if (go != null) into.Add(go);
}
private static string PathOf(Transform node, Transform root)
{
if (node == root) return node.name;
var names = new List<string>();
for (Transform t = node; t != null && t != root; t = t.parent) names.Add(t.name);
names.Reverse();
return root.name + "/" + string.Join("/", names);
}
// ─── Who drops an item ───────────────────────────────────────────────
/// <summary>
/// Finds every prefab with a component that REFERENCES the named item: a drop table, a pickable,
/// a destructible, a creature's loot. Written for soft tissue, which the design says comes from
/// the Mistlands ancient skulls while the skull prefab itself drops nothing (probe 1): the drop
/// has to be somewhere else, probably in the fragments the skull spawns when destroyed.
/// </summary>
private static void WhoDrops(string itemName)
{
Log($"==================== WHO REFERENCES '{itemName}' ====================");
if (ZNetScene.instance == null)
{
Log("ZNetScene is not up: load a world and run it again.");
return;
}
int hits = 0;
foreach (GameObject prefab in ZNetScene.instance.m_prefabs)
{
if (prefab == null || prefab.name == itemName) continue;
foreach (Component component in prefab.GetComponentsInChildren<Component>(true))
{
if (component == null || component is Transform || component is ItemDrop) continue;
if (References(component, itemName, 0)) { Log($"{prefab.name} :: {component.GetType().Name} on '{component.name}'"); hits++; }
}
}
Log($"{hits} reference(s) to '{itemName}'.");
}
private static bool References(object value, string itemName, int depth)
{
if (value == null || depth > 3) return false;
foreach (FieldInfo field in value.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public))
{
object fieldValue;
try { fieldValue = field.GetValue(value); }
catch (Exception) { continue; }
if (fieldValue == null) continue;
if (fieldValue is UnityEngine.Object unityObject)
{
if (unityObject != null && unityObject.name == itemName) return true;
continue;
}
Type t = fieldValue.GetType();
if (t.IsPrimitive || t.IsEnum || fieldValue is string) continue;
if (fieldValue is IList list)
{
foreach (object item in list)
{
if (item is UnityEngine.Object o) { if (o != null && o.name == itemName) return true; }
else if (item != null && !item.GetType().IsPrimitive && References(item, itemName, depth + 1)) return true;
}
}
else if (!t.IsAbstract && t.Namespace == null && References(fieldValue, itemName, depth + 1))
{
return true;
}
}
return false;
}
// ─── How every creature takes lightning ──────────────────────────────
/// <summary>
/// The constructs deal lightning, so a creature that resists or is immune to it resists the
/// constructs (Alfar doc sec. 17.13). This is the table to read before pricing them.
/// </summary>
private static void DumpLightningTable()
{
Log("==================== LIGHTNING TABLE ====================");
if (ZNetScene.instance == null)
{
Log("ZNetScene is not up (you are in the menu): load a world and run `alfarprobe lightning`.");
return;
}
var rows = new List<string>();
foreach (GameObject prefab in ZNetScene.instance.m_prefabs)
{
if (prefab == null) continue;
Character character = prefab.GetComponent<Character>();
if (character == null) continue;
rows.Add($"{prefab.name,-28} faction={character.m_faction,-12} hp={character.m_health,7:0} " +
$"boss={(character.m_boss ? "Y" : "n")} lightning={character.m_damageModifiers.m_lightning} " +
$"fire={character.m_damageModifiers.m_fire} spirit={character.m_damageModifiers.m_spirit}");
}
rows.Sort(StringComparer.Ordinal);
foreach (string row in rows) Log(row);
Log($"{rows.Count} creatures. Anything not 'Normal' under lightning is resistant, weak or immune.");
}
}
}

View file

@ -1,40 +0,0 @@
namespace RacesOfValheim
{
/// <summary>
/// The Alfar: light-bodied casters whose one resource is eitr (Alfar_Progettazione.txt).
///
/// Only the race check lives here for now. The shield, the death timer, the powers and the
/// Nexus each get their own file as they are written; the look is AlfarVisuals and its patches.
/// </summary>
public static class AlfarRace
{
/// <summary>
/// Everything the race registers with Jotunn. Called from RacesOfValheim.CreateAllModAssets,
/// which runs on PrefabManager.OnVanillaPrefabsAvailable: the one moment Jotunn takes new
/// status effects, items and prefabs into ObjectDB. Registered later, nothing can spawn.
/// </summary>
public static void CreateModAssets()
{
AlfarStatusEffects.Register();
AlfarDrones.Register();
AlfarConstructs.Register();
AlfarSigil.Register();
AlfarNexus.Register();
AlfarChests.Register();
AlfarLjosgard.Register();
AlfarTowers.Register();
}
/// <summary>
/// The local player's race, read from m_customData like every other race's IsXxx() (guide
/// 5.4: never from the body model index, which is not a race).
/// </summary>
public static bool IsLocalAlfar()
{
Player player = Player.m_localPlayer;
return player != null &&
player.m_customData.TryGetValue("Race", out string race) &&
race == AlfarConfig.RaceId;
}
}
}

View file

@ -1,169 +0,0 @@
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Alfar's passive carrier. For now it holds only the FEATHER FALL: with eitr in the pool the
/// body is lowered instead of dropped.
///
/// Valheim already has the mechanism (the Feather Cape): SE_Stats.m_maxMaxFallSpeed makes
/// StatusEffect.ModifyWalkVelocity clamp the downward speed (verified in the IL, doc sec. 16B).
/// So the effect is an SE_Stats with that field switched on while there is eitr and off when
/// there is none - and a fall at eitr zero is a normal, fast, damaging fall.
///
/// The fall DAMAGE is a separate matter, handled by the shield prefix (AlfarEitr): a fall is free
/// while there is eitr. This effect is what makes it look like falling softly.
///
/// Rebuilt every tick for the same reason the Sverm's is: Setup runs once, at spawn, so anything
/// written there is frozen.
/// </summary>
public class SE_AlfarStats : SE_Stats
{
public const string EffectName = "SE_AlfarStats";
public override void Setup(Character character)
{
base.Setup(character);
name = EffectName;
m_name = "$rov_se_alfar_stats_name";
m_tooltip = "$rov_se_alfar_stats_tooltip";
Rebuild();
}
public override void UpdateStatusEffect(float dt)
{
base.UpdateStatusEffect(dt);
Rebuild();
}
private void Rebuild()
{
Player player = m_character as Player;
bool charged = player != null && player.GetEitr() > 0f;
// Written on the LIVE effect, not on the registered template: SEMan clones what it is
// given, so a template edited afterwards reaches nobody.
m_maxMaxFallSpeed = charged && AlfarConfig.SoftFall.Value ? AlfarConfig.FeatherFallSpeed.Value : 0f;
// The archon form is faster. SE_Stats.m_speedModifier is added to the body's speed factor.
m_speedModifier = AlfarArchon.Active ? AlfarPowerConfig.ArchonSpeedBonus.Value : 0f;
}
}
/// <summary>
/// A marker with a countdown: the HUD prints the remaining time of any effect that has a m_ttl, so
/// the cooldowns of the powers, the Heimkall wait and the archon form all show on screen without a
/// line of UI code (the Dvergar's cooldown icons do the same).
/// </summary>
public class SE_AlfarTimer : StatusEffect
{
}
public static class AlfarStatusEffects
{
public static readonly string[] TimerIds = { "skrid", "graf", "kall", "storm", "beam", "kyrr", "heimkall", "archon" };
public static string TimerName(string id) { return "SE_AlfarTimer_" + id; }
private static string TimerIcon(string id)
{
switch (id)
{
case "graf": return "TrophyDeathsquito";
case "kall": return "Thunderstone";
case "storm": return "OrbThunderBlood";
case "beam": return "Crystal";
case "kyrr": return "FreezeGland";
case "archon": return "TrophyFader";
default: return "Eitr";
}
}
/// <summary>Starts (or restarts) the on-screen countdown of a power, the Heimkall wait or the form.</summary>
public static void ShowTimer(string id, float seconds)
{
Player player = Player.m_localPlayer;
if (player == null || seconds <= 0f) return;
int hash = TimerName(id).GetStableHashCode();
SEMan seman = player.GetSEMan();
seman.RemoveStatusEffect(hash, true);
seman.AddStatusEffect(hash, true);
StatusEffect effect = seman.GetStatusEffect(hash);
if (effect != null) effect.m_ttl = seconds;
}
public static void ClearTimer(string id)
{
Player player = Player.m_localPlayer;
if (player != null) player.GetSEMan().RemoveStatusEffect(TimerName(id).GetStableHashCode(), true);
}
public static bool HasTimer(string id)
{
Player player = Player.m_localPlayer;
return player != null && player.GetSEMan().HaveStatusEffect(TimerName(id).GetStableHashCode());
}
public static void Register()
{
foreach (string id in TimerIds)
{
Sprite timerIcon = null;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(TimerIcon(id));
ItemDrop sourceDrop = source != null ? source.GetComponent<ItemDrop>() : null;
if (sourceDrop != null && sourceDrop.m_itemData != null && sourceDrop.m_itemData.m_shared != null &&
sourceDrop.m_itemData.m_shared.m_icons != null && sourceDrop.m_itemData.m_shared.m_icons.Length > 0)
{
timerIcon = sourceDrop.m_itemData.m_shared.m_icons[0];
}
var timer = ScriptableObject.CreateInstance<SE_AlfarTimer>();
timer.name = TimerName(id);
timer.m_name = "$rov_se_alfar_timer_" + id + "_name";
timer.m_icon = timerIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(timer, fixReference: false));
}
Sprite icon = null;
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>("Eitr");
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null &&
drop.m_itemData.m_shared.m_icons != null && drop.m_itemData.m_shared.m_icons.Length > 0)
{
icon = drop.m_itemData.m_shared.m_icons[0];
}
var stats = ScriptableObject.CreateInstance<SE_AlfarStats>();
stats.name = SE_AlfarStats.EffectName;
stats.m_name = "$rov_se_alfar_stats_name";
stats.m_icon = icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(stats, fixReference: false));
}
/// <summary>Adds the passive to a player that lacks it: status effects do not survive death or a reload.</summary>
public static void Ensure(Player player)
{
if (player == null) return;
int hash = SE_AlfarStats.EffectName.GetStableHashCode();
if (!player.GetSEMan().HaveStatusEffect(hash))
{
player.GetSEMan().AddStatusEffect(hash, true);
}
}
/// <summary>Takes the passive off a player who stopped being an Alfr.</summary>
public static void Remove(Player player)
{
if (player == null) return;
int hash = SE_AlfarStats.EffectName.GetStableHashCode();
if (player.GetSEMan().HaveStatusEffect(hash))
{
player.GetSEMan().RemoveStatusEffect(hash, true);
}
}
}
}

View file

@ -1,239 +0,0 @@
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The PRISMAVARD, the Alfar's towers (Alfar_Progettazione.txt sec. 8.6): the charred ballista of the
/// Ashlands, smaller and bronze, turned around to defend. Read from the live prefab (doc 16C P5):
///
/// - it is NOT a Piece: it has Turret, WearNTear and DropOnDestroyed and nothing that lets the
/// hammer place it, so a Piece is added here;
/// - it is an ENEMY tower: it targets players and tamed creatures and not enemies, so the three
/// flags are turned round;
/// - m_maxAmmo is 0 and HasAmmo() is true when it is 0 (read in the IL): the vanilla tower has
/// infinite ammunition, so "consumes nothing" is free; what is changed is the AMMO, a bolt that
/// does lightning, so the shot is ours.
///
/// It only works inside a Ljoskjarne's radius (AlfarTower switches the Turret off outside it), has a
/// shield equal to its health that returns by itself, and is repaired with the hammer and by the
/// drones like any building.
/// </summary>
public static class AlfarTowers
{
public const string PieceName = "AlfarPrismavard";
public const string PieceDisplay = "$rov_piece_alfar_prismavard_name";
public const string AmmoName = "AlfarPrismBolt";
public const string ProjectileName = "AlfarPrismProjectile";
public static void Register()
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("piece_Charred_Balista");
if (source == null)
{
Jotunn.Logger.LogWarning("[Alfar] No 'piece_Charred_Balista': the Prismavard is not registered.");
return;
}
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, source);
if (prefab == null) return;
Turret turret = prefab.GetComponent<Turret>();
if (turret == null)
{
Jotunn.Logger.LogWarning("[Alfar] The charred ballista has no Turret component: no Prismavard.");
return;
}
// Turned around: it defends the base against enemies and never at players or their tames.
turret.m_targetPlayers = false;
turret.m_targetTamed = false;
turret.m_targetEnemies = true;
turret.m_returnAmmoOnDestroy = false;
// The ammunition: a bolt that does lightning, shot from a projectile that spares friends
// and buildings. m_maxAmmo stays 0, which means infinite.
GameObject ammo = RegisterAmmo(turret);
if (ammo != null)
{
ItemDrop ammoDrop = ammo.GetComponent<ItemDrop>();
turret.m_defaultAmmo = ammoDrop;
if (turret.m_allowedAmmo != null && turret.m_allowedAmmo.Count > 0)
{
var allowed = turret.m_allowedAmmo[0];
allowed.m_ammo = ammoDrop;
turret.m_allowedAmmo[0] = allowed;
}
}
WearNTear wear = prefab.GetComponent<WearNTear>();
if (wear != null) wear.m_health *= AlfarNexusConfig.TowerHealthFactor.Value;
// The loot of an enemy ballista: a tower of ours must not be a way to farm it.
foreach (DropOnDestroyed drop in prefab.GetComponentsInChildren<DropOnDestroyed>(true))
{
if (drop != null) Object.DestroyImmediate(drop);
}
prefab.transform.localScale = Vector3.one * AlfarNexusConfig.TowerScale.Value;
ZNetView nview = prefab.GetComponent<ZNetView>();
if (nview != null) nview.m_syncInitialScale = true;
AlfarConstructs.Tint(prefab, new Color(0.85f, 0.58f, 0.28f, 1f));
AlfarMark mark = prefab.AddComponent<AlfarMark>();
mark.Role = "tower";
AlfarPieceShield shield = prefab.AddComponent<AlfarPieceShield>();
shield.Max = wear != null ? wear.m_health : 100f;
shield.Shield = shield.Max;
prefab.AddComponent<AlfarTower>();
Sprite icon = AlfarNexus.BorrowIcon("Crystal") ?? AlfarNexus.BorrowIcon("Bronze");
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplay;
piece.m_canBeRemoved = true;
piece.m_icon = icon;
piece.m_groundOnly = false;
piece.m_groundPiece = false;
Piece template = PrefabManager.Cache.GetPrefab<Piece>("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_prismavard_desc",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Misc,
Icon = icon,
Requirements = new[]
{
new RequirementConfig("Bronze", AlfarNexusConfig.TowerBronze.Value, 0, true),
new RequirementConfig("Crystal", AlfarNexusConfig.TowerCrystal.Value, 0, true),
},
}));
// No cap on how many (the user said so), but one rule: inside a Ljoskjarne's radius.
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_tower_needs_nexus"));
return false;
}
return true;
});
AlfarPieces.Extra.Add(PieceName);
}
private static GameObject RegisterAmmo(Turret turret)
{
ItemDrop original = turret.m_defaultAmmo;
if (original == null)
{
Jotunn.Logger.LogWarning("[Alfar] The ballista has no default ammo to copy.");
return null;
}
GameObject ammo = PrefabManager.Instance.CreateClonedPrefab(AmmoName, original.gameObject);
if (ammo == null) return null;
ItemDrop drop = ammo.GetComponent<ItemDrop>();
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = "$rov_item_alfar_prismbolt_name";
HitData.DamageTypes damage = default(HitData.DamageTypes);
damage.m_lightning = AlfarNexusConfig.TowerDamage.Value;
shared.m_damages = damage;
// The projectile it flies as: a copy that spares friends and buildings.
GameObject originalProjectile = shared.m_attack != null ? shared.m_attack.m_attackProjectile : null;
if (originalProjectile != null)
{
GameObject projectile = PrefabManager.Instance.CreateClonedPrefab(ProjectileName, originalProjectile);
Projectile settings = projectile != null ? projectile.GetComponent<Projectile>() : null;
if (settings != null)
{
settings.m_hitFriendly = false;
settings.m_noDamageFriendly = true;
settings.m_aoeSkipWearNTear = true;
PrefabManager.Instance.AddPrefab(projectile);
shared.m_attack.m_attackProjectile = projectile;
}
}
ItemManager.Instance.AddItem(new CustomItem(ammo, fixReference: false));
return ammo;
}
}
/// <summary>The tower runs only while a Ljoskjarne's radius covers it: outside, the Turret is off.</summary>
public class AlfarTower : MonoBehaviour
{
private Turret turret;
private float nextCheck;
private void Awake() { turret = GetComponent<Turret>(); }
private void Update()
{
if (turret == null || Time.time < nextCheck) return;
nextCheck = Time.time + 2f;
bool powered = AlfarNexusBehaviour.Covering(transform.position) != null;
if (turret.enabled != powered) turret.enabled = powered;
}
}
/// <summary>
/// A building's shield: equal to its health, back at 1% a second after five quiet seconds. Its own
/// absorption on WearNTear.ApplyDamage, the stage every blow on a building ends in; the hammer and
/// the drones repair the HEALTH, the shield returns by itself.
/// </summary>
public class AlfarPieceShield : MonoBehaviour
{
public float Max;
public float Shield;
private float lastHit = -999f;
private void Update()
{
if (Shield >= Max || Time.time - lastHit < 5f) return;
Shield = Mathf.Min(Max, Shield + Max * 0.01f * Time.deltaTime);
}
public float Absorb(float damage)
{
if (damage <= 0f) return damage;
lastHit = Time.time;
float absorbed = Mathf.Min(Shield, damage);
Shield -= absorbed;
return damage - absorbed;
}
[HarmonyPatch(typeof(WearNTear), "ApplyDamage")]
public static class Alfar_PieceShield_Patch
{
public static void Prefix(WearNTear __instance, ref float __0)
{
AlfarPieceShield shield = __instance != null ? __instance.GetComponent<AlfarPieceShield>() : null;
if (shield != null) __0 = shield.Absorb(__0);
}
}
}
}

View file

@ -1,525 +0,0 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// What an Alfr looks like (Alfar_Progettazione.txt sec. 7): ash-grey skin, five percent taller
/// and a little thinner than a Viking, no hair, no beard, and two completely black eyes.
///
/// Everything here is written the way the Sverm and the Dvergar already write theirs, because
/// each of those shapes cost somebody a test session:
/// - the race is read off the ZDO, so remote players render right, falling back to
/// m_customData for the menu preview (same shape as SvermVisuals.GetPlayerRace);
/// - the skin is written AFTER Valheim rebuilds the body material (see AlfarPatches);
/// - the scale goes on the "Visual" child and never the root, and only ever undoes its own;
/// - the eyes are spheres on the head bone with every offset divided by lossyScale, because
/// the player armature is authored at scale 100.
///
/// The eyes are the Sverm's spheres with the glow taken out: same geometry, a matte black
/// material, no emission at all.
/// </summary>
public static class AlfarVisuals
{
private const string EyesName = "AlfarEyes";
private const string HeadBoneName = "Head";
// ─── Race check ──────────────────────────────────────────────────────
public static string GetPlayerRace(Player player)
{
if (player == null) return "Human";
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
string race = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(race)) return race;
}
if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string custom))
{
return custom;
}
return "Human";
}
public static bool IsAlfarPlayer(Player player) => GetPlayerRace(player) == AlfarConfig.RaceId;
// ─── Scale ───────────────────────────────────────────────────────────
/// <summary>
/// +5% in height and a little less wide. NON-uniform, so the scale is a Vector3 and not the
/// single float the other races write.
///
/// The reset only ever undoes a scale that looks like ours: another race (the Trol, the
/// Dvergar) may be sizing this player and RaceScale exists so the two do not fight.
/// </summary>
public static void ApplyScale(Player player, bool isAlfar)
{
if (player == null) return;
GameObject visual = Traverse.Create(player).Field("m_visual").GetValue<GameObject>();
if (visual == null) return;
Vector3 ours = new Vector3(AlfarConfig.WidthScale.Value, AlfarConfig.HeightScale.Value, AlfarConfig.WidthScale.Value);
// The archon form is bigger: published in the ZDO, so every client sizes it the same.
Vector3 archon = ours * AlfarPowerConfig.ArchonScale.Value;
bool inArchon = isAlfar && AlfarArchon.IsArchon(player);
Vector3 current = visual.transform.localScale;
Vector3 target = inArchon ? archon : ours;
if (!isAlfar)
{
// Undo only a scale that is one of ours, the normal one or the archon's.
if (!LooksLike(current, ours) && !LooksLike(current, archon)) return;
target = Vector3.one;
}
if (!LooksLike(current, target))
{
visual.transform.localScale = target;
}
}
private static bool LooksLike(Vector3 a, Vector3 b)
{
return Mathf.Abs(a.x - b.x) < 0.001f && Mathf.Abs(a.y - b.y) < 0.001f && Mathf.Abs(a.z - b.z) < 0.001f;
}
// ─── Hair and beard ──────────────────────────────────────────────────
/// <summary>
/// Takes the hair and the beard off the VISUAL only. The Skeleton also rewrites the saved
/// profile, which makes the loss permanent; the Alfar do not, so a reset to Human gets the
/// hair back the next time the game rebuilds the equipment visuals.
///
/// Since Valheim 1.0 these take an item hash and not a name: 0 is the empty slot.
/// </summary>
public static void ApplyHairless(Player player)
{
if (player == null) return;
VisEquipment vis = player.GetComponent<VisEquipment>();
if (vis == null) return;
vis.SetHairItem(0);
vis.SetBeardItem(0);
}
// ─── Eyes ────────────────────────────────────────────────────────────
/// <summary>
/// Which way the skull faces, measured once when the eyes are built and kept for as long as
/// they exist (RigBindPose explains why it is read from the bind pose and not live).
/// </summary>
private class EyeFrame : MonoBehaviour
{
public Vector3 LocalForward = Vector3.forward;
public Vector3 LocalUp = Vector3.up;
public Vector3 LocalRight = Vector3.right;
}
private static Shader cachedShader;
private static bool shaderResolved;
public static void ApplyEyes(Player player)
{
if (player == null) return;
Transform headBone = FindBone(player, HeadBoneName);
if (headBone == null) return; // rig not up yet; try again next pass
Transform eyes = headBone.Find(EyesName);
if (!IsAlfarPlayer(player) || player.IsDead())
{
if (eyes != null)
{
// Renamed first: Destroy is deferred to the end of the frame, and every call
// until then would otherwise find it again.
eyes.name = EyesName + "_Removed";
Object.Destroy(eyes.gameObject);
}
return;
}
if (eyes == null)
{
// Sitting, attached, mid-attack or asleep the head can be turned away from the
// body's forward at the instant the frame is measured, which puts the eyes behind
// the skull. Wait for a neutral moment (the same guard as the Sverm's).
if (player.IsAttached() || player.IsAttachedToShip() || player.InAttack() || player.IsSleeping())
{
return;
}
eyes = BuildEyes(player, headBone);
}
if (eyes == null) return;
PlaceEyes(player, eyes);
}
/// <summary>
/// A grey's eyes: wide black almonds, outer corners raised, wrapping round the sides of the
/// face. Each is a sphere squashed to an ellipsoid and turned in the skull's own frame.
///
/// FIXED HEAD-LOCAL UNITS, never headBone.lossyScale. The Alfar Visual is scaled
/// non-uniformly, so the head's lossyScale is only an approximation that changes as the
/// head turns; recomputed on the 0.5s cosmetic pass it made the eyes trail the face. The
/// face is skinned to the same bone through the same matrices, so a constant local offset
/// stays glued to it at any body scale, and PlaceEyes only has to run when the eyes change.
/// </summary>
private static void PlaceEyes(Player player, Transform holder)
{
EyeFrame frame = holder.GetComponent<EyeFrame>();
if (frame == null) return;
const float toLocal = PlayerFace.MetresToHeadLocal;
float height = AlfarConfig.EyeHeight;
float separation = AlfarConfig.EyeSeparation;
float size = AlfarConfig.EyeSizeMultiplier.Value;
PlayerFace.AdjustEyes(player, ref height, ref separation, ref size);
Quaternion facing = Quaternion.LookRotation(frame.LocalForward, frame.LocalUp);
for (int i = 0; i < holder.childCount; i++)
{
Transform eye = holder.GetChild(i);
// Index 0 is offset against the right axis, so it is the model's left eye. The
// slant and the wrap are mirrored so both outer corners go up and back.
float side = i == 0 ? -1f : 1f;
// This eye's hand corrections (RaceEyeTuning).
float forward = AlfarConfig.EyeForward;
float eyeHeight = height;
float eyeSeparation = separation;
float eyeSize = size;
float wrap = AlfarConfig.EyeWrap;
float slant = AlfarConfig.EyeSlant;
float tilt = 0f;
RaceEyeTuning.Eye tuning = RaceEyeTuning.For(AlfarConfig.RaceId, player, side);
if (tuning != null)
{
forward += tuning.Forward;
eyeHeight += tuning.Height;
eyeSeparation += tuning.Separation;
eyeSize *= tuning.Size;
tilt = tuning.RotX;
wrap += tuning.RotY;
slant += tuning.RotZ;
}
Vector3 offset = frame.LocalForward * forward + frame.LocalUp * eyeHeight
+ frame.LocalRight * (side * eyeSeparation);
eye.localPosition = offset * toLocal;
eye.localRotation = facing * Quaternion.Euler(tilt, wrap * side, slant * side);
eye.localScale = AlfarConfig.EyeExtent * (eyeSize * toLocal);
}
}
private static Transform BuildEyes(Player player, Transform headBone)
{
Shader shader = ResolveShader(player);
if (shader == null) return null;
GameObject holder = new GameObject(EyesName);
holder.transform.SetParent(headBone, false);
holder.transform.localPosition = Vector3.zero;
holder.transform.localRotation = Quaternion.identity;
holder.transform.localScale = Vector3.one;
EyeFrame frame = holder.AddComponent<EyeFrame>();
RigBindPose.MeasureHeadFrame(player, headBone, "Alfar",
out frame.LocalForward, out frame.LocalUp, out frame.LocalRight);
for (int i = 0; i < 2; i++)
{
// Spheres, not quads: a quad seen edge-on is a line and vanishes.
GameObject eye = GameObject.CreatePrimitive(PrimitiveType.Sphere);
eye.name = "Eye" + i;
foreach (Collider collider in eye.GetComponents<Collider>())
{
Object.Destroy(collider);
}
eye.transform.SetParent(holder.transform, false);
eye.transform.localPosition = Vector3.zero;
eye.transform.localRotation = Quaternion.identity;
eye.transform.localScale = Vector3.zero; // PlaceEyes runs immediately after this
Renderer renderer = eye.GetComponent<Renderer>();
renderer.material = BlackMaterial(shader);
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
renderer.receiveShadows = false;
}
return holder.transform;
}
/// <summary>
/// Black with a wet sheen: no emission, but smooth enough to catch a highlight, which is
/// what makes a grey's eyes read as eyes and not as two holes punched in the face.
/// </summary>
private static Material BlackMaterial(Shader shader)
{
Material material = new Material(shader);
material.color = Color.black;
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Color.black);
if (material.HasProperty("_Glossiness")) material.SetFloat("_Glossiness", 0.8f);
if (material.HasProperty("_Smoothness")) material.SetFloat("_Smoothness", 0.8f);
if (material.HasProperty("_Metallic")) material.SetFloat("_Metallic", 0f);
return material;
}
/// <summary>
/// Custom/Creature first, for the reason the Sverm's own resolver gives: Valheim dithers the
/// player away when the camera gets inside them, and only the game's own shaders know about
/// it, so eyes on an unlit shader would hang in the air while the face dissolved.
/// </summary>
private static Shader ResolveShader(Player player)
{
if (shaderResolved) return cachedShader;
// CUSTOM/CREATURE, found the one way that works in play. Two earlier attempts failed in
// opposite directions and both are on record in the log:
// 1. Shader.Find("Custom/Creature") returns null in the main-menu preview (Valheim's
// shaders are not all loaded by name until something has used them), so the code
// fell to Sprites/Default and CACHED it for the whole session;
// 2. taking the player's own body shader gave 'Custom/Player', the SKIN shader: it
// paints the skin texture, so the eyes came out white.
// So: ask Shader.Find, and failing that read the shader off a real creature's material
// (the Deathsquito's, the very prefab the drones are cloned from) once the world is up.
// A failure is never cached, and in the menu preview there are simply no eyes yet.
Shader shader = Shader.Find("Custom/Creature");
if (shader == null && ZNetScene.instance != null)
{
GameObject creature = ZNetScene.instance.GetPrefab("Deathsquito");
Renderer renderer = creature != null ? creature.GetComponentInChildren<Renderer>(true) : null;
if (renderer != null && renderer.sharedMaterial != null) shader = renderer.sharedMaterial.shader;
}
if (shader == null)
{
// The main-menu preview has no world and so no creature to read a shader from. Its eyes
// are only for show and are thrown away with the preview, so a plain unlit black will do
// there - and it is NOT cached, so the world gets the real one.
ZNetView preview = player != null ? player.GetComponent<ZNetView>() : null;
if (preview == null || !preview.IsValid()) return Shader.Find("Sprites/Default");
return null;
}
Jotunn.Logger.LogInfo($"[Alfar] Eye shader resolved to '{shader.name}'.");
shaderResolved = true;
cachedShader = shader;
return cachedShader;
}
// ─── Skin ────────────────────────────────────────────────────────────
/// <summary>Ash grey, or the glow colour while the archon form is up.</summary>
public static Color SkinFor(Player player)
{
return AlfarArchon.IsArchon(player) ? AlfarPowerConfig.ArchonColor.Value : AlfarConfig.SkinColor.Value;
}
private const string GlowName = "AlfarArchonGlow";
/// <summary>
/// A blue light on the body while the archon form is up, taken off when it is not. Every
/// client runs this for every Alfr in range, so the glow is seen by everyone.
/// </summary>
public static void ApplyArchonGlow(Player player)
{
if (player == null) return;
Transform existing = player.transform.Find(GlowName);
bool want = IsAlfarPlayer(player) && AlfarArchon.IsArchon(player) && !player.IsDead();
if (!want)
{
if (existing != null) Object.Destroy(existing.gameObject);
return;
}
if (existing == null)
{
GameObject holder = new GameObject(GlowName);
holder.transform.SetParent(player.transform, false);
holder.transform.localPosition = Vector3.up * 1.2f;
existing = holder.transform;
Light light = holder.AddComponent<Light>();
light.type = LightType.Point;
light.range = 9f;
light.intensity = 3f;
light.shadows = LightShadows.None;
}
Light glow = existing.GetComponent<Light>();
if (glow != null) glow.color = AlfarPowerConfig.ArchonColor.Value;
}
/// <summary>
/// The grey, for real. A tint on _SkinColor only MULTIPLIES the skin texture, and that texture is
/// pink: multiplied by a grey it comes out as a darker human skin, not as grey skin (the second
/// test: "the skin is the normal colour"). So the body's texture is replaced by a DESATURATED
/// copy, made once on the GPU and read back, and _SkinColor then only sets how light the grey is.
/// The original texture is remembered per material so a reset to human puts it back.
/// </summary>
private static readonly Dictionary<Texture, Texture2D> greyOf = new Dictionary<Texture, Texture2D>();
private static readonly Dictionary<Material, Texture> originalTexture = new Dictionary<Material, Texture>();
private static Texture2D Desaturated(Texture source)
{
Texture2D grey;
if (greyOf.TryGetValue(source, out grey) && grey != null) return grey;
RenderTexture target = RenderTexture.GetTemporary(source.width, source.height, 0,
RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
RenderTexture previous = RenderTexture.active;
try
{
Graphics.Blit(source, target);
RenderTexture.active = target;
grey = new Texture2D(source.width, source.height, TextureFormat.RGBA32, true);
grey.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0);
Color32[] pixels = grey.GetPixels32();
for (int i = 0; i < pixels.Length; i++)
{
Color32 c = pixels[i];
byte luma = (byte)(c.r * 0.299f + c.g * 0.587f + c.b * 0.114f);
pixels[i] = new Color32(luma, luma, luma, c.a);
}
grey.SetPixels32(pixels);
grey.Apply(true);
grey.name = source.name + "_AlfarGrey";
}
catch (System.Exception e)
{
Jotunn.Logger.LogWarning("[Alfar] Could not make the grey skin texture: " + e.Message);
grey = null;
}
finally
{
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(target);
}
if (grey != null) greyOf[source] = grey;
return grey;
}
/// <summary>
/// Puts the grey texture on every skin material of the body (or takes it off again). Runs from the
/// UpdateColors postfix, so it covers the main-menu preview and every client, and from the
/// cosmetic pass, so it survives anything that rebuilds the body.
/// </summary>
public static void ApplyGreyTexture(VisEquipment vis, bool on)
{
if (vis == null || vis.m_bodyModel == null) return;
foreach (Material material in vis.m_bodyModel.materials)
{
if (material == null || !material.HasProperty("_SkinColor") || !material.HasProperty("_MainTex")) continue;
Texture current = material.GetTexture("_MainTex");
if (on)
{
if (current == null) continue;
bool ours = false;
foreach (Texture2D grey in greyOf.Values) if (grey == current) { ours = true; break; }
if (ours) continue;
Texture2D desaturated = Desaturated(current);
if (desaturated == null) continue;
originalTexture[material] = current;
material.SetTexture("_MainTex", desaturated);
}
else
{
Texture original;
if (originalTexture.TryGetValue(material, out original) && original != null)
{
material.SetTexture("_MainTex", original);
}
originalTexture.Remove(material);
}
}
}
/// <summary>
/// Keeps the skin right for whoever it is: the grey and its tint for an Alfr, the original for
/// anyone who stopped being one. The tint is only written when it differs, and UpdateColors is
/// pushed only then, so it costs a colour compare.
/// </summary>
public static void SyncSkin(Player player, bool isAlfar)
{
if (player == null) return;
VisEquipment vis = player.GetComponent<VisEquipment>();
if (vis == null || vis.m_bodyModel == null) return;
if (!isAlfar)
{
if (originalTexture.Count > 0) ApplyGreyTexture(vis, false);
return;
}
ApplyGreyTexture(vis, true);
Material material = vis.m_bodyModel.material;
if (material == null || !material.HasProperty("_SkinColor")) return;
Color wanted = SkinFor(player);
Color current = material.GetColor("_SkinColor");
if (Mathf.Abs(current.r - wanted.r) < 0.01f && Mathf.Abs(current.g - wanted.g) < 0.01f &&
Mathf.Abs(current.b - wanted.b) < 0.01f) return;
Traverse.Create(vis).Method("UpdateColors").GetValue();
}
// ─── Hands ───────────────────────────────────────────────────────────
/// <summary>The right hand bone: where the beam leaves from.</summary>
public static Transform RightHand(Player player)
{
return player != null ? FindBone(player, "RightHand") : null;
}
private static Transform FindBone(Player player, string boneName)
{
VisEquipment visEq = player.GetComponent<VisEquipment>();
if (visEq == null || visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return null;
foreach (Transform bone in visEq.m_bodyModel.bones)
{
if (bone != null && bone.name == boneName) return bone;
}
// Loose match, because rigs are not consistent about capitalisation or prefixes.
string wanted = boneName.ToLowerInvariant();
foreach (Transform bone in visEq.m_bodyModel.bones)
{
if (bone != null && bone.name.ToLowerInvariant().Contains(wanted)) return bone;
}
return null;
}
}
}

View file

@ -1,303 +0,0 @@
using System.Collections.Generic;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Reads out a creature's animator, because guessing at animation has cost this mod real time:
/// a howl that was looked for under three wrong names, a taunt animation nobody knew played, and
/// a sound prefab that killed the process when spawned on its own.
///
/// WHAT UNITY LETS US SEE AT RUNTIME, and what it does not, because the line matters:
///
/// Readable. Every parameter with its type. Every layer. Every CLIP in the controller with its
/// name and length, through RuntimeAnimatorController.animationClips - so a creature's whole
/// vocabulary can be listed without ever wearing it. And every AnimationEvent on every clip:
/// the instant, the method name it calls, and its parameters. That last one is where a sound
/// fired by an animation lives, which is the thing this was written to find.
///
/// Not readable. The state machine. States and transitions live in AnimatorController, which is
/// an editor-only type, and GetCurrentAnimatorStateInfo hands back hashes with no names. States
/// can only be guessed and then confirmed: AnimatorStateInfo.IsName("Layer.Name") answers yes or
/// no, and Animator.Play takes a state name we can try and then verify by reading back which
/// clip actually started.
///
/// So "catch the howl and trigger just that stretch" is possible, in this order: list the clips
/// here, find the one that looks like a howl, look at its events to see whether the sound is
/// wired into the animation, then Play the state and CrossFade back to idle at the point wanted.
/// Worth knowing before starting: if the sound is an animation event, playing the clip alone will
/// not make it, because events are dispatched to a component on the animated object and Valheim's
/// dispatcher is CharacterAnimEvent. The animation is the prize; the audio we already play
/// ourselves.
/// </summary>
public class DumpAnimCommand : ConsoleCommand
{
public override string Name => "dumpanim";
public override string Help =>
"[DEBUG] dumpanim <prefab> - lists a creature's animator parameters, layers, clips and " +
"every animation event on them. dumpanim live - logs which clip each animator under you " +
"starts playing, as it happens; run it again to stop.";
public override void Run(string[] args)
{
if (args.Length == 0)
{
Console.instance.Print("dumpanim <prefab> | dumpanim live");
return;
}
if (args[0].ToLower() == "live")
{
ToggleWatcher();
return;
}
DumpPrefab(args[0]);
}
/// <summary>
/// Everything the controller of <paramref name="prefabName"/> can play. Reads a prefab in
/// memory, so it needs no transformation and cannot disturb a live one.
/// </summary>
private static void DumpPrefab(string prefabName)
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
if (prefab == null)
{
Report($"[Anim] '{prefabName}' is not in the prefab cache.");
return;
}
Animator[] animators = prefab.GetComponentsInChildren<Animator>(true);
if (animators.Length == 0)
{
// Not a creature. Say what it is anyway: this is also how a sound prefab gets looked
// at without being spawned, which matters for the ones that cannot safely be spawned.
Report($"[Anim] '{prefabName}' has no Animator. Contents:");
foreach (Transform t in prefab.GetComponentsInChildren<Transform>(true))
{
Jotunn.Logger.LogInfo($"[Anim] '{PathOf(t)}' [{ComponentsOf(t.gameObject)}]");
DescribeAudio(t.gameObject);
}
return;
}
Report($"[Anim] '{prefabName}': {animators.Length} animator(s).");
foreach (Animator animator in animators)
{
RuntimeAnimatorController controller = animator.runtimeAnimatorController;
Report($"[Anim] on '{PathOf(animator.transform)}' controller " +
$"'{(controller != null ? controller.name : "none")}'");
// What else lives on that object, because an animation event is delivered to THESE
// components and nowhere else. CharacterAnimEvent showing up here is the game's own
// receiver; a form that carries it is a form where vanilla is already handling - or
// already failing to handle - every event the clips fire.
Jotunn.Logger.LogInfo($"[Anim] receivers: [{ComponentsOf(animator.gameObject)}]");
if (controller == null) continue;
foreach (AnimatorControllerParameter p in animator.parameters)
{
Jotunn.Logger.LogInfo($"[Anim] param {p.name} ({p.type})");
}
for (int i = 0; i < animator.layerCount; i++)
{
Jotunn.Logger.LogInfo($"[Anim] layer {i} '{animator.GetLayerName(i)}'");
}
AnimationClip[] clips = controller.animationClips;
Report($"[Anim] {clips.Length} clip(s):");
foreach (AnimationClip clip in clips)
{
if (clip == null) continue;
AnimationEvent[] events = clip.events;
Jotunn.Logger.LogInfo(
$"[Anim] '{clip.name}' {clip.length:F2}s loop={clip.isLooping} " +
$"events={events.Length}");
foreach (AnimationEvent e in events)
{
// The object reference is the interesting one: a sound wired into an
// animation arrives here as the asset itself, name included.
string reference = e.objectReferenceParameter != null
? $" ref='{e.objectReferenceParameter.name}' ({e.objectReferenceParameter.GetType().Name})"
: "";
Jotunn.Logger.LogInfo(
$"[Anim] @{e.time:F2}s {e.functionName}(" +
$"string='{e.stringParameter}' float={e.floatParameter:F2} " +
$"int={e.intParameter}){reference}");
}
}
}
}
private static void ToggleWatcher()
{
if (Player.m_localPlayer == null)
{
Console.instance.Print("dumpanim live needs you to be in the world.");
return;
}
AnimatorWatcher existing = Player.m_localPlayer.GetComponent<AnimatorWatcher>();
if (existing != null)
{
Object.Destroy(existing);
Report("[Anim] live watch off.");
return;
}
Player.m_localPlayer.gameObject.AddComponent<AnimatorWatcher>();
Report("[Anim] live watch on: every clip change under you, as it happens.");
}
/// <summary>
/// Why a sound prefab is or is not audible when it is simply instantiated.
///
/// The AudioSource settings say whether anything starts by itself, and ZSFX's own fields say
/// what it would play if asked - it keeps a LIST of clips and chooses at play time, so a
/// prefab whose AudioSource has no clip is normal rather than broken. Read through reflection
/// because these are the game's private serialized fields.
/// </summary>
private static void DescribeAudio(GameObject go)
{
AudioSource audio = go.GetComponent<AudioSource>();
if (audio != null)
{
Jotunn.Logger.LogInfo(
$"[Anim] AudioSource playOnAwake={audio.playOnAwake} " +
$"clip='{(audio.clip != null ? audio.clip.name : "none")}' " +
$"volume={audio.volume:F2} spatialBlend={audio.spatialBlend:F2} " +
$"range={audio.minDistance:F1}-{audio.maxDistance:F1} loop={audio.loop} " +
$"mixer='{(audio.outputAudioMixerGroup != null ? audio.outputAudioMixerGroup.name : "none")}'");
}
foreach (Component comp in go.GetComponents<Component>())
{
if (comp == null || comp.GetType().Name != "ZSFX") continue;
List<string> fields = new List<string>();
foreach (System.Reflection.FieldInfo f in comp.GetType().GetFields(
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.NonPublic))
{
object value = f.GetValue(comp);
System.Array array = value as System.Array;
if (array == null)
{
fields.Add($"{f.Name}={value}");
continue;
}
// The elements, not just the count. m_audioClips is where a sound's actual clips
// live, and whether they are AudioClips or unloaded soft references is the whole
// question when a sound spawns and stays silent.
List<string> elements = new List<string>();
for (int e = 0; e < array.Length && e < 4; e++)
{
object item = array.GetValue(e);
Object asObject = item as Object;
elements.Add(item == null
? "null"
: $"{item.GetType().Name}:'{(asObject != null ? asObject.name : item.ToString())}'");
}
fields.Add($"{f.Name}[{array.Length}]={{{string.Join(", ", elements.ToArray())}}}");
}
Jotunn.Logger.LogInfo($"[Anim] ZSFX {string.Join(" ", fields.ToArray())}");
Jotunn.Logger.LogInfo(
$"[Anim] ZSFX methods: {string.Join(", ", MethodNamesOf(comp))}");
}
}
private static string[] MethodNamesOf(Component comp)
{
List<string> names = new List<string>();
foreach (System.Reflection.MethodInfo m in comp.GetType().GetMethods(
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.DeclaredOnly))
{
names.Add(m.Name + "(" + m.GetParameters().Length + ")");
}
return names.ToArray();
}
/// <summary>The component type names on one object, Transform left out as noise.</summary>
private static string ComponentsOf(GameObject go)
{
List<string> names = new List<string>();
foreach (Component comp in go.GetComponents<Component>())
{
if (comp != null && !(comp is Transform)) names.Add(comp.GetType().Name);
}
return string.Join(", ", names.ToArray());
}
private static string PathOf(Transform t)
{
string path = t.name;
for (Transform p = t.parent; p != null; p = p.parent) path = p.name + "/" + path;
return path;
}
/// <summary>To the log and to the console both, since one of the two is always the wrong one.</summary>
private static void Report(string line)
{
Jotunn.Logger.LogInfo(line);
if (Console.instance != null) Console.instance.Print(line);
}
/// <summary>
/// Watches every animator under the player and says when one starts a different clip.
///
/// Only the change is logged, not the state: an animator asked every frame would fill the log
/// with the idle it is already playing. The heaviest clip is the one reported, because during
/// a transition two are live at once and the heavier one is the one being watched on screen.
/// </summary>
private class AnimatorWatcher : MonoBehaviour
{
private readonly Dictionary<Animator, string> last = new Dictionary<Animator, string>();
private void Update()
{
foreach (Animator animator in GetComponentsInChildren<Animator>(true))
{
if (animator == null || animator.runtimeAnimatorController == null) continue;
AnimatorClipInfo[] playing = animator.GetCurrentAnimatorClipInfo(0);
if (playing.Length == 0) continue;
AnimationClip heaviest = null;
float weight = -1f;
foreach (AnimatorClipInfo info in playing)
{
if (info.clip != null && info.weight > weight)
{
heaviest = info.clip;
weight = info.weight;
}
}
if (heaviest == null) continue;
string previous;
if (last.TryGetValue(animator, out previous) && previous == heaviest.name) continue;
last[animator] = heaviest.name;
Jotunn.Logger.LogInfo(
$"[Anim] live: '{PathOf(animator.transform)}' -> '{heaviest.name}' " +
$"{heaviest.length:F2}s weight={weight:F2} events={heaviest.events.Length}");
}
}
}
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 259 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 340 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 441 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 339 KiB

View file

@ -1,170 +0,0 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Whether a player is a bat, on any client.
///
/// Stamina Flight flies on m_flying (DirectedFlight.cs), which vanilla's AI and damage never
/// look at, so monsters notice and hurt that bat with no help.
///
/// Free Flight flies on vanilla's debug-fly flag, and vanilla reads that flag as "this player
/// is not really here". Six places, read out of assembly_valheim:
///
/// BaseAI.CanHearTarget, BaseAI.CanSeeTarget and BaseAI's HuntPlayer fallback ask
/// Player.InDebugFlyMode() and drop the player.
/// MonsterAI.UpdateSleep asks IsDebugFlying() and will not wake, twice over.
/// Character.ApplyDamage and Character.RPC_Damage ask IsDebugFlying() and drop the hit.
///
/// The patches below keep the flag (it IS the flight) and lie about it in exactly those
/// places, for bats only. InDebugFlyMode() is forced false flat: those three AI paths are its
/// only callers. IsDebugFlying() cannot be: Character.UpdateMotion reads it to hold the bat in
/// the air, so it reads false only while the call stack is inside one of the methods that push
/// the counter. The patches were removed with the old flight in v1.6.1 and came back with it.
/// </summary>
public static class AswidBatForm
{
/// <summary>
/// The ZDO flag AswidRace writes when the form goes up. Replicated, so it answers for
/// remote players too.
/// </summary>
public const string BatZdoKey = "Aswid_IsBatForm";
private static readonly int BatFormHash = "SE_BatForm".GetStableHashCode();
// How deep we are inside vanilla calls that must not see the debug-fly flag. A counter,
// not a bool: ApplyDamage runs inside RPC_Damage, so the frames nest.
private static int unmaskDepth;
public static bool Unmasked => unmaskDepth > 0;
public static void PushUnmask() { unmaskDepth++; }
public static void PopUnmask() { if (unmaskDepth > 0) unmaskDepth--; }
/// <summary>
/// The ZDO first and the status effect only as a fallback: the ZDO is the one that is true
/// on every client, and the status effect covers the local player during the frames of the
/// transform where the ZDO write has not landed yet.
/// </summary>
public static bool IsBat(Player player)
{
if (player == null) return false;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetBool(BatZdoKey, false)) return true;
return player == Player.m_localPlayer &&
player.GetSEMan() != null &&
player.GetSEMan().HaveStatusEffect(BatFormHash);
}
}
/// <summary>Free Flight: monsters see and hear a bat. See AswidBatForm for why this one is safe flat.</summary>
[HarmonyPatch(typeof(Player), "InDebugFlyMode")]
public static class Aswid_BatIsVisibleToAI_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
if (__result && AswidBatForm.IsBat(__instance)) __result = false;
}
}
/// <summary>
/// The scoped half: false only inside the methods that push the counter, so flight, motion,
/// the camera and UpdateStats still read the flag as true.
/// </summary>
[HarmonyPatch(typeof(Player), "IsDebugFlying")]
public static class Aswid_BatIsDebugFlying_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
if (!__result || !AswidBatForm.Unmasked) return;
if (AswidBatForm.IsBat(__instance)) __result = false;
}
}
/// <summary>
/// A hit landing on a free-flying bat. Finalizer rather than Postfix: the counter has to come
/// down even when the method throws, and a void Finalizer leaves the exception alone.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage")]
public static class Aswid_BatTakesDamage_Patch
{
public static void Prefix(Character __instance, ref bool __state)
{
__state = __instance is Player player && AswidBatForm.IsBat(player);
if (__state) AswidBatForm.PushUnmask();
}
public static void Finalizer(bool __state)
{
if (__state) AswidBatForm.PopUnmask();
}
}
/// <summary>The networked half of the same thing: a hit sent by another machine.</summary>
[HarmonyPatch(typeof(Character), "RPC_Damage")]
public static class Aswid_BatTakesRemoteDamage_Patch
{
public static void Prefix(Character __instance, ref bool __state)
{
__state = __instance is Player player && AswidBatForm.IsBat(player);
if (__state) AswidBatForm.PushUnmask();
}
public static void Finalizer(bool __state)
{
if (__state) AswidBatForm.PopUnmask();
}
}
/// <summary>
/// Notes when the local player last lost health, for the bat's combat lock. ApplyDamage is the
/// one final stage for direct hits, burning, poison and bleeding, so comparing health around it
/// catches them all, and a hit fully blocked or absorbed (Alfar shield, Heimkall) is no hurt.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Aswid_BatCombatLock_Patch
{
public static void Prefix(Character __instance, ref float __state)
{
__state = __instance == Player.m_localPlayer ? __instance.GetHealth() : -1f;
}
public static void Postfix(Character __instance, float __state)
{
if (__state < 0f) return;
if (__instance.GetHealth() < __state) AswidRace.LastHurtTime = Time.time;
}
}
/// <summary>
/// Sleepers. UpdateSleep picks the closest player itself, possibly a remote bat, so the counter
/// goes up for the whole call and the bat test happens in the IsDebugFlying postfix, which only
/// runs its test for a player already debug flying.
/// </summary>
[HarmonyPatch(typeof(MonsterAI), "UpdateSleep")]
public static class Aswid_BatWakesSleepers_Patch
{
public static void Prefix() { AswidBatForm.PushUnmask(); }
public static void Finalizer() { AswidBatForm.PopUnmask(); }
}
/// <summary>
/// The revert path cannot handle a bat that dies: AswidRace.Update() returns early on IsDead(),
/// so the coroutine that takes the form down never starts. The flight flag would stay on and
/// the ZDO would stay true, which is a respawned player floating over the ground with a bat
/// drawn on them.
/// </summary>
[HarmonyPatch(typeof(Player), "OnDeath")]
public static class Aswid_BatDiesAsBat_Patch
{
public static void Prefix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
if (AswidRace.Instance == null) return;
AswidRace.Instance.HardResetBatForm();
}
}
}

View file

@ -27,8 +27,8 @@ namespace RacesOfValheim
public const string SuperiorBaseName = "MeadBaseSuperiorBloodPotion";
public const string SuperiorPotionName = "MeadSuperiorBloodPotion";
private const string PotionDisplayName = "$rov_item_aswid_bloodpotion_name";
private const string SuperiorPotionDisplayName = "$rov_item_aswid_superiorbloodpotion_name";
private const string PotionDisplayName = "Blood Potion";
private const string SuperiorPotionDisplayName = "Superior Blood Potion";
private const float HealDuration = 8f;
private const float HealFraction = 0.05f;
@ -54,14 +54,15 @@ namespace RacesOfValheim
SE_BloodPotion superiorDrink = CreateEffect("SE_SuperiorBloodPotion", SuperiorPotionDisplayName,
SuperiorHealFraction, AswidBloodRefinery.SuperiorEssenceName, "MoltenCore");
GameObject meadBase = CloneItem(BaseName, "MeadBaseHealthMinor", "$rov_item_aswid_bloodpotionbase_name",
"$rov_item_aswid_bloodpotionbase_desc");
GameObject meadBase = CloneItem(BaseName, "MeadBaseHealthMinor", "Blood Potion Mead Base",
"Blood, berries and crypt light, waiting on a barrel.");
GameObject potion = CloneItem(PotionName, "MeadHealthMinor", PotionDisplayName,
"$rov_item_aswid_bloodpotion_desc");
GameObject superiorBase = CloneItem(SuperiorBaseName, "MeadBaseHealthMedium", "$rov_item_aswid_superiorbloodpotionbase_name",
"$rov_item_aswid_superiorbloodpotionbase_desc");
"Drink and the hunger stops mattering for a while. Fills every stomach with blood essence, " +
"full or not, and knits the flesh back together.");
GameObject superiorBase = CloneItem(SuperiorBaseName, "MeadBaseHealthMedium", "Superior Blood Potion Mead Base",
"The twice-rendered draught, still raw.");
GameObject superiorPotion = CloneItem(SuperiorPotionName, "MeadHealthMedium", SuperiorPotionDisplayName,
"$rov_item_aswid_superiorbloodpotion_desc");
"The same mercy, twice as deep.");
AttachEffect(potion, drink);
AttachEffect(superiorPotion, superiorDrink);
@ -175,7 +176,7 @@ namespace RacesOfValheim
SE_BloodPotion effect = ScriptableObject.CreateInstance<SE_BloodPotion>();
effect.name = name;
effect.m_name = displayName;
effect.m_tooltip = "$rov_se_aswid_bloodpotion_tooltip"; // numbers go in at display, see GetTooltipString
effect.m_tooltip = $"Stomachs filled with blood. Healing {Mathf.RoundToInt(fraction * 100f)}% over {HealDuration:0} seconds.";
effect.m_ttl = HealDuration;
effect.m_healFraction = fraction;
effect.m_essencePrefab = essencePrefab;
@ -233,11 +234,8 @@ namespace RacesOfValheim
{
if (fermenter == null || GetContentMethod == null) return false;
// Valheim 1.0: GetContent returns the stable hash of the prefab name, not the name. The old
// "as string" read null for every barrel and the speed-up silently stopped.
int content = System.Convert.ToInt32(GetContentMethod.Invoke(fermenter, null));
return content != 0
&& (content == BaseName.GetStableHashCode() || content == SuperiorBaseName.GetStableHashCode());
string content = GetContentMethod.Invoke(fermenter, null) as string;
return content == BaseName || content == SuperiorBaseName;
}
private static Player.Food MakeFood(ItemDrop drop, GameObject prefab, string prefabName)
@ -286,19 +284,6 @@ namespace RacesOfValheim
public float m_healFraction = 0.05f;
public string m_essencePrefab = "";
/// <summary>
/// The tooltip's $1 and $2 are the heal share and the duration. Filled in here, at display
/// time, because a translation can only be looked up once the language is loaded, and the
/// game localizes this string after us in a single pass that would leave $1 as it is.
/// </summary>
public override string GetTooltipString()
{
string text = base.GetTooltipString();
if (Localization.instance == null) return text;
return Localization.instance.Localize(text,
Mathf.RoundToInt(m_healFraction * 100f).ToString(), m_ttl.ToString("0"));
}
public override void Setup(Character character)
{
// SEMan clones the effect before setting it up, so writing the resolved amount here

View file

@ -30,10 +30,10 @@ namespace RacesOfValheim
// The Aswid food patches recognise a meal by its display name, so these strings are part
// of the contract with AswidPatches - see IsAswidMeal.
public const string EssenceDisplayName = "$rov_item_aswid_bloodessence_name";
public const string SuperiorEssenceDisplayName = "$rov_item_aswid_superiorbloodessence_name";
public const string CoreDisplayName = "$rov_item_aswid_bloodcore_name";
public const string PieceDisplayName = "$rov_piece_aswid_bloodrefinery_name";
public const string EssenceDisplayName = "Blood Essence";
public const string SuperiorEssenceDisplayName = "Superior Blood Essence";
public const string CoreDisplayName = "Blood Core";
public const string PieceDisplayName = "Blood Refinery";
// Regeneration is tied to the health value rather than set per tier, so 60 hp gives 5 and
// 80 hp gives 6.67 without a second number to keep in sync.
@ -68,7 +68,6 @@ namespace RacesOfValheim
{ "AsksvinCarrionRibcage", 3 },
{ "AsksvinCarrionSkull", 3 },
{ "UndeadBjornRibcage", 3 }, // Deep North
{ "ElakingHairBundle", 20 }, // Deep North, dropped by the Elaking
};
// Vanilla grills. Anything they cook counts as raw flesh, which keeps modded meat working.
@ -95,7 +94,7 @@ namespace RacesOfValheim
public static bool IsAswidMeal(ItemDrop.ItemData item)
{
if (item == null || item.m_shared == null || item.m_shared.m_name == null) return false;
return item.m_shared.m_name.StartsWith(AswidRace.AswidFoodNamePrefix)
return item.m_shared.m_name.StartsWith("Aswid Food:")
|| item.m_shared.m_name == EssenceDisplayName
|| IsEssence(item);
}
@ -123,7 +122,8 @@ namespace RacesOfValheim
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = CoreDisplayName;
shared.m_description = "$rov_item_aswid_bloodcore_desc";
shared.m_description = "A knot of clotted blood kept beating by something that is not a heart. " +
"The dead trade them; only the dead know how they are made.";
shared.m_itemType = ItemDrop.ItemData.ItemType.Material;
shared.m_food = 0f;
shared.m_foodStamina = 0f;
@ -142,7 +142,8 @@ namespace RacesOfValheim
EssencePrefab = BuildEssence(
EssenceName,
EssenceDisplayName,
"$rov_item_aswid_bloodessence_desc",
"Blood rendered down to what it actually is. The only real food an Aswid can " +
"still chew, and the base of every draught worth brewing.",
food: 60f,
tint: EssenceTint,
iconSource: "GemstoneRed");
@ -150,7 +151,7 @@ namespace RacesOfValheim
SuperiorEssencePrefab = BuildEssence(
SuperiorEssenceName,
SuperiorEssenceDisplayName,
"$rov_item_aswid_superiorbloodessence_desc",
"The same blood, rendered twice. Darker, thicker, and worth five of the first pass.",
food: 80f,
tint: SuperiorEssenceTint,
iconSource: "MoltenCore");
@ -233,11 +234,8 @@ namespace RacesOfValheim
refinery.m_haveMeatObject = smelter.m_haveOreObject;
refinery.m_noMeatObject = smelter.m_noOreObject;
refinery.m_animators = smelter.m_animators;
// Crossed on purpose: the sounds sit the other way round from the slots. The ore
// effect is the dry clatter and the fuel effect the wet slap, so flesh takes the
// fuel one and bone the ore one.
refinery.m_meatAddedEffects = smelter.m_fuelAddedEffects;
refinery.m_boneAddedEffects = smelter.m_oreAddedEffects;
refinery.m_meatAddedEffects = smelter.m_oreAddedEffects;
refinery.m_boneAddedEffects = smelter.m_fuelAddedEffects;
refinery.m_produceEffects = smelter.m_produceEffects;
refinery.m_smokeSpawner = smelter.m_smokeSpawner;
@ -245,8 +243,8 @@ namespace RacesOfValheim
// Two Radiators under _enabled are what shot the tester: see IsOffensive.
StripOffensive(prefab, PieceName);
SanitiseEffects(refinery.m_meatAddedEffects, PieceName + ".fuelAdded");
SanitiseEffects(refinery.m_boneAddedEffects, PieceName + ".oreAdded");
SanitiseEffects(refinery.m_meatAddedEffects, PieceName + ".oreAdded");
SanitiseEffects(refinery.m_boneAddedEffects, PieceName + ".fuelAdded");
SanitiseEffects(refinery.m_produceEffects, PieceName + ".produce");
prefab.transform.localScale = Vector3.one * ModelScale;
@ -266,7 +264,7 @@ namespace RacesOfValheim
PieceConfig config = new PieceConfig
{
Name = PieceDisplayName,
Description = "$rov_piece_aswid_bloodrefinery_desc",
Description = "Flesh goes in, bone goes in, and what is left of both comes out red.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Requirements = new[]
@ -338,6 +336,8 @@ namespace RacesOfValheim
// The raw -> cooked table the Draugh already maintains is the source of truth.
meatToCooked = new Dictionary<string, string>(DraughFoodPatches.rawToCookedMapping);
meatToCooked.Remove("GreydwarfEye"); // stew ingredient, not flesh
meatToCooked["AsksvinMeat"] = "CookedAsksvinMeat";
meatToCooked["BoneMawSerpentMeat"] = "CookedBoneMawSerpentMeat";
foreach (string stationName in CookingStationPrefabs)
{
@ -566,7 +566,7 @@ namespace RacesOfValheim
if (!AswidBloodRefinery.IsEssence(item)) return true;
if (AswidRace.IsAswid()) return true;
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_living_blood_curdles_living_throat"));
player.Message(MessageHud.MessageType.Center, "Living blood curdles in a living throat.");
return false;
}
}

View file

@ -1,70 +0,0 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Claws of the Beast: the Bjorn claw, burned down to almost black.
///
/// Everything about how they behave - a timed skill (RaceClawsConfig.ActivateKey), issued and
/// retracted on its own, back in hand the moment the hands are free while it runs, tier damage
/// as slash - lives in RaceClawSet. This file is only the Aswid's half of the answer: which
/// model, what colour, and when the race is wearing another body.
///
/// The tint is config rather than a constant because "almost black" is a look, not a number,
/// and it needs one pass in front of a mirror. It is applied to the item's own copies of the
/// model's materials, so the vanilla weapon is untouched for everyone else.
/// </summary>
public class AswidClaws : RaceClawSet
{
public static readonly AswidClaws Instance = new AswidClaws();
public override string RaceId => "Aswid";
public override string ItemName => "AswidBeastClaws";
public override string DisplayName => "$rov_item_aswid_claws_name";
public override string Description => "$rov_item_aswid_claws_desc";
// The Bjorn claw first, by name, because that is the one this race is meant to wear. The
// rest are the near-identical ids the manifest also carries - see SvermConfig's own
// fallback list for why a single name is not trusted here.
public override string[] ModelPrefabs => new[]
{
"FistBjornClaw",
"FistBjornUndeadClaw",
"FistBjornClawUndead",
"FistUnbjornClaw",
};
/// <summary>Published by AswidRace.UpdateAswidState, so a remote Aswid claws at its own tier.</summary>
public override string StateZdoKey => "RacesOfValheim_AswidState";
public override Color? Tint => new Color(
AswidConfig.ClawTintRed.Value,
AswidConfig.ClawTintGreen.Value,
AswidConfig.ClawTintBlue.Value,
1f);
/// <summary>
/// A bat and a bank of mist have no hands. IsTransformed is the local player's own flag;
/// the two ZDO booleans are how AswidPatches already publishes the same thing for everyone
/// else, which is what makes this answer correctly for a remote attacker.
/// </summary>
public override bool IsTransformed(Player player)
{
if (player == null) return false;
if (player == Player.m_localPlayer && AswidRace.Instance != null && AswidRace.Instance.IsTransformed)
{
return true;
}
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
return nview.GetZDO().GetBool("Aswid_IsBatForm", false) ||
nview.GetZDO().GetBool("Aswid_IsMistForm", false);
}
return false;
}
}
}

View file

@ -33,82 +33,6 @@ namespace RacesOfValheim
public static ConfigEntry<float> BloodMagicSkillGainMultiplier;
public static ConfigEntry<float> SurtlingFormDamageBonus;
// ─── Stamina ─────────────────────────────────────────────────────────────
// The race used to have infinite stamina. Now it has a large pool that grows with each
// boss, on top of what its devoured food gives - added, never assigned, so stamina mods
// still stack.
public static ConfigEntry<float> BaseStaminaBonus;
public static ConfigEntry<float> StaminaBonusPerState;
public static ConfigEntry<float> StaminaCostMultiplier;
// ─── Weaknesses ──────────────────────────────────────────────────────────
// The Discord reports said the race had no real downsides. Each weakness has its own
// switch, so a single player can drop one; on a server the host's values win.
public static ConfigEntry<bool> SunlightEnabled;
public static ConfigEntry<float> SunHealthRegenPenalty;
public static ConfigEntry<float> SunStaminaRegenPenalty;
public static ConfigEntry<float> SunSpeedPenalty;
public static ConfigEntry<float> SunHealthLossPerSecond;
public static ConfigEntry<float> SunHealthFloor;
public static ConfigEntry<bool> FireWeaknessEnabled;
public static ConfigEntry<float> FireWeakness;
public static ConfigEntry<bool> FaderRemovesFireWeakness;
public static ConfigEntry<bool> PierceWeaknessEnabled;
public static ConfigEntry<float> PierceWeakness;
// ─── Running Water ─────────────────────────────────────────────────────
// Lore says a vampire cannot cross running water unaided (Dagaz's report). Swimming costs
// more, and open water - sea, river or lake - burns, swimming or flying over it; a boat
// carries you, which the lore allows, though the camera still sways on board. The camera sway is a per-player comfort choice and stays local
// (ConfigSync's "camera sway" key part).
public static ConfigEntry<bool> RunningWaterEnabled;
public static ConfigEntry<bool> WaterOceanOnly;
public static ConfigEntry<float> SwimStaminaMultiplier;
public static ConfigEntry<float> SeaHealthLossPerSecond;
public static ConfigEntry<float> SeaStaminaDrainPerSecond;
public static ConfigEntry<float> SeaHealthFloor;
public static ConfigEntry<bool> SeaCameraSway;
public static ConfigEntry<float> SeaCameraSwayStrength;
// ─── Bat Form ────────────────────────────────────────────────────────────
// The bat flies on the same directed flight as the Skadi's drakes (DirectedFlight.cs),
// with its own numbers. It used to fly on vanilla's debug-fly flag: 50 m/s, free, blind
// to carry weight, and ignored by every monster until AswidBatAggro lied to six vanilla
// methods about it. The old flight came back as Free Flight, for players who want it
// (building tall); AswidBatForm holds the aggro patches it needs.
public enum EncumberedMode { Allowed, Blocked }
public enum BatFlightRuleMode { PlayerChoice, AlwaysStaminaFlight, AlwaysFreeFlight }
public static ConfigEntry<bool> FreeBatFlight;
public static ConfigEntry<BatFlightRuleMode> BatFlightRule;
/// <summary>Which flight a bat taken now gets: the server's rule first, then the player's own pick.</summary>
public static bool UsesFreeBatFlight()
{
switch (BatFlightRule.Value)
{
case BatFlightRuleMode.AlwaysStaminaFlight: return false;
case BatFlightRuleMode.AlwaysFreeFlight: return true;
default: return FreeBatFlight.Value;
}
}
public static ConfigEntry<float> BatTurnSpeed;
public static ConfigEntry<float> BatGlideSpeed;
public static ConfigEntry<float> BatBoostSpeed;
public static ConfigEntry<float> BatSprintSpeed;
public static ConfigEntry<float> BatReverseSpeed;
public static ConfigEntry<float> BatLiftoffSpeed;
public static ConfigEntry<float> BatHoverSeconds;
public static ConfigEntry<float> BatPoweredStaminaPerSecond;
public static ConfigEntry<float> BatSprintStaminaPerSecond;
public static ConfigEntry<EncumberedMode> BatEncumbered;
public static ConfigEntry<float> BatEncumberedExtraCost;
public static ConfigEntry<float> BatMaxDuration;
public static ConfigEntry<float> BatDurationPerState;
public static ConfigEntry<float> BatCooldown;
public static ConfigEntry<float> BatCombatLock;
// ─── Vampiric Aura (passive, always active) ──────────────────────────────
public static ConfigEntry<float> AuraTickInterval;
public static ConfigEntry<float> AuraRadiusDay;
@ -116,8 +40,6 @@ namespace RacesOfValheim
public static ConfigEntry<float> AuraBaseDamage;
public static ConfigEntry<float> AuraBloodMagicScaling;
public static ConfigEntry<float> AuraExecuteThreshold;
public static ConfigEntry<bool> AuraInBatForm;
public static ConfigEntry<int> BatAuraUnlockState;
// ─── Superhuman Senses (tier 5+ passive) ─────────────────────────────────
public static ConfigEntry<float> SensesRadius;
@ -132,52 +54,11 @@ namespace RacesOfValheim
// ─── Devour ────────────────────────────────────────────────────────────
public static ConfigEntry<float> DevourCooldown;
// What a devoured creature feeds - see AswidRace.ApplyFoodBalance.
public static ConfigEntry<float> DevourHealthMultiplier;
public static ConfigEntry<float> DevourStaminaShare;
public static ConfigEntry<float> EarlyStaminaShare;
public static ConfigEntry<float> FoodCapBase;
public static ConfigEntry<float> FoodCapPerBiome;
// ─── Domination (tier 6+ ability, native Interact key) ───────────────────
public static ConfigEntry<float> EnslaveCooldown;
public static ConfigEntry<float> ThrallLifetime;
// ─── Eyes ──────────────────────────────────────────────────────────────
// The Aswid wears the vanilla skeleton's eye lights (AswidVisuals), and where a borrowed
// object sits on a borrowed rig is not something to get right by reasoning about it. All
// of these read live, so they can be dragged in Configuration Manager while looking at the
// face. Once the pose settles they could collapse back into constants, the same way the
// mandible's did - but unlike the mandible these are worth keeping, because the source
// creature and the colour are genuine preferences.
public static ConfigEntry<string> EyeSourceModel;
public static ConfigEntry<int> EyeFinalStage;
public static ConfigEntry<float> EarlyEyeColorRed;
public static ConfigEntry<float> EarlyEyeColorGreen;
public static ConfigEntry<float> EarlyEyeColorBlue;
public static ConfigEntry<float> EarlyEyeGlowStrength;
public static ConfigEntry<float> EyeColorRed;
public static ConfigEntry<float> EyeColorGreen;
public static ConfigEntry<float> EyeColorBlue;
public static ConfigEntry<float> EyeGlowStrength;
public static ConfigEntry<float> EyeSizeMultiplier;
public static ConfigEntry<float> EyeForwardOffset;
public static ConfigEntry<float> EyeHeightOffset;
public static ConfigEntry<float> EyeSeparationOffset;
public static ConfigEntry<float> EyeRotationX;
public static ConfigEntry<float> EyeRotationY;
public static ConfigEntry<float> EyeRotationZ;
public static ConfigEntry<bool> EyeSmoke;
public static ConfigEntry<bool> EyeFlatColorShader;
// ─── Claws of the Beast ────────────────────────────────────────────────
// The tint the Bjorn claw is worn at (AswidClaws). Config rather than a constant because
// "almost black" is a look and not a number, and it multiplies the model's own texture, so
// what a given value looks like depends on the model. Reads live.
public static ConfigEntry<float> ClawTintRed;
public static ConfigEntry<float> ClawTintGreen;
public static ConfigEntry<float> ClawTintBlue;
public static void Bind(ConfigFile config)
{
const string keybinds = "Aswid - Keybinds";
@ -190,7 +71,7 @@ namespace RacesOfValheim
TameKey = config.Bind(keybinds, "Tame", new KeyboardShortcut(KeyCode.U),
new ConfigDescription("Tames the creature under your cursor, if your tier allows it."));
ToggleDevourKey = config.Bind(keybinds, "Toggle Devour Ability", new KeyboardShortcut(KeyCode.I),
new ConfigDescription("Turns the Vampiric Aura and the automatic Devour-on-kill behavior on or off together. Turn this off before talking to Haldor/Hildir - the aura does not recognize traders and will attack them."));
new ConfigDescription("Turns the automatic Devour-on-kill behavior on or off."));
const string combat = "Aswid - Passive Combat";
DamageBonusPerState = config.Bind(combat, "Damage Bonus Per State", 2f,
@ -206,96 +87,6 @@ namespace RacesOfValheim
SurtlingFormDamageBonus = config.Bind(combat, "Surtling Form Damage Bonus", 30f,
new ConfigDescription("Flat damage added to every attack once the tier 8 Surtling form is unlocked.", new AcceptableValueRange<float>(0f, 100f)));
const string stamina = "Aswid - Stamina";
BaseStaminaBonus = config.Bind(stamina, "Base Stamina Bonus", 25f,
new ConfigDescription("Max stamina added on top of the game's base 75 and your food, before any boss.", new AcceptableValueRange<float>(0f, 300f)));
StaminaBonusPerState = config.Bind(stamina, "Stamina Bonus Per State", 10f,
new ConfigDescription("Max stamina added per progression state (8 at Fader).", new AcceptableValueRange<float>(0f, 50f)));
StaminaCostMultiplier = config.Bind(stamina, "Stamina Cost Multiplier", 1f,
new ConfigDescription("Multiplies every stamina cost: sprinting, swimming, attacks, blocking. 1 is the normal cost, 0.5 half. There is no infinite setting on purpose; set the bonuses above high instead.", new AcceptableValueRange<float>(0.1f, 2f)));
const string weak = "Aswid - Weaknesses";
SunlightEnabled = config.Bind(weak, "Sunlight", true,
new ConfigDescription("Weakens you by day while you stand under open sky. A roof (the same test as the game's Sheltered status), a dungeon, the Swamp, the Mistlands, the night and your own Eclipse all shield you.", null));
SunHealthRegenPenalty = config.Bind(weak, "Sunlight Health Regen Penalty", 0.5f,
new ConfigDescription("Health regeneration lost in sunlight. 0.5 = half.", new AcceptableValueRange<float>(0f, 1f)));
SunStaminaRegenPenalty = config.Bind(weak, "Sunlight Stamina Regen Penalty", 0.25f,
new ConfigDescription("Stamina regeneration lost in sunlight. 0.25 = a quarter.", new AcceptableValueRange<float>(0f, 1f)));
SunSpeedPenalty = config.Bind(weak, "Sunlight Speed Penalty", 0.1f,
new ConfigDescription("Movement speed lost in sunlight. 0.1 = 10% slower.", new AcceptableValueRange<float>(0f, 0.9f)));
SunHealthLossPerSecond = config.Bind(weak, "Sunlight Health Loss Per Second", 0.5f,
new ConfigDescription("Health the sun burns away each second. 0 turns it off.", new AcceptableValueRange<float>(0f, 10f)));
SunHealthFloor = config.Bind(weak, "Sunlight Health Floor", 0.3f,
new ConfigDescription("The sun stops burning at this fraction of your max health, so it weakens you but never kills you. 0.3 = 30%.", new AcceptableValueRange<float>(0f, 1f)));
FireWeaknessEnabled = config.Bind(weak, "Fire Weakness", true,
new ConfigDescription("Fire, burning included, hurts more.", null));
FireWeakness = config.Bind(weak, "Fire Weakness Amount", 0.25f,
new ConfigDescription("Extra fire damage taken. 0.25 = 25% more. Resistance meads and armour still reduce it.", new AcceptableValueRange<float>(0f, 2f)));
FaderRemovesFireWeakness = config.Bind(weak, "Fader Removes Fire Weakness", true,
new ConfigDescription("Defeating Fader, the boss that grants the Surtling form, ends the fire weakness.", null));
PierceWeaknessEnabled = config.Bind(weak, "Pierce Weakness", true,
new ConfigDescription("Pierce damage (arrows, spears, stakes) hurts more. Mist Form's immunity still wins.", null));
PierceWeakness = config.Bind(weak, "Pierce Weakness Amount", 0.2f,
new ConfigDescription("Extra pierce damage taken. 0.2 = 20% more.", new AcceptableValueRange<float>(0f, 2f)));
const string water = "Aswid - Running Water";
RunningWaterEnabled = config.Bind(water, "Running Water", true,
new ConfigDescription("Swimming costs more stamina, and open water - the sea, rivers, lakes - hurts you while you swim in it or fly over it. Standing on, steering or sitting in a boat protects you. Wading, docks and bridges are safe.", null));
WaterOceanOnly = config.Bind(water, "Ocean Only", false,
new ConfigDescription("Limits the burn, the drain and the camera sway to the Ocean biome, leaving rivers and lakes alone. The swim stamina cost applies everywhere either way.", null));
SwimStaminaMultiplier = config.Bind(water, "Swim Stamina Multiplier", 2f,
new ConfigDescription("Multiplies the stamina swimming costs, anywhere. At 0 stamina the game's own drowning starts. Around 5 and up, swimming any distance is no longer possible.", new AcceptableValueRange<float>(1f, 10f)));
SeaHealthLossPerSecond = config.Bind(water, "Open Water Health Loss Per Second", 1f,
new ConfigDescription("Health open water burns away each second.", new AcceptableValueRange<float>(0f, 20f)));
SeaStaminaDrainPerSecond = config.Bind(water, "Open Water Stamina Drain Per Second", 2f,
new ConfigDescription("Stamina open water drains each second, on top of what swimming or flying costs.", new AcceptableValueRange<float>(0f, 30f)));
SeaHealthFloor = config.Bind(water, "Open Water Health Floor", 0.1f,
new ConfigDescription("The water's burn stops at this fraction of your max health. Drowning, once your stamina runs out, has no floor.", new AcceptableValueRange<float>(0f, 1f)));
SeaCameraSway = config.Bind(water, "Camera Sway", true,
new ConfigDescription("The camera rolls gently while you are out on the water, on a boat too, as if seasick. Local: each player chooses for themselves.", null));
SeaCameraSwayStrength = config.Bind(water, "Camera Sway Strength", 1f,
new ConfigDescription("How far the camera rolls. 1 is about 4 degrees. Local.", new AcceptableValueRange<float>(0f, 3f)));
const string batform = "Aswid - Bat Form";
FreeBatFlight = config.Bind(batform, "Free Bat Flight", false,
new ConfigDescription("Off: Stamina Flight, the settings below. On: the old Free Flight, up to 50 m/s with no stamina cost and no weight limit; Jump rises, Left Ctrl sinks. Your own choice, unless the server's Bat Flight Rule forces one. Takes effect the next time you become a bat."));
BatFlightRule = config.Bind(batform, "Bat Flight Rule", BatFlightRuleMode.PlayerChoice,
new ConfigDescription("Server rule. PlayerChoice: each player's Free Bat Flight setting decides. AlwaysStaminaFlight / AlwaysFreeFlight: every bat flies that way. On a server only the host's or the server's value counts."));
// Same controls as the Skadi's drake: aim with the camera, W beats forward, Shift
// sprints, S beats backwards, and letting go hovers briefly before gliding down.
BatTurnSpeed = config.Bind(batform, "Turn Speed", 180f,
new ConfigDescription("Degrees per second the bat turns towards where you aim.", new AcceptableValueRange<float>(30f, 720f)));
BatGlideSpeed = config.Bind(batform, "Glide Speed", 6f,
new ConfigDescription("Speed while gliding down with no key held, in m/s.", new AcceptableValueRange<float>(0f, 30f)));
// Not "Flight Speed": that key held the old debug-fly multiplier, and an existing .cfg
// would load its 1 here as one metre per second.
BatBoostSpeed = config.Bind(batform, "Boost Speed", 13f,
new ConfigDescription("Speed while holding W, in m/s. Costs the powered stamina below.", new AcceptableValueRange<float>(0f, 60f)));
BatSprintSpeed = config.Bind(batform, "Sprint Speed", 24f,
new ConfigDescription("Speed while holding W and Shift, in m/s. Costs the sprint stamina on top. The old bat flew at 50.", new AcceptableValueRange<float>(0f, 80f)));
BatReverseSpeed = config.Bind(batform, "Reverse Speed", 8f,
new ConfigDescription("Speed while holding S, in m/s. Costs the powered stamina.", new AcceptableValueRange<float>(0f, 40f)));
BatLiftoffSpeed = config.Bind(batform, "Liftoff Speed", 9f,
new ConfigDescription("Climb speed out of water, in m/s. Always free, so a bat that touches the sea can still leave it.", new AcceptableValueRange<float>(0f, 30f)));
BatHoverSeconds = config.Bind(batform, "Hover Seconds", 3f,
new ConfigDescription("How long the bat holds its height after the last powered beat before it starts to glide down.", new AcceptableValueRange<float>(0f, 30f)));
BatPoweredStaminaPerSecond = config.Bind(batform, "Flight Stamina Per Second", 3f,
new ConfigDescription("Stamina per second while holding W or S. Out of stamina, the bat can only glide. 0 makes flight free, like the drake's.", new AcceptableValueRange<float>(0f, 60f)));
BatSprintStaminaPerSecond = config.Bind(batform, "Sprint Stamina Per Second", 12f,
new ConfigDescription("Extra stamina per second while sprinting, on top of the flight cost.", new AcceptableValueRange<float>(0f, 60f)));
BatEncumbered = config.Bind(batform, "While Encumbered", EncumberedMode.Allowed,
new ConfigDescription("Allowed: the bat flies while you carry too much, at the extra stamina cost below. Blocked: you cannot take bat form while encumbered, and a bat that becomes encumbered in the air can only glide down.", null));
BatEncumberedExtraCost = config.Bind(batform, "Encumbered Extra Stamina Cost", 0.15f,
new ConfigDescription("With 'Allowed' above: how much more flight and sprint cost while encumbered. 0.15 = 15% more.", new AcceptableValueRange<float>(0f, 1f)));
BatMaxDuration = config.Bind(batform, "Max Duration", 0f,
new ConfigDescription("Seconds the bat form lasts before you turn back on your own. 0 means no limit: stamina is the limit.", new AcceptableValueRange<float>(0f, 3600f)));
BatDurationPerState = config.Bind(batform, "Duration Per State", 0f,
new ConfigDescription("Seconds added to the max duration per progression state. Does nothing while the max duration is 0.", new AcceptableValueRange<float>(0f, 600f)));
BatCooldown = config.Bind(batform, "Cooldown", 0f,
new ConfigDescription("Seconds after leaving bat form before you can take it again. 0 means none.", new AcceptableValueRange<float>(0f, 3600f)));
BatCombatLock = config.Bind(batform, "Combat Lock", 2.5f,
new ConfigDescription("Seconds after you last lost health (a hit, or a tick of fire, poison or bleeding) before you can take bat form. Turning back from bat form is never blocked. 0 means none.", new AcceptableValueRange<float>(0f, 30f)));
const string aura = "Aswid - Vampiric Aura";
AuraTickInterval = config.Bind(aura, "Tick Interval", 0.25f,
new ConfigDescription("Seconds between aura damage/lifesteal ticks.", new AcceptableValueRange<float>(0.05f, 2f)));
@ -309,10 +100,6 @@ namespace RacesOfValheim
new ConfigDescription("Extra damage per tick at 100 Blood Magic skill (scales linearly from 0).", new AcceptableValueRange<float>(0f, 20f)));
AuraExecuteThreshold = config.Bind(aura, "Execute Threshold", 0.20f,
new ConfigDescription("Non-boss enemies at or below this fraction of max health are executed by the aura instead of merely damaged.", new AcceptableValueRange<float>(0f, 1f)));
AuraInBatForm = config.Bind(aura, "Active In Bat Form", false,
new ConfigDescription("Lets the aura drain while you are a bat from the start, as it did before. Off: the bat has no aura until the unlock state below.", null));
BatAuraUnlockState = config.Bind(aura, "Bat Form Unlock State", 7,
new ConfigDescription("The progression state at which the bat gets its aura back (7 = The Queen). 0 means never, so only the setting above can turn it on.", new AcceptableValueRange<int>(0, 8)));
const string senses = "Aswid - Superhuman Senses";
SensesRadius = config.Bind(senses, "Detection Radius", 100f,
@ -334,154 +121,13 @@ namespace RacesOfValheim
const string devour = "Aswid - Devour";
DevourCooldown = config.Bind(devour, "Consume Cooldown", 5f,
new ConfigDescription("How long one body stays drunk-dry, in seconds. A single death is reported to the devour more than once - by two damage patches, by the aura's execute, by a thrall's kill - and this is the window that keeps those from feeding you twice off the same corpse. It is per body, not per player: killing a whole pack at once devours every one of them. One second is used as the floor, so no corpse feeds you twice even at 0.", new AcceptableValueRange<float>(0f, 60f)));
DevourHealthMultiplier = config.Bind(devour, "Health Multiplier", 0.9f,
new ConfigDescription("Scales the health every devoured creature feeds you. 1 is the old amount.", new AcceptableValueRange<float>(0f, 2f)));
DevourStaminaShare = config.Bind(devour, "Stamina Share", 0.10f,
new ConfigDescription("Fraction of that health turned into stamina instead, for creatures past the Black Forest. 0.1 = 10%.", new AcceptableValueRange<float>(0f, 1f)));
EarlyStaminaShare = config.Bind(devour, "Early Creature Stamina Share", 0.60f,
new ConfigDescription("The same, for Meadows and Black Forest creatures. Above 0.5 they feed more stamina than health. Set it equal to the one above to treat every creature alike.", new AcceptableValueRange<float>(0f, 1f)));
FoodCapBase = config.Bind(devour, "Food Health Cap Base", 15f,
new ConfigDescription("Creatures with no hand-set meal feed half their health. That is capped at this plus the per-biome value times the biome's number (Meadows 1 ... Deep North 8). With the defaults: Black Forest 45, Mountains 75, Plains 90.", new AcceptableValueRange<float>(0f, 150f)));
FoodCapPerBiome = config.Bind(devour, "Food Health Cap Per Biome", 15f,
new ConfigDescription("See the base cap above.", new AcceptableValueRange<float>(0f, 50f)));
// Jotunn's server sync assigns Value, which fires SettingChanged, so the server's
// numbers reach the foods the same way a local drag does.
foreach (var entry in new[] { DevourHealthMultiplier, DevourStaminaShare, EarlyStaminaShare, FoodCapBase, FoodCapPerBiome })
{
entry.SettingChanged += (_, __) => AswidRace.ApplyAllFoodBalance();
}
new ConfigDescription("Minimum seconds between devouring a corpse, outside of an execute (which bypasses this).", new AcceptableValueRange<float>(0f, 60f)));
const string domination = "Aswid - Domination";
EnslaveCooldown = config.Bind(domination, "Enslave Cooldown", 900f,
new ConfigDescription("Seconds between dominating a creature, tier 6+.", new AcceptableValueRange<float>(0f, 3600f)));
ThrallLifetime = config.Bind(domination, "Thrall Lifetime", 60f,
new ConfigDescription("Seconds a dominated thrall survives before it dies on its own.", new AcceptableValueRange<float>(10f, 600f)));
BindEyes(config);
BindClaws(config);
}
/// <summary>
/// The Claws of the Beast. Only their colour is tunable: everything about how they behave
/// is shared with the Fenrir's and the Sverm's, and a race that could quietly retune its
/// own claw damage would defeat the point of balancing the three against one yardstick.
/// </summary>
private static void BindClaws(ConfigFile config)
{
const string claws = "Aswid - Claws";
ClawTintRed = config.Bind(claws, "Claw Tint Red", 0.12f,
new ConfigDescription("Multiplied into the claw model's own colours. All three near zero is what makes them read as almost black.",
new AcceptableValueRange<float>(0f, 1f), new ConfigurationManagerAttributes { Order = 30 }));
ClawTintGreen = config.Bind(claws, "Claw Tint Green", 0.11f,
new ConfigDescription("As above, green channel.",
new AcceptableValueRange<float>(0f, 1f), new ConfigurationManagerAttributes { Order = 29 }));
ClawTintBlue = config.Bind(claws, "Claw Tint Blue", 0.13f,
new ConfigDescription("As above, blue channel. A shade above the other two keeps the black cold rather than muddy.",
new AcceptableValueRange<float>(0f, 1f), new ConfigurationManagerAttributes { Order = 28 }));
}
/// <summary>
/// The eye lights. Everything here is read every frame by AswidVisuals, so a slider moves
/// the eyes while you are looking at them - no relog, no equipment change.
///
/// The offsets are deltas on the pose the source creature authored its own eyes at, which
/// is why they all default to zero: zero means "exactly where the game's skeleton wears
/// them", and that is already the right place for a face on this rig.
/// </summary>
private static void BindEyes(ConfigFile config)
{
const string eyes = "Aswid - Eyes";
EyeSourceModel = config.Bind(eyes, "Eye Source Model", "Skeleton",
new ConfigDescription(
"Which creature's eye lights to wear. The plain skeleton's are smaller and dimmer than the poison one's; Hildir's are its own. Changing this rebuilds the pair.",
new AcceptableValueList<string>("Skeleton", "Skeleton_Poison", "Skeleton_Hildir"),
new ConfigurationManagerAttributes { Order = 100 }));
EyeFinalStage = config.Bind(eyes, "Eye Final Stage", 8,
new ConfigDescription("The progression state at which the eyes turn red. Below it they burn the spectral green set out just under here; 8 is Fader, the last one.",
new AcceptableValueRange<int>(1, 8), new ConfigurationManagerAttributes { Order = 95 }));
EarlyEyeColorRed = config.Bind(eyes, "Early Eye Colour Red", 0.08f,
new ConfigDescription("Red channel of the pre-final tint. Near zero: what little there is only keeps the green from reading as pure cyan.",
new AcceptableValueRange<float>(0f, 8f), new ConfigurationManagerAttributes { Order = 94 }));
EarlyEyeColorGreen = config.Bind(eyes, "Early Eye Colour Green", 1.4f,
new ConfigDescription("Green channel of the pre-final tint - the one doing the work.",
new AcceptableValueRange<float>(0f, 8f), new ConfigurationManagerAttributes { Order = 93 }));
EarlyEyeColorBlue = config.Bind(eyes, "Early Eye Colour Blue", 0.5f,
new ConfigDescription("Blue channel of the pre-final tint. A third of the green is what makes it read as cold and spectral rather than as a leaf.",
new AcceptableValueRange<float>(0f, 8f), new ConfigurationManagerAttributes { Order = 92 }));
EarlyEyeGlowStrength = config.Bind(eyes, "Early Eye Glow Strength", 0.8f,
new ConfigDescription("How bright the green burns. Deliberately below the red's, so arriving at the last stage is a visible change and not just a hue swap.",
new AcceptableValueRange<float>(0f, 3f), new ConfigurationManagerAttributes { Order = 91 }));
EyeColorRed = config.Bind(eyes, "Eye Colour Red", 2f,
new ConfigDescription("Red channel of the final-stage tint. Past 1 is HDR, which is what the bloom pass needs to make it glow rather than merely be red.",
new AcceptableValueRange<float>(0f, 8f), new ConfigurationManagerAttributes { Order = 90 }));
EyeColorGreen = config.Bind(eyes, "Eye Colour Green", 0.05f,
new ConfigDescription("Green channel of the final-stage tint. Near zero is what keeps a bright red from washing out to pink.",
new AcceptableValueRange<float>(0f, 8f), new ConfigurationManagerAttributes { Order = 89 }));
EyeColorBlue = config.Bind(eyes, "Eye Colour Blue", 0.02f,
new ConfigDescription("Blue channel of the final-stage tint. Near zero, same reason as green.",
new AcceptableValueRange<float>(0f, 8f), new ConfigurationManagerAttributes { Order = 88 }));
EyeGlowStrength = config.Bind(eyes, "Eye Glow Strength", 1f,
new ConfigDescription("How bright the final-stage red burns - the single knob for it, since the hue is already pure. Expect a floor: below the bloom threshold the eyes stop glowing and become flat dots.",
new AcceptableValueRange<float>(0f, 3f), new ConfigurationManagerAttributes { Order = 87 }));
// ─── Ranges are deliberately wide ────────────────────────────────
// These started at +/-0.1 m and 0.1-5x, on the assumption that the borrowed sockets
// land close to right and only need nudging. They do not, and a slider that cannot
// reach the correct value is worse than no slider - it looks like the setting does not
// work. Wide enough to dig the pair out of the skull from any starting point, and to
// find the right size by eye when the source model's own scale does not transfer.
// Every one of these is live: the eye ticker reapplies them each frame, so a drag in
// Configuration Manager moves them while you watch.
// ─── The defaults below were found in game, not derived ──────────
// The borrowed sockets do not arrive on the face by themselves: their authored pose
// and scale belong to the Skeleton's own rig and none of it transfers cleanly to a
// player armature (see AswidVisuals.BuildEyes for what does and does not carry over).
// Four attempts to compute the remainder each missed, so it was dialled in on screen
// instead and the answer written down here. That is what these seven numbers are - a
// measurement, not a taste. Treat them as the working baseline: a fresh install lands
// on a correct face, and the sliders are then free to be about taste again.
//
// The -180 on Z is the honest shape of it: the socket arrives upside down relative to
// the player's head bone, and this is the half turn that rights it.
EyeSizeMultiplier = config.Bind(eyes, "Eye Size Multiplier", 1.1f,
new ConfigDescription("Scales both sockets. 1 is the size the source creature wears them at.",
new AcceptableValueRange<float>(0.01f, 50f), new ConfigurationManagerAttributes { Order = 80 }));
EyeForwardOffset = config.Bind(eyes, "Eye Forward Offset", 0.013f,
new ConfigDescription("Moves both eyes out of (or into) the face, in metres. Positive is forward, out of the skull.",
new AcceptableValueRange<float>(-0.5f, 0.5f), new ConfigurationManagerAttributes { Order = 70 }));
EyeHeightOffset = config.Bind(eyes, "Eye Height Offset", 0.004f,
new ConfigDescription("Moves both eyes up or down the face, in metres. Positive is up.",
new AcceptableValueRange<float>(-0.5f, 0.5f), new ConfigurationManagerAttributes { Order = 69 }));
EyeSeparationOffset = config.Bind(eyes, "Eye Separation Offset", 0.007f,
new ConfigDescription("Pushes the two eyes apart (or together), in metres. Each moves away from the centre of the face, so this is half the change in the gap.",
new AcceptableValueRange<float>(-0.5f, 0.5f), new ConfigurationManagerAttributes { Order = 68 }));
EyeRotationX = config.Bind(eyes, "Eye Rotation X", 0f,
new ConfigDescription("Turns both eyes on the spot. Only matters if the borrowed socket is flat enough to be seen edge-on.",
new AcceptableValueRange<float>(-180f, 180f), new ConfigurationManagerAttributes { Order = 60 }));
EyeRotationY = config.Bind(eyes, "Eye Rotation Y", 22.068f,
new ConfigDescription("As above, around the second axis - but MIRRORED: the left eye turns the opposite way, so the pair toes in or out together instead of both pointing off the same shoulder.",
new AcceptableValueRange<float>(-180f, 180f), new ConfigurationManagerAttributes { Order = 59 }));
EyeRotationZ = config.Bind(eyes, "Eye Rotation Z", -180f,
new ConfigDescription("As above, around the third axis. The default half turn is what rights the borrowed socket, which arrives upside down on a player's head bone.",
new AcceptableValueRange<float>(-180f, 180f), new ConfigurationManagerAttributes { Order = 58 }));
EyeSmoke = config.Bind(eyes, "Eye Smoke", false,
new ConfigDescription("Lights the smoke the creature carries inside its own sockets and leaves switched off. Tinted to match the eyes, so it turns with them at the last stage.",
null, new ConfigurationManagerAttributes { Order = 50 }));
EyeFlatColorShader = config.Bind(eyes, "Eye Flat Colour Shader", false,
new ConfigDescription("Escape hatch: if the borrowed material refuses the red tint, this repaints the sockets with a plain colour shader instead - guaranteed red, but the socket loses its own texture. Changing this rebuilds the pair.",
null, new ConfigurationManagerAttributes { Order = 49 }));
}
}
}

View file

@ -53,9 +53,7 @@ namespace RacesOfValheim
// Valheim 1.0 appended a 'short variant' parameter to this overload. The type array has to
// match it exactly or the patch silently fails to bind and PatchAll throws.
[HarmonyPatch(typeof(SEMan), "AddStatusEffect", new System.Type[] { typeof(int), typeof(bool), typeof(int), typeof(float), typeof(short) })]
[HarmonyPatch(typeof(SEMan), "AddStatusEffect", new System.Type[] { typeof(int), typeof(bool), typeof(int), typeof(float) })]
public static class AswidSEManPatch
{
public static bool Prefix(SEMan __instance, ref int nameHash)
@ -219,32 +217,6 @@ namespace RacesOfValheim
}
}
/// <summary>
/// Fire and pierce hurt the Aswid more: fire for the old way vampires end, pierce for the
/// stake. A plain multiplier, like the Trol's fire weakness, rather than DamageModifier.Weak,
/// which is a fixed +50% with nothing in between. ApplyDamage runs after resistances, so a
/// fire resistance mead still helps, and Mist Form's pierce immunity has already zeroed the
/// pierce by the time this sees it.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage")]
public static class Aswid_Weakness_Patch
{
public static void Prefix(Character __instance, ref HitData hit)
{
if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return;
if (AswidRace.HasFireWeakness(BossProgressionManager.GetCurrentProgressionState()) && hit.m_damage.m_fire > 0f)
{
hit.m_damage.m_fire *= 1f + AswidConfig.FireWeakness.Value;
}
if (AswidConfig.PierceWeaknessEnabled.Value && hit.m_damage.m_pierce > 0f)
{
hit.m_damage.m_pierce *= 1f + AswidConfig.PierceWeakness.Value;
}
}
}
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Aswid_Attack_Patch
{
@ -265,33 +237,6 @@ namespace RacesOfValheim
}
}
/// <summary>
/// Bat and mist form shut the rest of the human's attack loop as well as StartAttack: crossbow
/// reload and draw live in PlayerAttackInput, and the form's Animator fires the held attack
/// through OnAttackTrigger. See Fenrir's BlockPlayerAttackInputPatch.
/// </summary>
public static class AswidFormAttackLoop
{
public static bool InForm(Humanoid player)
{
if (player != Player.m_localPlayer) return false;
return player.GetComponentInChildren<BatFormBehavior>() != null
|| player.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode());
}
}
[HarmonyPatch(typeof(Player), "PlayerAttackInput")]
public static class Aswid_BlockAttackInput_Patch
{
public static bool Prefix(Player __instance) => !AswidFormAttackLoop.InForm(__instance);
}
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))]
public static class Aswid_BlockAttackTrigger_Patch
{
public static bool Prefix(Humanoid __instance) => !AswidFormAttackLoop.InForm(__instance);
}
[HarmonyPatch(typeof(Character), "SetRun")]
public static class Aswid_Run_Patch
{
@ -367,11 +312,14 @@ namespace RacesOfValheim
}
}
// Otherwise vanilla's answer stands: it already allows replacing the
// most depleted meal past half its time, and already showed its "too
// full" message when it refused. Forcing false here used to block
// that replacement, silently.
if (canRefresh) __result = true;
if (canRefresh)
{
__result = true;
}
else
{
__result = false; // Nessuno spazio disponibile, cibo si disintegra
}
}
}
else
@ -433,11 +381,17 @@ namespace RacesOfValheim
Player.Food f = foodObj as Player.Food;
if (f != null && f.m_item.m_shared.m_name == item.m_shared.m_name && f.CanEatAgain())
{
// Was `f.m_time = 0f`, which expired the meal instead of renewing
// it - see RaceFoodRefresh for the whole story. The fourth slot
// above genuinely does count up from zero; this list does not.
RaceFoodRefresh.Refresh(__instance, f, item);
f.m_time = 0f;
f.m_item = item;
var consumeEffects = HarmonyLib.Traverse.Create(__instance).Field("m_consumeItemEffects").GetValue<EffectList>();
if (consumeEffects != null) consumeEffects.Create(__instance.transform.position, Quaternion.identity, __instance.transform, 1f, -1);
var zanim = HarmonyLib.Traverse.Create(__instance).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null) zanim.SetTrigger("eat");
if (item.m_shared.m_food > 0f) __instance.Heal(item.m_shared.m_food, true);
refreshed = true;
break;
}
@ -449,9 +403,9 @@ namespace RacesOfValheim
return false;
}
// Full, no fourth slot free, no slot holding this meal. Native EatFood
// replaces the most depleted meal past half its time, or refuses.
return true;
// Se pieno e senza 4° slot disponibile, fallisce e disintegra
__result = false;
return false;
}
else
{
@ -513,7 +467,7 @@ namespace RacesOfValheim
// AswidConfig.TameKey) - the hint never matched the working key, and would have
// gone stale again the moment that key was rebound. MainKey.ToString() reads back
// whatever is actually bound.
__result += ModText.Get("rov_hover_aswid_tame", AswidConfig.TameKey.Value.MainKey);
__result += $"\n[<color=yellow><b>{AswidConfig.TameKey.Value.MainKey}</b></color>] Tame";
}
}
}
@ -523,7 +477,7 @@ namespace RacesOfValheim
{
public static bool Prefix(Hud __instance, Player player)
{
if (player == Player.m_localPlayer && DraughRace.IsDraugh())
if (player == Player.m_localPlayer && (AswidRace.IsAswid() || DraughRace.IsDraugh()))
{
if (__instance.m_staminaBar2Root != null && __instance.m_staminaBar2Root.gameObject.activeSelf)
{
@ -531,15 +485,6 @@ namespace RacesOfValheim
}
return false;
}
// Vanilla switches the bar on once, when the HUD is built, and never again. Without
// this a player who left the Draugh had no stamina bar until relog - and an Aswid
// updating from a version that still hid it would have none either.
if (player == Player.m_localPlayer && __instance.m_staminaBar2Root != null
&& !__instance.m_staminaBar2Root.gameObject.activeSelf)
{
__instance.m_staminaBar2Root.gameObject.SetActive(true);
}
return true;
}
}
@ -561,9 +506,9 @@ namespace RacesOfValheim
__instance.m_icon = null;
}
__instance.m_name = "$rov_se_aswid_nightaura_name";
__instance.m_name = "Night Aura";
__instance.m_startMessage = ""; // "The darkness empowers you.";
__instance.m_tooltip = "$rov_se_aswid_nightaura_tooltip";
__instance.m_tooltip = "The cold strengthens your beastly senses.";
if (__instance is SE_Stats stats)
{
@ -587,8 +532,7 @@ namespace RacesOfValheim
if (__instance == Player.m_localPlayer && RaceInput.Allowed && AswidConfig.ToggleDevourKey.Value.IsDownIgnoringHeldKeys())
{
AswidRace.DevourEnabled = !AswidRace.DevourEnabled;
AswidRace.AuraEnabled = AswidRace.DevourEnabled;
string msg = ModText.Get(AswidRace.DevourEnabled ? "rov_msg_aswid_aura_enabled" : "rov_msg_aswid_aura_disabled");
string msg = AswidRace.DevourEnabled ? "Devour Ability: ENABLED" : "Devour Ability: DISABLED";
__instance.Message(MessageHud.MessageType.Center, msg);
}
@ -624,13 +568,6 @@ namespace RacesOfValheim
{
bool isBat = nview.GetZDO().GetBool("Aswid_IsBatForm", false);
bool isMist = nview.GetZDO().GetBool("Aswid_IsMistForm", false);
// The bat flies on m_flying, which only the bat's own client sets. Mirror it here
// and switch gravity off for the duration, or this copy sinks to the terrain
// whatever altitude is replicated - the same fix ZdoVisualSync applies to drakes.
HarmonyLib.Traverse.Create(player).Field("m_flying").SetValue(isBat);
Rigidbody body = player.GetComponent<Rigidbody>();
if (body != null && body.useGravity == isBat) body.useGravity = !isBat;
Transform playerVisual = player.transform.Find("Visual");
@ -854,104 +791,6 @@ namespace RacesOfValheim
stamina += extraFood.m_stamina;
eitr += extraFood.m_eitr;
}
// Added on top of whatever vanilla and other mods put here, never assigned: a mod that
// raises max stamina has to keep raising it for an Aswid too.
stamina += AswidRace.GetStaminaBonus(BossProgressionManager.GetCurrentProgressionState());
}
}
/// <summary>
/// The Aswid's stamina. It used to be infinite: the Skeleton's UseStamina skip covered the
/// Aswid too, which made every stamina mod, food and skill meaningless for the race (the Discord
/// reports that started the rebalance). The cost is now scaled rather than skipped, so the
/// call still reaches vanilla - and any other mod patching it - with a smaller number.
/// </summary>
[HarmonyPatch(typeof(Player), "UseStamina")]
public static class Aswid_UseStamina_Patch
{
public static void Prefix(Player __instance, ref float v)
{
if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return;
v *= AswidConfig.StaminaCostMultiplier.Value;
if (Aswid_SwimCost_Patch.Swimming && AswidConfig.RunningWaterEnabled.Value)
{
v *= AswidConfig.SwimStaminaMultiplier.Value;
}
}
}
/// <summary>
/// Marks the frames where vanilla charges for a swim stroke, so Aswid_UseStamina_Patch can
/// make that one cost dearer. Player.OnSwimming is the only place swimming spends stamina,
/// and it also runs the drowning check right after - which is what makes a high multiplier
/// play as "cannot swim" without any code of ours deciding who drowns.
/// </summary>
[HarmonyPatch(typeof(Player), "OnSwimming")]
public static class Aswid_SwimCost_Patch
{
public static bool Swimming { get; private set; }
public static void Prefix(Player __instance)
{
Swimming = __instance == Player.m_localPlayer;
}
public static void Finalizer()
{
Swimming = false;
}
}
/// <summary>
/// The seasick camera: a slow roll while the Aswid is out on the water, on a boat too. Applied after
/// vanilla has settled the camera's rotation for the frame, as a roll around the view axis,
/// so it never moves where the player aims - only how the horizon sits.
/// </summary>
[HarmonyPatch(typeof(GameCamera), "GetCameraPosition")]
public static class Aswid_SeaCameraSway_Patch
{
private const float DegreesAtStrengthOne = 4f;
private static float sway;
public static void Postfix(float dt, ref Quaternion rot)
{
bool on = AswidRace.OnWater && AswidConfig.SeaCameraSway.Value && AswidRace.IsAswid() &&
Player.m_localPlayer != null && !Player.m_localPlayer.IsDead();
// Eased in and out over about a second, so leaving the sea does not snap the horizon.
sway = Mathf.MoveTowards(sway, on ? 1f : 0f, dt);
if (sway <= 0f) return;
float t = Time.time;
float roll = (Mathf.Sin(t * 0.9f) + 0.4f * Mathf.Sin(t * 2.3f)) * DegreesAtStrengthOne *
AswidConfig.SeaCameraSwayStrength.Value * sway;
rot *= Quaternion.AngleAxis(roll, Vector3.forward);
}
}
/// <summary>
/// Pukeberries empty the fourth stomach too.
///
/// SE_Puke calls RemoveOneFood once a second, and vanilla only ever picks from its own three
/// slots, so the Aswid's fourth meal survived the berries. It now goes into the same random
/// draw as the other three, the way the Trol's extra slots do.
/// </summary>
[HarmonyPatch(typeof(Player), "RemoveOneFood")]
public static class Aswid_PlayerRemoveOneFood_Patch
{
public static bool Prefix(Player __instance, System.Collections.Generic.List<Player.Food> ___m_foods, ref bool __result)
{
if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return true;
if (!AswidFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) || extraFood == null) return true;
int vanillaCount = ___m_foods != null ? ___m_foods.Count : 0;
if (Random.Range(0, vanillaCount + 1) < vanillaCount) return true; // one of vanilla's three
AswidFoodManager.ClearFood(__instance);
__result = true;
return false;
}
}

File diff suppressed because it is too large Load diff

View file

@ -156,8 +156,8 @@ namespace RacesOfValheim
ItemDrop itemDrop = clone.GetComponent<ItemDrop>();
if (itemDrop == null) return false;
itemDrop.m_itemData.m_shared.m_name = "$rov_item_aswid_spectralclaw_name";
itemDrop.m_itemData.m_shared.m_description = "$rov_item_aswid_spectralclaw_desc";
itemDrop.m_itemData.m_shared.m_name = "Spectral Claw";
itemDrop.m_itemData.m_shared.m_description = "A claw of pure shadow, bound to your rage rather than your grip.";
itemDrop.m_itemData.m_shared.m_weight = 0f;
itemDrop.m_itemData.m_shared.m_useDurability = false;
itemDrop.m_itemData.m_shared.m_questItem = true; // undroppable, unsellable

View file

@ -11,8 +11,8 @@ namespace RacesOfValheim
{
base.Setup(character);
name = "SE_AswidStats";
m_name = "$rov_se_aswid_stats_name";
m_tooltip = "$rov_se_aswid_stats_tooltip";
m_name = "Benedictus et Afflictus";
m_tooltip = "Vampiric senses and life drain.";
}
public void UpdateStats(int state)
@ -59,59 +59,20 @@ namespace RacesOfValheim
{
base.Setup(character);
name = "SE_BatForm";
m_name = "$rov_se_aswid_batform_name";
m_tooltip = "$rov_se_aswid_batform_tooltip";
m_name = "Like a Bat out of Hell";
m_tooltip = "You have taken the form of a Bat. You can fly, but cannot attack.";
m_fallDamageModifier = -1f; // Immune to fall damage just in case
}
}
/// <summary>
/// Sunlight on an exposed Aswid. Its numbers are rewritten from AswidConfig every time
/// AswidRace.UpdateSunlight runs, so a slider moves them live; the health loss is not a stat
/// and is applied by that same tick.
/// </summary>
public class SE_AswidSunlight : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
name = "SE_AswidSunlight";
m_name = "$rov_se_aswid_sunlight_name";
m_tooltip = "$rov_se_aswid_sunlight_tooltip";
Refresh();
}
public void Refresh()
{
m_healthRegenMultiplier = 1f - AswidConfig.SunHealthRegenPenalty.Value;
m_staminaRegenMultiplier = 1f - AswidConfig.SunStaminaRegenPenalty.Value;
m_speedModifier = -AswidConfig.SunSpeedPenalty.Value;
}
}
/// <summary>
/// Open water under an Aswid off a boat. Only a marker: the burn and the drain are applied by
/// AswidRace.UpdateOpenSea, and the camera sway reads AswidRace.OnWater.
/// </summary>
public class SE_AswidOpenSea : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
name = "SE_AswidOpenSea";
m_name = "$rov_se_aswid_opensea_name";
m_tooltip = "$rov_se_aswid_opensea_tooltip";
}
}
public class SE_MistForm : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
name = "SE_MistForm";
m_name = "$rov_se_aswid_mistform_name";
m_tooltip = "$rov_se_aswid_mistform_tooltip";
m_name = "Weight of Shadows";
m_tooltip = "You are mist. Immune to physical damage and poison. Cannot attack or run.";
m_fallDamageModifier = -1f;
m_mods = new System.Collections.Generic.List<HitData.DamageModPair>
{
@ -129,7 +90,7 @@ namespace RacesOfValheim
{
base.Setup(character);
name = "SE_AswidSensesMark";
m_name = "$rov_se_aswid_sensed_name";
m_name = "Sensed";
m_tooltip = "";
m_ttl = 2f;
m_icon = null; // No icon needed for mobs
@ -142,8 +103,8 @@ namespace RacesOfValheim
{
base.Setup(character);
name = "SE_SuperhumanSenses";
m_name = "$rov_se_aswid_auspex_name";
m_tooltip = "$rov_se_aswid_auspex_tooltip";
m_name = "Auspex";
m_tooltip = "Sensing life force of nearby creatures.";
}
}
@ -153,26 +114,16 @@ namespace RacesOfValheim
{
var aswidStats = ScriptableObject.CreateInstance<SE_AswidStats>();
aswidStats.name = "SE_AswidStats";
aswidStats.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyDeathsquito")?.m_itemData.m_shared.m_icons[0];
aswidStats.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyBat")?.m_itemData.m_shared.m_icons[0];
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(aswidStats, fixReference: false));
var batForm = ScriptableObject.CreateInstance<SE_BatForm>();
batForm.name = "SE_BatForm";
batForm.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyDeathsquito")?.m_itemData.m_shared.m_icons[0];
batForm.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyBat")?.m_itemData.m_shared.m_icons[0];
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(batForm, fixReference: false));
var sunlight = ScriptableObject.CreateInstance<SE_AswidSunlight>();
sunlight.name = "SE_AswidSunlight";
sunlight.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophySurtling")?.m_itemData.m_shared.m_icons[0];
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(sunlight, fixReference: false));
var openSea = ScriptableObject.CreateInstance<SE_AswidOpenSea>();
openSea.name = "SE_AswidOpenSea";
openSea.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophySerpent")?.m_itemData.m_shared.m_icons[0];
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(openSea, fixReference: false));
var mistForm = ScriptableObject.CreateInstance<SE_MistForm>();
mistForm.name = "SE_MistForm";
mistForm.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyWraith")?.m_itemData.m_shared.m_icons[0];
@ -181,7 +132,7 @@ namespace RacesOfValheim
var sensesMark = ScriptableObject.CreateInstance<SE_AswidSensesMark>();
sensesMark.name = "SE_AswidSensesMark";
sensesMark.m_name = "$rov_se_aswid_sensed_name";
sensesMark.m_name = "Sensed";
sensesMark.m_ttl = 2f;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(sensesMark, fixReference: false));

View file

@ -81,12 +81,12 @@ namespace RacesOfValheim
if (m_ai.GetFollowTarget() == user.gameObject)
{
m_ai.SetFollowTarget(null);
user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_staying", m_character.m_name));
user.Message(MessageHud.MessageType.Center, $"{m_character.m_name} is staying.");
}
else
{
m_ai.SetFollowTarget(user.gameObject);
user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_following", m_character.m_name));
user.Message(MessageHud.MessageType.Center, $"{m_character.m_name} is following.");
}
}
return true;
@ -98,7 +98,7 @@ namespace RacesOfValheim
float cooldown = AswidRace.GetEnslaveCooldown();
if (cooldown > 0)
{
user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_dominate_cooldown_m_s", Mathf.CeilToInt(cooldown / 60f), Mathf.CeilToInt(cooldown % 60f)));
user.Message(MessageHud.MessageType.Center, $"Dominate on cooldown ({Mathf.CeilToInt(cooldown / 60f)}m {Mathf.CeilToInt(cooldown % 60f)}s)");
return false;
}
@ -117,13 +117,10 @@ namespace RacesOfValheim
m_ai.SetFollowTarget(user.gameObject);
}
// "vfx_surtling_death" was asked for here and is not a prefab in this game, so dominating
// a creature happened with no effect at all. The generic body-sized puff, rather than the
// Wraith's mist the Mist Form wears: nothing about domination is misty.
GameObject vfx = ZNetScene.instance.GetPrefab("vfx_corpse_destruction_medium");
GameObject vfx = ZNetScene.instance.GetPrefab("vfx_surtling_death");
if (vfx) Instantiate(vfx, m_character.transform.position, Quaternion.identity);
user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_dominated", m_character.m_name));
user.Message(MessageHud.MessageType.Center, $"{m_character.m_name} dominated!");
return true;
}
@ -142,22 +139,18 @@ namespace RacesOfValheim
if (isEnslaved)
{
bool following = m_ai != null && m_ai.GetFollowTarget() != null;
return (following ? ModText.Get("rov_hover_aswid_stay") : ModText.Get("rov_hover_aswid_follow"));
return following ? "[<color=yellow><b>E</b></color>] Stay" : "[<color=yellow><b>E</b></color>] Follow";
}
else
{
if (BossProgressionManager.GetCurrentProgressionState() < 6) return "";
float cd = AswidRace.GetEnslaveCooldown();
if (cd > 0) return ModText.Get("rov_hover_aswid_dominate_cooldown_m", Mathf.CeilToInt(cd / 60f));
return ModText.Get("rov_hover_aswid_dominate");
if (cd > 0) return $"[<color=red>E</color>] Dominate (Cooldown: {Mathf.CeilToInt(cd / 60f)}m)";
return "[<color=yellow><b>E</b></color>] Dominate";
}
}
// New in Valheim 1.0: Hoverable gained this. Every vanilla implementation returns a
// serialised m_hoverOffset, which is 0 unless the prefab sets one, so 0 is vanilla behaviour.
public float GetHoverOffset() => 0f;
public string GetHoverName()
{
return ""; // Character component already provides the name

View file

@ -1,28 +1,16 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Aswid's burning eyes: the vanilla skeleton's own eye lights, worn spectral green until
/// the last tier and red once it arrives.
/// The Aswid's glowing eyes: two small emissive spheres burned into the face, evil red.
///
/// They used to be two spheres built from scratch on an Unlit/Color shader, the same trick the
/// Dvergar and the Sverm still use, because a player's eyes are painted into the skin texture
/// and Custom/Player has no emission channel to light them with. Those spheres were fine and
/// they were also obviously spheres. What the game already has is better: the creature named
/// 'Skeleton' carries two objects, eye_l and eye_r, parented to its Head bone and drawn with a
/// material built for exactly this - a lit socket seen from any angle.
///
/// Borrowing them is cheap because the skeleton is skinned to the player's own rig: its Head
/// bone is our Head bone, so the local pose those two objects were authored at lands on a
/// player's face without a single measurement. The placement config below is deltas on top of
/// that pose, not a placement of its own, and 0 means "wherever the game put them".
///
/// Only the Aswid is changed by this file. The Dvergar (DvergarVisuals) and the Sverm
/// (SvermVisuals) keep their own spheres - they each own a copy of the sphere code, so nothing
/// here reaches them.
/// Built the same way the Dvergar's eyes are (see DvergarVisuals.ApplyEyes) and for the same
/// reason - a player's eyes are painted into the skin texture, and Custom/Player has no
/// emission channel to light them with. The geometry is shared work: both races render on the
/// plain human rig (Aswid tints it, same as Dvergar), so the head bone, its axes, and the
/// spherical-cap placement trick all carry over unchanged. Only the numbers differ, because an
/// Aswid stands at normal human scale most of the time instead of the Dvergar's 0.78.
///
/// Runs for local and remote players alike, which is why it takes a Player rather than reading
/// Player.m_localPlayer.
@ -31,39 +19,65 @@ namespace RacesOfValheim
{
private const string EyesName = "AswidEyes";
// The two objects to look for inside whichever creature the config points at. Both vanilla
// skeletons carry this pair; the material differs (skeleton_eye vs skeleton_eye_big) and
// that difference is the whole reason the source is a config and not a constant.
private static readonly string[] SourceEyeNames = { "eye_l", "eye_r" };
// ─── Glow colour ────────────────────────────────────────────────────
// HDR on purpose - past 1 is what makes the bloom pass pick these up at all - but only
// just past it. The first attempt used (6, 0.08, 0.03) at full strength and came out as a
// white headlamp with a red halo: bloom spreads the excess outward and saturates the core,
// so beyond a point more brightness buys nothing but a bigger white disc and *less* red.
// The Dvergar hit this exact wall and answered it by dimming, which is the same answer
// here.
//
// The near-zero green and blue are what keep it red rather than pink as it brightens.
// Not tied to star tier: unlike the Dvergar, whose colour borrows a real creature's
// progression, the Aswid has no such reference to read from.
public static readonly Color EvilEyeColor = new Color(4f, 0.06f, 0.02f, 1f);
// Darker than the Dvergar's 0.3, which put the red at an effective 1.2 - above 1, so the
// core clipped to a flat saturated red and the shade was decided by the clip rather than
// by the colour. 0.2 lands it at 0.8: under the clip, so the red keeps its depth and reads
// as blood rather than as a warning light.
//
// This is the one knob for how dark the eyes are - the hue is already pure red, so with
// green and blue at zero there is nothing left to darken *except* the intensity. Lower it
// further for deeper, but expect a floor: bloom only picks up what is bright enough to
// pass its threshold, so far enough down the eyes stop glowing and become flat dots.
public static readonly float EyeGlowStrength = 0.2f;
// ─── Placement ──────────────────────────────────────────────────────
// The Dvergar's numbers, carried over unchanged. That is not laziness - it is the only
// correct conversion, and the arithmetic says so:
//
// local offset = config x scale x (1 / headBone.lossyScale)
// lossyScale = 100 (the armature's authored scale) x scale
// => config x scale / (100 x scale) = config / 100
//
// The scale cancels. These constants live in the *unscaled* rig's units, and the face they
// have to land on shrinks and grows by exactly the same factor, so the same config value
// lands on the same part of the face at any size. Both races render on the plain human
// rig, so the Dvergar's tuning transfers verbatim.
//
// The first version of this file rescaled them by 0.78 on the theory that the Dvergar's
// values were "pre-shrink" and needed converting up to human size. They are not, and it
// put the eyes 18mm deeper and 40mm lower in rig units - on a human skull, the drop from
// the eye line to the mouth.
//
// What this also means: the Fader-tier +10% (Aswid_PlayerUpdate_Patch in AswidPatches.cs)
// needs no special case. It is not that the multiply handles it - the multiply cancels
// out. It is that the offsets are expressed in the head bone's own local space, and a
// child transform rides its parent's scale for free.
public static readonly float EyeSeparation = 0.032f; // half the distance between them
public static readonly float EyeForward = 0.081f; // centre out from the head bone
public static readonly float EyeHeight = 0.181f; // up from the head bone
public static readonly float EyeSize = 0.062f; // across, so a 24mm radius at 0.78
// Carried over from the Dvergar's own tuning on this same rig: the face is not flat, so
// two eyes placed symmetrically do not come out looking symmetrical. May need a pass in
// game to confirm it holds at Aswid's own scale - flip to index 1 in PlaceEyes if it turns
// out to be the wrong eye.
public static readonly float LeftEyeSizeMultiplier = 0.85f;
public const string PlayerHeadBoneName = "Head";
// ─── Placement, and why the numbers are unitless ─────────────────────
// The offsets below are applied as: local offset = config x scale x (1 / headBone.lossyScale)
// and lossyScale is the armature's authored 100x times the player's own scale, so the
// scale cancels and a given config value lands on the same part of the face at any size -
// Fader-tier growth included. Kept in the arithmetic because it is honest about intent.
// The eye_l/eye_r pair is borrowed for its MESH AND MATERIAL only, never for its position.
// Their authored local offset lives in the Skeleton creature's own rig, at whatever scale
// that rig happens to use at the eye bone - measured at 0.02 lossy scale against this
// player rig's 95-100, a roughly 5000x difference with no fixed ratio to correct for,
// because nothing ties one prefab's rig scale to another's. Carrying that number over
// unchanged (even after remapping which axis is which) put the eyes some 0.2 world units
// off the head bone - visibly floating above the face. These three are the pre-rewrite
// sphere code's own numbers, tuned by eye on THIS player rig and confirmed by playtest
// before the borrowed-eye-light rewrite - the one measurement in this file that is
// actually expressed in the right units to begin with.
private const float BaseEyeForward = 0.081f;
private const float BaseEyeHeight = 0.181f;
private const float BaseEyeSeparation = 0.032f;
// The borrowed socket at the size the Skeleton wears it, times the config multiplier, was
// two green blocks on the face; at half it was smaller than the painted eye underneath,
// which then showed round it. Applied before the multiplier, so a saved config keeps its
// meaning as "relative to the default".
private const float BaseEyeScale = 0.75f;
// ─── Race check ─────────────────────────────────────────────────────
/// <summary>
@ -90,63 +104,21 @@ namespace RacesOfValheim
/// <summary>
/// The skull's own idea of forward, up and right, measured once while the head is still
/// looking where the body is, plus what the eyes currently in place were built from. Kept
/// on the eye holder so it survives as long as the eyes do, and so nothing is tempted to
/// work it out again from a rig that has since moved.
/// looking where the body is. Kept on the eye holder so it survives as long as the eyes
/// do, and so nothing is tempted to work it out again from a rig that has since moved.
/// </summary>
private class EyeFrame : MonoBehaviour
{
public Vector3 LocalForward = Vector3.forward;
public Vector3 LocalUp = Vector3.up;
public Vector3 LocalRight = Vector3.right;
// What these eyes were cloned from, and whether they were flattened onto a plain
// colour shader. Either one changing in Configuration Manager means the pair has to be
// built again rather than merely moved.
public string SourceModel = "";
public bool FlatShader;
// Which body the base pose was measured for: the female face puts the eyes elsewhere
// (PlayerFace), so a change of body model is a rebuild too.
public bool Female;
}
/// <summary>The pose an eye was authored at on the creature. Everything else is a delta on this.</summary>
private class EyeBase : MonoBehaviour
{
public Vector3 Position;
public Quaternion Rotation = Quaternion.identity;
public Vector3 Scale = Vector3.one;
}
private static Shader cachedGlowShader;
private static bool glowShaderResolved;
/// <summary>
/// Reapplies the eyes every frame, which is what makes the Configuration Manager sliders
/// move them while you watch. Added to a player once they turn out to be an Aswid and
/// destroyed when they stop being one; VisEquipment's own refresh is what puts it back.
/// </summary>
public class EyeTicker : MonoBehaviour
{
private Player m_player;
private void Awake()
{
m_player = GetComponent<Player>();
}
private void LateUpdate()
{
if (m_player == null)
{
Destroy(this);
return;
}
ApplyEyes(m_player);
}
}
/// <summary>
/// Keeps the pair of lit sockets burning over the player's painted-on eyes. Safe to call
/// Keeps two small emissive spheres burning over the player's painted-on eyes. Safe to call
/// for anyone: it removes them again from whoever is not a living Aswid.
///
/// Parented straight onto the head bone rather than Character.m_eye - the Dvergar tried
@ -172,52 +144,23 @@ namespace RacesOfValheim
eyes.name = EyesName + "_Removed";
Object.Destroy(eyes.gameObject);
}
EyeTicker ticker = player.GetComponent<EyeTicker>();
if (ticker != null) Object.Destroy(ticker);
return;
}
if (player.GetComponent<EyeTicker>() == null)
{
player.gameObject.AddComponent<EyeTicker>();
}
// A different source creature, or the shader override being flipped, changes what the
// eyes are rather than where they sit - so the pair is thrown away and built again.
if (eyes != null)
{
EyeFrame existing = eyes.GetComponent<EyeFrame>();
if (existing == null ||
existing.SourceModel != AswidConfig.EyeSourceModel.Value ||
existing.FlatShader != AswidConfig.EyeFlatColorShader.Value ||
existing.Female != PlayerFace.IsFemale(player))
{
eyes.name = EyesName + "_Removed";
Object.Destroy(eyes.gameObject);
eyes = null;
}
}
if (eyes == null)
{
// BuildEyes takes a one-time reading of the head bone's pose to work out which way
// the skull faces, and caches it for as long as the eyes exist. Sitting, attached,
// mid-attack or asleep, the head can be turned away from the body's own forward at
// that instant, which is how the snap-to-axis has picked the wrong side and left
// the eyes behind the skull before (see DvergarVisuals.ApplyEyes). Waiting for a
// plain standing pose costs nothing - ApplyEyes runs again on the next tick either
// way.
if (player.IsAttached() || player.IsAttachedToShip() || player.InAttack() || player.IsSleeping())
{
return;
}
eyes = BuildEyes(player, headBone);
}
if (eyes == null) return; // already logged once by the builder
if (eyes == null) eyes = BuildEyes(headBone);
if (eyes == null) return; // already logged once by the resolver
PlaceEyes(player, headBone, eyes);
PaintEyes(eyes, GetEyeColor(player));
Color glow = GetEyeColor();
foreach (Renderer renderer in eyes.GetComponentsInChildren<Renderer>(true))
{
Material material = renderer.material;
if (material == null) continue;
material.color = glow;
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", glow);
}
}
/// <summary>
@ -225,29 +168,21 @@ namespace RacesOfValheim
/// DvergarVisuals.FindHeadBone for why: the avatar's HumanBodyBones.Head moves with the
/// player but ignores the head's own idle animation, and only VisEquipment.m_bodyModel's
/// own bone array is the one the skinned mesh - and every animation - actually drives.
///
/// THE ANIMATOR'S HEAD IS NOT AN ACCEPTABLE ANSWER, and this used to fall back to it
/// "so that something renders if the body model is not up yet". That fallback is what put
/// the eyes at the wrong height: the avatar's HumanBodyBones.Head is a DIFFERENT transform,
/// sitting at a different place in the hierarchy, so a holder parented to it hangs at the
/// wrong height for as long as it lives - and it lives until the player changes race. It
/// only ever bit once the claws landed, because equipping an item on spawn moved the first
/// build a few frames earlier, into the window where the body model is not up yet.
///
/// Returning null costs nothing: the ticker calls this again next frame, and a frame with
/// no eyes is invisible next to a session with them on the jaw.
/// </summary>
private static Transform FindHeadBone(Player player)
{
VisEquipment visEq = player.GetComponent<VisEquipment>();
if (visEq == null || visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return null;
foreach (Transform bone in visEq.m_bodyModel.bones)
if (visEq != null && visEq.m_bodyModel != null && visEq.m_bodyModel.bones != null)
{
if (bone != null && bone.name == PlayerHeadBoneName) return bone;
foreach (Transform bone in visEq.m_bodyModel.bones)
{
if (bone != null && bone.name == PlayerHeadBoneName) return bone;
}
}
return null;
// Last resort, and only so that something renders if the body model is not up yet.
Animator animator = player.GetComponentInChildren<Animator>();
return animator != null ? animator.GetBoneTransform(HumanBodyBones.Head) : null;
}
/// <summary>
@ -258,55 +193,25 @@ namespace RacesOfValheim
/// </summary>
private static float GetPlayerScale(Player player) => player.transform.localScale.x;
/// <summary>
/// The tier this particular Aswid is rendering at. Off the ZDO, so a remote player's eyes
/// burn at their own standing rather than at ours; without one - the main-menu preview -
/// fall back to what this client can work out, the same fallback the Skeleton's visuals
/// make (SkeletonVisuals.GetProgressionState).
/// </summary>
private static int GetProgressionState(Player player)
private static Color GetEyeColor()
{
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview != null && nview.IsValid())
{
return nview.GetZDO().GetInt("RacesOfValheim_AswidState", 0);
}
return BossProgressionManager.GetCurrentProgressionState();
float strength = EyeGlowStrength;
return new Color(
EvilEyeColor.r * strength,
EvilEyeColor.g * strength,
EvilEyeColor.b * strength,
EvilEyeColor.a);
}
/// <summary>
/// Spectral green for as long as the Aswid is still becoming one, and red only at the end.
/// Puts the two eyes where the face is, in the head bone's own coordinates, every frame.
/// See DvergarVisuals.PlaceEyes for the full derivation of the axes.
///
/// The red was the colour from the start and it reads as arrival, so it is worth not
/// spending it early: every tier below the last burns a cold green instead, dimmer on
/// purpose - the green is the eyes of something dead, the red is the eyes of something
/// that has finished feeding. Each has its own brightness rather than sharing one, because
/// "not too bright" is exactly the difference between them.
/// </summary>
private static Color GetEyeColor(Player player)
{
bool final = GetProgressionState(player) >= AswidConfig.EyeFinalStage.Value;
float strength = final
? AswidConfig.EyeGlowStrength.Value
: AswidConfig.EarlyEyeGlowStrength.Value;
Color hue = final
? new Color(AswidConfig.EyeColorRed.Value, AswidConfig.EyeColorGreen.Value, AswidConfig.EyeColorBlue.Value)
: new Color(AswidConfig.EarlyEyeColorRed.Value, AswidConfig.EarlyEyeColorGreen.Value, AswidConfig.EarlyEyeColorBlue.Value);
return new Color(hue.r * strength, hue.g * strength, hue.b * strength, 1f);
}
/// <summary>
/// Moves each eye off the pose it was authored at, by the config's deltas, in the head
/// bone's own coordinates. Every value at 0 (and size at 1) leaves them exactly where the
/// game's own skeleton wears them, which is the intended starting point.
///
/// See DvergarVisuals.PlaceEyes for the full derivation of the axes: they are measured
/// once at build time and snapped to the skull's square axes, because the raw measurement
/// is taken at whatever pose the head happens to hold that frame and arrives tilted.
/// The scale term is kept for the Dvergar's sake and because it is honest about intent,
/// but it does not do the work it looks like it does: lossyScale already contains the
/// player's scale, so the multiply and the divide cancel and the local offset is simply
/// config/100 at every size. Growth is handled by the parenting, not by this arithmetic -
/// see the note on the placement constants above.
/// </summary>
private static void PlaceEyes(Player player, Transform headBone, Transform holder)
{
@ -318,132 +223,49 @@ namespace RacesOfValheim
EyeFrame frame = holder.GetComponent<EyeFrame>();
if (frame == null) return;
float scale = GetPlayerScale(player) * toLocal;
Vector3 localForward = frame.LocalForward;
Vector3 localUp = frame.LocalUp;
Vector3 localRight = frame.LocalRight;
float scale = GetPlayerScale(player);
Vector3 baseLocal = localForward * (EyeForward * scale * toLocal)
+ localUp * (EyeHeight * scale * toLocal);
float eyeLocalSize = EyeSize * scale * toLocal;
for (int i = 0; i < holder.childCount; i++)
{
Transform eye = holder.GetChild(i);
EyeBase authored = eye.GetComponent<EyeBase>();
if (authored == null) continue;
// Which way "outwards" is for this particular eye, read from where the creature
// put it rather than from the order the children happen to be in. Widening then
// pushes both eyes apart whichever one this is.
float side = Mathf.Sign(Vector3.Dot(authored.Position, frame.LocalRight));
if (side == 0f) side = i == 0 ? -1f : 1f;
// Index 0 is offset against the right axis, so it is the model's left eye - the
// one on your right as you face it.
float side = i == 0 ? -1f : 1f;
float size = i == 0 ? eyeLocalSize * LeftEyeSizeMultiplier : eyeLocalSize;
// This eye's hand corrections (RaceEyeTuning), on top of the race's own offsets.
RaceEyeTuning.Eye tuning = RaceEyeTuning.For("Aswid", player, side);
float forward = AswidConfig.EyeForwardOffset.Value + (tuning != null ? tuning.Forward : 0f);
float height = AswidConfig.EyeHeightOffset.Value + (tuning != null ? tuning.Height : 0f);
float separation = AswidConfig.EyeSeparationOffset.Value + (tuning != null ? tuning.Separation : 0f);
float size = AswidConfig.EyeSizeMultiplier.Value * (tuning != null ? tuning.Size : 1f);
Vector3 shift = frame.LocalForward * (forward * scale)
+ frame.LocalUp * (height * scale);
// YAW IS MIRRORED, the other two are not. Turning both eyes the same way on Y
// makes the pair look sideways - both point off the same shoulder, because a face
// is symmetric about its centre line and yaw is the axis that crosses it. Negating
// it on the left eye turns them out from (or in towards) the nose together, which
// is what "toe them in a bit" actually means on a pair of eyes.
//
// Pitch and roll are shared deliberately: both eyes looking up is a face looking
// up, and mirroring either of those would cross them instead of aiming them.
//
// This twist is on the HEAD BONE's raw axes (it multiplies from the left), and on
// this rig those are not the face's: bone X points out of the face and bone Z
// sideways. The defaults were dialled in against that, so it stays as it is.
Quaternion twist = Quaternion.Euler(
AswidConfig.EyeRotationX.Value,
AswidConfig.EyeRotationY.Value * side,
AswidConfig.EyeRotationZ.Value);
// The RaceEyeTuning corrections turn the eye on the FACE's axes instead: conjugated by
// the face frame, X tips it, Y turns it toward the temple and Z raises the outer
// corner, the same on both eyes. Added to the bone-axis twist above, X rolled the
// eyes and a mirrored Z tipped one up and the other down.
Quaternion nudge = Quaternion.identity;
if (tuning != null)
{
nudge = authored.Rotation
* Quaternion.Euler(tuning.RotX, tuning.RotY * side, tuning.RotZ * side)
* Quaternion.Inverse(authored.Rotation);
}
eye.localPosition = authored.Position + shift +
frame.LocalRight * (side * separation * scale);
eye.localRotation = nudge * twist * authored.Rotation;
eye.localScale = authored.Scale * size;
eye.localPosition = baseLocal + localRight * (side * EyeSeparation * scale * toLocal);
eye.localScale = Vector3.one * size;
}
}
/// <summary>
/// Tints the borrowed material red - the one thing about these eyes that is not the
/// skeleton's.
///
/// Every colour property the shader turns out to have is written, rather than guessing
/// which one it uses: a Valheim VFX material can carry _Color, _TintColor, _EmissionColor
/// or none of them, and writing a property a shader does not have is an error while
/// writing all of the ones it does is free.
/// Rounds a direction to the nearest of the six axis directions. Whichever component is
/// largest wins, sign included.
/// </summary>
private static void PaintEyes(Transform holder, Color glow)
private static Vector3 SnapToAxis(Vector3 direction)
{
bool smoke = AswidConfig.EyeSmoke.Value;
float x = Mathf.Abs(direction.x);
float y = Mathf.Abs(direction.y);
float z = Mathf.Abs(direction.z);
foreach (Renderer renderer in holder.GetComponentsInChildren<Renderer>(true))
{
Material material = renderer.material;
if (material == null) continue;
if (material.HasProperty("_Color")) material.SetColor("_Color", glow);
if (material.HasProperty("_TintColor")) material.SetColor("_TintColor", glow);
if (material.HasProperty("_BaseColor")) material.SetColor("_BaseColor", glow);
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", glow);
}
// The smoke curling out of the sockets is authored on the creature but left switched
// off there, waiting for a script that this clone does not have. Off by default here
// too: it is a much louder effect than the glow itself.
foreach (ParticleSystem ps in holder.GetComponentsInChildren<ParticleSystem>(true))
{
if (ps.gameObject.activeSelf != smoke) ps.gameObject.SetActive(smoke);
if (!smoke) continue;
ParticleSystem.MainModule main = ps.main;
main.startColor = new ParticleSystem.MinMaxGradient(glow);
}
if (x >= y && x >= z) return new Vector3(Mathf.Sign(direction.x), 0f, 0f);
if (y >= z) return new Vector3(0f, Mathf.Sign(direction.y), 0f);
return new Vector3(0f, 0f, Mathf.Sign(direction.z));
}
/// <summary>
/// Which way the skull faces, from the bind pose rather than from this frame's animation.
/// See RigBindPose for why that distinction is the whole bug - shared with the Dvergar and
/// the Sverm, which hit it too.
/// </summary>
private static void MeasureFrame(Player player, Transform headBone, EyeFrame frame)
private static Transform BuildEyes(Transform headBone)
{
RigBindPose.MeasureHeadFrame(player, headBone, "Aswid",
out frame.LocalForward, out frame.LocalUp, out frame.LocalRight);
}
private static Transform BuildEyes(Player player, Transform headBone)
{
string modelName = AswidConfig.EyeSourceModel.Value;
List<Transform> sources = FindSourceEyes(modelName);
if (sources.Count == 0) return null; // already logged once by the finder
// The placement below divides by this, and the rig reports 0 for a frame or two while
// it is still coming up. Returning null costs nothing - ApplyEyes calls again next
// tick - where dividing by it would put the pair somewhere unrecoverable.
if (Mathf.Abs(headBone.lossyScale.x) < 0.0001f) return null;
// Anything of ours left anywhere else on this player goes first. ApplyEyes only ever
// looks under the head bone, so a holder that ended up on some other transform is
// invisible to it - it would build a second pair beside the wrong one rather than
// replace it. That is exactly the state the animator fallback used to leave behind.
SweepStrayHolders(player, headBone);
Shader glow = ResolveGlowShader();
if (glow == null) return null;
GameObject holder = new GameObject(EyesName);
holder.transform.SetParent(headBone, false);
@ -451,228 +273,43 @@ namespace RacesOfValheim
holder.transform.localRotation = Quaternion.identity;
holder.transform.localScale = Vector3.one;
// Which way the skull faces, taken from the BIND POSE rather than from the pose the
// head happens to hold on this frame. See MeasureFrame - this is the whole reason a
// rebuild is no longer a lottery.
// Ask the rig which way it faces, once, and round the answer to the skull's own axes -
// see DvergarVisuals.BuildEyes for why the raw, unrounded measurement puts the eyes at
// the jaw instead of the eye line.
Transform root = headBone.root;
EyeFrame frame = holder.AddComponent<EyeFrame>();
MeasureFrame(player, headBone, frame);
frame.SourceModel = modelName;
frame.FlatShader = AswidConfig.EyeFlatColorShader.Value;
frame.Female = PlayerFace.IsFemale(player);
frame.LocalForward = SnapToAxis(headBone.InverseTransformDirection(root.forward));
frame.LocalUp = SnapToAxis(headBone.InverseTransformDirection(root.up));
frame.LocalRight = Vector3.Cross(frame.LocalUp, frame.LocalForward).normalized;
float baseHeight = BaseEyeHeight;
float baseSeparation = BaseEyeSeparation;
float baseSize = BaseEyeScale;
PlayerFace.AdjustEyes(player, ref baseHeight, ref baseSeparation, ref baseSize);
// canonicalToFrame turns "face forward, as authored" into "face forward, on THIS
// rig's own axes" - the rotation that carries the ordinary (X,Y,Z) convention onto
// (frame.LocalRight, frame.LocalUp, frame.LocalForward). Used for the socket's base
// facing below; NOT used for position - see BaseEyeForward/Height/Separation for why.
Quaternion canonicalToFrame = Quaternion.LookRotation(frame.LocalForward, frame.LocalUp);
foreach (Transform source in sources)
for (int i = 0; i < 2; i++)
{
GameObject eye = Object.Instantiate(source.gameObject, holder.transform);
eye.name = source.name;
// Spheres, not quads: a quad seen edge-on is a line and vanishes, which is why an
// earlier attempt on the Dvergar came and went with the camera angle. A sphere
// reads the same from every direction and is properly hidden by the skull when the
// head is between it and the camera.
GameObject eye = GameObject.CreatePrimitive(PrimitiveType.Sphere);
eye.name = "Eye" + i;
// LEFT vs RIGHT read from the source object's own name, not from list order -
// "eye_l"/"eye_r" is the actual contract FindSourceEyes matches against; the order
// GetComponentsInChildren happens to walk the source hierarchy in is not.
float side = source.name.ToLowerInvariant().Contains("_l") ? -1f : 1f;
// Placed from the player's own measured frame and three fixed constants, NOT from
// source.localPosition. The borrowed position is authored on the Skeleton
// creature's own rig, at whatever scale that rig happens to use at the eye bone -
// measured at 0.02 lossy scale against this player rig's ~95-100, and nothing ties
// one prefab's rig scale to another's, so there is no reliable factor to correct
// it by. In game it landed 0.22 m straight up from the head bone and barely any
// forward, where 0.181 up / 0.081 forward is the face - eyes above the skull.
//
// THE / lossyScale IS NOT OPTIONAL. The constants are world metres; localPosition
// is in the head bone's own space, which the armature authors at ~95-100x. Setting
// them without this term puts the eyes 0.081 x 95 = 7.7 m out - off the model
// entirely and invisible, which is exactly what dropping this term did once
// already. PlaceEyes applies the config offsets through the same 1/lossy factor
// for the same reason, and the pre-rewrite sphere code always had it.
float toLocal = 1f / headBone.lossyScale.x;
Vector3 basePosition = frame.LocalForward * (BaseEyeForward * toLocal)
+ frame.LocalUp * (baseHeight * toLocal)
+ frame.LocalRight * (side * baseSeparation * toLocal);
// The socket's own authored tilt is skipped for the same reason its position is -
// canonicalToFrame alone (face forward, on this rig's axes) is what the config's
// twist then nudges from in PlaceEyes.
Quaternion baseRotation = canonicalToFrame;
// SCALE IS INHERITED, so the authored localScale cannot come across either.
//
// source.localScale is authored under the Skeleton's own parent chain, which puts
// that object at 0.02 lossy scale in the world. Re-parented under a head bone at
// ~95 and left alone, the same number renders the mesh some 4750x too big: an eye
// the size of the character, centred near the face, therefore mostly INSIDE the
// skull, with the corners that clear it reading as flat rectangles rather than as
// eyes. That is one bug with two faces - "wrong place" and "blocky" were the same
// scale error seen from outside and from in front.
//
// lossyScale (world) rather than localScale (relative to a parent we do not have)
// is the honest quantity to carry over: it is the size the game actually draws
// this object at on a real skeleton. Divided into the new parent's scale, the pair
// lands at exactly the size vanilla wears them, which is the whole point of
// borrowing them instead of drawing spheres.
Vector3 baseScale = source.lossyScale * (toLocal * baseSize);
// Remembered before anything moves it, because everything the config does is
// expressed as a delta on this.
EyeBase authored = eye.AddComponent<EyeBase>();
authored.Position = basePosition;
authored.Rotation = baseRotation;
authored.Scale = baseScale;
eye.transform.localPosition = basePosition;
eye.transform.localRotation = baseRotation;
eye.transform.localScale = baseScale;
// Allowlist, not a blocklist - the same rule the skeleton's own glow and the head
// flame are cloned under. Whatever rode along goes, whatever type it turns out to
// be; EyeBase is added back afterwards because it is ours.
foreach (Component comp in eye.GetComponentsInChildren<Component>(true))
foreach (Collider collider in eye.GetComponents<Collider>())
{
if (comp is Transform || comp is MeshRenderer || comp is MeshFilter ||
comp is ParticleSystem || comp is ParticleSystemRenderer || comp is EyeBase)
{
continue;
}
Object.Destroy(comp);
Object.Destroy(collider);
}
foreach (Renderer renderer in eye.GetComponentsInChildren<Renderer>(true))
{
renderer.enabled = true;
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
renderer.receiveShadows = false;
eye.transform.SetParent(holder.transform, false);
eye.transform.localPosition = Vector3.zero;
eye.transform.localRotation = Quaternion.identity;
eye.transform.localScale = Vector3.zero; // PlaceEyes runs immediately after this
// The escape hatch, for if the borrowed material turns out not to take a tint:
// a plain colour shader renders past 1 so the bloom pass picks it up, at the
// cost of the socket's own texture.
if (!AswidConfig.EyeFlatColorShader.Value) continue;
Shader flat = ResolveGlowShader();
if (flat != null) renderer.material = new Material(flat);
}
eye.SetActive(true);
Renderer renderer = eye.GetComponent<Renderer>();
renderer.material = new Material(glow);
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
renderer.receiveShadows = false;
}
LogMaterialsOnce(modelName, holder.transform);
// What the pair was actually anchored to. If the height is ever wrong again, this line
// is the answer rather than the start of another guess: it names the bone, its parent,
// and the axes the offsets are measured along.
Jotunn.Logger.LogInfo(
$"[Aswid] Eyes built on bone '{headBone.name}' (parent '{(headBone.parent != null ? headBone.parent.name : "-")}') " +
$"at world y={headBone.position.y:F2}, lossyScale={headBone.lossyScale.x:F1}, " +
$"localUp={frame.LocalUp}, localForward={frame.LocalForward}.");
return holder.transform;
}
/// <summary>
/// Destroys every eye holder on this player that is not parented to the bone we are about
/// to build on. Runs only when a pair is being built, which is on a race change or a config
/// change - never on a hot path.
/// </summary>
private static void SweepStrayHolders(Player player, Transform keepParent)
{
if (player == null) return;
foreach (Transform t in player.GetComponentsInChildren<Transform>(true))
{
if (t == null || t.name != EyesName) continue;
if (t.parent == keepParent) continue;
Jotunn.Logger.LogInfo(
$"[Aswid] Removing a stray eye holder parented to '{(t.parent != null ? t.parent.name : "-")}'.");
// Renamed first: Destroy is deferred to the end of the frame, and this sweep would
// otherwise find it again on the next build.
t.name = EyesName + "_Removed";
Object.Destroy(t.gameObject);
}
}
private static readonly HashSet<string> warnedSources = new HashSet<string>();
private static readonly HashSet<string> loggedMaterials = new HashSet<string>();
/// <summary>
/// The creature's own eye objects, by name. Not cached: this runs when the pair is built,
/// which is on a race change or a config change and not on any hot path.
/// </summary>
private static List<Transform> FindSourceEyes(string modelName)
{
List<Transform> found = new List<Transform>();
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(modelName);
if (prefab == null)
{
if (warnedSources.Add(modelName))
{
Jotunn.Logger.LogWarning(
$"[Aswid] Eye source prefab '{modelName}' not found - the eyes stay dark. " +
"Check the model name in Configuration Manager.");
}
return found;
}
foreach (Transform t in prefab.GetComponentsInChildren<Transform>(true))
{
string lower = t.name.ToLower();
foreach (string wanted in SourceEyeNames)
{
if (lower == wanted) { found.Add(t); break; }
}
}
if (found.Count == 0 && warnedSources.Add(modelName + ":eyes"))
{
Jotunn.Logger.LogWarning(
$"[Aswid] '{modelName}' carries no {string.Join("/", SourceEyeNames)} objects - the eyes stay dark.");
}
return found;
}
/// <summary>
/// Says what the borrowed material actually is, once per source. If red does not take,
/// this line is the answer: it names the shader and every colour property it exposes.
/// </summary>
private static void LogMaterialsOnce(string modelName, Transform holder)
{
if (!loggedMaterials.Add(modelName)) return;
foreach (Renderer renderer in holder.GetComponentsInChildren<Renderer>(true))
{
Material material = renderer.sharedMaterial;
if (material == null) continue;
List<string> properties = new List<string>();
foreach (string name in new[] { "_Color", "_TintColor", "_BaseColor", "_EmissionColor" })
{
if (material.HasProperty(name)) properties.Add(name);
}
Jotunn.Logger.LogInfo(
$"[Aswid] Eye '{renderer.name}' from '{modelName}': material '{material.name}' " +
$"shader '{(material.shader != null ? material.shader.name : "none")}' " +
$"colour properties: {(properties.Count > 0 ? string.Join(", ", properties.ToArray()) : "none")}");
}
}
private static Shader cachedGlowShader;
private static bool glowShaderResolved;
/// <summary>
/// Finds a shader that will render a flat colour past 1 so the bloom pass picks it up.
/// Opaque first, deliberately - see DvergarVisuals.ResolveGlowShader: a transparent shader

View file

@ -1,169 +1,54 @@
using HarmonyLib;
using UnityEngine;
using Jotunn.Managers;
namespace RacesOfValheim
{
/// <summary>
/// The bat's flight, held on for as long as the worn model exists.
///
/// The bat flies on Character.m_flying and is steered by DirectedFlightPatch, the same
/// controls as the Skadi's drake; this class only hands over the bat's own numbers and keeps
/// the flag up. It used to fly on vanilla's debug-fly flag, which ignored carry weight, cost
/// nothing, moved at 50 m/s and made every monster blind to the player - the Discord reports
/// that started the 2026 rebalance.
///
/// Other clients learn the bat is airborne from Aswid_IsBatForm in the ZDO, which
/// Aswid_MultiplayerVisuals_Patch mirrors into their copy's m_flying.
///
/// FREE FLIGHT. A player who picks it (or a server that forces it, AswidConfig.UsesFreeBatFlight)
/// gets the old flight back: vanilla's debug fly, both halves (the field for the local physics,
/// s_debugFly in the ZDO for everyone else), and no DirectedFlight. The mode is read once, when
/// the form goes up. AswidBatForm keeps monsters seeing and hurting a free-flying bat.
/// </summary>
public class BatFormBehavior : MonoBehaviour, IDirectedFlyer
public class BatFormBehavior : MonoBehaviour
{
private static readonly System.Reflection.FieldInfo FlyingField =
AccessTools.Field(typeof(Character), "m_flying");
private static readonly System.Reflection.FieldInfo DebugFlyField =
AccessTools.Field(typeof(Player), "m_debugFly");
private Animator anim;
private AswidProgression.FormRules formRules;
private float startTime;
private bool warnedTooHeavy;
private bool expired;
private bool free;
public void Initialize(AswidProgression.FormRules rules)
{
this.formRules = rules;
}
// ─── IDirectedFlyer ─────────────────────────────────────────────────────
// A bat is never grounded on purpose: it flies for as long as the form lasts.
public bool IsFlying => true;
public float LastPoweredTime { get; set; }
public float TurnSpeed => AswidConfig.BatTurnSpeed.Value;
public float GlideSpeed => AswidConfig.BatGlideSpeed.Value;
public float BoostSpeed => AswidConfig.BatBoostSpeed.Value;
public float SprintSpeed => AswidConfig.BatSprintSpeed.Value;
public float ReverseSpeed => AswidConfig.BatReverseSpeed.Value;
public float LiftoffSpeed => AswidConfig.BatLiftoffSpeed.Value;
public float HoverSeconds => AswidConfig.BatHoverSeconds.Value;
public float PoweredStaminaPerSecond => AswidConfig.BatPoweredStaminaPerSecond.Value * EncumberedCostFactor();
public float SprintStaminaPerSecond => AswidConfig.BatSprintStaminaPerSecond.Value * EncumberedCostFactor();
public bool CanPower => !(IsEncumbered() && AswidConfig.BatEncumbered.Value == AswidConfig.EncumberedMode.Blocked);
private static bool IsEncumbered()
{
return Player.m_localPlayer != null && Player.m_localPlayer.IsEncumbered();
}
private static float EncumberedCostFactor()
{
return IsEncumbered() ? 1f + AswidConfig.BatEncumberedExtraCost.Value : 1f;
}
/// <summary>
/// The form's lifetime in seconds at the current state, or 0 for no limit. The per-state
/// bonus is Dissolution's "scales with boss progression", and only means anything on top
/// of a base limit.
/// </summary>
public static float MaxDuration()
{
float max = AswidConfig.BatMaxDuration.Value;
if (max <= 0f) return 0f;
return max + AswidConfig.BatDurationPerState.Value * BossProgressionManager.GetCurrentProgressionState();
}
private void Start()
{
anim = GetComponentInChildren<Animator>();
startTime = Time.time;
LastPoweredTime = Time.time;
free = AswidConfig.UsesFreeBatFlight();
if (!free) DirectedFlight.Register(this);
Hold();
if (Player.m_localPlayer != null)
{
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(true);
}
}
private void Update()
{
Player player = Player.m_localPlayer;
if (player == null || player.IsDead()) return;
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return;
// Held every frame rather than set once, for the same reason the debug-fly flag was:
// anything that clears it mid-form (a vanilla reset, another mod) would drop the bat
// into walking with the model still on.
Hold();
// Free Flight ignores weight, so only Stamina Flight warns about it.
if (!free)
{
if (!CanPower && !warnedTooHeavy)
{
warnedTooHeavy = true;
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_too_heavy_to_beat"));
}
else if (CanPower)
{
warnedTooHeavy = false;
}
}
float max = MaxDuration();
if (max > 0f && !expired && Time.time - startTime >= max && AswidRace.Instance != null)
{
expired = true;
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_form_fades"));
AswidRace.Instance.ForceRevert();
}
// Ensure flight remains on continuously
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(true);
// Sync Animator
if (anim != null)
{
Vector3 vel = player.GetVelocity();
Vector3 vel = Player.m_localPlayer.GetVelocity();
vel.y = 0f;
anim.SetFloat("forward_speed", vel.magnitude);
float speed = vel.magnitude;
// Bats don't necessarily have a complex animator like players,
// but if they do have a speed or flying parameter, we set it here.
anim.SetFloat("forward_speed", speed);
anim.SetBool("flying", true);
}
}
private void OnDestroy()
{
DirectedFlight.Unregister(this);
SetFlying(false);
}
private void Hold()
{
if (free) SetDebugFly(true);
else SetFlying(true);
}
/// <summary>
/// The local half of Stamina Flight. The remote half is the Aswid_IsBatForm ZDO flag
/// AswidRace already writes, so there is nothing to replicate here. Turning it off also
/// turns debug fly off, so every exit path ends both flights whichever one was up.
/// </summary>
public static void SetFlying(bool flying)
{
Player player = Player.m_localPlayer;
if (player == null) return;
if (FlyingField != null) FlyingField.SetValue(player, flying);
if (!flying) SetDebugFly(false);
}
/// <summary>
/// Both halves of debug fly, for Free Flight. The ZDO write every frame is not network
/// spam: ZDO.Set returns early when the value is unchanged.
/// </summary>
private static void SetDebugFly(bool flying)
{
Player player = Player.m_localPlayer;
if (player == null) return;
if (DebugFlyField != null) DebugFlyField.SetValue(player, flying);
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.IsOwner()) nview.GetZDO().Set(ZDOVars.s_debugFly, flying);
if (Player.m_localPlayer != null)
{
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(false);
}
}
}
}

View file

@ -79,16 +79,14 @@ namespace RacesOfValheim
private bool OnAddMeat(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
return TryAdd(user, item, isMeat: true) || item != null;
return TryAdd(user, item, isMeat: true);
}
private bool OnAddBone(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
return TryAdd(user, item, isMeat: false) || item != null;
return TryAdd(user, item, isMeat: false);
}
// Both switches treat an item in hand as handled whatever TryAdd says: false makes
// Humanoid.UseItem cover our own message with the generic "$msg_cantuseon".
private bool TryAdd(Humanoid user, ItemDrop.ItemData item, bool isMeat)
{
if (user == null) return false;
@ -98,7 +96,7 @@ namespace RacesOfValheim
if (item == null) item = FindUsable(inventory, isMeat);
if (item == null)
{
user.Message(MessageHud.MessageType.Center, (isMeat ? ModText.Get("rov_msg_aswid_no_raw_flesh_render") : ModText.Get("rov_msg_aswid_no_bone_grind")));
user.Message(MessageHud.MessageType.Center, isMeat ? "No raw flesh to render." : "No bone to grind.");
return false;
}

Binary file not shown.

View file

@ -1,368 +0,0 @@
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Bone Ship, first piece: the small one, a clone of the Karve. See Skeleton_BoneShip.txt, sections
/// 2, 10 and 11 - every number and node name below was read off the game, not remembered.
///
/// WHAT THIS STEP DOES
/// - A new buildable ship, BoneKarve, cloned from "Karve" so the vanilla one is left alone.
/// - A hull that is rotten from the first day: WearNTear is pointed at the prefab's own worn hull as
/// its "new" one, so full health shows the worn model, and a light tint goes on top. The game's
/// SetHealthVisual guards the equal case (it only turns a visual off when it differs from the new
/// one), so m_new == m_worn is a supported shape, not a trick. The fresh hull is switched off in
/// the prefab or both would show at once.
/// - It goes where the sails are not: the wind-independent push (SailK) and a sail that never
/// unfurls, in BoneShipSailForcePatch and BoneShipSailPatch below.
///
/// WHAT IS NOT HERE YET: the torn sail texture, the bones, the rowers, the figurehead, the altar, the
/// roster and the archers. Each is its own step. The archer's mount already exists (ShipMount.cs).
/// </summary>
public static class BoneShip
{
// Every vanilla ship but the Raft has a bone version (the design, 2026-10-05). The names are what
// ShipMountTest's post table and the rest of the Bone Ship know them by.
public const string KarveName = "BoneKarve";
public const string LongshipName = "BoneLongship";
public const string AshlandsName = "BoneAshlands";
/// <summary>The hover name of the altar on the deck, where bone fragments are offered.</summary>
public const string AltarName = "$rov_piece_boneship_altar_name";
/// <summary>
/// Places in the roster, melee and archers, by ship (Skeleton_BoneShip.txt 5.7). The small ship is
/// the pile's idea at half size, the Longship a pile's 4+4, and the Ashlands ship - the biggest hull,
/// three times the Karve's mass - 6+6 (decided). Constants, because the answer is a balance call.
/// The rowers' seats follow: one per place, half on each side.
/// </summary>
private const int KarveMelee = 2, KarveRanged = 2;
private const int LongshipMelee = 4, LongshipRanged = 4;
private const int AshlandsMelee = 6, AshlandsRanged = 6;
public static int MeleeCapOf(Component ship) =>
IsKarve(ship) ? KarveMelee : IsAshlands(ship) ? AshlandsMelee : LongshipMelee;
public static int RangedCapOf(Component ship) =>
IsKarve(ship) ? KarveRanged : IsAshlands(ship) ? AshlandsRanged : LongshipRanged;
private static bool IsAshlands(Component ship)
{
return ship != null && ship.name.StartsWith(AshlandsName);
}
private static bool IsKarve(Component ship)
{
return ship != null && ship.name.StartsWith(KarveName);
}
public static bool IsKarveShip(Component ship) => IsKarve(ship);
/// <summary>Half the length of the hull, read from the OnboardTrigger every ship carries.</summary>
public static float HalfLengthOf(Component ship)
{
Transform trigger = ship != null ? ship.transform.Find("OnboardTrigger") : null;
BoxCollider box = trigger != null ? trigger.GetComponent<BoxCollider>() : null;
return box != null ? Mathf.Abs(box.size.z * trigger.localScale.z) * 0.5f : 0f;
}
/// <summary>Our prefab, the vanilla one it is cloned from, and the localisation key stem.</summary>
private struct Spec
{
public string Name;
public string Source;
public string KeyStem;
public Spec(string name, string source, string keyStem) { Name = name; Source = source; KeyStem = keyStem; }
}
private static readonly Spec[] Specs =
{
new Spec(KarveName, "Karve", "karve"),
new Spec(LongshipName, "VikingShip", "longship"),
new Spec(AshlandsName, "VikingShip_Ashlands", "ashlands"),
};
private static string DisplayKey(Spec s) => "$rov_piece_boneship_" + s.KeyStem + "_name";
private static string DescriptionKey(Spec s) => "$rov_piece_boneship_" + s.KeyStem + "_desc";
/// <summary>
/// What the oarsmen push with, as a share of what a perfect wind would. Wind direction and strength
/// no longer matter, so this is the whole sail. The vanilla factor is angle * lerp(0.25, 1, wind):
/// 1.0 is the best a real wind can ever do, and a good breeze on a good heading is about 0.7. Measured
/// on a Karve at Full: 0.46 gave 4.5 m/s. 0.75 is the proposal; to be tuned with an F8 at cruise.
/// </summary>
public const float SailK = 0.75f;
/// <summary>The key part of every bone ship's recipe: the swamp's Wishbone. One per ship.</summary>
private const string WishbonePrefab = "Wishbone";
/// <summary>
/// What each costs. The Wishbone is the decided part; the rest are PLACEHOLDERS that grow with the
/// hull, and the Ashlands one asks for the fine wood a late-game ship would. The workbench requirement
/// comes from the vanilla ship each one is cloned from. Open to every race: nothing here, or on the
/// pieces, asks who is building.
/// </summary>
private static RequirementConfig[] CostOf(string name)
{
switch (name)
{
case KarveName:
return new[]
{
new RequirementConfig(WishbonePrefab, 1, 0, true),
new RequirementConfig("Wood", 30, 0, true),
new RequirementConfig("BoneFragments", 60, 0, true),
new RequirementConfig("Resin", 10, 0, true),
};
case LongshipName:
return new[]
{
new RequirementConfig(WishbonePrefab, 1, 0, true),
new RequirementConfig("Wood", 60, 0, true),
new RequirementConfig("BoneFragments", 120, 0, true),
new RequirementConfig("Resin", 20, 0, true),
};
default: // the Ashlands one
return new[]
{
new RequirementConfig(WishbonePrefab, 1, 0, true),
new RequirementConfig("FineWood", 60, 0, true),
new RequirementConfig("BoneFragments", 200, 0, true),
new RequirementConfig("Resin", 30, 0, true),
};
}
}
/// <summary>Multiplied into the worn hull's colour: a touch darker and greener on top of the worn one.</summary>
private static readonly Color RotTint = new Color(0.80f, 0.82f, 0.72f, 1f);
public static bool IsBoneShip(Ship ship)
{
return ship != null && ship.GetComponent<BoneShipMarker>() != null;
}
public static void Register()
{
BoneShipArcher.Register();
foreach (Spec spec in Specs)
{
RegisterShip(spec);
}
}
private static void RegisterShip(Spec spec)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(spec.Name, spec.Source);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] Could not clone '{spec.Source}'; {spec.Name} is not registered.");
return;
}
prefab.AddComponent<BoneShipMarker>();
RotHull(prefab, spec.Name);
BoneShipSail.Apply(prefab, spec.Name);
// The roster (the altar's bookkeeping and the troops) and the fittings (bones and the altar
// itself, built when the ship is in the world). The roster registers its RPC in Awake.
prefab.AddComponent<BoneShipRoster>();
prefab.AddComponent<BoneShipFittings>();
prefab.AddComponent<BoneShipRowers>(); // the oarsmen; how many show is the roster's count
Piece piece = prefab.GetComponent<Piece>();
if (piece == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] The cloned '{spec.Source}' has no Piece; {spec.Name} is not registered.");
return;
}
piece.m_name = DisplayKey(spec);
piece.m_description = DescriptionKey(spec);
Sprite icon = BorrowIcon("TrophySkeleton");
if (icon != null) piece.m_icon = icon;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = DisplayKey(spec),
Description = DescriptionKey(spec),
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Misc,
CraftingStation = CraftingStations.Workbench,
Icon = icon,
Requirements = CostOf(spec.Name),
}));
}
/// <summary>
/// Worn hull from full health. Every vanilla ship keeps its three hull visuals where WearNTear can
/// name them - m_new, m_worn, m_broken - whatever the node path (Karve: ship/visual_new,
/// Longship and Ashlands: ship/visual/hull_new), so the clone's own fields are read instead of a
/// path per ship. The fresh one is on in the prefab and has to be switched off, or both would show.
/// </summary>
private static void RotHull(GameObject prefab, string name)
{
WearNTear wear = prefab.GetComponent<WearNTear>();
if (wear == null || wear.m_new == null || wear.m_worn == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] {name}: WearNTear has no new/worn hull to swap; the hull stays as it is.");
return;
}
GameObject fresh = wear.m_new;
GameObject worn = wear.m_worn;
if (fresh == worn) return;
wear.m_new = worn;
fresh.SetActive(false);
Tint(worn, RotTint);
}
/// <summary>
/// Darkens the Piece-shader materials of a hull. COPIES them, so the vanilla ship that shares the
/// asset keeps its colour; the water mask and anything without a plain colour are left alone.
/// </summary>
private static void Tint(GameObject root, Color tint)
{
Dictionary<Material, Material> copies = new Dictionary<Material, Material>();
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
Material[] shared = renderer.sharedMaterials;
bool changed = false;
for (int i = 0; i < shared.Length; i++)
{
Material source = shared[i];
if (source == null || source.shader == null) continue;
if (source.shader.name != "Custom/Piece" || !source.HasProperty("_Color")) continue;
Material copy;
if (!copies.TryGetValue(source, out copy))
{
copy = new Material(source) { name = source.name + "_bone" };
copy.SetColor("_Color", source.GetColor("_Color") * tint);
copies[source] = copy;
}
shared[i] = copy;
changed = true;
}
if (changed) renderer.sharedMaterials = shared;
}
}
public static void EnsureKnown(Player player)
{
if (player == null) return;
Traverse traverse = Traverse.Create(player);
bool any = false;
foreach (Spec spec in Specs)
{
GameObject prefab = PrefabManager.Instance.GetPrefab(spec.Name);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece == null) continue;
traverse.Method("AddKnownPiece", piece).GetValue();
any = true;
}
if (any) traverse.Method("UpdateAvailablePiecesList").GetValue();
}
private static Sprite BorrowIcon(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null
? drop.m_itemData.m_shared.m_icons
: null;
if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0];
Jotunn.Logger.LogWarning($"[BoneShip] Could not borrow the icon from '{prefabName}'.");
return null;
}
}
/// <summary>Marks a ship as one of ours. No logic: the patches below and the archers look for it.</summary>
public class BoneShipMarker : MonoBehaviour
{
}
/// <summary>
/// The oarsmen's push, in place of the wind's.
///
/// Ship.GetSailForce is, read off the IL: normalize(windDir + forward) * angleFactor * lerp(0.25, 1,
/// windIntensity) * m_sailForceFactor * sailSize, smoothed into m_sailForce over a second. The angle
/// factor is zero when the wind comes from ahead - that is what stops a vanilla ship dead. For a bone
/// ship the target is simply forward * m_sailForceFactor * sailSize * SailK, smoothed the same way with
/// the same two private fields, so the ship accelerates like a sailing one and the vanilla factor of
/// each hull (Karve 0.03, VikingShip 0.05, Ashlands 0.085) still scales the push.
///
/// sailSize is 0 below Half, 0.5 at Half and 1 at Full, so Slow and Back are untouched: they were
/// never the wind's.
/// </summary>
[HarmonyPatch(typeof(Ship), "GetSailForce")]
public static class BoneShipSailForcePatch
{
private static readonly FieldInfo SailForce = AccessTools.Field(typeof(Ship), "m_sailForce");
private static readonly FieldInfo WindChangeVelocity = AccessTools.Field(typeof(Ship), "m_windChangeVelocity");
public static bool Prefix(Ship __instance, float sailSize, ref Vector3 __result)
{
if (!BoneShip.IsBoneShip(__instance)) return true;
if (SailForce == null || WindChangeVelocity == null) return true; // changed under us: fall back to vanilla
Vector3 current = (Vector3)SailForce.GetValue(__instance);
Vector3 velocity = (Vector3)WindChangeVelocity.GetValue(__instance);
Vector3 target = __instance.transform.forward * (__instance.m_sailForceFactor * sailSize * BoneShip.SailK);
current = Vector3.SmoothDamp(current, target, ref velocity, 1f, 99f);
SailForce.SetValue(__instance, current);
WindChangeVelocity.SetValue(__instance, velocity);
__result = current;
return false;
}
}
/// <summary>
/// The sail never unfurls and the mast never turns to the wind: there is no sailing to show. Half and
/// Full would otherwise raise a sail that is meant to hang in rags. UpdateSail is what runs
/// UpdateSailSize (the furl animation) and then turns the mast, so skipping it skips both.
/// What the sail looks like left alone is for the game to show: the prefab's own pose.
/// </summary>
[HarmonyPatch(typeof(Ship), "UpdateSail")]
public static class BoneShipSailPatch
{
public static bool Prefix(Ship __instance)
{
return !BoneShip.IsBoneShip(__instance);
}
}
/// <summary>Makes the piece buildable without having to craft its parts first, like the bone pile.</summary>
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class BoneShipKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
BoneShip.EnsureKnown(__instance);
}
}
}

View file

@ -1,54 +0,0 @@
using UnityEngine;
using Jotunn.Managers;
namespace RacesOfValheim
{
/// <summary>
/// The archer a bone ship carries: the Bound Sentry, with the parts of it that make no sense on a deck
/// taken away and the ones that make it a ship's archer put in.
///
/// A PREFAB OF ITS OWN, not the sentry with a component added when it is spawned. A component added in
/// play is not saved: after a reload the archer would come back with no mount, and stand on nothing. This
/// one is built with ShipMount and ShipBust already on it, so a reloaded archer finds its ship again by the
/// id in its own ZDO (see ShipMount) and the roster, which counts archers by that id, never has to rebuild
/// one that was already there.
///
/// Taken away from the sentry:
/// - RaisedThrall. The orders (follow, wait, go home) are for troops; an archer on a mast of the ship
/// has no business following anyone, and E on it would send it after the player;
/// - CharacterDrop. The sentry gives back what it cost when it falls. This one is invulnerable while the
/// ship stands, and when the ship goes down it goes too - which must not pay out a soul stone and ten
/// bone fragments for every archer on every ship that sinks.
/// What stays is the bow, the AI and the tamed flag the spawner sets.
/// </summary>
public static class BoneShipArcher
{
public const string Name = "BoneShipArcher";
public static void Register()
{
// The sentry is registered by the bone pile, earlier in the same window.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(Name, SkeletonSentry.SentryName);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] Could not clone '{SkeletonSentry.SentryName}'; the ships have no archers.");
return;
}
foreach (RaisedThrall thrall in prefab.GetComponentsInChildren<RaisedThrall>(true))
{
if (thrall != null) Object.DestroyImmediate(thrall);
}
foreach (CharacterDrop drop in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drop != null) Object.DestroyImmediate(drop);
}
prefab.AddComponent<ShipMount>();
prefab.AddComponent<ShipBust>();
PrefabManager.Instance.AddPrefab(prefab);
}
}
}

View file

@ -1,572 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// What is bolted to a bone ship's hull: the bones along both rails and the bow, a few scattered on the
/// deck, and the ALTAR where bone fragments are offered (see BoneShipRoster).
///
/// Built when the ship comes into the world, on every client, and not baked into the prefab - because
/// the three hulls are different shapes (the Karve's nodes bear no relation to the Longship's, and the
/// Ashlands ship's rope nodes are in another axis altogether) and the only generic way to find "the rail"
/// and "the deck" on all of them is to ask the physics engine. So a ray is dropped from above at points
/// scanned inward from outside the hull; the first thing it lands on is the rail's top, and a ray down the
/// centre line lands on the deck. The mast, the sail and the ropes are skipped by NAME up the hierarchy,
/// because the boom of the Karve is a collider that spans the whole beam at six metres.
///
/// Everything is deterministic from the ship's own id, so every client builds the same bones.
///
/// The bones are borrowed models (ModelBorrow strips them to renderers) cached once as templates and
/// copied, so a ship coming into view is a few dozen cheap instantiates and not a few dozen strips.
/// The model names that are not certain to exist - the bigger bones - are tried in order and whatever
/// resolves is logged once.
/// </summary>
public class BoneShipFittings : MonoBehaviour
{
private const string SkullPrefab = "TrophySkeleton";
private const string FragmentsPrefab = "BoneFragments";
// The bigger bones along the rail. A pickable from the forest crypts: it is a pile of remains meant to
// be seen, and it is certain to exist (the earlier guesses - bone_stack, skull_pile, a ribcage item -
// never were). Kept as a list so a second model is one more entry.
private static readonly string[] LargeBonePrefabs = { "Pickable_ForestCryptRemains01" };
internal const float RayStartHeight = 14f;
private const float RayLength = 32f;
// The offering chest next to the cargo hatch. Both are tunable by eye: ChestSize is the borrowed chest's
// widest side in metres (the model is measured and fitted by ModelBorrow), ChestHeight the box that is
// clicked and where the skull sits.
private const string ChestPrefab = "piece_chest_wood";
private const float ChestSize = 0.85f;
private const float ChestHeight = 0.62f;
private static GameObject s_holder;
private static readonly Dictionary<string, GameObject> s_templates = new Dictionary<string, GameObject>();
private static bool s_reported;
/// <summary>Where the altar ended up, in the ship's space. The roster keeps its hover on this.</summary>
public Switch Altar { get; private set; }
/// <summary>One archer's place: where it stands on the ship (ship space) and whether it is a bust.</summary>
public struct ArcherPost
{
public Vector3 Local;
public bool Bust;
}
/// <summary>
/// Where the ship's archers stand, found by ray once the hull's colliders exist. Null until then; the
/// roster waits for it. The small ship has one, at the bow; the large ones a pair, bow and stern.
/// All are busts - only the chest and up shows, a figurehead that shoots.
/// </summary>
public List<ArcherPost> ArcherPosts { get; private set; }
private void Start()
{
StartCoroutine(Build());
}
private IEnumerator Build()
{
ZNetView nview = GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) yield break; // a placement ghost: no bones
// One physics step so the hull's colliders exist for the rays.
yield return new WaitForFixedUpdate();
yield return null;
Bounds hull;
if (!TryHullExtent(out hull))
{
Jotunn.Logger.LogWarning($"[BoneShip] '{name}' has no OnboardTrigger to measure; no bones were fitted.");
yield break;
}
ReportModels();
System.Random rng = new System.Random(nview.GetZDO().m_uid.GetHashCode());
float hx = hull.extents.x;
float hz = hull.extents.z;
int rays = 0;
int placed = 0;
// ---- both rails
int slots = Mathf.Max(4, Mathf.RoundToInt(2f * 0.92f * hz / 1.3f));
for (int side = -1; side <= 1; side += 2)
{
for (int i = 0; i < slots; i++)
{
float t = slots == 1 ? 0.5f : i / (float)(slots - 1);
float z = Mathf.Lerp(-0.92f * hz, 0.92f * hz, t) + Range(rng, -0.25f, 0.25f);
Vector3 point;
if (!FindRail(side, z, hx, out point, ref rays)) continue;
if (rays >= 40) { rays = 0; yield return null; }
if (PlaceOnRail(point, side, rng)) placed++;
}
}
// ---- the bow: a cluster on the centre line at the very front
Vector3 bow;
if (FindSurface(new Vector3(0f, RayStartHeight, 0.90f * hz), out bow))
{
for (int k = 0; k < 3; k++)
{
Vector3 p = bow + new Vector3(Range(rng, -0.35f, 0.35f), 0.02f, Range(rng, -0.35f, 0.15f));
if (Place(SkullPrefab, p, Range(rng, 0.30f, 0.42f), rng, 25f)) placed++;
}
}
// ---- loose on the deck
int scatter = Mathf.Max(5, slots / 2);
for (int k = 0; k < scatter; k++)
{
float x = Range(rng, -0.55f, 0.55f) * hx;
float z = Range(rng, -0.8f, 0.8f) * hz;
if (NearHatch(x, z)) continue; // keep the cargo hatch and the offering chest beside it clear
Vector3 point;
if (!FindSurface(new Vector3(x, RayStartHeight, z), out point)) continue;
if (Place(FragmentsPrefab, point + Vector3.up * 0.02f, Range(rng, 0.22f, 0.34f), rng, 180f)) placed++;
if (++rays >= 40) { rays = 0; yield return null; }
}
BuildAltar(hz, rng);
FindArcherPosts(hz);
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': {placed} bones fitted, altar {(Altar != null ? "built" : "not built")}, " +
$"{ArcherPosts.Count} archer post(s).");
}
// ---------------------------------------------------------------- the archers' posts
/// <summary>
/// Bow always; the large ships a second one at the stern. A point at the very tip of a hull is often
/// past the end of its colliders and the surface there climbs steeply, so any slope counts and, if
/// nothing is under the point, the search walks back toward the middle in 30 cm steps.
/// </summary>
private void FindArcherPosts(float hz)
{
ArcherPosts = new List<ArcherPost>();
AddPost(+0.93f * hz, -1f);
if (!BoneShip.IsKarveShip(this)) AddPost(-0.88f * hz, +1f);
}
private void AddPost(float z, float towardMiddle)
{
for (float back = 0f; back <= 2.4f; back += 0.3f)
{
Vector3 point;
if (!FindSurface(new Vector3(0f, RayStartHeight, z + towardMiddle * back), out point, -1f)) continue;
// A hand's breadth INTO the stem, not on top of it: the pelvis stub the bust leaves where the legs
// were then sits in the wood instead of resting on it, which is what made it look hung in air.
ArcherPosts.Add(new ArcherPost { Local = point + Vector3.down * 0.10f, Bust = true });
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': archer post at local ({point.x:F2}, {point.y:F2}, {point.z:F2}) " +
(back > 0f ? $"(walked back {back:F1} m from the tip)." : "(at the tip)."));
return;
}
Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no hull found for an archer at z {z:F1}; that post is empty.");
}
// ---------------------------------------------------------------- the altar
/// <summary>
/// The offering chest: a wooden chest standing on the deck NEXT TO THE CARGO HATCH. Every ship has
/// that hatch (the "piece_chest" Container, a flat square lid on the centre line: 0.9 m on the Karve,
/// 1.5 on the Longship, 1.8 on the Ashlands ship), so it is the one spot that is the same idea on all
/// three and the one a player already knows to look at. The first version put an altar of bones a
/// fixed distance down the centre line, which on the Karve is the stretch between the mast and the
/// helm, right where its rowers sit.
///
/// Candidate places are tried beside the hatch, then behind it, then in front, and a candidate is
/// taken only if the whole footprint of the chest lies on FLAT deck at the hatch's own height - five
/// rays, the centre and four points around it - and is clear of the mast. A Karve is narrow and its
/// hull closes in toward the bow, so beside the hatch is not always deck; the rays are what say so.
/// </summary>
private void BuildAltar(float hz, System.Random rng)
{
Vector3 spot;
string where;
if (!FindChestSpot(hz, out spot, out where))
{
Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no flat deck found for the offering chest; it was not built.");
return;
}
GameObject chest = new GameObject("BoneChest");
chest.transform.SetParent(transform, false);
chest.transform.localPosition = spot;
// Its front toward the stern, where the helm is and where a player stands when he looks around.
chest.transform.localRotation = Quaternion.Euler(0f, 180f, 0f);
chest.layer = LayerMask.NameToLayer("piece_nonsolid");
// The model: the wooden chest of the game, shut, with a skull on the lid so it reads as ours.
GameObject template = TemplateOf(ChestPrefab);
if (template != null)
{
GameObject model = Object.Instantiate(template, chest.transform, false);
model.name = ChestPrefab;
model.transform.localPosition = Vector3.zero;
model.transform.localScale = Vector3.one * ChestSize;
// A chest prefab carries both an open and a closed lid; the container switches them at run
// time and the copy has no container, so the open one is turned off here.
foreach (Transform node in model.GetComponentsInChildren<Transform>(true))
{
if (node != model.transform && node.name.ToLowerInvariant() == "open") node.gameObject.SetActive(false);
}
}
else
{
Jotunn.Logger.LogWarning($"[BoneShip] No '{ChestPrefab}' to borrow; the offering chest is a box of fragments instead.");
Place(FragmentsPrefab, chest.transform, new Vector3(0f, 0f, 0f), 0.45f, rng, 10f);
}
Place(SkullPrefab, chest.transform, new Vector3(0f, ChestHeight, 0f), 0.26f, rng, 8f);
BoxCollider box = chest.AddComponent<BoxCollider>();
box.center = new Vector3(0f, ChestHeight * 0.5f, 0f);
box.size = new Vector3(ChestSize * 0.95f, ChestHeight, ChestSize * 0.65f);
Switch sw = chest.AddComponent<Switch>();
sw.m_name = BoneShip.AltarName;
Altar = sw;
BoneShipRoster roster = GetComponent<BoneShipRoster>();
if (roster != null) roster.Bind(sw);
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': offering chest {where} the cargo hatch, at local " +
$"({spot.x:F2}, {spot.y:F2}, {spot.z:F2}).");
}
private bool FindChestSpot(float hz, out Vector3 spot, out string where)
{
spot = Vector3.zero;
where = "";
Transform hatch = transform.Find("piece_chest");
BoxCollider hatchBox = hatch != null ? hatch.GetComponent<BoxCollider>() : null;
if (hatch == null)
{
// A ship with no cargo hatch: the old rule, a fixed place down the centre line.
where = "(no hatch found, fixed spot behind the middle) of";
return FindSurface(new Vector3(0f, RayStartHeight, -0.42f * hz), out spot);
}
Vector3 centre = hatch.localPosition;
float half = hatchBox != null ? Mathf.Abs(hatchBox.size.x * hatch.localScale.x) * 0.5f : 0.6f;
float gap = half + ChestSize * 0.5f + 0.1f;
Vector3 hatchTop;
if (!FindSurface(new Vector3(centre.x, RayStartHeight, centre.z), out hatchTop)) return false;
float level = hatchTop.y;
// Beside first (the hatch is on the centre line, so beside is out toward a rail), then behind and
// in front. The mast is on the centre line too, and its collider is skipped by the ray, so it is
// kept away from by position.
Vector2[] offsets =
{
new Vector2(+gap, 0f), new Vector2(-gap, 0f), new Vector2(0f, -gap), new Vector2(0f, +gap),
};
string[] names = { "right of", "left of", "behind", "in front of" };
List<Vector2> masts = MastPositions();
for (int i = 0; i < offsets.Length; i++)
{
Vector2 c = new Vector2(centre.x + offsets[i].x, centre.z + offsets[i].y);
if (NearAny(masts, c, 0.7f)) continue;
if (!FlatDeckAround(c, level, ChestSize * 0.5f, out spot)) continue;
where = names[i];
return true;
}
return false;
}
/// <summary>
/// The chest's whole footprint is on deck: the centre and four points half a chest away all find a
/// surface that is flat and at the hatch's own height. Returns the centre's point.
/// </summary>
private bool FlatDeckAround(Vector2 c, float level, float reach, out Vector3 centre)
{
Vector2[] around = { Vector2.zero, new Vector2(reach, 0f), new Vector2(-reach, 0f), new Vector2(0f, reach), new Vector2(0f, -reach) };
centre = Vector3.zero;
for (int i = 0; i < around.Length; i++)
{
Vector3 p;
if (!FindSurface(new Vector3(c.x + around[i].x, RayStartHeight, c.y + around[i].y), out p, 0.85f)) return false;
if (Mathf.Abs(p.y - level) > 0.22f) return false;
if (i == 0) centre = p;
}
return true;
}
/// <summary>Within a couple of metres of the cargo hatch, on any side: where the chest will stand.</summary>
private bool NearHatch(float x, float z)
{
Transform hatch = transform.Find("piece_chest");
if (hatch == null) return false;
Vector2 d = new Vector2(x - hatch.localPosition.x, z - hatch.localPosition.z);
return d.sqrMagnitude < 2.2f * 2.2f;
}
private List<Vector2> MastPositions()
{
List<Vector2> masts = new List<Vector2>();
foreach (Transform t in GetComponentsInChildren<Transform>(true))
{
if (t == transform || t.name.ToLowerInvariant() != "mast") continue;
Vector3 local = transform.InverseTransformPoint(t.position);
masts.Add(new Vector2(local.x, local.z));
}
return masts;
}
private static bool NearAny(List<Vector2> points, Vector2 p, float distance)
{
foreach (Vector2 q in points)
{
if ((q - p).sqrMagnitude < distance * distance) return true;
}
return false;
}
// ---------------------------------------------------------------- placing
private bool PlaceOnRail(Vector3 point, int side, System.Random rng)
{
double roll = rng.NextDouble();
Vector3 up = point + Vector3.up * 0.02f;
if (roll < 0.38) return Place(SkullPrefab, up, Range(rng, 0.30f, 0.38f), rng, 14f);
if (roll < 0.70) return Place(FragmentsPrefab, up, Range(rng, 0.28f, 0.40f), rng, 180f);
if (roll < 0.88)
{
// The big ones lean outward over the side, like something draped there.
string large = LargestAvailable();
return Place(large ?? SkullPrefab, up + new Vector3(side * 0.05f, 0f, 0f), large != null ? Range(rng, 0.7f, 1.0f) : 0.42f, rng, 20f);
}
return false; // a gap, on purpose: a hull that is covered evenly looks decorated, not grown over
}
private bool Place(string prefabName, Vector3 localPosition, float size, System.Random rng, float tilt)
{
return Place(prefabName, transform, localPosition, size, rng, tilt);
}
private static bool Place(string prefabName, Transform parent, Vector3 localPosition, float size, System.Random rng, float tilt)
{
GameObject template = TemplateOf(prefabName);
if (template == null) return false;
GameObject copy = Object.Instantiate(template, parent, false);
copy.name = prefabName;
copy.transform.localPosition = localPosition;
copy.transform.localRotation = Quaternion.Euler(Range(rng, -tilt, tilt), (float)rng.NextDouble() * 360f, Range(rng, -tilt, tilt));
copy.transform.localScale = Vector3.one * size;
return true;
}
// ---------------------------------------------------------------- models
/// <summary>
/// One stripped, 1 m model per source prefab, kept under an inactive holder that survives scene loads.
/// Built on first use. The holder being inactive is what keeps the template from ever being drawn.
/// </summary>
private static GameObject TemplateOf(string prefabName)
{
GameObject cached;
if (s_templates.TryGetValue(prefabName, out cached)) return cached;
if (s_holder == null)
{
s_holder = new GameObject("RoV_BoneShipModels");
s_holder.SetActive(false);
Object.DontDestroyOnLoad(s_holder);
}
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
GameObject template = null;
if (source != null)
{
template = ModelBorrow.Attach(s_holder.transform, prefabName, source, Vector3.zero, Quaternion.identity, 1f, "BoneShip");
StripEffects(template);
}
s_templates[prefabName] = template;
return template;
}
/// <summary>
/// A dropped item is dressed to be seen from far away: sparkles, a glow, sometimes a light and a
/// sound. ModelBorrow removes everything that THINKS (scripts, colliders, bodies, the network
/// view) but a particle system or a light does not think, it just plays - so the first version of
/// the fittings lit every bone on the hull like a drop on the ground, and the whole ship glowed.
///
/// Only meshes are wanted. A node that carries an effect and no mesh goes with all its children;
/// otherwise just the effect components come off. A particle system cannot be removed while its
/// renderer is there, so the renderer goes first.
/// </summary>
internal static void StripEffects(GameObject template)
{
if (template == null) return;
foreach (ParticleSystem system in template.GetComponentsInChildren<ParticleSystem>(true))
{
if (system == null) continue;
GameObject node = system.gameObject;
if (node == template || node.GetComponent<MeshRenderer>() != null || node.GetComponent<SkinnedMeshRenderer>() != null)
{
ParticleSystemRenderer renderer = node.GetComponent<ParticleSystemRenderer>();
if (renderer != null) Object.DestroyImmediate(renderer);
Object.DestroyImmediate(system);
}
else
{
Object.DestroyImmediate(node);
}
}
foreach (Light light in template.GetComponentsInChildren<Light>(true))
{
if (light != null) Object.DestroyImmediate(light);
}
foreach (AudioSource audio in template.GetComponentsInChildren<AudioSource>(true))
{
if (audio != null) Object.DestroyImmediate(audio);
}
foreach (TrailRenderer trail in template.GetComponentsInChildren<TrailRenderer>(true))
{
if (trail != null) Object.DestroyImmediate(trail);
}
foreach (LineRenderer line in template.GetComponentsInChildren<LineRenderer>(true))
{
if (line != null) Object.DestroyImmediate(line);
}
}
private static string LargestAvailable()
{
foreach (string name in LargeBonePrefabs)
{
if (TemplateOf(name) != null) return name;
}
return null;
}
private static void ReportModels()
{
if (s_reported) return;
s_reported = true;
List<string> found = new List<string>();
List<string> missing = new List<string>();
foreach (string name in LargeBonePrefabs)
{
(TemplateOf(name) != null ? found : missing).Add(name);
}
Jotunn.Logger.LogInfo("[BoneShip] large bone models: found [" + string.Join(", ", found.ToArray()) +
"], missing [" + string.Join(", ", missing.ToArray()) + "].");
}
// ---------------------------------------------------------------- measuring
/// <summary>
/// The hull's footprint in the ship's own space, from the OnboardTrigger every ship has: the volume
/// the game uses to decide who is aboard is, by construction, about the hull.
/// </summary>
internal bool TryHullExtent(out Bounds bounds)
{
bounds = new Bounds();
Transform trigger = transform.Find("OnboardTrigger");
BoxCollider box = trigger != null ? trigger.GetComponent<BoxCollider>() : null;
if (box == null) return false;
Vector3 centre = transform.InverseTransformPoint(trigger.TransformPoint(box.center));
Vector3 size = Vector3.Scale(box.size, trigger.lossyScale) ;
size = new Vector3(Mathf.Abs(size.x), Mathf.Abs(size.y), Mathf.Abs(size.z));
bounds = new Bounds(centre, size);
return true;
}
/// <summary>
/// The top of the rail on one side at one z: scanned from outside the hull inward, the first ray that
/// lands on the ship is the outer edge of the rail.
/// </summary>
internal bool FindRail(int side, float z, float hx, out Vector3 point, ref int rays)
{
for (float x = 1.15f * hx; x > 0.3f * hx; x -= 0.12f)
{
rays++;
if (FindSurface(new Vector3(side * x, RayStartHeight, z), out point)) return true;
}
point = Vector3.zero;
return false;
}
/// <summary>
/// The highest solid surface of THIS ship under a local point, in local space. Triggers, and anything
/// whose name up the hierarchy says mast, sail, cloth or rope, are not the hull.
/// </summary>
internal bool FindSurface(Vector3 localOrigin, out Vector3 localPoint, float minUp = 0.2f)
{
Vector3 origin = transform.TransformPoint(localOrigin);
RaycastHit best = default(RaycastHit);
bool found = false;
float bestDistance = float.MaxValue;
foreach (RaycastHit hit in Physics.RaycastAll(origin, -transform.up, RayLength))
{
Collider collider = hit.collider;
if (collider == null || collider.isTrigger) continue;
if (!collider.transform.IsChildOf(transform)) continue;
if (Vector3.Dot(hit.normal, transform.up) < minUp) continue;
if (IsRigging(collider.transform)) continue;
if (hit.distance >= bestDistance) continue;
best = hit;
bestDistance = hit.distance;
found = true;
}
localPoint = found ? transform.InverseTransformPoint(best.point) : Vector3.zero;
return found;
}
private bool IsRigging(Transform t)
{
for (; t != null && t != transform; t = t.parent)
{
string n = t.name.ToLowerInvariant();
if (n.Contains("mast") || n.Contains("sail") || n.Contains("cloth") || n.Contains("rope")) return true;
}
return false;
}
private static float Range(System.Random rng, float min, float max)
{
return min + (float)rng.NextDouble() * (max - min);
}
}
}

View file

@ -1,709 +0,0 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The ship as a mobile bone pile. Skeleton_BoneShip.txt, sections 5.3-5.7.
///
/// Bone fragments are offered at the altar, twenty to a PLACE, and a place is paid for once and refills
/// itself for ever - exactly the bone pile's economy (SkeletonBonePileBehaviour), because it is the same
/// design: nothing is created or consumed when a skeleton falls, the place simply stands up again.
///
/// What is different is where the troops are. UNDERWAY they are DATA: a count per kind in the ship's own
/// ZDO ("aboard"), no creature, no AI, nothing to fall in the water. When the ship has been stopped for a
/// few seconds with land in reach they come ashore one at a time, real tamed skeletons that follow whoever
/// built the ship; when it moves off again, the ones that are following and close enough go back aboard,
/// one at a time, and become a number again.
///
/// The rest of the world is COUNTED, never tallied. A troop's ZDO carries the id of its ship; "how many
/// are out" is however many loaded troops carry it. A death, a despawn, a player killing his own
/// skeleton all correct themselves, as on the pile. The known price is the pile's too: a troop in an
/// unloaded zone is not counted, so its place can refill while it is away.
///
/// Troops are NOT bound to a point (no RaisedThrall anchor): a ship moves, and the anchor logic would
/// read the empty water it sailed from as a fallen station and wither them. They are bound to the ship by
/// id, and die with it. Only the owner of the ship's ZDO runs any of this.
/// </summary>
public class BoneShipRoster : MonoBehaviour
{
// ZDO keys, on the ship.
private const string KeyBones = "RoV_bshBones";
private const string KeySlotsMelee = "RoV_bshSlotsM";
private const string KeySlotsRanged = "RoV_bshSlotsR";
private const string KeyAboardMelee = "RoV_bshAbM";
private const string KeyAboardRanged = "RoV_bshAbR";
/// <summary>
/// Set when a troop that was told to go home boards a ship that is standing still: they have been
/// called back on purpose, so nobody should be sent straight out again. Cleared the moment the ship
/// moves, so the next stop lands the crew as usual.
/// </summary>
private const string KeyHold = "RoV_bshHold";
/// <summary>A recalled troop further than BoardRange but within this many metres is walked to the ship.</summary>
private const float RecallReach = 80f;
/// <summary>How many rowers should show: everyone aboard. Read by the rowers when they exist.</summary>
public const string KeyRowers = "RoV_bshRowers";
/// <summary>ZDO key on a TROOP: the id of the ship it belongs to.</summary>
public const string KeyShip = "RoV_bshShip";
// ─── Balance. Same numbers as the pile where the idea is the same. ───
private const float TickSeconds = 0.5f;
private const float DockedSeconds = 2.5f; // stopped this long before anyone comes ashore
private const float UnderwaySeconds = 1.0f; // moving this long before anyone goes back aboard
private const float StepSeconds = 0.8f; // one troop at a time, this far apart
private const float StillSpeed = 0.6f; // m/s: slower than this counts as stopped
private const float BoardRange = 20f; // decided with the orders: same as the pile's home check
private const float LandingBand = 10f; // how far past the hull to look for shore
private const float LandingMargin = 0.25f; // metres above the water for it to count as land
private ZNetView m_nview;
private Ship m_ship;
private Rigidbody m_body;
// The archers are not troops and are not counted with them: their own key, their own check.
private const float ArcherCheckSeconds = 2f;
private const float ArcherGraceSeconds = 4f; // a post whose registered archer is gone this long gets a new one
private float m_archerTimer;
private float[] m_postEmptyFor = new float[0];
private float m_stillTime;
private float m_movingTime;
private float m_stepTimer;
private float m_refillTimer;
private int m_deployIndex;
private bool m_toldNoShore;
private readonly List<Vector3> m_recentLandings = new List<Vector3>();
private void Awake()
{
m_nview = GetComponent<ZNetView>();
m_ship = GetComponent<Ship>();
m_body = GetComponent<Rigidbody>();
if (m_nview == null || m_nview.GetZDO() == null) return; // a placement ghost
m_nview.Register<string, int>("RoV_BshFeed", RPC_Feed);
WearNTear wear = GetComponent<WearNTear>();
if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed));
InvokeRepeating("Tick", 2f, TickSeconds);
}
/// <summary>The altar's Switch, once the fittings have built it.</summary>
public void Bind(Switch altar)
{
if (altar == null) return;
altar.m_onUse = OnUse;
altar.m_onHover = Hover;
}
// ---------------------------------------------------------------- interaction
// With an item in hand every outcome counts as handled, refusals included: false makes
// Humanoid.UseItem cover our own message with the generic one. Same as the pile.
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
return Use(user, item) || item != null;
}
private bool Use(Humanoid user, ItemDrop.ItemData item)
{
Player player = user as Player;
if (player == null || item == null) return false;
Inventory inventory = player.GetInventory();
if (inventory == null) return false;
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
if (prefabName != SkeletonBonePile.BonePrefab)
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
// Bone is measured in fragments, not places: what is left to buy, minus what is already part-paid
// towards the next place. Taken from the player only if the ship will actually keep it.
int room = (TotalCap() - PaidSlots()) * SkeletonBonePile.BonesPerSlot - m_nview.GetZDO().GetInt(KeyBones);
if (room <= 0)
{
player.Message(MessageHud.MessageType.Center, "$msg_itsfull");
return false;
}
int taken = Mathf.Min(Mathf.Max(1, item.m_stack), room);
player.Message(MessageHud.MessageType.Center, $"$msg_added {item.m_shared.m_name} x{taken}");
inventory.RemoveItem(item, taken);
m_nview.InvokeRPC("RoV_BshFeed", prefabName, taken);
return true;
}
private void RPC_Feed(long sender, string prefabName, int count)
{
if (!m_nview.IsOwner()) return;
if (prefabName != SkeletonBonePile.BonePrefab) return;
if (count < 1) count = 1;
int bones = m_nview.GetZDO().GetInt(KeyBones) + count;
// Melee places fill first, then the archers'. A loop, so a whole stack cannot overflow into bones
// that are never counted.
while (bones >= SkeletonBonePile.BonesPerSlot && PaidSlots() < TotalCap())
{
bones -= SkeletonBonePile.BonesPerSlot;
if (Slots(SkeletonBonePile.KindMelee) < MeleeCap()) SetSlots(SkeletonBonePile.KindMelee, Slots(SkeletonBonePile.KindMelee) + 1);
else SetSlots(SkeletonBonePile.KindRanged, Slots(SkeletonBonePile.KindRanged) + 1);
}
m_nview.GetZDO().Set(KeyBones, bones);
}
private string Hover()
{
int outM = CountDeployed(SkeletonBonePile.KindMelee);
int outR = CountDeployed(SkeletonBonePile.KindRanged);
int aboard = Aboard(SkeletonBonePile.KindMelee) + Aboard(SkeletonBonePile.KindRanged);
string body = ModText.Get("rov_hover_boneship_roster",
outM + Aboard(SkeletonBonePile.KindMelee), Slots(SkeletonBonePile.KindMelee), MeleeCap(),
outR + Aboard(SkeletonBonePile.KindRanged), Slots(SkeletonBonePile.KindRanged), RangedCap(),
aboard);
int bonesToward = m_nview.GetZDO().GetInt(KeyBones);
int placesLeft = TotalCap() - PaidSlots();
body += placesLeft > 0
? ModText.Get("rov_hover_skeleton_bone_toward_next_places", bonesToward, SkeletonBonePile.BonesPerSlot, placesLeft)
: ModText.Get("rov_hover_skeleton_every_place_bought");
if (m_refillTimer > 0f)
{
int left = Mathf.Max(1, Mathf.CeilToInt(SkeletonBonePile.RespawnSeconds - m_refillTimer));
body += ModText.Get("rov_hover_skeleton_next_rises_s", left);
}
body += ModText.Get("rov_hover_boneship_bone_hand");
return Localization.instance.Localize($"{BoneShip.AltarName} ({body})");
}
// ---------------------------------------------------------------- the tick
private void Tick()
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
if (m_ship == null) return;
Refill();
PublishRowers();
m_archerTimer += TickSeconds;
if (m_archerTimer >= ArcherCheckSeconds)
{
TickArchers(m_archerTimer);
m_archerTimer = 0f;
}
bool stopped = m_ship.GetSpeedSetting() == Ship.Speed.Stop &&
(m_body == null || m_body.velocity.magnitude < StillSpeed);
if (stopped)
{
m_stillTime += TickSeconds;
m_movingTime = 0f;
}
else
{
m_movingTime += TickSeconds;
m_stillTime = 0f;
m_toldNoShore = false;
m_recentLandings.Clear();
}
// Moving off ends any hold: the next stop lands the crew as usual.
if (!stopped && m_movingTime >= UnderwaySeconds && m_nview.GetZDO().GetBool(KeyHold, false))
{
m_nview.GetZDO().Set(KeyHold, false);
}
WalkRecalled();
m_stepTimer -= TickSeconds;
if (m_stepTimer > 0f) return;
// A troop sent home boards whether the ship is moving or not; the ones merely following only
// when it is underway. Whichever is first takes the step.
bool underway = !stopped && m_movingTime >= UnderwaySeconds;
string boarded = BoardOne(underway);
if (boarded != null)
{
m_stepTimer = StepSeconds;
// Anyone who boards while the ship is standing still came aboard on purpose - called back, or
// walked up the plank - and must not be sent straight out again. Held until the ship moves.
if (stopped) m_nview.GetZDO().Set(KeyHold, true);
return;
}
if (stopped && m_stillTime >= DockedSeconds && !m_nview.GetZDO().GetBool(KeyHold, false))
{
if (TryDeploy()) m_stepTimer = StepSeconds;
}
}
/// <summary>
/// A paid place with nobody in it - not aboard and not standing somewhere - fills after a while, as
/// the pile's does. Melee first. It fills ABOARD, so on a stopped ship it is then the next to come
/// ashore by the ordinary route.
/// </summary>
private void Refill()
{
string empty = FirstEmptyKind();
if (empty == null)
{
m_refillTimer = 0f;
return;
}
m_refillTimer += TickSeconds;
if (m_refillTimer < SkeletonBonePile.RespawnSeconds) return;
m_refillTimer = 0f;
SetAboard(empty, Aboard(empty) + 1);
}
private string FirstEmptyKind()
{
if (Slots(SkeletonBonePile.KindMelee) - CountDeployed(SkeletonBonePile.KindMelee) - Aboard(SkeletonBonePile.KindMelee) > 0)
return SkeletonBonePile.KindMelee;
if (Slots(SkeletonBonePile.KindRanged) - CountDeployed(SkeletonBonePile.KindRanged) - Aboard(SkeletonBonePile.KindRanged) > 0)
return SkeletonBonePile.KindRanged;
return null;
}
private void PublishRowers()
{
int rowers = Aboard(SkeletonBonePile.KindMelee) + Aboard(SkeletonBonePile.KindRanged);
if (m_nview.GetZDO().GetInt(KeyRowers, -1) != rowers) m_nview.GetZDO().Set(KeyRowers, rowers);
}
// ---------------------------------------------------------------- coming ashore
private bool TryDeploy()
{
int melee = Aboard(SkeletonBonePile.KindMelee);
int ranged = Aboard(SkeletonBonePile.KindRanged);
if (melee + ranged == 0) return false;
Vector3 landing;
if (!FindLanding(out landing))
{
// Open water or a cliff: they stay at the oars. Said once per stop, to whoever is looking.
if (!m_toldNoShore && Player.m_localPlayer != null &&
Vector3.Distance(Player.m_localPlayer.transform.position, transform.position) < 40f)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_boneship_no_shore"));
}
m_toldNoShore = true;
return false;
}
// Whichever kind has more waiting goes first, so the line comes ashore mixed, not all spears then all bows.
string kind = melee >= ranged ? SkeletonBonePile.KindMelee : SkeletonBonePile.KindRanged;
string prefabName = kind == SkeletonBonePile.KindRanged ? SkeletonBonePile.ThrallRangedName : SkeletonBonePile.ThrallMeleeName;
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] No '{prefabName}' in ZNetScene; nothing can come ashore.");
return false;
}
GameObject spawned = Instantiate(prefab, landing, Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f));
// Tamed, so it never turns on its master: the two calls RaisedThrall.Bind makes, without the anchor.
MonsterAI ai = spawned.GetComponent<MonsterAI>();
if (ai != null) ai.MakeTame();
Character character = spawned.GetComponent<Character>();
if (character != null) character.SetTamed(true);
ZNetView troopView = spawned.GetComponent<ZNetView>();
if (troopView != null && troopView.GetZDO() != null) troopView.GetZDO().Set(KeyShip, m_nview.GetZDO().m_uid);
// Out and following their master. NOT through RaisedThrall.SetFollowing: that refuses anyone who is
// not a Skeleton, and the ship is open to every race - a non-Skeleton's crew would come ashore, stand
// there, and never be able to come back aboard, because boarding is for the ones that follow. So the
// follow target is set directly, as the ship's own right.
Player master = Master();
if (ai != null && master != null) ai.SetFollowTarget(master.gameObject);
SetAboard(kind, Aboard(kind) - 1);
m_recentLandings.Add(landing);
if (m_recentLandings.Count > 12) m_recentLandings.RemoveAt(0);
return true;
}
/// <summary>
/// Dry land near the hull. Looks on rings around the ship, nearest first, from just past the hull out
/// to LandingBand metres beyond it; a point is land if the terrain there is above the water. The first
/// ring angle moves on with each troop, and a point near one already used is skipped, so they do not
/// all stack on one spot.
/// </summary>
private bool FindLanding(out Vector3 landing)
{
landing = Vector3.zero;
if (ZoneSystem.instance == null) return false;
float hull = Mathf.Max(BoneShip.HalfLengthOf(this), 4f);
float water = ZoneSystem.instance.m_waterLevel + LandingMargin;
for (float radius = hull + 1.5f; radius <= hull + 1.5f + LandingBand; radius += 1.5f)
{
for (int step = 0; step < 24; step++)
{
float angle = (m_deployIndex * 47f + step * 15f) * Mathf.Deg2Rad;
Vector3 point = transform.position + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * radius;
float ground = ZoneSystem.instance.GetGroundHeight(point);
if (ground < water) continue;
if (NearRecent(point)) continue;
landing = new Vector3(point.x, ground + 0.5f, point.z);
m_deployIndex++;
return true;
}
}
return false;
}
private bool NearRecent(Vector3 point)
{
foreach (Vector3 used in m_recentLandings)
{
Vector3 d = used - point;
d.y = 0f;
if (d.sqrMagnitude < 1.4f * 1.4f) return true;
}
return false;
}
// ---------------------------------------------------------------- going back aboard
/// <summary>
/// Takes ONE troop back aboard: it vanishes and the count goes up. Which: the nearest, within
/// BoardRange, that was SENT HOME (a "go home" order, the troop's RoV_bshRecall flag) - or, when the
/// ship is underway, that is following its master. Ones told to wait, and followers when the ship is
/// standing still, stay where they are: an outpost, still counted, still this ship's.
/// Returns "recalled" or "following" for what it took, null for nothing.
/// </summary>
private string BoardOne(bool underway)
{
Player master = Master();
Character nearest = null;
RaisedThrall nearestThrall = null;
bool nearestRecalled = false;
float best = BoardRange * BoardRange;
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
if (thrall == null) continue;
bool recalled = IsRecalled(character);
// A troop that follows its master and has WALKED ONTO THE DECK is aboard, whatever the ship is
// doing: standing about on the planks as a creature is not what a crew is. The first version
// only took followers once the ship was underway, so stepping off and back on left the crew
// standing on deck, never at the oars, until the ship moved.
bool followingMaster = master != null && thrall.IsFollowing(master);
bool following = followingMaster && (underway || OnDeck(character));
if (!recalled && !following) continue;
float distance = (character.transform.position - transform.position).sqrMagnitude;
if (distance >= best) continue;
best = distance;
nearest = character;
nearestThrall = thrall;
nearestRecalled = recalled;
}
if (nearest == null) return null;
string kind = nearestThrall.Kind == SkeletonBonePile.KindRanged ? SkeletonBonePile.KindRanged : SkeletonBonePile.KindMelee;
ZNetView troopView = nearest.GetComponent<ZNetView>();
if (troopView != null) troopView.ClaimOwnership(); // it may belong to another client's zone
ZNetScene.instance.Destroy(nearest.gameObject);
SetAboard(kind, Aboard(kind) + 1);
return nearestRecalled ? "recalled" : "following";
}
/// <summary>
/// A recalled troop out of boarding range walks to the ship: its patrol point is pinned on the ship
/// every tick, because the ship may be moving. Past RecallReach it is not chased - out of earshot.
/// </summary>
private void WalkRecalled()
{
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
if (!IsRecalled(character)) continue;
float distance = Vector3.Distance(character.transform.position, transform.position);
if (distance <= BoardRange || distance > RecallReach) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
if (thrall != null) thrall.WalkTo(transform.position);
}
}
/// <summary>Standing inside the hull's boarding volume: the same box the game uses to decide who is aboard.</summary>
private bool OnDeck(Character character)
{
BoneShipFittings fittings = GetComponent<BoneShipFittings>();
Bounds hull;
if (fittings == null || !fittings.TryHullExtent(out hull)) return false;
return hull.Contains(transform.InverseTransformPoint(character.transform.position));
}
private static bool IsRecalled(Character character)
{
ZNetView view = character.GetComponent<ZNetView>();
return view != null && view.GetZDO() != null && view.GetZDO().GetBool(RaisedThrall.KeyRecall, false);
}
// ---------------------------------------------------------------- the archers
/// <summary>
/// Keeps the ship's archers standing. Counted from the world, like the troops: a loaded archer
/// carrying this ship's id and a post number holds that post. A post nobody holds for a while gets a
/// new archer - not at once, because after a reload the ship is loaded a moment before the archers
/// that were standing on it, and spawning then would double them. A second archer found on a post
/// that is already held is removed.
/// </summary>
private void TickArchers(float elapsed)
{
BoneShipFittings fittings = GetComponent<BoneShipFittings>();
if (fittings == null || fittings.ArcherPosts == null) return; // the hull is not measured yet
int posts = fittings.ArcherPosts.Count;
if (m_postEmptyFor.Length != posts) m_postEmptyFor = new float[posts];
ZDO shipZdo = m_nview.GetZDO();
ZDOID mine = shipZdo.m_uid;
// ---- 1. the archers that are in the world now: adopt the first of each post, remove the rest.
//
// The ship keeps a REGISTER of who holds each post (its own ZDO, one id per post). The first
// version only counted the archers it could see and spawned one for any post it saw nobody on -
// and "can see" is only what is loaded, so a ship that woke before its archers did, or a post
// whose archer sat in a zone the owner had not loaded, got a second archer on top of the first,
// again at every reload. The register does not depend on what is loaded. Archers made before the
// register existed have no entry: the first found is adopted, the others are the duplicates.
foreach (Character character in Character.GetAllCharacters())
{
if (character == null) continue;
ZNetView view = character.GetComponent<ZNetView>();
if (view == null || view.GetZDO() == null) continue;
if (view.GetZDO().GetZDOID(ShipMount.KeyArcherShip) != mine) continue;
int post = view.GetZDO().GetInt(ShipMount.KeyArcherPost, -1);
if (post < 0 || post >= posts)
{
RemoveArcher(character, view, "a post this ship no longer has");
continue;
}
ZDOID registered = shipZdo.GetZDOID(SlotKey(post));
ZDOID self = view.GetZDO().m_uid;
if (registered == ZDOID.None) shipZdo.Set(SlotKey(post), self);
else if (registered != self) RemoveArcher(character, view, "a duplicate on post " + post);
}
// ---- 2. posts whose registered archer is gone: a new one, after a short grace.
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(BoneShipArcher.Name) : null;
for (int i = 0; i < posts; i++)
{
ZDOID registered = shipZdo.GetZDOID(SlotKey(i));
bool exists = registered != ZDOID.None && ZDOMan.instance != null && ZDOMan.instance.GetZDO(registered) != null;
if (exists)
{
m_postEmptyFor[i] = 0f;
continue;
}
m_postEmptyFor[i] += elapsed;
if (m_postEmptyFor[i] < ArcherGraceSeconds) continue;
m_postEmptyFor[i] = 0f;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] No '{BoneShipArcher.Name}' in ZNetScene; the ship has no archer at post {i}.");
continue;
}
SpawnArcher(prefab, i, fittings.ArcherPosts[i]);
}
}
private static string SlotKey(int post) => "RoV_bshArcher" + post;
private void RemoveArcher(Character character, ZNetView view, string why)
{
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': removing an archer - {why}.");
view.ClaimOwnership();
ZNetScene.instance.Destroy(character.gameObject);
}
private void SpawnArcher(GameObject prefab, int post, BoneShipFittings.ArcherPost at)
{
Vector3 world = transform.TransformPoint(at.Local);
GameObject archer = Instantiate(prefab, world, transform.rotation);
// The ship's id and the place on it go into the archer's own ZDO at once, before its mount first
// runs, so it knows where it stands from its first physics step - and again after any reload.
ZNetView view = archer.GetComponent<ZNetView>();
if (view != null && view.GetZDO() != null)
{
ZDO zdo = view.GetZDO();
zdo.Set(ShipMount.KeyArcherShip, m_nview.GetZDO().m_uid);
zdo.Set(ShipMount.KeyArcherPoint, at.Local);
zdo.Set(ShipMount.KeyArcherBust, at.Bust);
zdo.Set(ShipMount.KeyArcherPost, post);
// Signed into the ship's register straight away, so the very next check already knows.
m_nview.GetZDO().Set(SlotKey(post), zdo.m_uid);
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': archer raised on post {post} at local " +
$"({at.Local.x:F2}, {at.Local.y:F2}, {at.Local.z:F2}).");
}
// Tamed, so it never turns on whoever is aboard: the two calls the sentry's seed makes.
MonsterAI ai = archer.GetComponent<MonsterAI>();
if (ai != null) ai.MakeTame();
Character character = archer.GetComponent<Character>();
if (character != null) character.SetTamed(true);
}
// ---------------------------------------------------------------- the ship falls
/// <summary>
/// The ship going down takes its troops with it, those that are loaded. Same as the pile's immediate
/// off switch: a garrison that refills for free needs something that ends it. Any in an unloaded zone
/// outlive the ship - the known gap, noted in the design.
/// </summary>
private void OnDestroyed()
{
if (m_nview == null || !m_nview.IsOwner()) return;
int lost = 0;
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
if (thrall != null) thrall.Kill();
lost++;
}
// The archers go down with it as well; they are not counted among the troops that are lost.
ZDOID mine = m_nview.GetZDO().m_uid;
foreach (Character character in Character.GetAllCharacters())
{
if (character == null) continue;
ZNetView view = character.GetComponent<ZNetView>();
if (view == null || view.GetZDO() == null) continue;
if (view.GetZDO().GetZDOID(ShipMount.KeyArcherShip) != mine) continue;
view.ClaimOwnership();
ZNetScene.instance.Destroy(character.gameObject);
}
if (lost > 0 && Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_boneship_sunk", lost));
}
}
// ---------------------------------------------------------------- state
private Player Master()
{
Piece piece = GetComponent<Piece>();
long creator = piece != null ? piece.GetCreator() : 0L;
if (creator != 0L)
{
foreach (Player player in Player.GetAllPlayers())
{
if (player != null && player.GetPlayerID() == creator) return player;
}
}
// Its builder is not here: whoever is nearest, so a ship found abandoned is still crewed.
return Player.GetClosestPlayer(transform.position, 40f);
}
private bool BelongsHere(Character character)
{
ZNetView view = character.GetComponent<ZNetView>();
if (view == null || view.GetZDO() == null) return false;
return view.GetZDO().GetZDOID(KeyShip) == m_nview.GetZDO().m_uid;
}
private int CountDeployed(string kind)
{
int count = 0;
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
string troopKind = thrall != null && thrall.Kind == SkeletonBonePile.KindRanged
? SkeletonBonePile.KindRanged : SkeletonBonePile.KindMelee;
if (troopKind == kind) count++;
}
return count;
}
private int Slots(string kind) => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(kind == SkeletonBonePile.KindRanged ? KeySlotsRanged : KeySlotsMelee) : 0;
private void SetSlots(string kind, int value)
{
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(kind == SkeletonBonePile.KindRanged ? KeySlotsRanged : KeySlotsMelee, Mathf.Max(0, value));
}
private int Aboard(string kind) => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(kind == SkeletonBonePile.KindRanged ? KeyAboardRanged : KeyAboardMelee) : 0;
private void SetAboard(string kind, int value)
{
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(kind == SkeletonBonePile.KindRanged ? KeyAboardRanged : KeyAboardMelee, Mathf.Max(0, value));
}
private int PaidSlots() => Slots(SkeletonBonePile.KindMelee) + Slots(SkeletonBonePile.KindRanged);
private int MeleeCap() => BoneShip.MeleeCapOf(this);
private int RangedCap() => BoneShip.RangedCapOf(this);
private int TotalCap() => MeleeCap() + RangedCap();
}
}

View file

@ -1,480 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The oarsmen: skeletons seated at benches along both sides, pulling oars, who are the reason a ship
/// with no wind in its sail goes anywhere. Skeleton_BoneShip.txt, sections 1 and 3.4.
///
/// PURE SCENERY. There is no creature here: no Character, no AI, no network object. Each is a copy of the
/// skeleton's MODEL, and how many are visible is one number the roster keeps in the ship's own ZDO
/// (RoV_bshRowers = how many troops are aboard), so every client draws the same crew and they come
/// ashore one at a time exactly as the roster says. How hard they pull is the ship's own gear
/// (Stop, Slow, Half, Full, Back), which every client already has, so nothing here needs to be sent.
///
/// NOTHING TO REUSE: no ship in the game has oars (the dump found none), so the oars are built here too,
/// from two stretched cubes in the ship's own wood.
///
/// SEATED WITHOUT A SEATED ANIMATION. The model stands, but is lowered until its hips are at bench
/// height: the legs go down through the deck, which hides them from above, so what shows is a body sitting
/// at a bench. The same trick as the bust at the bow, and for the same reason - the model cannot be cut.
///
/// THE ARMS follow the oar. Each arm bone is turned, in world space, to point at its grip on the handle
/// (FromToRotation from where it points now to where the grip is), after the animator has posed it, so
/// nothing depends on the rig's local axes, which were never read. The bones are found by name (the rig is
/// Mixamo-style: LeftArm, LeftForeArm, LeftHand) and, when any is missing, the whole skeleton is logged
/// once so the names can be corrected; the crew then still sits and rocks, with arms at their sides.
///
/// THE STROKE. One shared phase per ship, all oars in time. The blade sweeps aft in the water (the pull,
/// the rower leans back and the handle comes toward his chest) and forward out of it (the recovery, the
/// blade lifted). The period follows the gear; Back runs it in reverse; Stop lets the oars settle level.
/// </summary>
public class BoneShipRowers : MonoBehaviour
{
// The model, and how big the oarsmen are.
private const string SkeletonPrefab = "Skeleton";
private const float ModelHeight = 1.7f;
// Where on the hull they sit, as fractions of the half length, from the stern forward. The Karve's
// are further apart because its helm and bow seats leave less room between.
// The Karve's front pair moved from +0.22 to -0.12 of the half length: the cargo hatch is at z = +1.3
// and the offering chest stands beside it, and a bench at +1.0 was in the way.
private static readonly float[] SmallSeatsZ = { -0.40f, -0.12f };
private static readonly float[] LargeSeatsZ = { -0.50f, -0.26f, -0.02f, 0.22f };
private const float SeatHeight = 0.47f; // hips above the deck: a bench and a little
private const float OarlockLift = 0.12f; // oarlock above the rail's top
private const float OarInboard = 0.75f; // handle end, from the oarlock
private const float OarOutboard = 1.70f; // blade end
// The stroke.
private const float SweepMax = 0.45f; // radians, blade fore and aft
private const float LiftMax = 0.35f; // radians, blade up on the recovery
private const float LeanMax = 14f; // degrees, rower back and forth
private const float PeriodSlow = 2.6f;
private const float PeriodHalf = 1.9f;
private const float PeriodFull = 1.3f;
private class Seat
{
public GameObject Root; // at the hips, in the ship's space
public GameObject Bench;
public Transform Lean; // rotates about the hips
public Transform Oar;
public int Side; // +1 right, -1 left
public Vector3 Oarlock; // ship space
public Transform LeftArm, LeftFore, LeftHand, RightArm, RightFore, RightHand;
}
private readonly List<Seat> m_seats = new List<Seat>();
private ZNetView m_nview;
private Ship m_ship;
private float m_phase;
private float m_amplitude;
private bool m_built;
private static GameObject s_holder;
private static GameObject s_template;
private static bool s_templateTried;
private static Mesh s_cube;
private static bool s_loggedBones;
private void Start()
{
m_nview = GetComponent<ZNetView>();
m_ship = GetComponent<Ship>();
if (m_nview == null || !m_nview.IsValid()) return; // a placement ghost
StartCoroutine(Build());
}
// ---------------------------------------------------------------- building
private IEnumerator Build()
{
// The fittings measure the hull the same way, a physics step after the ship exists.
yield return new WaitForFixedUpdate();
yield return null;
yield return null;
BoneShipFittings fittings = GetComponent<BoneShipFittings>();
Bounds hull;
if (fittings == null || !fittings.TryHullExtent(out hull))
{
Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no hull to seat rowers on.");
yield break;
}
GameObject template = Template();
if (template == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] No '{SkeletonPrefab}' model; '{name}' has no rowers.");
yield break;
}
float hx = hull.extents.x;
float hz = hull.extents.z;
float[] zs = SeatStations((BoneShip.MeleeCapOf(this) + BoneShip.RangedCapOf(this)) / 2);
Material wood = FindWood();
int rays = 0;
for (int side = -1; side <= 1; side += 2)
{
foreach (float f in zs)
{
float z = f * hz;
Vector3 rail;
if (!fittings.FindRail(side, z, hx, out rail, ref rays)) continue;
float seatX = side * Mathf.Max(0.45f, Mathf.Abs(rail.x) - 0.55f);
Vector3 deck;
if (!fittings.FindSurface(new Vector3(seatX, BoneShipFittings.RayStartHeight, z), out deck)) continue;
m_seats.Add(MakeSeat(template, wood, side, deck, rail, z));
if (++rays >= 30) { rays = 0; yield return null; }
}
}
// Fill order: both sides at each station, from the bow back, so a short crew is balanced.
m_seats.Sort((a, b) =>
{
int byStation = b.Root.transform.localPosition.z.CompareTo(a.Root.transform.localPosition.z);
return byStation != 0 ? byStation : a.Side.CompareTo(b.Side);
});
m_built = true;
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': {m_seats.Count} rowers' seats built.");
}
/// <summary>
/// Where along the hull the benches go, for this many on each side: the hand-placed lists where they
/// were tuned (two on the Karve, four on the Longship), an even spread from the stern forward for any
/// other number - the Ashlands ship has six a side.
/// </summary>
private static float[] SeatStations(int perSide)
{
if (perSide == SmallSeatsZ.Length) return SmallSeatsZ;
if (perSide == LargeSeatsZ.Length) return LargeSeatsZ;
float[] stations = new float[perSide];
for (int i = 0; i < perSide; i++)
{
float t = perSide == 1 ? 0.5f : i / (float)(perSide - 1);
stations[i] = Mathf.Lerp(-0.52f, 0.24f, t);
}
return stations;
}
private Seat MakeSeat(GameObject template, Material wood, int side, Vector3 deck, Vector3 rail, float z)
{
Seat seat = new Seat { Side = side };
// The hips, at bench height above the deck.
GameObject root = new GameObject("Rower");
root.transform.SetParent(transform, false);
root.transform.localPosition = deck + Vector3.up * SeatHeight;
seat.Root = root;
GameObject lean = new GameObject("Lean");
lean.transform.SetParent(root.transform, false);
seat.Lean = lean.transform;
// Facing the stern, as an oarsman does. The model's own front turned out to be the OTHER way from
// what a 180 degree turn assumed - the first build had the crew looking at the bow - so it is
// left as it comes: no turn.
GameObject model = Instantiate(template, lean.transform, false);
model.name = "model";
model.transform.localRotation = Quaternion.identity;
model.transform.localScale = Vector3.one * (ModelHeight / 1.8f);
model.SetActive(true);
Animator animator = model.GetComponentInChildren<Animator>(true);
if (animator != null)
{
// The idle clip fires animation events at a receiver the strip removed: unanswered, each
// one logs an error. Switched off, the clip still poses the body.
animator.fireEvents = false;
animator.applyRootMotion = false;
}
FindBones(model.transform, seat);
SeatHips(model.transform, lean.transform, seat);
// A bench, across the beam, so nobody sits on nothing.
GameObject bench = MakeBox("Bench", transform, wood, new Vector3(0.85f, 0.07f, 0.34f));
bench.transform.localPosition = new Vector3(deck.x, deck.y + SeatHeight - 0.09f, z);
// The oar: pivot at the oarlock on the rail, a shaft and a blade along its own +z (outboard).
seat.Oarlock = new Vector3(rail.x, rail.y + OarlockLift, z);
GameObject oar = new GameObject("Oar");
oar.transform.SetParent(transform, false);
oar.transform.localPosition = seat.Oarlock;
seat.Oar = oar.transform;
float length = OarInboard + OarOutboard;
GameObject shaft = MakeBox("Shaft", oar.transform, wood, new Vector3(0.07f, 0.07f, length));
shaft.transform.localPosition = new Vector3(0f, 0f, (OarOutboard - OarInboard) * 0.5f);
GameObject blade = MakeBox("Blade", oar.transform, wood, new Vector3(0.20f, 0.03f, 0.55f));
blade.transform.localPosition = new Vector3(0f, 0f, OarOutboard - 0.27f);
root.SetActive(false);
oar.SetActive(false);
bench.SetActive(false);
seat.Root = root;
seat.Bench = bench;
return seat;
}
/// <summary>Moves the model so its hips sit on the lean pivot - or, if no hips are found, by height.</summary>
private static void SeatHips(Transform model, Transform pivot, Seat seat)
{
Transform hips = Find(model, "hips") ?? Find(model, "pelvis");
if (hips != null)
{
Vector3 hipsInPivot = pivot.InverseTransformPoint(hips.position);
model.localPosition -= hipsInPivot;
}
else
{
model.localPosition = new Vector3(0f, -0.95f * (ModelHeight / 1.8f), 0f);
}
}
// ---------------------------------------------------------------- the stroke
private void Update()
{
if (!m_built || m_ship == null || m_nview == null || !m_nview.IsValid()) return;
int crew = m_nview.GetZDO().GetInt(BoneShipRoster.KeyRowers, 0);
Ship.Speed gear = m_ship.GetSpeedSetting();
float period = gear == Ship.Speed.Full ? PeriodFull : gear == Ship.Speed.Half ? PeriodHalf : PeriodSlow;
bool rowing = gear != Ship.Speed.Stop && (crew > 0);
m_amplitude = Mathf.MoveTowards(m_amplitude, rowing ? 1f : 0f, Time.deltaTime * 1.5f);
if (rowing) m_phase = Mathf.Repeat(m_phase + Time.deltaTime / period * (gear == Ship.Speed.Back ? -1f : 1f), 1f);
float twoPi = Mathf.PI * 2f;
float sweep = -Mathf.Cos(twoPi * m_phase); // forward extreme at 0, aft at 0.5
float recovery = Mathf.Clamp01(-Mathf.Sin(twoPi * m_phase) * 2f); // 1 mid-recovery, 0 in the water
recovery = recovery * recovery * (3f - 2f * recovery);
float lift = Mathf.Lerp(-0.08f, LiftMax, recovery);
float lean = LeanMax * sweep;
for (int i = 0; i < m_seats.Count; i++)
{
Seat seat = m_seats[i];
bool shown = i < crew;
seat.Root.SetActive(shown);
seat.Oar.gameObject.SetActive(shown);
seat.Bench.SetActive(shown);
if (!shown) continue;
float psi = SweepMax * sweep * m_amplitude;
float lam = Mathf.Lerp(0.10f, lift, m_amplitude);
// The oar's outboard direction in the ship's space: out across the beam, a little fore or
// aft with the sweep (positive aft), and tilted up by the lift.
Vector3 outward = new Vector3(seat.Side * Mathf.Cos(psi) * Mathf.Cos(lam),
Mathf.Sin(lam),
-Mathf.Sin(psi) * Mathf.Cos(lam));
seat.Oar.localRotation = Quaternion.LookRotation(outward, Vector3.up);
seat.Lean.localRotation = Quaternion.AngleAxis(lean * m_amplitude, Vector3.right);
}
}
/// <summary>After the animator: the arms reach for the handle.</summary>
private void LateUpdate()
{
if (!m_built) return;
foreach (Seat seat in m_seats)
{
if (!seat.Root.activeSelf) continue;
// Two grips on the handle, near and far from the chest.
Vector3 gripNear = seat.Oar.TransformPoint(0f, 0f, -OarInboard * 0.55f);
Vector3 gripFar = seat.Oar.TransformPoint(0f, 0f, -OarInboard * 0.15f);
Reach(seat.LeftArm, seat.LeftFore, gripNear);
Reach(seat.LeftFore, seat.LeftHand, gripNear);
Reach(seat.RightArm, seat.RightFore, gripFar);
Reach(seat.RightFore, seat.RightHand, gripFar);
}
}
/// <summary>Turns a bone, in world space, so the line to its child points at the target.</summary>
private static void Reach(Transform bone, Transform child, Vector3 target)
{
if (bone == null || child == null) return;
Vector3 now = child.position - bone.position;
Vector3 want = target - bone.position;
if (now.sqrMagnitude < 1e-6f || want.sqrMagnitude < 1e-6f) return;
bone.rotation = Quaternion.FromToRotation(now, want) * bone.rotation;
}
// ---------------------------------------------------------------- bones
private static void FindBones(Transform model, Seat seat)
{
seat.LeftArm = Find(model, "leftarm");
seat.LeftFore = Find(model, "leftforearm");
seat.LeftHand = Find(model, "lefthand");
seat.RightArm = Find(model, "rightarm");
seat.RightFore = Find(model, "rightforearm");
seat.RightHand = Find(model, "righthand");
if (seat.LeftArm != null && seat.LeftFore != null && seat.LeftHand != null &&
seat.RightArm != null && seat.RightFore != null && seat.RightHand != null) return;
if (s_loggedBones) return;
s_loggedBones = true;
List<string> names = new List<string>();
foreach (Transform t in model.GetComponentsInChildren<Transform>(true)) names.Add(t.name);
Jotunn.Logger.LogWarning("[BoneShip] The rowers' arm bones were not all found by name; they will hang at " +
"their sides. Skeleton: " + string.Join(", ", names.ToArray()));
}
/// <summary>A bone by name, ignoring case and any "mixamorig:"-style prefix.</summary>
private static Transform Find(Transform root, string lowerName)
{
foreach (Transform t in root.GetComponentsInChildren<Transform>(true))
{
string n = t.name.ToLowerInvariant();
int colon = n.LastIndexOf(':');
if (colon >= 0) n = n.Substring(colon + 1);
if (n == lowerName) return t;
}
return null;
}
// ---------------------------------------------------------------- model, wood, boxes
/// <summary>
/// The skeleton's model with nothing that acts. Instantiated into an INACTIVE holder, so nothing wakes,
/// and then stripped in DEPENDENCY order: ModelBorrow's one pass is not safe on a creature, because
/// Unity refuses to remove a component another one requires - Humanoid under CharacterDrop - and the
/// Humanoid it leaves behind is a live creature. The Hive taught that: it broke the hammer for every
/// piece in the game. So each pass removes only what nothing still present requires, and passes repeat.
/// </summary>
private static GameObject Template()
{
if (s_templateTried) return s_template;
s_templateTried = true;
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(SkeletonPrefab);
if (source == null) return null;
s_holder = new GameObject("RoV_BoneShipRowers");
s_holder.SetActive(false);
Object.DontDestroyOnLoad(s_holder);
GameObject copy = Object.Instantiate(source, s_holder.transform);
copy.name = "RowerTemplate";
StripBehaviours(copy);
foreach (Rigidbody body in copy.GetComponentsInChildren<Rigidbody>(true)) if (body != null) Object.DestroyImmediate(body);
foreach (Collider collider in copy.GetComponentsInChildren<Collider>(true)) if (collider != null) Object.DestroyImmediate(collider);
BoneShipFittings.StripEffects(copy);
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
copy.transform.localScale = Vector3.one;
s_template = copy;
return s_template;
}
private static void StripBehaviours(GameObject root)
{
for (int pass = 0; pass < 12; pass++)
{
bool any = false;
bool removed = false;
foreach (MonoBehaviour behaviour in root.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour == null) continue;
any = true;
if (RequiredByAnother(behaviour)) continue;
Object.DestroyImmediate(behaviour);
removed = true;
}
if (!any) return;
if (!removed) break;
}
int left = 0;
foreach (MonoBehaviour behaviour in root.GetComponentsInChildren<MonoBehaviour>(true)) if (behaviour != null) left++;
if (left > 0) Jotunn.Logger.LogWarning($"[BoneShip] {left} component(s) of the rower model could not be removed.");
}
private static bool RequiredByAnother(MonoBehaviour behaviour)
{
System.Type type = behaviour.GetType();
foreach (Component other in behaviour.GetComponents<Component>())
{
if (other == null || other == behaviour) continue;
foreach (object attribute in other.GetType().GetCustomAttributes(typeof(RequireComponent), true))
{
RequireComponent need = (RequireComponent)attribute;
if (Needs(need.m_Type0, type) || Needs(need.m_Type1, type) || Needs(need.m_Type2, type)) return true;
}
}
return false;
}
private static bool Needs(System.Type required, System.Type type)
{
return required != null && required.IsAssignableFrom(type);
}
/// <summary>The ship's own rotten wood, so the oars and benches match: the first Piece-shader material on it.</summary>
private Material FindWood()
{
foreach (Renderer renderer in GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer || renderer is LineRenderer) continue;
foreach (Material material in renderer.sharedMaterials)
{
if (material != null && material.shader != null && material.shader.name == "Custom/Piece") return material;
}
}
return null;
}
private static GameObject MakeBox(string name, Transform parent, Material material, Vector3 size)
{
if (s_cube == null)
{
GameObject primitive = GameObject.CreatePrimitive(PrimitiveType.Cube);
s_cube = primitive.GetComponent<MeshFilter>().sharedMesh;
Object.Destroy(primitive);
}
GameObject box = new GameObject(name);
box.transform.SetParent(parent, false);
box.transform.localScale = size;
box.AddComponent<MeshFilter>().sharedMesh = s_cube;
MeshRenderer renderer = box.AddComponent<MeshRenderer>();
if (material != null) renderer.sharedMaterial = material;
return box;
}
}
}

View file

@ -1,178 +0,0 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The bone ships' sails: black, and torn.
///
/// Every vanilla sail is a Custom/Vegetation material - an alpha-cutout shader (it has a _Cutoff of
/// 0.5) - so a hole is simply a texel whose alpha is under that. Nothing is imported: the texture is
/// drawn here in code, one per source material (sail_white on the Karve, sail and sail_brown on the
/// Longship, ashlandshipsail_mat on the Ashlands ship), and goes onto a COPY of the material so the
/// vanilla ships keep theirs.
///
/// The holes come from value noise, not a drawing, because the sail's UV layout was not read. Two
/// scales: broad tears, and small shreds, with the top and bottom edges frayed. Whether the shader
/// actually clips on that alpha is the one thing only the game can confirm.
/// </summary>
public static class BoneShipSail
{
private const int Size = 256;
// The big tears: a share of the sail, roughly. Higher threshold = fewer, smaller holes.
private const float TearThreshold = 0.62f;
private const float ShredThreshold = 0.70f;
public static void Apply(GameObject prefab, string shipName)
{
Dictionary<Material, Material> copies = new Dictionary<Material, Material>();
int seed = shipName.GetHashCode();
foreach (Renderer renderer in prefab.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer || renderer is LineRenderer) continue;
Material[] shared = renderer.sharedMaterials;
bool changed = false;
for (int i = 0; i < shared.Length; i++)
{
Material source = shared[i];
if (!IsSail(source)) continue;
Material copy;
if (!copies.TryGetValue(source, out copy))
{
copy = new Material(source) { name = source.name + "_bone" };
copy.SetTexture("_MainTex", Draw(seed + source.name.GetHashCode()));
copy.SetColor("_Color", Color.white);
copies[source] = copy;
}
shared[i] = copy;
changed = true;
}
if (changed) renderer.sharedMaterials = shared;
}
if (copies.Count == 0)
{
Jotunn.Logger.LogWarning($"[BoneShip] {shipName}: no sail material found, the sail is left as it is.");
}
}
private static bool IsSail(Material material)
{
if (material == null || material.shader == null) return false;
if (!material.HasProperty("_MainTex")) return false;
string name = material.name.ToLowerInvariant();
return name.Contains("sail");
}
// ---------------------------------------------------------------- the texture
private static Texture2D Draw(int seed)
{
Texture2D texture = new Texture2D(Size, Size, TextureFormat.RGBA32, true)
{
name = "boneship_sail",
wrapMode = TextureWrapMode.Clamp,
filterMode = FilterMode.Bilinear,
};
Color32[] pixels = new Color32[Size * Size];
for (int y = 0; y < Size; y++)
{
float v = (y + 0.5f) / Size;
for (int x = 0; x < Size; x++)
{
float u = (x + 0.5f) / Size;
pixels[y * Size + x] = Pixel(u, v, seed);
}
}
texture.SetPixels32(pixels);
texture.Apply(true, false);
return texture;
}
private static Color32 Pixel(float u, float v, int seed)
{
// Cloth: near black, mottled, with a faint warp of vertical streaks.
float mottle = Fbm(u * 7f, v * 7f, seed + 3);
float streak = 0.5f + 0.5f * Mathf.Sin(u * 90f + Fbm(u * 3f, v * 3f, seed + 5) * 6f);
float shade = Mathf.Lerp(0.04f, 0.17f, mottle) * Mathf.Lerp(0.85f, 1.05f, streak);
Color cloth = new Color(shade * 1.00f, shade * 0.97f, shade * 0.93f, 1f);
// Holes. Each term is an alpha with 0.5 at its own edge; the lowest wins.
float tear = Fbm(u * 4f, v * 4f, seed + 11);
float shred = Fbm(u * 13f, v * 13f, seed + 29);
float alpha = 1f;
alpha = Mathf.Min(alpha, 0.5f + (TearThreshold - tear) * 14f);
alpha = Mathf.Min(alpha, 0.5f + (ShredThreshold - shred) * 14f);
// Fringe: the top and bottom edges are eaten away in ragged teeth, the sides a little.
float edge = Mathf.Min(v, 1f - v);
float teeth = ValueNoise(u * 22f, v * 3f, seed + 41);
alpha = Mathf.Min(alpha, 0.5f + (teeth * 0.16f - edge) * 28f);
float side = Mathf.Min(u, 1f - u);
float sideTeeth = ValueNoise(u * 3f, v * 20f, seed + 53);
alpha = Mathf.Min(alpha, 0.5f + (sideTeeth * 0.07f - side) * 28f);
// Scorched round the holes: darker where the tear is nearly through.
float burn = Mathf.Clamp01((tear - (TearThreshold - 0.10f)) * 8f);
cloth = Color.Lerp(cloth, new Color(0.015f, 0.015f, 0.015f, 1f), burn * 0.8f);
cloth.a = Mathf.Clamp01(alpha);
return cloth;
}
// ---------------------------------------------------------------- noise
private static float Hash(int x, int y, int seed)
{
unchecked
{
int h = x * 374761393 + y * 668265263 + seed * 1442695041;
h = (h ^ (h >> 13)) * 1274126177;
return ((h ^ (h >> 16)) & 0xffff) / 65535f;
}
}
private static float ValueNoise(float x, float y, int seed)
{
int xi = Mathf.FloorToInt(x);
int yi = Mathf.FloorToInt(y);
float tx = x - xi;
float ty = y - yi;
tx = tx * tx * (3f - 2f * tx);
ty = ty * ty * (3f - 2f * ty);
float a = Hash(xi, yi, seed);
float b = Hash(xi + 1, yi, seed);
float c = Hash(xi, yi + 1, seed);
float d = Hash(xi + 1, yi + 1, seed);
return Mathf.Lerp(Mathf.Lerp(a, b, tx), Mathf.Lerp(c, d, tx), ty);
}
private static float Fbm(float x, float y, int seed)
{
float value = 0f;
float amplitude = 0.5f;
for (int octave = 0; octave < 4; octave++)
{
value += amplitude * ValueNoise(x, y, seed + octave * 17);
x *= 2.03f;
y *= 2.03f;
amplitude *= 0.5f;
}
return value / 0.9375f; // 0.5 + 0.25 + 0.125 + 0.0625, so the sum stays in 0..1
}
}
}

View file

@ -1,392 +0,0 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Holds a creature to one spot of a ship's deck, however the ship moves.
///
/// The Bone Ship's archers (Skeleton_BoneShip.txt, section 6) are the Bound Sentry - a tamed archer
/// whose speeds are all zero - and zero speed alone does not keep a Character on a moving deck: it
/// is carried only as far as the game's own ground-body inheritance happens to carry it. So each
/// physics step the mount sets its position to the ship's local point and its velocity to the ship's
/// velocity at that point. Rotation is left to the archer: it turns to face what it shoots.
///
/// Runs on the OWNER of the archer only; everyone else sees the result through the creature's own
/// ZSyncTransform.
///
/// TWO WAYS TO KNOW THE SHIP. The F7 experiment sets Ship and LocalPoint directly and the mount does not
/// survive a reload (an archer that wakes without its ship is removed). The real archers are a prefab
/// of their own (BoneShipArcher) that carries this component from the start, and know their ship by its
/// id in their own ZDO: after a reload the ship is looked up again as soon as it is loaded. If the ship's
/// ZDO is gone altogether for a few seconds, the ship has sunk, and the archer goes with it - "it dies
/// with the ship", with nothing to remember.
/// </summary>
public class ShipMount : MonoBehaviour
{
/// <summary>ZDO keys on a ship's ARCHER: the ship it guards, and where it stands on it.</summary>
public const string KeyArcherShip = "RoV_bshArcherShip";
public const string KeyArcherPoint = "RoV_bshArcherPoint";
public const string KeyArcherBust = "RoV_bshArcherBust";
public const string KeyArcherPost = "RoV_bshArcherPost";
/// <summary>Seconds without the ship's ZDO before the archer decides the ship is gone.</summary>
private const float GoneAfter = 6f;
/// <summary>The ship this creature is bolted to.</summary>
public Ship Ship;
/// <summary>Where on that ship, in the ship's own space.</summary>
public Vector3 LocalPoint;
private ZNetView m_nview;
private Rigidbody m_body;
private Rigidbody m_shipBody;
private ZDOID m_shipId = ZDOID.None;
private bool m_byId;
private float m_missing;
private float m_nextResolve;
private void Awake()
{
m_nview = GetComponent<ZNetView>();
m_body = GetComponent<Rigidbody>();
// No interpolation on the archer's own body: the transform is set by hand every frame in
// LateUpdate, and a body that interpolates between physics steps would fight that and put back
// the very stutter this exists to remove.
if (m_body != null) m_body.interpolation = RigidbodyInterpolation.None;
}
private void Start()
{
if (Ship != null) { IgnoreShipColliders(); return; }
// The real archers: the ship is a number in their own ZDO. Read on EVERY client, not just the
// owner, because every client pins the visual to the ship (LateUpdate).
if (m_nview == null || !m_nview.IsValid()) return;
m_shipId = m_nview.GetZDO().GetZDOID(KeyArcherShip);
if (m_shipId == ZDOID.None) return;
LocalPoint = m_nview.GetZDO().GetVec3(KeyArcherPoint, Vector3.zero);
m_byId = true;
}
/// <summary>
/// Every frame, on every client: the archer's transform is the ship's local point, taken from the
/// ship's own (interpolated) transform at render time.
///
/// The physics pin below only moves the archer once per physics step, from where the ship was at the
/// start of that step. The ship is drawn smoothly between steps and the archer was not, so at speed
/// it jumped in 50 Hz hops against a hull that glides - "in jerks", and, trailing a step behind,
/// looking not quite attached. Setting the transform here, after everything else has moved it, makes
/// it exactly as smooth as the hull it stands on. For a remote client this also overrides the
/// position the network would give it, which is itself a few steps old.
/// </summary>
private void LateUpdate()
{
if (Ship == null)
{
if (m_byId && Time.time >= m_nextResolve)
{
m_nextResolve = Time.time + 0.5f;
TryResolveShip();
}
return;
}
transform.position = Ship.transform.TransformPoint(LocalPoint);
}
private bool TryResolveShip()
{
GameObject found = ZNetScene.instance != null ? ZNetScene.instance.FindInstance(m_shipId) : null;
Ship ship = found != null ? found.GetComponent<Ship>() : null;
if (ship == null) return false;
Ship = ship;
m_missing = 0f;
IgnoreShipColliders();
return true;
}
/// <summary>
/// Pinned inside the ship's own volume, so it must not fight the ship's colliders: with them live the
/// physics keeps trying to push it out and the mount keeps putting it back. Ignoring them costs
/// nothing - it is invulnerable, and nobody needs to bump into it.
/// </summary>
private void IgnoreShipColliders()
{
Collider[] mine = GetComponentsInChildren<Collider>(true);
Collider[] theirs = Ship.GetComponentsInChildren<Collider>(true);
foreach (Collider a in mine)
{
if (a == null) continue;
foreach (Collider b in theirs)
{
if (b != null) Physics.IgnoreCollision(a, b, true);
}
}
}
private void FixedUpdate()
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
if (Ship == null)
{
if (m_byId) FindShip();
else if (ZNetScene.instance != null) ZNetScene.instance.Destroy(gameObject); // the experiment's way
return;
}
if (m_body == null) return;
if (m_shipBody == null) m_shipBody = Ship.GetComponent<Rigidbody>();
Vector3 target = Ship.transform.TransformPoint(LocalPoint);
m_body.position = target;
m_body.velocity = m_shipBody != null ? m_shipBody.GetPointVelocity(target) : Vector3.zero;
}
/// <summary>
/// Looks the ship up by id. Loaded: bolted on. Not loaded but still in the world's books: wait, it is
/// about to be (they load together). Not in the books at all, for long enough: it has sunk.
/// </summary>
private void FindShip()
{
if (TryResolveShip()) return;
if (ZDOMan.instance != null && ZDOMan.instance.GetZDO(m_shipId) != null)
{
m_missing = 0f;
return;
}
m_missing += Time.fixedDeltaTime;
if (m_missing >= GoneAfter && ZNetScene.instance != null) ZNetScene.instance.Destroy(gameObject);
}
}
/// <summary>
/// Makes an archer a BUST: the leg bones are collapsed to nothing every frame, so only the pelvis, the
/// chest and the arms show - a figurehead that shoots.
///
/// The model cannot be cut, so the legs are scaled to zero where they join the hips: everything skinned
/// to them folds into that point. A leg bone's children inherit the zero, so feet and shins go with it.
/// It is done in LateUpdate, after the animator has written its pose, so nothing animated can put them
/// back. The BONE NAMES are not verified - they are searched for ("upleg", "thigh", "upperleg") on the
/// first frame and what was found is logged. If it finds none it logs the whole skeleton, which is the
/// list the next attempt is written from.
/// </summary>
public class ShipBust : MonoBehaviour
{
private static readonly string[] LegBones = { "upleg", "thigh", "upperleg", "leg_upper" };
private readonly List<Transform> m_legs = new List<Transform>();
/// <summary>Set by the F7 experiment; the real archers say so in their ZDO instead.</summary>
public bool Force;
private void Start()
{
// On the prefab of the real archers this component is always there, and only the ones placed as a
// bust (the ZDO says so) are cut off at the waist; the deck ones keep their legs.
ZNetView nview = GetComponent<ZNetView>();
bool bust = Force || (nview != null && nview.IsValid() && nview.GetZDO().GetBool(ShipMount.KeyArcherBust, false));
if (!bust)
{
enabled = false;
return;
}
foreach (Transform t in GetComponentsInChildren<Transform>(true))
{
string n = t.name.ToLowerInvariant();
foreach (string key in LegBones)
{
if (!n.Contains(key)) continue;
// Only the topmost of a chain: a bone whose parent is already a leg is covered by it.
if (!m_legs.Contains(t.parent)) m_legs.Add(t);
break;
}
}
if (m_legs.Count > 0)
{
List<string> names = new List<string>();
foreach (Transform t in m_legs) names.Add(t.name);
Jotunn.Logger.LogInfo("[ShipBust] collapsing " + m_legs.Count + " leg bone(s): " + string.Join(", ", names.ToArray()));
return;
}
// Nothing matched: say what is there so the names can be read instead of guessed.
List<string> all = new List<string>();
foreach (Transform t in GetComponentsInChildren<Transform>(true)) all.Add(t.name);
Jotunn.Logger.LogWarning("[ShipBust] no leg bone matched. Skeleton: " + string.Join(", ", all.ToArray()));
}
private void LateUpdate()
{
foreach (Transform leg in m_legs)
{
if (leg != null) leg.localScale = Vector3.zero;
}
}
}
/// <summary>
/// A ship's archer cannot be killed - it goes down with the ship, which is the stake. Skipping
/// Character.Damage is enough: the Bound Sentry's own regeneration patch only listens to it too.
/// </summary>
[HarmonyPatch(typeof(Character), "Damage")]
public static class ShipMountInvulnerablePatch
{
public static bool Prefix(Character __instance)
{
return __instance.GetComponent<ShipMount>() == null;
}
}
/// <summary>
/// The deck-finding and post table the bone ships use to place their archers.
///
/// WHERE: a local (x, z) per ship, and the height is NOT guessed - a ray is dropped from above that
/// spot and the deck is wherever it first hits the ship's own solid collider. The mast and the sail's
/// cloth collider are skipped. The point it settled on is reported, so a bad spot is fixed by editing
/// the table below, not by reading code.
/// </summary>
public static class ShipMountTest
{
private const float ShipRange = 40f;
private const float RayStartHeight = 8f;
private const float RayLength = 20f;
/// <summary>
/// One archer's place: where on the deck (local x, z), and whether it is a BUST - only the chest and
/// up shows, the legs are collapsed, and it stands on the stem as a figurehead that shoots.
/// </summary>
private struct Post
{
public Vector2 At;
public bool Bust;
public Post(float x, float z, bool bust) { At = new Vector2(x, z); Bust = bust; }
}
/// <summary>
/// The Karve's bow is at about local z = +4.8 (its WaterTrigger sits there, and the hull mesh is
/// ~10 m long); the post is a little back from the very tip so the ray finds the hull under it.
/// The large ships keep their deck posts until they get a bust of their own.
/// </summary>
private static readonly Dictionary<string, Post[]> Posts = new Dictionary<string, Post[]>
{
{ "Karve", new[] { new Post(0f, 4.3f, true) } },
{ "BoneKarve", new[] { new Post(0f, 4.3f, true) } },
{ "VikingShip", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
{ "BoneLongship", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
{ "VikingShip_Ashlands", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
{ "BoneAshlands", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
};
private static readonly Post[] DefaultPosts = { new Post(0f, 0f, false) };
/// <summary>
/// How far above the hull's surface a bust stands, in metres: the pelvis is left as a stub where the
/// legs were, and this keeps that stub inside the stem instead of above it. To be tuned by eye.
/// </summary>
private const float BustLift = 0.0f;
/// <summary>The deck under a local (x, z): the highest solid surface of THIS ship, not the mast or the sail.</summary>
private static bool FindDeck(Ship ship, Vector2 post, bool bust, out Vector3 local, out string hitName)
{
local = Vector3.zero;
hitName = "";
// A deck is flat. A bow is not: near the stem the hull's surface climbs steeply, and a flat-only
// filter (normal.y >= 0.5) found nothing there at all. A bust takes ANY surface of the ship under
// the point, and if the point is past the end of the hull it walks back toward the middle until
// something is there - the step it settled on shows in the reported local z.
float minUp = bust ? -1f : 0.5f;
float maxBack = bust ? 2.4f : 0f;
const float Step = 0.3f;
for (float back = 0f; back <= maxBack + 0.001f; back += Step)
{
Vector3 origin = ship.transform.TransformPoint(new Vector3(post.x, RayStartHeight, post.y - back));
Vector3 down = -ship.transform.up;
RaycastHit best = default(RaycastHit);
bool found = false;
float bestDistance = float.MaxValue;
foreach (RaycastHit hit in Physics.RaycastAll(origin, down, RayLength))
{
if (hit.collider == null || hit.collider.isTrigger) continue;
if (!hit.collider.transform.IsChildOf(ship.transform)) continue;
if (Vector3.Dot(hit.normal, ship.transform.up) < minUp) continue;
string n = hit.collider.name.ToLowerInvariant();
if (n.Contains("mast") || n.Contains("cloth")) continue;
if (hit.distance >= bestDistance) continue;
best = hit;
bestDistance = hit.distance;
found = true;
}
if (!found) continue;
local = ship.transform.InverseTransformPoint(best.point);
hitName = best.collider.name + (back > 0f ? " (stepped back " + back.ToString("F1") + " m)" : "");
return true;
}
return false;
}
private static Ship NearestShip()
{
Player player = Player.m_localPlayer;
if (player == null) return null;
Ship best = null;
float bestDistance = ShipRange;
foreach (Ship ship in Object.FindObjectsOfType<Ship>())
{
float distance = Vector3.Distance(ship.transform.position, player.transform.position);
if (distance >= bestDistance) continue;
best = ship;
bestDistance = distance;
}
return best;
}
private static List<ShipMount> MountsOn(Ship ship)
{
List<ShipMount> mounts = new List<ShipMount>();
foreach (Character character in Character.GetAllCharacters())
{
if (character == null) continue;
ShipMount mount = character.GetComponent<ShipMount>();
if (mount != null && mount.Ship == ship) mounts.Add(mount);
}
return mounts;
}
/// <summary>"Karve(Clone)" to "Karve".</summary>
private static string Clean(string name)
{
int paren = name.IndexOf('(');
return (paren >= 0 ? name.Substring(0, paren) : name).Trim();
}
private static void Report(string line)
{
Jotunn.Logger.LogInfo(line);
if (Console.instance != null) Console.instance.Print(line);
}
}
}

View file

@ -39,26 +39,6 @@ namespace RacesOfValheim
{ "FaderDrop", 8 } // Fader - Fader relic
};
/// <summary>
/// The boss's name as the game's own localization token, for text shown to players:
/// Valheim translates it wherever it is localized, so "The Elder" arrives in every language.
/// GetBossNameForState stays English, for logs and anything not localized.
/// </summary>
public static string GetBossTokenForState(int state)
{
switch (state)
{
case 2: return "$enemy_eikthyr";
case 3: return "$enemy_gdking";
case 4: return "$enemy_bonemass";
case 5: return "$enemy_dragon";
case 6: return "$enemy_goblinking";
case 7: return "$enemy_seekerqueen";
case 8: return "$enemy_fader";
default: return GetBossNameForState(state);
}
}
public static string GetBossNameForState(int state)
{
switch (state)
@ -115,36 +95,6 @@ namespace RacesOfValheim
}
}
/// <summary>
/// Whether this character carries a claimed personal tier at all. Distinct from
/// "PersonalState == MinState": the getter answers MinState for a character who has never
/// claimed anything AND for one who has been reset, and the Reset Progression button needs
/// to tell the player which of the two just happened.
/// </summary>
public static bool HasPersonalState
{
get
{
Player player = Player.m_localPlayer;
if (player == null || player.m_customData == null) return false;
return player.m_customData.ContainsKey(PersonalStateKey);
}
}
/// <summary>
/// Gives back every tier claimed with a boss relic. The key is removed rather than written
/// back as MinState so the character reads as one that never claimed anything - which is
/// what a reset means, and what HasPersonalState above then reports.
///
/// The relics themselves do not come back: RaceMenuWardBehavior.UseItem consumed them.
/// </summary>
public static void ClearPersonalState()
{
Player player = Player.m_localPlayer;
if (player == null || player.m_customData == null) return;
player.m_customData.Remove(PersonalStateKey);
}
/// <summary>
/// Returns the current progression state of the world based on defeated bosses.
/// 1 = No bosses defeated

View file

@ -1,356 +0,0 @@
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The two Bone Servants and their tables. Servants that work the stations around them and never
/// lift a hand against anything.
///
/// TWO TRADES, and that was the first thing the working version asked for. One servant serving a
/// whole yard spends its life walking: with the kitchen at one edge of the circle and the furnaces
/// at the other, travel eats the margin that keeps food off the fire. So there is a SMITH for the
/// Smelter family and a COOK for cooking stations and mead, each with its own table, each with its
/// own twenty-metre circle - and the two circles may sit on top of each other, because the servants
/// never look at the same station. PieceDensityLimit counts by prefab name, so "no second table
/// within forty metres" keeps smith away from smith and cook away from cook, and needed no change
/// at all to let a smith and a cook stand side by side.
///
/// The smith keeps the ORIGINAL prefab names, BoneServant and ServantTable. That is not tidiness -
/// it means a table already standing in a test world keeps working and keeps its servant instead of
/// becoming a missing prefab at the next load.
///
/// TWO PREFABS EACH, forced the same way the sentry's are: a Character cannot sit in the hammer's
/// piece table, so the buildable thing is the table and the servant is instantiated by it. Unlike
/// the sentry there is no seed piece to throw away, because here the table is not scaffolding - it
/// is the anchor, the summoning point and the only interface the feature has.
///
/// WHAT WAS DELIBERATELY NOT REUSED. The design said the servant would be a RaisedThrall, and it is
/// not. RaisedThrall brings the anchor, the leash and the withering, all of which are wanted - but
/// it also brings RaisedThrallInteractPatch, which turns E on the creature into a follow command.
/// A servant that can be told to follow you out of its own circle is a servant that stops serving,
/// and "E does nothing on the servant" was decided explicitly. So the useful half is reused as a
/// static - RaisedThrall.RegisterStation / StationStandsAt, which is what makes the table findable -
/// and the anchor and wither clock are thirty lines inside BoneServantAI. The alternative was
/// editing RaisedThrall.cs, which is shared with five other chains.
/// </summary>
public static class BoneServant
{
// The smith inherits the names the single servant had, so nothing already built is orphaned.
public const string SmithName = "BoneServant";
public const string SmithTableName = "ServantTable";
public const string SmithDisplay = "$rov_creature_bonesmith_name";
public const string SmithTableDisplay = "$rov_piece_smithtable_name";
public const string CookName = "BoneCook";
public const string CookTableName = "CookTable";
public const string CookDisplay = "$rov_creature_bonecook_name";
public const string CookTableDisplay = "$rov_piece_cooktable_name";
/// <summary>Vanilla's guaranteed-melee skeleton: the plain one rolls its own weapon, and the
/// point here is to have none at all.</summary>
private const string ServantSource = "Skeleton_NoArcher";
public const float Health = 100f;
/// <summary>Two circles of twenty metres cannot overlap if the tables are forty apart, which is
/// how the question of two servants of the SAME trade fighting over one chest was answered - by
/// making the situation impossible to build rather than by sharing state between them.</summary>
public const float TableSpacing = 40f;
private const float TableScale = 0.8f;
/// <summary>
/// One skull, one wishbone, eight stone - the same price for both tables.
///
/// The skull is TrophySkeleton and NOT this mod's own CursedSkull, and that is forced rather
/// than chosen: the cursed skull is bought from the Skeleton faction's merchant, so building it
/// into the cook's price would make the cook unbuildable by the only race allowed to build it.
/// A skeleton trophy is a skull anyone can go and get.
///
/// The wishbone is a real cost and worth knowing about: it is Bonemass's drop and the only
/// treasure-finder in the game, so a standing table keeps yours locked up. Recovered in full
/// when the table is removed, like every other recipe in this mod.
/// </summary>
private static RequirementConfig[] Recipe()
{
return new[]
{
new RequirementConfig("TrophySkeleton", 1, 0, true),
new RequirementConfig("Wishbone", 1, 0, true),
new RequirementConfig("Stone", 8, 0, true),
};
}
public static void Register()
{
if (RegisterServant(SmithName, SmithDisplay, ButlerFamily.Forge))
{
RegisterTable(SmithTableName, SmithTableDisplay, SmithName, ButlerFamily.Forge,
"$rov_piece_smithtable_desc",
"Coal");
PieceDensityLimit.Register(SmithTableName, TableSpacing, 1,
"rov_msg_build_limit_smithtable");
// Two races, and it is the wider of the two locks: the Skeleton raises the dead to work
// for it, and Skadi's hold is a forge under ice.
PieceDensityLimit.RegisterGate(SmithTableName, (player, position) =>
{
if (SkeletonRace.IsSkeleton() || SkadiRace.IsLocalSkadi()) return true;
if (player != null)
{
player.Message(MessageHud.MessageType.Center,
ModText.Get("rov_msg_butler_bones_do_not_answer_blood"));
}
return false;
});
}
if (RegisterServant(CookName, CookDisplay, ButlerFamily.Kitchen))
{
RegisterTable(CookTableName, CookTableDisplay, CookName, ButlerFamily.Kitchen,
"$rov_piece_cooktable_desc",
"CookedMeat");
PieceDensityLimit.Register(CookTableName, TableSpacing, 1,
"rov_msg_build_limit_cooktable");
// Skadi alone. A hearth kept by something dead is hers, not the Skeleton's.
PieceDensityLimit.RegisterGate(CookTableName, (player, position) =>
{
if (SkadiRace.IsLocalSkadi()) return true;
if (player != null)
{
player.Message(MessageHud.MessageType.Center,
ModText.Get("rov_msg_butler_only_skadi_s_hearth_kept"));
}
return false;
});
}
}
// ---------------------------------------------------------------- the servants
private static bool RegisterServant(string prefabName, string displayName, ButlerFamily family)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, ServantSource);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Butler] Could not clone {ServantSource}; " +
$"{displayName} is not registered.");
return false;
}
Character character = prefab.GetComponent<Character>();
if (character != null)
{
character.m_name = displayName;
character.m_health = Health;
character.m_faction = Character.Faction.Players;
}
// Nothing in its hands, and nothing to roll for. Belt and braces with the AI prefix: the
// code that would swing a weapon never runs, but a servant carrying a rusty sword around
// the kitchen would still look like a mistake.
Humanoid humanoid = prefab.GetComponent<Humanoid>();
if (humanoid != null)
{
humanoid.m_defaultItems = 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];
}
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null)
{
ai.m_randomMoveRange = 0f; // it never wanders: every step it takes is a decision
ai.m_avoidFire = false; // it works next to kilns for a living
ai.m_afraidOfFire = false;
}
// A servant that dropped bones would be a bone mill, exactly as with the garrison.
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
// Ten seconds unhurt, then two percent a second. The sentry's regeneration, whole.
prefab.AddComponent<SkeletonSentryBehaviour>();
BoneServantAI servant = prefab.AddComponent<BoneServantAI>();
servant.m_family = family;
PrefabManager.Instance.AddPrefab(prefab);
return true;
}
// ---------------------------------------------------------------- the tables
private static void RegisterTable(string pieceName, string displayName, string servantPrefab,
ButlerFamily family, string description, string iconSource)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(pieceName, "piece_cartographytable");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Butler] Could not clone piece_cartographytable; " +
$"the {displayName} is not registered.");
return;
}
// The MapTable trap, and it is the reason this is a blanket sweep by capability rather than
// a named DestroyImmediate: MapTable is Interactable AND Hoverable, so it takes the E key
// before our own Switch ever sees it and opens the shared map instead. Same bug as the
// barrel's Container on the Fenrir trough and the Trader on the vanilla wolf; the Dvergar
// contract bank pays for this lesson already.
foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour == null) continue;
if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue;
Object.DestroyImmediate(behaviour);
}
prefab.transform.localScale = Vector3.one * TableScale;
Dress(prefab, family);
ServantTableBehaviour table = prefab.AddComponent<ServantTableBehaviour>();
table.m_switch = prefab.AddComponent<Switch>();
table.m_switch.m_name = displayName;
table.m_title = displayName;
table.m_servantPrefab = servantPrefab;
table.m_family = family;
Sprite icon = BorrowIcon(iconSource) ?? BorrowIcon("TrophySkeleton");
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = displayName;
piece.m_canBeRemoved = true;
// Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch
// the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's
// mesh floor - so players saw no ghost at all and could not tell why. A station belongs
// in a house or a cave as much as outside.
piece.m_groundPiece = false;
piece.m_groundOnly = false;
piece.m_icon = icon;
Piece template = PrefabManager.Cache.GetPrefab<Piece>("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 = displayName,
Description = description,
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = icon,
Requirements = Recipe(),
}));
}
// The look, in the table's own space BEFORE TableScale, so sizes are divided by it to come out
// in real metres. The cover lies where the map was: x -2.06 to 0.62, read off the mesh. Its top
// is the Dvergar bank's PileHeight, on the same vanilla mesh; the mesh's own height is no use
// here, since the writing desk stands taller than the map.
private const float CoverTop = 1.05f;
private static readonly Vector3 TradeSpot = new Vector3(-0.75f, CoverTop, 0.2f);
private static readonly Vector3 SkullSpot = new Vector3(-1.55f, CoverTop, 0.35f);
private const float AnvilSize = 0.75f;
private const float MealSize = 0.6f;
private const float SkullSize = 0.45f;
/// <summary>
/// The map painted over - a sheet of chainmail for the smith, a red and white tablecloth for the
/// cook - with the trade's own work on it (an anvil, a meal) and a skeleton's skull beside it.
/// </summary>
private static void Dress(GameObject prefab, ButlerFamily family)
{
bool forge = family == ButlerFamily.Forge;
LayCover(prefab, forge ? "SmithMail" : "CookCloth", metal: forge);
float metres = 1f / TableScale;
if (forge)
{
ModelBorrow.Attach(prefab.transform, "TableAnvil", "forge_ext2",
TradeSpot, Quaternion.identity, AnvilSize * metres, "Butler", activeOnly: true);
}
else
{
ModelBorrow.Attach(prefab.transform, "TableMeal", "MeatPlatter",
TradeSpot, Quaternion.identity, MealSize * metres, "Butler", activeOnly: true);
}
ModelBorrow.Attach(prefab.transform, "TableSkull", "TrophySkeleton",
SkullSpot, Quaternion.Euler(0f, -150f, 0f), SkullSize * metres, "Butler", activeOnly: true);
}
/// <summary>
/// The cartography table's own textures with the map painted over, offline:
/// scripts/paint_cook_cloth.py (CookCloth) and scripts/paint_smith_mail.py (SmithMail). Each set
/// has its own worn texture for a damaged table (a stained cloth, rusted mail) and its own normal
/// map, so the coastline's relief does not show through. The mail also brings a metallic map,
/// which is what makes the rings shine; the cloth keeps vanilla's, which is metal nowhere.
/// </summary>
private static void LayCover(GameObject prefab, string set, bool metal)
{
var cover = new System.Collections.Generic.Dictionary<string, Texture>();
AddCover(cover, "Cartographer_d", set + "_d.png", false);
AddCover(cover, "Cartographer_worn_d", set + "_worn_d.png", false);
AddCover(cover, "Cartographer_n", set + "_n.png", true);
if (metal) AddCover(cover, "Cartographer_m", set + "_m.png", true);
PieceLook.Retexture(prefab.transform, cover);
}
private static void AddCover(System.Collections.Generic.Dictionary<string, Texture> cover,
string vanilla, string resource, bool linear)
{
Texture2D texture = PieceLook.LoadTexture(resource, linear);
if (texture != null) cover[vanilla] = texture;
}
public static void EnsureKnown(Player player)
{
if (player == null) return;
Traverse traverse = Traverse.Create(player);
LearnPiece(traverse, SmithTableName);
LearnPiece(traverse, CookTableName);
traverse.Method("UpdateAvailablePiecesList").GetValue();
}
private static void LearnPiece(Traverse player, string pieceName)
{
GameObject prefab = PrefabManager.Instance.GetPrefab(pieceName);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece == null) return;
player.Method("AddKnownPiece", piece).GetValue();
}
private static Sprite BorrowIcon(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(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;
}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class BoneServantKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
BoneServant.EnsureKnown(__instance);
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,50 +0,0 @@
using BepInEx.Configuration;
namespace RacesOfValheim
{
/// <summary>
/// The four knobs the Bone Servant exposes, and deliberately only four.
///
/// Butler_BoneServant.txt sec. 14 turned down "expose everything": tick cadence, safety margins,
/// penalty-box time and the spacing between tables are constants in the code, because they are
/// numbers that get tuned once during the test and then never again - and every config entry is
/// maintained forever.
///
/// The sigil is here for a different reason from the other three. It is a PLACEHOLDER: bone
/// fragments stand in for a craftable sigil that only gets made if the feature leaves the test,
/// and being able to move the mark onto another item without a rebuild is the whole point of the
/// entry.
/// </summary>
public static class ButlerConfig
{
public static ConfigEntry<string> SigilItem;
public static ConfigEntry<float> WorkRadius;
public static ConfigEntry<float> FuelThreshold;
public static ConfigEntry<float> ResummonSeconds;
public static void Bind(ConfigFile config)
{
const string section = "Butler - Bone Servant";
SigilItem = config.Bind(section, "Sigil Item", "BoneFragments",
new ConfigDescription("Prefab name of the item that marks a chest as the servant's. " +
"A chest holding at least one of these is worked from and " +
"delivered to; every other chest is left alone. The sigil itself " +
"is never taken and never processed."));
WorkRadius = config.Bind(section, "Work Radius", 20f,
new ConfigDescription("Metres from the Servant's Table within which chests and stations " +
"are served.", new AcceptableValueRange<float>(5f, 40f)));
FuelThreshold = config.Bind(section, "Fuel Threshold", 0.25f,
new ConfigDescription("Refuel a station when its fuel drops below this fraction of its " +
"maximum, and only while it has something to work on.",
new AcceptableValueRange<float>(0f, 1f)));
ResummonSeconds = config.Bind(section, "Resummon Cooldown", 0f,
new ConfigDescription("Seconds that must pass before a fallen servant can be raised " +
"again. Zero is free and immediate, which is what the test runs on.",
new AcceptableValueRange<float>(0f, 600f)));
}
}
}

View file

@ -1,524 +0,0 @@
using System;
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Which servant a station belongs to.
///
/// The split is not cosmetic, it is the answer to the one complaint the first working version drew:
/// with a kitchen at one edge of the circle and three furnaces at the other, a single servant spends
/// its life walking and the margin that keeps food off the fire gets eaten by travel. Two servants
/// with two tables in the same yard walk half as far each.
///
/// It also cuts the AI in half along a seam that was already there. FORGE cannot spoil - a smelter
/// holds its ore forever and drops its own output - so the forge servant has no clock, never runs,
/// and never pre-empts itself. All of that machinery lives on in the KITCHEN, which is the only
/// place it was ever needed.
/// </summary>
public enum ButlerFamily
{
/// <summary>Smelter: furnace, blast furnace, charcoal kiln, windmill, spinning wheel, eitr
/// refinery. Nothing here has a deadline.</summary>
Forge,
/// <summary>CookingStation and Fermenter: hearths, ovens and mead. The only family with a
/// clock.</summary>
Kitchen,
}
/// <summary>
/// One working station, seen through the handful of questions the servant ever asks it.
///
/// THREE FAMILIES, and they are not variations on a theme - they behave OPPOSITELY on output, which
/// is the single fact the whole feature is built around (Butler_BoneServant.txt sec. 5, all of it
/// read off assembly_valheim.dll with Cecil rather than guessed):
///
/// Smelter furnace, blast furnace, charcoal kiln, windmill, spinning wheel, eitr
/// refinery. Its output FALLS ON THE GROUND BY ITSELF - UpdateSmelter runs
/// RemoveOneOre -> QueueProcessed -> SpawnProcessed with nobody asking. Nothing
/// to pull; the servant just picks the bars up.
/// CookingStation hearth, iron cooking station, stone oven. Output STAYS IN THE SLOT and keeps
/// cooking: Done at m_cookTime, Burnt at exactly twice it (verified: the IL
/// literally loads m_cookTime, pushes 2 and multiplies). This is the family that
/// can lose you food, and the only one with a clock.
/// Fermenter mead. Output stays in until the tap is opened, and never spoils.
///
/// NOTHING HERE KNOWS WHAT A MATERIAL IS. Every family exposes IsItemAllowed(string) and
/// GetItemConversion(string), matching on the PREFAB name (m_from.gameObject.name - verified), so
/// the servant asks the station "do you take this?" instead of carrying a list of ores and crops.
/// That is what makes it serve this mod's own stations, other races' stations, and other mods'
/// stations without a line of code per station.
///
/// WHY SO MUCH REFLECTION. Every one of those question methods is PRIVATE in this build -
/// GetQueueSize, IsItemAllowed, GetSlot, GetFuel, HaveDoneItem, IsFireLit, GetStatus, the lot - and
/// both Status enums are private nested types, so they cannot even be named in source. The
/// alternative was reimplementing each station's rules by reading its public m_conversion list,
/// which would be a second copy of vanilla's logic drifting out of step at the next patch. Calling
/// the real method through a cached MethodInfo is the smaller lie. The enum values are hard-coded
/// as ints, and they are not guesses: Cecil reports NotDone=0, Done=1, Burnt=2 and Empty=0,
/// Fermenting=1, Exposed=2, Ready=3.
///
/// Every write goes through InvokeRPC with the name the station REGISTERED, which carries the
/// "RPC_" prefix in this build - "RPC_AddOre", not "AddOre". A wrong name here is a silent no-op,
/// which is exactly the class of bug that takes an evening to find, so the four names below were
/// read out of each Awake() rather than remembered.
///
/// A wrong ARGUMENT LIST is not silent: Valheim 1.0 added a trailing "bool cheated" to every
/// add-item RPC (and the Fermenter's now takes the prefab's stable hash, not its name), and the
/// old calls threw EndOfStreamException on the receiving end, every tick. The servant's goods
/// are real, so cheated is always false.
/// </summary>
public abstract class ButlerStation
{
public Component Behaviour;
public ZNetView Nview;
public Transform Transform;
public Vector3 Position { get { return Transform.position; } }
public ZDOID Id
{
get { return Nview != null && Nview.IsValid() ? Nview.GetZDO().m_uid : ZDOID.None; }
}
public bool Alive { get { return Behaviour != null && Nview != null && Nview.IsValid(); } }
/// <summary>Wraps whichever of the three this object is, or null if it is not a station.</summary>
public static ButlerStation From(GameObject go)
{
if (go == null) return null;
ZNetView nview = go.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return null;
Smelter smelter = go.GetComponent<Smelter>();
if (smelter != null) return Fill(new SmelterStation { m_smelter = smelter }, smelter, nview);
CookingStation cooking = go.GetComponent<CookingStation>();
if (cooking != null) return Fill(new CookingStationStation { m_cooking = cooking }, cooking, nview);
Fermenter fermenter = go.GetComponent<Fermenter>();
if (fermenter != null) return Fill(new FermenterStation { m_fermenter = fermenter }, fermenter, nview);
return null;
}
private static ButlerStation Fill(ButlerStation station, Component behaviour, ZNetView nview)
{
station.Behaviour = behaviour;
station.Nview = nview;
station.Transform = behaviour.transform;
return station;
}
/// <summary>
/// Taking ownership before writing is the multiplayer rule of this feature (sec. 10), and it
/// buys a second thing that matters here: once we own the ZDO the RPC runs locally and
/// immediately, so GetQueueSize and GetFuel answer truthfully on the very next line instead of
/// a network round trip later.
/// </summary>
protected void Claim()
{
if (Nview != null && Nview.IsValid() && !Nview.IsOwner()) Nview.ClaimOwnership();
}
// ---------------------------------------------------------------- what the servant asks
/// <summary>Which of the two servants this one belongs to.</summary>
public abstract ButlerFamily Family { get; }
/// <summary>Can it work at all right now - fire lit, roof up? An inoperable station is skipped
/// in silence, which is a decision and not an oversight (sec. 7.7).</summary>
public abstract bool Operable { get; }
/// <summary>How many more items it can take. Zero means full.</summary>
public abstract int FreeSlots { get; }
public abstract bool Accepts(string prefabName);
/// <summary>Puts one unit in. Called FreeSlots times at most, never more.</summary>
public abstract void Add(string prefabName);
/// <summary>True while it has something to work on - so an empty furnace is never stoked.</summary>
public abstract bool HasWork { get; }
public abstract string FuelPrefab { get; }
/// <summary>Units of fuel it wants right now, already filtered by the configured threshold.</summary>
public abstract int FuelWanted { get; }
public abstract void AddFuel();
/// <summary>Something finished and needs a hand to get out. Always false for the Smelter, which
/// throws its own output on the floor.</summary>
public abstract bool HasOutput { get; }
/// <summary>Gets the finished goods onto the ground at <paramref name="at"/>, where the one
/// pickup routine will find them.</summary>
public abstract void PullOutput(Vector3 at);
/// <summary>
/// How many times PullOutput is worth calling in a single visit, which is not the same question
/// as how much is finished.
///
/// One, everywhere except the hearth. The Fermenter is the reason this is not simply "keep
/// pulling while HasOutput": tapping does not clear Ready straight away - DelayedTap waits
/// m_tapDelay for the animation - so a loop on HasOutput would pull the same tap over and over
/// in one frame.
/// </summary>
public virtual int OutputPulls { get { return 1; } }
/// <summary>Seconds until something in here is ruined. float.MaxValue for the two families that
/// cannot spoil, which is what keeps the urgency comparison honest without special cases.</summary>
public virtual float SecondsToSpoil { get { return float.MaxValue; } }
// ================================================================ the private doors
/// <summary>
/// Every private member of the three station classes this feature touches, resolved once.
///
/// Anything that fails to resolve stays null and its caller falls back to the safe answer -
/// "cannot tell, do not act" - so a future patch that renames one method costs that one
/// capability and a line in the log, not a servant that stands still or, worse, one that keeps
/// pouring ore into a station it can no longer read.
/// </summary>
private static class Vanilla
{
public static readonly MethodInfo SmelterQueueSize = AccessTools.Method(typeof(Smelter), "GetQueueSize");
public static readonly MethodInfo SmelterAllowed =
AccessTools.Method(typeof(Smelter), "IsItemAllowed", new[] { typeof(string) });
public static readonly MethodInfo SmelterFuel = AccessTools.Method(typeof(Smelter), "GetFuel");
public static readonly FieldInfo SmelterHaveRoof = AccessTools.Field(typeof(Smelter), "m_haveRoof");
public static readonly MethodInfo CookGetSlot = AccessTools.Method(typeof(CookingStation), "GetSlot");
public static readonly MethodInfo CookEmpty = AccessTools.Method(typeof(CookingStation), "IsEmpty");
public static readonly MethodInfo CookHaveDone = AccessTools.Method(typeof(CookingStation), "HaveDoneItem");
public static readonly MethodInfo CookAllowed =
AccessTools.Method(typeof(CookingStation), "IsItemAllowed", new[] { typeof(string) });
public static readonly MethodInfo CookConversion =
AccessTools.Method(typeof(CookingStation), "GetItemConversion", new[] { typeof(string) });
public static readonly MethodInfo CookFuel = AccessTools.Method(typeof(CookingStation), "GetFuel");
public static readonly MethodInfo CookFireLit = AccessTools.Method(typeof(CookingStation), "IsFireLit");
public static readonly MethodInfo FermenterStatus = AccessTools.Method(typeof(Fermenter), "GetStatus");
// 1.0 dropped the string overload: the Fermenter matches on GetStableHashCode of the name.
public static readonly MethodInfo FermenterAllowed =
AccessTools.Method(typeof(Fermenter), "IsItemAllowed", new[] { typeof(int) });
// CookingStation.Status and Fermenter.Status are private nested enums: they cannot be named
// in source, so they travel as ints. Values read from the assembly, not assumed.
public const int CookNotDone = 0;
public const int CookDone = 1;
public const int CookBurnt = 2;
public const int FermentEmpty = 0;
public const int FermentExposed = 2;
public const int FermentReady = 3;
public static bool Call(MethodInfo method, object target, bool fallback)
{
if (method == null) return fallback;
return (bool)method.Invoke(target, null);
}
public static int CallInt(MethodInfo method, object target, int fallback)
{
if (method == null) return fallback;
return Convert.ToInt32(method.Invoke(target, null));
}
public static float CallFloat(MethodInfo method, object target, float fallback)
{
if (method == null) return fallback;
return Convert.ToSingle(method.Invoke(target, null));
}
public static bool Allowed(MethodInfo method, object target, string prefabName)
{
if (method == null || string.IsNullOrEmpty(prefabName)) return false;
return (bool)method.Invoke(target, new object[] { prefabName });
}
}
// ================================================================ Smelter
private class SmelterStation : ButlerStation
{
public Smelter m_smelter;
public override ButlerFamily Family { get { return ButlerFamily.Forge; } }
public override bool Operable
{
get
{
if (!m_smelter.m_requiresRoof) return true;
if (Vanilla.SmelterHaveRoof == null) return true; // cannot tell: let it try
return (bool)Vanilla.SmelterHaveRoof.GetValue(m_smelter);
}
}
private int Queued { get { return Vanilla.CallInt(Vanilla.SmelterQueueSize, m_smelter, int.MaxValue); } }
public override int FreeSlots
{
get { return Mathf.Max(0, m_smelter.m_maxOre - Queued); }
}
public override bool Accepts(string prefabName)
{
return Vanilla.Allowed(Vanilla.SmelterAllowed, m_smelter, prefabName);
}
public override void Add(string prefabName)
{
Claim();
Nview.InvokeRPC("RPC_AddOre", prefabName, false);
}
public override bool HasWork { get { return Queued > 0; } }
public override string FuelPrefab
{
get { return m_smelter.m_fuelItem != null ? m_smelter.m_fuelItem.gameObject.name : null; }
}
public override int FuelWanted
{
get
{
if (m_smelter.m_fuelItem == null || m_smelter.m_maxFuel <= 0) return 0;
if (!HasWork) return 0;
float fuel = Vanilla.CallFloat(Vanilla.SmelterFuel, m_smelter, float.MaxValue);
if (fuel >= m_smelter.m_maxFuel * ButlerConfig.FuelThreshold.Value) return 0;
return Mathf.Max(0, Mathf.FloorToInt(m_smelter.m_maxFuel - fuel));
}
}
public override void AddFuel()
{
Claim();
Nview.InvokeRPC("RPC_AddFuel");
}
// The whole point of this family: nothing to collect, it drops its own.
public override bool HasOutput { get { return false; } }
public override void PullOutput(Vector3 at) { }
}
// ================================================================ CookingStation
private class CookingStationStation : ButlerStation
{
public CookingStation m_cooking;
public override ButlerFamily Family { get { return ButlerFamily.Kitchen; } }
private int SlotCount
{
get { return m_cooking.m_slots != null ? m_cooking.m_slots.Length : 0; }
}
/// <summary>GetSlot hands back four values through out parameters, one of which is a
/// private enum. Through reflection that means an args array and an int. The fourth, a
/// bool "cheated", arrived with 1.0; it is ignored, but the array must have room for it.</summary>
private bool ReadSlot(int index, out string name, out float cooked, out int status)
{
name = null;
cooked = 0f;
status = Vanilla.CookNotDone;
if (Vanilla.CookGetSlot == null) return false;
object[] args = new object[] { index, null, null, null, null };
Vanilla.CookGetSlot.Invoke(m_cooking, args);
name = args[1] as string;
cooked = Convert.ToSingle(args[2]);
status = Convert.ToInt32(args[3]);
return true;
}
public override bool Operable
{
get { return !m_cooking.m_requireFire || Vanilla.Call(Vanilla.CookFireLit, m_cooking, false); }
}
public override int FreeSlots
{
get
{
int free = 0;
for (int i = 0; i < SlotCount; i++)
{
string name;
float cooked;
int status;
if (!ReadSlot(i, out name, out cooked, out status)) return 0;
if (string.IsNullOrEmpty(name)) free++;
}
return free;
}
}
public override bool Accepts(string prefabName)
{
return Vanilla.Allowed(Vanilla.CookAllowed, m_cooking, prefabName);
}
public override void Add(string prefabName)
{
Claim();
Nview.InvokeRPC("RPC_AddItem", prefabName, false);
}
public override bool HasWork { get { return !Vanilla.Call(Vanilla.CookEmpty, m_cooking, true); } }
public override string FuelPrefab
{
get
{
return m_cooking.m_useFuel && m_cooking.m_fuelItem != null
? m_cooking.m_fuelItem.gameObject.name
: null;
}
}
public override int FuelWanted
{
get
{
if (!m_cooking.m_useFuel || m_cooking.m_fuelItem == null || m_cooking.m_maxFuel <= 0) return 0;
if (!HasWork) return 0;
float fuel = Vanilla.CallFloat(Vanilla.CookFuel, m_cooking, float.MaxValue);
if (fuel >= m_cooking.m_maxFuel * ButlerConfig.FuelThreshold.Value) return 0;
return Mathf.Max(0, Mathf.FloorToInt(m_cooking.m_maxFuel - fuel));
}
}
public override void AddFuel()
{
Claim();
Nview.InvokeRPC("RPC_AddFuel");
}
public override bool HasOutput { get { return Vanilla.Call(Vanilla.CookHaveDone, m_cooking, false); } }
/// <summary>
/// ONE CALL, ONE SLOT - and the 1 is the count, not the slot.
///
/// Read again off the IL after the cook was reported losing a meat per batch, because the
/// first reading of it was wrong in a way that mattered. RPC_RemoveDoneItem walks the slots,
/// finds the FIRST one that is Done, spawns its item <c>amount</c> times, clears that slot,
/// sends RPC_SetSlotVisual and RETURNS. It does not go on to the other slots. So the
/// argument is a multiplier - anything above 1 prints money - and a hearth with five cooked
/// slots needs five calls, which is what OutputPulls below is for.
/// </summary>
public override void PullOutput(Vector3 at)
{
Claim();
Nview.InvokeRPC("RPC_RemoveDoneItem", at, 1);
}
/// <summary>One call per slot, so a full hearth is emptied in one visit instead of one item
/// per errand. The loop that uses this stops on HasOutput anyway; this is only its bound.</summary>
public override int OutputPulls { get { return Mathf.Max(1, SlotCount); } }
/// <summary>
/// The clock this whole feature exists for. Done at m_cookTime, Burnt at 2x - so what is
/// left is 2*cookTime - cookedTime, and a slot already Done is the urgent one because its
/// remaining half is all that stands between dinner and charcoal.
///
/// GetItemConversion is asked with whatever name the slot currently holds, which is the raw
/// item before Done and the COOKED one after: CookingStation.GetItemConversion matches on
/// both m_from and m_to (verified), so the cook time is readable in either phase.
/// </summary>
public override float SecondsToSpoil
{
get
{
if (Vanilla.CookConversion == null) return float.MaxValue;
float soonest = float.MaxValue;
for (int i = 0; i < SlotCount; i++)
{
string name;
float cooked;
int status;
if (!ReadSlot(i, out name, out cooked, out status)) break;
if (string.IsNullOrEmpty(name)) continue;
if (status == Vanilla.CookBurnt) continue; // already lost, no hurry
CookingStation.ItemConversion conversion =
Vanilla.CookConversion.Invoke(m_cooking, new object[] { name })
as CookingStation.ItemConversion;
if (conversion == null) continue;
float left = conversion.m_cookTime * 2f - cooked;
if (left < soonest) soonest = left;
}
return soonest;
}
}
}
// ================================================================ Fermenter
private class FermenterStation : ButlerStation
{
public Fermenter m_fermenter;
/// <summary>Mead goes with the food. It has no deadline of its own, so it costs the cook
/// nothing beyond one more thing to fill and one more tap to open.</summary>
public override ButlerFamily Family { get { return ButlerFamily.Kitchen; } }
private int Status
{
get { return Vanilla.CallInt(Vanilla.FermenterStatus, m_fermenter, Vanilla.FermentExposed); }
}
public override bool Operable { get { return Status != Vanilla.FermentExposed; } }
public override int FreeSlots { get { return Status == Vanilla.FermentEmpty ? 1 : 0; } }
public override bool Accepts(string prefabName)
{
if (Vanilla.FermenterAllowed == null || string.IsNullOrEmpty(prefabName)) return false;
return (bool)Vanilla.FermenterAllowed.Invoke(m_fermenter, new object[] { prefabName.GetStableHashCode() });
}
public override void Add(string prefabName)
{
Claim();
Nview.InvokeRPC("RPC_AddItem", prefabName.GetStableHashCode(), false);
}
public override bool HasWork { get { return Status != Vanilla.FermentEmpty; } }
public override string FuelPrefab { get { return null; } }
public override int FuelWanted { get { return 0; } }
public override void AddFuel() { }
public override bool HasOutput { get { return Status == Vanilla.FermentReady; } }
/// <summary>Opens the tap. The bottles are not out yet when this returns - DelayedTap waits
/// m_tapDelay for the animation - so the servant collects them on a later pass, which the
/// pickup sweep handles without knowing anything about fermenting.</summary>
public override void PullOutput(Vector3 at)
{
Claim();
Nview.InvokeRPC("RPC_Tap");
}
}
}
}

View file

@ -1,171 +0,0 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// A servant's table: an anchor, a summoning point and the feature's only window. One class serves
/// both trades - what changes between the smith's and the cook's is three fields set at
/// registration, not behaviour.
///
/// It does no work of its own. Everything it knows it asks the servant, and everything the servant
/// says it says here - the hover text is the ONE feedback channel this feature has, by decision, so
/// a servant that has stopped must be able to explain itself from a line of text or it is
/// indistinguishable from a broken mod.
///
/// E RAISES, and that is all E does. There is no pause switch and no automatic re-forming: a fallen
/// servant leaves the table empty until somebody notices. That was chosen over a sixty-second
/// respawn on the grounds that a death nobody notices is a death that might as well not happen.
///
/// It registers itself with RaisedThrall's station list, which is what BoneServantAI's wither clock
/// asks when it wants to know whether its table is still standing. That list is the only part of
/// the thrall machinery this feature uses.
/// </summary>
public class ServantTableBehaviour : MonoBehaviour
{
public Switch m_switch;
/// <summary>Set on the prefab at registration, so both travel to every instance.</summary>
public string m_title = "Servant's Table";
public string m_servantPrefab = BoneServant.SmithName;
public ButlerFamily m_family = ButlerFamily.Forge;
private const string KeyLastRaise = "RoV_butlerRaisedAt";
/// <summary>Where the servant stands up: in front of the table, clear of the mesh.</summary>
private const float RaiseOffset = 1.2f;
private ZNetView m_nview;
private void Awake()
{
RaisedThrall.RegisterStation(transform);
m_nview = GetComponent<ZNetView>();
if (m_switch != null)
{
m_switch.m_onUse = OnUse;
m_switch.m_onHover = Hover;
}
}
private void OnDestroy()
{
RaisedThrall.UnregisterStation(transform);
}
// ---------------------------------------------------------------- interaction
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
Player player = user as Player;
if (player == null) return false;
if (item != null)
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
// True, not false: false makes Humanoid.UseItem cover the message with $msg_cantuseon.
return true;
}
if (Servant() != null)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_butler_already_at_work"));
return false;
}
float wait = Cooldown();
if (wait > 0f)
{
player.Message(MessageHud.MessageType.Center,
ModText.Get("rov_msg_butler_bones_are_not_ready_s", Mathf.CeilToInt(wait)));
return false;
}
return Raise(player);
}
private bool Raise(Player player)
{
if (m_nview == null || !m_nview.IsValid()) return false;
if (ZNetScene.instance == null) return false;
GameObject prefab = ZNetScene.instance.GetPrefab(m_servantPrefab);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Butler] No '{m_servantPrefab}' in ZNetScene; nothing was raised.");
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_butler_nothing_answers"));
return false;
}
// Owner-only, so in multiplayer exactly one servant stands up rather than one per client.
m_nview.ClaimOwnership();
Vector3 at = transform.position + transform.forward * RaiseOffset;
GameObject spawned = Object.Instantiate(prefab, at, Quaternion.identity);
BoneServantAI servant = spawned.GetComponent<BoneServantAI>();
if (servant != null) servant.Bind(transform.position);
if (ZNet.instance != null) m_nview.GetZDO().Set(KeyLastRaise, ZNet.instance.GetTime().Ticks);
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_butler_servant_rises"));
return true;
}
/// <summary>Seconds still to wait, or zero. Kept in world time so logging out does not pay it off
/// for free - and configured to zero for the test, where it is simply never in the way.</summary>
private float Cooldown()
{
if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return 0f;
float required = ButlerConfig.ResummonSeconds.Value;
if (required <= 0f) return 0f;
long stamp = m_nview.GetZDO().GetLong(KeyLastRaise, 0L);
if (stamp == 0L) return 0f;
double elapsed = (ZNet.instance.GetTime() - new System.DateTime(stamp)).TotalSeconds;
return Mathf.Max(0f, required - (float)elapsed);
}
// ---------------------------------------------------------------- the hover
private string Hover()
{
BoneServantAI servant = Servant();
if (servant == null)
{
return ModText.Get("rov_hover_butler_no_servant_stands_here_raise", m_title);
}
string status = servant.Status;
if (string.IsNullOrEmpty(status)) status = ModText.Get("rov_hover_butler_waiting");
// m_title is a $token, and a hover text goes to the HUD as it is: nothing localizes it later.
return Localization.instance.Localize(m_title) + "\n" + status;
}
/// <summary>
/// This table's servant, if it is alive and loaded.
///
/// Matched by anchor rather than by a stored id, so a table rebuilt on the same spot adopts the
/// servant already standing there - and by TRADE as well, because a smith's table and a cook's
/// table are allowed to stand a metre apart and must not adopt each other's servant.
/// </summary>
private BoneServantAI Servant()
{
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead()) continue;
BoneServantAI servant = character.GetComponent<BoneServantAI>();
if (servant == null || servant.m_family != m_family) continue;
if (servant.IsBoundTo(transform.position)) return servant;
}
return null;
}
}
}

View file

@ -1,108 +0,0 @@
using System;
using System.Linq;
using System.Reflection;
using BepInEx.Configuration;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Marks every gameplay config entry as admin-only so Jotunn syncs it from the server to the
/// clients (and locks it for non-admins in Configuration Manager).
///
/// Jotunn only recognises ITS OWN ConfigurationManagerAttributes (global namespace, in
/// Jotunn.dll) as a tag - it does an `is` check, not the field-name duck typing Configuration
/// Manager does - so our internal look-alike tag is not enough. This runs once after every
/// Bind() and adds Jotunn's tag beside whatever tags the entry already has, rather than
/// touching each of the ~350 Bind() calls.
///
/// Left local, because they are per-player preferences and syncing them would only take the
/// choice away from the player: keybinds, and the purely cosmetic entries (eye/claw colours,
/// glow, tint, rotation and offset of models, the VFX toggle, the stamina-bar toggle, debug
/// logging). Anything that changes a number the game computes with stays synced.
/// </summary>
internal static class ConfigSync
{
// Whole sections that are cosmetic or per-player.
private static readonly string[] LocalSections =
{
"Alfar - Look",
"Aswid - Claws",
"Aswid - Eyes",
"Fenrir - Appearance",
"Skeleton - Visuals",
// Food and stamina for a Skeleton who wants them: each only gives up an advantage.
"Skeleton - Mortal Habits",
"Sverm - Dorsal Spines",
"Sverm - Emberform",
"Trol - Appearance",
"War Vulture - Model",
"War Vulture - Interface",
};
// Cosmetic entries scattered through otherwise gameplay sections.
private static readonly string[] LocalKeyParts =
{
"marker light", "tint", "colour", "color", "glow", "swarm scale", "log rounds", "debug",
// The Aswid's seasick camera: motion makes some players ill, so a server cannot force it.
"camera sway",
// Each player picks their own True Form: a player model mod (VRM and the like) breaks
// under the troll costume, so a server cannot be allowed to force the costume on.
"legacy true form",
// The player's own pick of bat flight; the synced Bat Flight Rule can override it.
"free bat flight",
};
public static void Apply(ConfigFile config)
{
FieldInfo descField = typeof(ConfigEntryBase)
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
.FirstOrDefault(f => f.FieldType == typeof(ConfigDescription));
if (descField == null)
{
Debug.LogWarning("[RacesOfValheim] Config sync skipped: ConfigEntryBase has no ConfigDescription field.");
return;
}
int synced = 0, local = 0;
foreach (ConfigDefinition def in config.Keys.ToList())
{
ConfigEntryBase entry = config[def];
if (!ShouldSync(entry)) { local++; continue; }
ConfigDescription old = entry.Description;
object[] tags = (old.Tags ?? new object[0]).Concat(new object[]
{
new global::ConfigurationManagerAttributes { IsAdminOnly = true }
}).ToArray();
descField.SetValue(entry, new ConfigDescription(old.Description, old.AcceptableValues, tags));
synced++;
}
Debug.Log($"[RacesOfValheim] Config sync: {synced} entries admin-synced, {local} left local.");
}
private static bool ShouldSync(ConfigEntryBase entry)
{
Type type = entry.SettingType;
if (type == typeof(KeyboardShortcut) || type == typeof(KeyCode)) return false;
string section = entry.Definition.Section ?? "";
string key = (entry.Definition.Key ?? "").ToLowerInvariant();
if (section.EndsWith("Keybinds", StringComparison.OrdinalIgnoreCase)) return false;
if (LocalSections.Contains(section, StringComparer.OrdinalIgnoreCase)) return false;
if (LocalKeyParts.Any(key.Contains)) return false;
// Model pose nudges (rotation/offset/yaw) are cosmetic, but "Attack Reach Offset" is a
// real hit-detection distance and must stay in step with the server.
if ((key.Contains("rotation") || key.Contains("offset") || key.Contains("yaw"))
&& !key.Contains("reach")) return false;
// Decorative note lines (CustomDrawer/ReadOnly) carry no value worth sending.
ConfigurationManagerAttributes ours = (entry.Description?.Tags ?? new object[0]).OfType<ConfigurationManagerAttributes>().FirstOrDefault();
if (ours != null && (ours.CustomDrawer != null || ours.ReadOnly == true)) return false;
return true;
}
}
}

View file

@ -1,32 +0,0 @@
using UnityEngine;
using BepInEx.Configuration;
namespace RacesOfValheim
{
/// <summary>
/// The mod-wide debug switches, in one "Debug" section rather than one per race. Bound last
/// from RacesOfValheim.Awake(), so Configuration Manager lists the section at the bottom.
///
/// Every entry stays local (never synced from the server): ConfigSync leaves KeyboardShortcut
/// entries and any key containing "debug" alone, so keep "Debug" in the key names.
/// </summary>
public static class DebugConfig
{
public static ConfigEntry<bool> EnableDebugKey;
public static ConfigEntry<KeyboardShortcut> DebugKey;
public static ConfigEntry<bool> LogFormHits;
public static void Bind(ConfigFile config)
{
const string section = "Debug";
EnableDebugKey = config.Bind(section, "Debug: Enable Debug Key", false,
new ConfigDescription("Turns on the debug key below. Leave it off unless you are sending a bug report."));
DebugKey = config.Bind(section, "Debug Key", new KeyboardShortcut(KeyCode.F8),
new ConfigDescription("Toggles the melee reach readout (top left and log) and writes what the Alfar drones and the camera's target are doing to the log."));
// Was "Fenrir - Debug" / "Debug: Log Form Hits" until v1.6.10. It covers the Skadi,
// Sverm and Trol forms too (FormMelee.LogHit), so it moved here.
LogFormHits = config.Bind(section, "Debug: Log Form Hits", false,
new ConfigDescription("Writes one log line per form claw, bite or swing: what was in reach, what it hit, and why anything was skipped. For bug reports about attacks that do no damage."));
}
}
}

View file

@ -1,263 +0,0 @@
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// A form that flies on Character's native flying-creature movement (m_flying) and is steered
/// by DirectedFlightPatch. The Skadi's drakes were the first; the Aswid's bat moved onto it from
/// vanilla's debug-fly flag in the 2026 rebalance, so the two share one set of controls and
/// differ only in the numbers each form hands back here.
/// </summary>
public interface IDirectedFlyer
{
/// <summary>False while the form is on the ground on purpose (a landed drake).</summary>
bool IsFlying { get; }
/// <summary>Time.time of the last powered or grounded moment; the hover window counts from it.</summary>
float LastPoweredTime { get; set; }
float TurnSpeed { get; }
float GlideSpeed { get; }
float BoostSpeed { get; }
float SprintSpeed { get; }
float ReverseSpeed { get; }
float LiftoffSpeed { get; }
float HoverSeconds { get; }
/// <summary>Stamina per second for powered flight (forward or reverse). 0 is free.</summary>
float PoweredStaminaPerSecond { get; }
/// <summary>Stamina per second for the sprint, charged on top of the powered cost.</summary>
float SprintStaminaPerSecond { get; }
/// <summary>False forbids powered flight outright, so the form can only glide and sink.</summary>
bool CanPower { get; }
}
public static class DirectedFlight
{
/// <summary>The local player's flying form, if any. Set and cleared by the form itself.</summary>
public static IDirectedFlyer Active { get; private set; }
public static void Register(IDirectedFlyer flyer) { Active = flyer; }
public static void Unregister(IDirectedFlyer flyer)
{
if (Active == flyer) Active = null;
}
/// <summary>The active form, only while it is actually in the air.</summary>
public static IDirectedFlyer Flying => Active != null && Active.IsFlying ? Active : null;
}
// The form flips the player into Character's native flying-creature movement (m_flying = true)
// instead of the debug-fly noclip, which lets us feed it a full 3D move direction.
// Character.UpdateFlying normally reads whatever m_moveDir the vanilla input pipeline last
// wrote (ground-plane WASD relative to camera yaw only); this patch overwrites it every frame
// with the camera's actual look direction (pitch included) so the player always glides toward
// wherever the mouse is aiming, with W powering forward, Shift spending stamina for a burst of
// speed, and S beating backwards away from whatever you are looking at.
[HarmonyPatch(typeof(Character), "UpdateFlying")]
public static class DirectedFlightPatch
{
// Tangent of the unpowered descent angle: 0.4 sinks at roughly 22 degrees below level.
private const float DESCENT_SLOPE = 0.4f;
// How much of the aim heading survives the climb out of water. Mostly up, with enough
// forward in it that the player still chooses which shore they surface towards.
private const float LIFTOFF_HEADING_BLEND = 0.35f;
// How far the left stick has to be pushed before it counts as W or S.
private const float StickThreshold = 0.5f;
/// <summary>
/// True while the local player is beating backwards this frame. Read by
/// SkadiReverseFacingPatch, which keeps the body pointed at the camera while it happens.
/// </summary>
public static bool Reversing { get; private set; }
// The September 2026 hotfix dropped the bool parameter from ZInput.GetJoyLeftStickY.
// A direct call binds to whichever signature we compiled against and throws
// MissingMethodException on the other, so resolve it at runtime and accept either.
private static readonly MethodInfo JoyLeftStickYMethod =
AccessTools.Method(typeof(ZInput), "GetJoyLeftStickY", new System.Type[0]) ??
AccessTools.Method(typeof(ZInput), "GetJoyLeftStickY", new[] { typeof(bool) });
private static float JoyLeftStickY()
{
if (JoyLeftStickYMethod == null) return 0f;
return (float)JoyLeftStickYMethod.Invoke(null, JoyLeftStickYArgs);
}
// Old signature: pass smooth = true, which was its default.
private static readonly object[] JoyLeftStickYArgs =
JoyLeftStickYMethod != null && JoyLeftStickYMethod.GetParameters().Length == 1 ? new object[] { true } : null;
public static void Prefix(Character __instance, float dt)
{
if (__instance != Player.m_localPlayer) return;
IDirectedFlyer form = DirectedFlight.Flying;
if (form == null)
{
Reversing = false;
return;
}
var traverse = Traverse.Create(__instance);
Vector3 lookDir = Player.m_localPlayer.GetLookDir();
bool input = RaceInput.Allowed;
// The pad's half of W/S: the left stick, read with vanilla's own sign -
// PlayerController.FixedUpdate takes forward as the NEGATED GetJoyLeftStickY.
// Flight only knows powered forward, reverse or neither, so the stick is a
// threshold, not a throttle. Steering stays on the camera, i.e. the right stick.
float stick = -JoyLeftStickY();
// The keyboard side reads vanilla's own Forward/Backward/Run actions, so a key the
// player rebound in the settings flies too, not just W, S and Shift.
bool forward = input && (ZInput.GetButton("Forward") || stick > StickThreshold);
// Forward wins a W+S mash rather than the two cancelling into a dead hover.
bool backward = input && !forward && (ZInput.GetButton("Backward") || stick < -StickThreshold);
// Sprint on a pad is vanilla's run button, wherever the chosen layout puts it.
bool sprintKey = input && (ZInput.GetButton("Run") || ZInput.GetButton("JoyRun"));
bool onGround = __instance.IsOnGround();
// IsSwimming is the exact test UpdateMotion uses to hand the frame to UpdateSwimming
// instead of UpdateFlying, so it is also the one condition DirectedFlightWaterPatch has
// to take back. Its half-second tail past leaving the water is welcome here - it
// keeps the climb going just long enough to clear the surface properly.
bool inWater = __instance.IsSwimming();
// Powered flight is paid for up front, per frame. A form that cannot pay - out of
// stamina, or barred from powering at all - falls through to the glide below rather
// than out of the sky.
if ((forward || backward) && !(form.CanPower && TrySpendStamina(form.PoweredStaminaPerSecond, dt)))
{
forward = false;
backward = false;
}
Reversing = backward;
// m_run only picks between the two fly speeds. Every mode now has its own speed, so
// leave it off and drive all of them through m_flySlowSpeed.
traverse.Field("m_run").SetValue(false);
// UpdateFlying rotates the body toward m_moveDir on its own, but at m_flyTurnSpeed,
// which sits at Character's 12 deg/s default because the Player prefab was never set
// up as a flying creature - a 90 degree turn would take over seven seconds, so the
// model reads as not turning at all. Give it a speed that suits a flying form.
traverse.Field("m_flyTurnSpeed").SetValue(form.TurnSpeed);
// Powered flight, ground contact and clawing out of water all refresh the hover
// window, so none of them can be followed by an immediate sink.
if (forward || backward || onGround || inWater) form.LastPoweredTime = Time.time;
Vector3 moveDir = lookDir;
float speed;
if (inWater)
{
// Wet wings still beat. Water used to be a trap: UpdateMotion hands a swimming
// character to UpdateSwimming before it ever looks at m_flying, so a form that
// touched the sea was stuck paddling with the flight controls doing nothing.
// DirectedFlightWaterPatch gives the frame back to flight, and this branch spends
// it climbing regardless of where the camera points, so the surface is always
// something you break out of rather than something you sit in. Free on purpose:
// a form that could not pay to leave the water would drown in it.
moveDir = (Vector3.up + FlatHeading(__instance, lookDir) * LIFTOFF_HEADING_BLEND).normalized;
speed = form.LiftoffSpeed;
}
else if (backward)
{
// Straight reverse thrust along the aim, pitch included: look down and beat back
// and you rise away from what you are looking at, which is the whole point of
// having a reverse - you can retreat without taking your eyes (or your breath
// attack, which fires along the same vector) off the target.
moveDir = -lookDir;
speed = form.ReverseSpeed;
}
else if (forward)
{
speed = form.BoostSpeed;
if (sprintKey && TrySpendStamina(form.SprintStaminaPerSecond, dt)) speed = form.SprintSpeed;
}
else if (onGround || Time.time - form.LastPoweredTime < form.HoverSeconds)
{
// Holding station: on the ground this keeps a touchdown from sliding the player
// forward forever, and in the air it gives the beats of level flight before the
// form starts to sink. m_moveDir stays full length so the body still turns to
// face the camera, and zeroing the speed (rather than the rigidbody velocity)
// avoids fighting the AddForce UpdateFlying queues, which caused visible jitter.
speed = 0f;
}
else
{
// Unpowered flight is a glide, not a hover with a joystick: drift along the
// heading the camera faces while losing height, so aiming at the sky without
// holding W no longer climbs.
moveDir = (FlatHeading(__instance, lookDir) + Vector3.down * DESCENT_SLOPE).normalized;
speed = form.GlideSpeed;
}
traverse.Field("m_moveDir").SetValue(moveDir);
traverse.Field("m_flySlowSpeed").SetValue(speed);
}
/// <summary>Aim flattened onto the ground plane, falling back to the body's own facing
/// when the player is looking straight up or down.</summary>
private static Vector3 FlatHeading(Character character, Vector3 lookDir)
{
Vector3 heading = new Vector3(lookDir.x, 0f, lookDir.z);
if (heading.sqrMagnitude < 0.0001f)
{
heading = character.transform.forward;
heading.y = 0f;
}
return heading.normalized;
}
/// <summary>
/// Charges this frame of a per-second cost. Returns false when the player cannot pay.
/// A rate of zero is always paid, so a free mode costs nothing and never fails.
/// </summary>
private static bool TrySpendStamina(float perSecond, float dt)
{
if (perSecond <= 0f) return true;
Player player = Player.m_localPlayer;
if (player == null) return false;
float cost = perSecond * dt;
if (!player.HaveStamina(cost)) return false;
player.UseStamina(cost);
return true;
}
}
/// <summary>
/// Character.UpdateMotion asks IsSwimming before it asks m_flying, so a flying form that
/// touched water was handed to UpdateSwimming every frame: the flight patch above never ran,
/// the form paddled on the surface, and there was no way back into the air short of finding
/// land. Hand those frames back to UpdateFlying, which is the only motion path the two methods
/// contend over: nothing else calls either of them, and everything that merely asks
/// IsSwimming - the Wet status, the animator, stamina - is left alone.
/// </summary>
[HarmonyPatch(typeof(Character), "UpdateSwimming")]
public static class DirectedFlightWaterPatch
{
private static readonly MethodInfo UpdateFlyingMethod = AccessTools.Method(typeof(Character), "UpdateFlying");
public static bool Prefix(Character __instance, float dt)
{
if (__instance != Player.m_localPlayer) return true;
if (DirectedFlight.Flying == null) return true;
// Fail open: if a game update ever renames the method, swim normally rather than
// freezing the player in place with no motion update at all.
if (UpdateFlyingMethod == null) return true;
UpdateFlyingMethod.Invoke(__instance, new object[] { dt });
return false;
}
}
}

View file

@ -33,7 +33,6 @@ namespace RacesOfValheim
// ─── Undead Fortitude (tier 4+: crit on staggered, death aura) ──────────
public static ConfigEntry<float> StaggerCritMultiplier;
public static ConfigEntry<float> DeathAuraRadius;
public static ConfigEntry<float> HumanMeatNourishmentMultiplier;
// ─── North Wind (tier 5+: AoE frost on parry, on the same cooldown) ──────
public static ConfigEntry<float> NorthWindCooldown;
@ -80,10 +79,6 @@ namespace RacesOfValheim
new ConfigDescription("Multiplies physical damage dealt to staggered enemies, tier 4+.", new AcceptableValueRange<float>(1f, 3f)));
DeathAuraRadius = config.Bind(fortitude, "Death Aura Radius", 100f,
new ConfigDescription("Meters within which an ally's death drops Human Meat for you, tier 4+.", new AcceptableValueRange<float>(10f, 300f)));
// A multiplier rather than absolute numbers: Human Meat is built from Blood Pudding's own
// nourishment at start-up, and those are the game's values, not ours to hardcode.
HumanMeatNourishmentMultiplier = config.Bind(fortitude, "Human Meat Nourishment Multiplier", 1f,
new ConfigDescription("Scales Human Meat's health, stamina and eitr against the Blood Pudding it is built from. Read once at start-up.", new AcceptableValueRange<float>(0.1f, 3f)));
const string northWind = "Draugh - North Wind";
NorthWindCooldown = config.Bind(northWind, "Cooldown", 20f,

View file

@ -18,25 +18,16 @@ namespace RacesOfValheim
{ "NeckTail", "NeckTailGrilled" },
{ "FishRaw", "FishCooked" },
{ "LoxMeat", "CookedLoxMeat" },
{ "SerpentMeat", "SerpentMeatCooked" },
{ "SerpentMeatRaw", "SerpentMeatCooked" },
{ "WolfMeat", "CookedWolfMeat" },
{ "DeerMeat", "CookedDeerMeat" },
{ "HareMeat", "CookedHareMeat" },
{ "ChickenMeat", "CookedChickenMeat" },
{ "BugMeat", "CookedBugMeat" },
{ "VoltureMeat", "CookedVoltureMeat" },
{ "VoltureMeat", "RoastedVoltureMeat" },
{ "GreydwarfEye", "DeerStew" },
{ "Entrails", "Sausages" },
{ "Bloodbag", "BloodPudding" },
{ "MooseMeat", "CookedMooseMeat" },
// Bjorn, the Valheim 1.0 bear.
{ "BjornMeat", "CookedBjornMeat" },
// Ashlands.
{ "AsksvinMeat", "CookedAsksvinMeat" },
{ "BoneMawSerpentMeat", "CookedBoneMawSerpentMeat" },
// Raw blubber keeps its own name and icon (EdibleUncooked_ copies them from the raw
// item) and gives the stats of Seal Meat Soup.
{ "SealBlubber", "SealSoup" }
{ "Bloodbag", "BloodPudding" }
};
[HarmonyPatch(typeof(Humanoid), "UseItem")]
@ -51,7 +42,7 @@ namespace RacesOfValheim
{
if (!DraughRace.IsDraugh())
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_this_rotting_flesh_fatal_living"));
player.Message(MessageHud.MessageType.Center, "This rotting flesh is fatal to the living.");
return false; // Block consumption
}
// If it IS a Draugh, let them consume it via native mechanics
@ -95,11 +86,6 @@ namespace RacesOfValheim
var zanim = Traverse.Create(player).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null) zanim.SetTrigger("eat");
}
else
{
// Vanilla's refusal message, which EatFood never shows by itself
player.CanEat(customItemDrop.m_itemData, true);
}
return false; // Skip native UseItem
}
}
@ -115,7 +101,7 @@ namespace RacesOfValheim
bool isFood = item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0;
if (isFood)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_draugr_consume_only_raw_flesh"));
player.Message(MessageHud.MessageType.Center, "Draugr consume only raw flesh, eyes, entrails or blood.");
return false; // Block it
}
}
@ -148,11 +134,17 @@ namespace RacesOfValheim
Player.Food f = foodObj as Player.Food;
if (f != null && f.m_item.m_shared.m_name == item.m_shared.m_name && f.CanEatAgain())
{
// Was `f.m_time = 0f`, which expired the flesh instead of renewing
// it. This is the original of the copy the Aswid and the Trenta
// both inherited - see RaceFoodRefresh.
RaceFoodRefresh.Refresh(__instance, f, item);
f.m_time = 0f;
f.m_item = item.Clone();
var consumeEffects = Traverse.Create(__instance).Field("m_consumeItemEffects").GetValue<EffectList>();
if (consumeEffects != null) consumeEffects.Create(__instance.transform.position, Quaternion.identity, __instance.transform, 1f, -1);
var zanim = Traverse.Create(__instance).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null) zanim.SetTrigger("eat");
if (item.m_shared.m_food > 0f) __instance.Heal(item.m_shared.m_food, true);
refreshed = true;
break;
}
@ -164,10 +156,9 @@ namespace RacesOfValheim
return false; // Skip native EatFood
}
// Full, and no slot holds this flesh. Native EatFood replaces the most
// depleted meal past half its time, or refuses - vanilla's own rule. This
// used to refuse outright, with no message.
return true;
// Inventory full
__result = false;
return false;
}
else
{

View file

@ -1,140 +0,0 @@
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Human Meat, the Bonemass-tier reward: an ally who dies near a Draugh leaves a piece of
/// themselves behind, and only a Draugh can stomach it.
///
/// THIS ITEM DID NOT EXIST. Two places in the mod already used it - the drop in
/// DraughProgressionPatches.Draugh_DeathAura_Patch and the "fatal to the living" block in
/// DraughFoodPatches - and both looked it up by the name "HumanMeat", which nothing registered.
/// So the drop never happened and the block never fired: a perk the README has promised since
/// 1.4 with no item behind it. The two consumers are unchanged; what was missing was the
/// producer.
///
/// BUILT FROM TWO VANILLA ITEMS, one for the look and one for the numbers:
///
/// RawMeat gives the clone its model and icon, because that is what a piece of somebody looks
/// like, and because the Draugh's whole food identity is raw flesh.
///
/// BloodPudding gives the nourishment, copied field by field at start-up rather than written
/// down here. Blood Pudding is a real cooked food in the game's own progression, so its
/// numbers are balanced against the rest of it, and reading them means this item follows any
/// change the game makes to them. DraughConfig.HumanMeatNourishmentMultiplier scales them.
/// Its stamina is folded into health rather than copied across - see the note further down.
///
/// RawMeat is a Material in vanilla - raw meat is not edible - so m_itemType is forced to
/// Consumable. That is the one assumption in here worth knowing about: the alternative, which
/// DraughRace.CreateModAssets uses for its EdibleUncooked_ items, is to clone the COOKED item and
/// dress it as the raw one, which gets consumability for free but keeps the cooked model. If the
/// game ever refuses to eat this, that is the fallback, and the log line below prints exactly
/// what was produced so it can be told apart from a missing prefab.
/// </summary>
internal static class DraughHumanMeat
{
/// <summary>The name the two consumers look it up by. Changing it breaks both.</summary>
public const string PrefabName = "HumanMeat";
private const string LookSource = "RawMeat";
private const string NourishmentSource = "BloodPudding";
/// <summary>
/// Darkens the meat and pulls it towards blood, so a stack of Human Meat is not mistaken for
/// the deer meat it is built from. Multiplied into the material's own colour, so it darkens
/// whatever the texture already is rather than replacing it.
/// </summary>
private static readonly Color Tint = new Color(0.62f, 0.34f, 0.38f, 1f);
/// <summary>
/// Called from DraughRace.CreateModAssets, which is to say while vanilla prefabs are
/// available and before anything can ask for this item.
/// </summary>
public static void Register()
{
ItemDrop look = FindItem(LookSource);
ItemDrop nourishment = FindItem(NourishmentSource);
if (look == null || nourishment == null)
{
// Nothing is registered rather than a half-built item: the two consumers both check
// for null, so no meat is a quiet no-op, while a nameless inedible one is not.
Jotunn.Logger.LogWarning(
$"[Draugh] Human Meat not registered: '{LookSource}' " +
$"{(look == null ? "missing" : "ok")}, '{NourishmentSource}' " +
$"{(nourishment == null ? "missing" : "ok")}.");
return;
}
CustomItem item = new CustomItem(PrefabName, LookSource);
ItemDrop.ItemData.SharedData shared = item.ItemDrop.m_itemData.m_shared;
ItemDrop.ItemData.SharedData source = nourishment.m_itemData.m_shared;
shared.m_name = "$rov_item_draugh_humanmeat_name";
shared.m_description = "$rov_item_draugh_humanmeat_desc";
// Raw meat is a Material in vanilla, so none of the food fields below would be read
// without this.
shared.m_itemType = ItemDrop.ItemData.ItemType.Consumable;
// BLOOD PUDDING'S STAMINA GOES ONTO HEALTH, AND STAMINA IS LEFT AT ZERO. A Draugh does
// not use stamina, so nourishment spent there is nourishment thrown away - the food
// slot would look full while giving the race half of what it cost. Adding the two
// together keeps the item worth the same as the pudding it is balanced against, which
// is the point of reading the pudding at all.
float scale = DraughConfig.HumanMeatNourishmentMultiplier.Value;
shared.m_food = (source.m_food + source.m_foodStamina) * scale;
shared.m_foodStamina = 0f;
shared.m_foodEitr = source.m_foodEitr * scale;
shared.m_foodRegen = source.m_foodRegen;
shared.m_foodBurnTime = source.m_foodBurnTime;
shared.m_maxStackSize = source.m_maxStackSize;
shared.m_consumeStatusEffect = source.m_consumeStatusEffect;
Recolour(item.ItemDrop.gameObject);
ItemManager.Instance.AddItem(item);
Jotunn.Logger.LogInfo(
$"[Draugh] Human Meat registered from '{LookSource}' + '{NourishmentSource}': " +
$"type={shared.m_itemType} food={shared.m_food:F0} stamina={shared.m_foodStamina:F0} " +
$"eitr={shared.m_foodEitr:F0} regen={shared.m_foodRegen:F0} " +
$"burn={shared.m_foodBurnTime:F0}s stack={shared.m_maxStackSize}.");
}
private static ItemDrop FindItem(string prefabName)
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
return prefab != null ? prefab.GetComponent<ItemDrop>() : null;
}
/// <summary>
/// Tints the clone's own materials, on copies.
///
/// The clone's renderers still point at the vanilla RawMeat materials, which are shared with
/// every piece of raw meat in the world - writing a colour into one of those would tint the
/// lot. Each renderer gets its own copy instead, which this prefab then owns.
/// </summary>
private static void Recolour(GameObject root)
{
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
Material[] materials = renderer.sharedMaterials;
if (materials == null) continue;
for (int i = 0; i < materials.Length; i++)
{
if (materials[i] == null) continue;
Material copy = new Material(materials[i]);
if (copy.HasProperty("_Color")) copy.color = copy.color * Tint;
materials[i] = copy;
}
renderer.sharedMaterials = materials;
}
}
}
}

View file

@ -22,7 +22,7 @@ namespace RacesOfValheim
// Invert the Wet debuff to actually heal the Draugh
__instance.m_healthRegenMultiplier = DraughConfig.WetHealthRegenMultiplier.Value;
__instance.m_staminaRegenMultiplier = 1f; // No stamina penalty
__instance.m_tooltip = "$rov_se_draugh_wet_tooltip";
__instance.m_tooltip = "The water restores your rotten flesh. Health regeneration increased.";
}
}
}
@ -98,25 +98,8 @@ namespace RacesOfValheim
attacker.ApplyDamage(poisonSplash, true, false);
// Visual effect for splash. "vfx_OozeHit" is not a prefab in this game -
// the blob's hit effect is vfx_blob_hit - and this was the one dead name
// in the mod that was passed to Instantiate unguarded, so every
// successful parry threw ArgumentException here and took the North Wind
// nova below down with it.
GameObject splashVfx = ZNetScene.instance.GetPrefab("vfx_blob_hit");
if (splashVfx != null)
{
UnityEngine.Object.Instantiate(splashVfx, attacker.GetCenterPoint(), Quaternion.identity);
}
// Said on every parry, which are rare enough not to be noise. A parry has
// to land inside a quarter-second window while blocking, so "nothing looks
// different" is as likely to mean the window was missed as it is to mean
// the splash did not draw - and there was no way to tell the two apart.
Jotunn.Logger.LogInfo(
$"[Draugh] Parry on '{attacker.name}': {DraughConfig.PoisonSplashDamage.Value:F0} poison, " +
$"blockTimer={blockTimer:F3} of {parryTime:F2}, " +
$"splash vfx={(splashVfx != null ? "vfx_blob_hit" : "NOT RESOLVED")}.");
// Visual effect for splash
UnityEngine.Object.Instantiate(ZNetScene.instance.GetPrefab("vfx_OozeHit"), attacker.GetCenterPoint(), Quaternion.identity);
// Stage 5: North Wind (AoE Frost)
if (state >= 5)
@ -153,7 +136,7 @@ namespace RacesOfValheim
}
}
Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, ModText.Get("rov_msg_draugh_northern_wind_blows"));
Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "The northern wind blows");
}
}
}
@ -312,7 +295,7 @@ namespace RacesOfValheim
if (prefab != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_swarm_terror"));
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Swarm of Terror!");
for (int i = 0; i < DraughConfig.SwarmSpawnCount.Value; i++)
{
@ -356,7 +339,7 @@ namespace RacesOfValheim
float healAmount = Player.m_localPlayer.GetMaxHealth() * DraughConfig.StealBreathHealPercent.Value;
Player.m_localPlayer.Heal(healAmount);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_steal_their_breath_death_denied"));
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Steal Their Breath! Death is denied.");
// Restore visuals immediately
if (Player.m_localPlayer.GetComponent<VisEquipment>() != null)

View file

@ -23,10 +23,6 @@ namespace RacesOfValheim
// Draugr is ever set up as a bench.
DraughSpawner.Register();
// The Bonemass-tier drop. Registered here for the same reason as the pile: two places in
// the mod already look it up by name, and until now nothing created it.
DraughHumanMeat.Register();
// Generate EdibleUncooked prefabs for Draugh raw food logic
foreach (var mapping in DraughFoodPatches.rawToCookedMapping)
{
@ -133,7 +129,7 @@ namespace RacesOfValheim
public System.Collections.IEnumerator UndyingWillRoutine(Player p)
{
p.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_zombie_ritual_activated_borrowed_time"));
p.Message(MessageHud.MessageType.Center, "Zombie Ritual Activated! Your borrowed time is fading...");
// Trigger a re-evaluation of visuals to apply the ghost effect
if (p.GetComponent<VisEquipment>() != null)

View file

@ -25,17 +25,17 @@ namespace RacesOfValheim
{
// ─── Names ───────────────────────────────────────────────────────────
public const string PieceName = "DraughBodyPile";
public const string PieceDisplayName = "$rov_piece_draugh_bodypile_name";
public const string PieceDisplayName = "Cursed Body Pile";
public const string BoneName = "CursedBone";
public const string BoneDisplayName = "$rov_item_draugh_cursedbone_name";
public const string BoneDisplayName = "Cursed Bone";
public const string GreaterBoneName = "GreaterCursedBone";
public const string GreaterBoneDisplayName = "$rov_item_draugh_greatercursedbone_name";
public const string GreaterBoneDisplayName = "Greater Cursed Bone";
public const string ThrallName = "DraughThrall_Draugr";
public const string ThrallEliteName = "DraughThrall_DraugrElite";
public const string ThrallDisplayName = "$rov_creature_draugh_thrall_name";
public const string ThrallEliteDisplayName = "$rov_creature_draugh_thrallelite_name";
public const string ThrallDisplayName = "Draugr Thrall";
public const string ThrallEliteDisplayName = "Draugr Elite Thrall";
// RaisedThrall groups by kind for follower caps and for the roster, so these are the strings
// that decide "is this one an officer" - no longer a display-name comparison.
@ -118,9 +118,9 @@ namespace RacesOfValheim
public static void Register()
{
RegisterBone(BoneName, BoneDisplayName, BoneTint,
"$rov_item_draugh_cursedbone_desc");
"A bone that will not stay quiet. The dead sell them; the dead do not say why.");
RegisterBone(GreaterBoneName, GreaterBoneDisplayName, GreaterBoneTint,
"$rov_item_draugh_greatercursedbone_desc");
"The same bone, older, and louder. A pile fed one of these starts keeping officers.");
RegisterThrall(ThrallName, "Draugr", ThrallDisplayName, KindNormal, MaxFollowers);
RegisterThrall(ThrallEliteName, "Draugr_Elite", ThrallEliteDisplayName, KindElite, MaxEliteFollowers);
@ -129,7 +129,7 @@ namespace RacesOfValheim
PieceDensityLimit.Register(PieceName,
PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxPilesInRange,
"rov_msg_build_limit_draugh_bodypile");
"The ground here already carries {0} of these. Find another country.");
}
// ---------------------------------------------------------------- items
@ -201,7 +201,7 @@ namespace RacesOfValheim
thrall.m_maxFollowers = maxFollowers;
thrall.m_witherSeconds = OrphanWitherSeconds;
thrall.m_homeCheckRange = HomeCheckRange;
thrall.m_refusalMessage = "$rov_msg_thrall_refusal_draugh";
thrall.m_refusalMessage = "The dead do not take orders from the living.";
PrefabManager.Instance.AddPrefab(prefab);
}
@ -251,12 +251,8 @@ namespace RacesOfValheim
piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplayName;
piece.m_canBeRemoved = true;
// Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch
// the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's
// mesh floor - so players saw no ghost at all and could not tell why. A station belongs
// in a house or a cave as much as outside.
piece.m_groundPiece = false;
piece.m_groundOnly = false;
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_icon = BorrowIcon(TrophyDraugr);
// Learned on the Furling's bushes: a Piece added to world scenery is born with no icon
@ -267,7 +263,7 @@ namespace RacesOfValheim
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = PieceDisplayName,
Description = "$rov_piece_draugh_bodypile_desc",
Description = "Feed it and it answers. The dead here are yours, if you are dead enough to ask.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = BorrowIcon(TrophyDraugr),

View file

@ -65,14 +65,7 @@ namespace RacesOfValheim
/// Raw flesh feeds it, a Draugr trophy is a whole batch, an Elite trophy is an officer, and a
/// Greater Cursed Bone upgrades it. Empty hands just report.
/// </summary>
// With an item in hand every outcome counts as handled, refusals included: false makes
// Humanoid.UseItem cover our own message with the generic "$msg_cantuseon".
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
return Use(user, item) || item != null;
}
private bool Use(Humanoid user, ItemDrop.ItemData item)
{
if (user == null) return false;
@ -82,7 +75,7 @@ namespace RacesOfValheim
if (item == null) item = FindAnyInput(inventory);
if (item == null)
{
user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_wants_flesh_or_head_one"));
user.Message(MessageHud.MessageType.Center, "It wants flesh, or the head of one of its own.");
return false;
}
@ -93,7 +86,7 @@ namespace RacesOfValheim
if (prefabName == DraughSpawner.TrophyDraugrElite && !IsUpgraded())
{
user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_this_pile_keeps_no_officers"));
user.Message(MessageHud.MessageType.Center, "This pile keeps no officers yet.");
return false;
}
@ -162,19 +155,19 @@ namespace RacesOfValheim
{
if (IsUpgraded())
{
user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_has_already_had_one"));
user.Message(MessageHud.MessageType.Center, "It has already had one.");
return false;
}
if (BossProgressionManager.GetCurrentProgressionState() < DraughSpawner.UpgradeProgressionState)
{
user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_bone_will_not_wake_something"));
user.Message(MessageHud.MessageType.Center, "The bone will not wake. Something older has to fall first.");
return false;
}
inventory.RemoveItem(item, 1);
m_nview.InvokeRPC("RoV_DraughUpgrade");
user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_pile_stirs_will_keep_officers"));
user.Message(MessageHud.MessageType.Center, "The pile stirs. It will keep officers now.");
return true;
}
@ -294,7 +287,7 @@ namespace RacesOfValheim
if (bound.Count > 0 && Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center,
ModText.Get("rov_msg_draugh_pile_broken_will_not_outlast", bound.Count));
$"The pile is broken. {bound.Count} will not outlast it by more than a minute.");
}
SetFlesh(0f);
@ -328,20 +321,21 @@ namespace RacesOfValheim
if (thrall.Kind == DraughSpawner.KindElite) aliveElite++; else aliveNormal++;
}
string body = ModText.Get("rov_hover_draugh_flesh_risen_waiting", Mathf.Floor(GetFlesh()), DraughSpawner.FleshPerThrall, aliveNormal, AliveCap(), GetReserve(), DraughSpawner.ReserveCap);
string body = $"flesh {Mathf.Floor(GetFlesh())}/{DraughSpawner.FleshPerThrall}, " +
$"risen {aliveNormal}/{AliveCap()}, waiting {GetReserve()}/{DraughSpawner.ReserveCap}";
if (IsUpgraded())
{
body += ModText.Get("rov_hover_draugh_officers_waiting", aliveElite, EliteCap(), GetReserveElite(), DraughSpawner.ReserveCapElite);
body += $"\nofficers {aliveElite}/{EliteCap()}, waiting {GetReserveElite()}/{DraughSpawner.ReserveCapElite}";
}
if (m_respawnTimer > 0f)
{
int left = Mathf.Max(1, Mathf.CeilToInt(DraughSpawner.RespawnSeconds - m_respawnTimer));
body += ModText.Get("rov_hover_draugh_next_rises_s", left);
body += $"\nnext rises in {left}s";
}
body += ModText.Get("rov_hover_draugh_feed_flesh_or_draugr_s");
body += "\n[<color=yellow><b>$KEY_Use</b></color>] Feed it flesh, or a draugr's head";
return Localization.instance.Localize($"{DraughSpawner.PieceDisplayName} ({body})");
}

View file

@ -45,7 +45,7 @@ namespace RacesOfValheim
if (player.GetEitr() < DvergarConfig.RunicPingEitrCost)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_not_enough_eitr"));
player.Message(MessageHud.MessageType.Center, "Not enough eitr");
return;
}
@ -55,7 +55,7 @@ namespace RacesOfValheim
int marked = MarkSurroundings(player);
player.Message(MessageHud.MessageType.Center,
(marked > 0 ? ModText.Get("rov_msg_dvergar_runic_ping_echoes_answer", marked) : ModText.Get("rov_msg_dvergar_runic_ping_stone_silent")));
marked > 0 ? $"Runic Ping: {marked} echoes answer" : "Runic Ping: the stone is silent");
}
/// <summary>
@ -173,7 +173,7 @@ namespace RacesOfValheim
if (player.GetEitr() < DvergarConfig.RunicOverchargeEitrCost)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_not_enough_eitr"));
player.Message(MessageHud.MessageType.Center, "Not enough eitr");
return;
}
@ -186,7 +186,7 @@ namespace RacesOfValheim
// The charge is held, not permanent: it lapses if no favoured blow lands in time.
if (se != null) se.m_ttl = DvergarConfig.RunicOverchargeWindow;
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_runic_overcharge_next_blow_loaded"));
player.Message(MessageHud.MessageType.Center, "Runic Overcharge: your next blow is loaded");
}
/// <summary>

View file

@ -36,7 +36,7 @@ namespace RacesOfValheim
public static class DvergarBanco
{
public const string PieceName = "DvergarContractBank";
public const string PieceDisplayName = "$rov_piece_dvergar_contractbank_name";
public const string PieceDisplayName = "Contract Bank";
public const string RaceId = DvergarConfig.RaceId;
/// <summary>The Queen's drop, mapped to state 7 in BossProgressionManager. Mistlands money for
@ -76,12 +76,6 @@ namespace RacesOfValheim
private const float PileHeight = 1.05f;
private const float PileSize = 0.45f;
// The dressing, in the same unscaled table space as the pile. The pile owns the centre, so the
// tankard stands just clear of it, on the near side.
private static readonly Color BankWoodTint = new Color(0.62f, 0.55f, 0.5f, 1f);
private static readonly Vector3 TankardSpot = new Vector3(0.45f, PileHeight, -0.25f);
private const float TankardSize = 0.38f;
public class Troop
{
public string Id;
@ -105,7 +99,7 @@ namespace RacesOfValheim
{
new Troop
{
Id = "escort", Display = "$rov_troop_dvergar_escort", Price = 400, NeedsUpgrade = false, Icon = "TrophyDvergr",
Id = "escort", Display = "Escort", Price = 400, NeedsUpgrade = false, Icon = "TrophyDvergr",
Members = new[]
{
new KeyValuePair<string, int>("Dverger", 1),
@ -114,7 +108,7 @@ namespace RacesOfValheim
},
new Troop
{
Id = "yard_patrol", Display = "$rov_troop_dvergar_yard_patrol", Price = 700, NeedsUpgrade = false, Icon = "TrophyDvergr",
Id = "yard_patrol", Display = "Yard Patrol", Price = 700, NeedsUpgrade = false, Icon = "TrophyDvergr",
Members = new[]
{
new KeyValuePair<string, int>("Dverger", 2),
@ -123,7 +117,7 @@ namespace RacesOfValheim
},
new Troop
{
Id = "fire_crew", Display = "$rov_troop_dvergar_fire_crew", Price = 1000, NeedsUpgrade = false, Icon = "TrophyDvergr",
Id = "fire_crew", Display = "Fire Crew", Price = 1000, NeedsUpgrade = false, Icon = "TrophyDvergr",
Members = new[]
{
new KeyValuePair<string, int>("Dverger", 1),
@ -133,7 +127,7 @@ namespace RacesOfValheim
},
new Troop
{
Id = "runic_crew", Display = "$rov_troop_dvergar_runic_crew", Price = 1500, NeedsUpgrade = true, Icon = "TrophyDvergr",
Id = "runic_crew", Display = "Runic Crew", Price = 1500, NeedsUpgrade = true, Icon = "TrophyDvergr",
Members = new[]
{
new KeyValuePair<string, int>("Dverger", 2),
@ -143,7 +137,7 @@ namespace RacesOfValheim
},
new Troop
{
Id = "ash_guard", Display = "$rov_troop_dvergar_ash_guard", Price = 2000, NeedsUpgrade = true, Icon = "TrophySeekerBrute",
Id = "ash_guard", Display = "Ash Guard", Price = 2000, NeedsUpgrade = true, Icon = "TrophySeekerBrute",
Members = new[]
{
new KeyValuePair<string, int>("DvergerAshlands", 2),
@ -201,7 +195,7 @@ namespace RacesOfValheim
PieceDensityLimit.Register(PieceName,
PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxBanksInRange,
"rov_msg_build_limit_dvergar_contractbank");
"There is already {0} contract bank within a day's walk. One ledger per valley.");
}
// ---------------------------------------------------------------- the hired
@ -239,7 +233,7 @@ namespace RacesOfValheim
thrall.m_maxFollowers = MaxFollowers;
thrall.m_witherSeconds = WitherSeconds;
thrall.m_homeCheckRange = HomeCheckRange;
thrall.m_refusalMessage = "$rov_msg_thrall_refusal_dvergar";
thrall.m_refusalMessage = "Your name is not on the contract.";
// Ten seconds unhurt, then two percent a second - the sentry's regeneration, shared with
// the Trol's troops and the Fenrir's pack. A dead mercenary still stays dead.
@ -282,12 +276,6 @@ namespace RacesOfValheim
prefab.transform.localScale = Vector3.one * TableScale;
// A counting table, not a map table: darker wood and a dvergr tankard beside the coin.
// Tinted BEFORE the tankard goes on, or it would be darkened too.
PieceLook.Tint(prefab.transform, BankWoodTint);
ModelBorrow.Attach(prefab.transform, "BankTankard", "Tankard_dvergr",
TankardSpot, Quaternion.identity, TankardSize, "Dvergar", activeOnly: true);
DvergarBancoBehaviour bank = prefab.AddComponent<DvergarBancoBehaviour>();
foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true))
@ -307,17 +295,6 @@ namespace RacesOfValheim
// Trol/TrolTotemStore.cs, which is generic and is deliberately NOT copied here.
Trader trader = prefab.GetComponent<Trader>() ?? prefab.AddComponent<Trader>();
trader.m_name = PieceDisplayName;
// DISABLED ON PURPOSE, and it is the line that keeps the log clean. Trader was written for
// Haldor, who is a creature with an animator and a LookAt rig: Trader.Update() calls
// m_animator.SetBool("Stand", ...) and m_lookAt.ResetTarget() with no null check on every
// frame no player is nearby, and Trader.Start() calls InvokeRepeating("RandomTalk", 0, 0)
// on a component nobody authored in the editor. On a table both of those are null, so the
// bank threw a NullReferenceException every frame from the moment it was built. A disabled
// component runs neither, and StoreGui needs neither: Show() only reads fields off the
// Trader and asks it for its item list, and GetComponent finds it disabled just the same.
// This is the same fix SvermHiveStore.Mount already carries for the Hive Market.
trader.enabled = false;
trader.m_items = new List<Trader.TradeItem>();
trader.m_useItems = new List<Trader.TraderUseItem>();
trader.m_randomTalk = new List<string>();
@ -347,12 +324,8 @@ namespace RacesOfValheim
piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplayName;
piece.m_canBeRemoved = true;
// Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch
// the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's
// mesh floor - so players saw no ghost at all and could not tell why. A station belongs
// in a house or a cave as much as outside.
piece.m_groundPiece = false;
piece.m_groundOnly = false;
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_icon = BorrowIcon("TrophyDvergr");
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
@ -364,7 +337,7 @@ namespace RacesOfValheim
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = PieceDisplayName,
Description = "$rov_piece_dvergar_contractbank_desc",
Description = "A ledger, a seal and a heap of coin. Sign here and someone else does the dying.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = BorrowIcon("TrophyDvergr"),
@ -416,10 +389,8 @@ namespace RacesOfValheim
/// The same shape as TrolTotemRaceLockPatch - the second station in the mod that refuses the hammer
/// outright, because hiring dvergr with dvergr money is the race's identity and not a tool it owns.
/// </summary>
// Valheim 1.0 appended a 'bool cheated' parameter to this overload. The type array has to
// match it exactly or the patch silently fails to bind and PatchAll throws.
[HarmonyPatch(typeof(Player), "PlacePiece",
new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool), typeof(bool) })]
new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })]
public static class DvergarBancoRaceLockPatch
{
public static bool Prefix(Player __instance, Piece __0)
@ -428,7 +399,7 @@ namespace RacesOfValheim
if (Utils.GetPrefabName(__0.gameObject) != DvergarBanco.PieceName) return true;
if (DvergarRace.IsDvergar()) return true;
__instance.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_contract_runic_do_not_sign"));
__instance.Message(MessageHud.MessageType.Center, "The contract is in runic. You do not sign it.");
return false;
}
}

View file

@ -66,10 +66,8 @@ namespace RacesOfValheim
if (!DvergarRace.IsDvergar())
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_ledger_not_written"));
// With an item in hand, false makes Humanoid.UseItem cover this message with its
// generic "$msg_cantuseon"; true tells it the use was handled here.
return item != null;
player.Message(MessageHud.MessageType.Center, "The ledger is not written for you.");
return false;
}
// The Queen's drop in hand rewrites the ledger: coin on the table, and two more crews.
@ -81,31 +79,29 @@ namespace RacesOfValheim
if (item != null)
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return true;
return false;
}
return OpenStore(player);
}
// Every refusal still returns true: this only runs from an item use, where false would
// make Humanoid.UseItem replace our message with the generic "$msg_cantuseon".
private bool TryUpgrade(Player player, ItemDrop.ItemData item)
{
if (IsUpgraded())
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_has_already_had_one"));
return true;
player.Message(MessageHud.MessageType.Center, "It has already had one.");
return false;
}
if (BossProgressionManager.GetCurrentProgressionState() < DvergarBanco.UpgradeProgressionState)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_not_while_she_still_sits"));
return true;
player.Message(MessageHud.MessageType.Center, "Not while she still sits under the mist.");
return false;
}
player.GetInventory().RemoveItem(item, 1);
m_nview.InvokeRPC("RoV_DvergarUpgrade");
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_ledger_rewritten_better_names_sign"));
player.Message(MessageHud.MessageType.Center, "The ledger is rewritten. Better names sign it now.");
return true;
}
@ -119,7 +115,7 @@ namespace RacesOfValheim
Trader trader = GetComponent<Trader>();
if (trader == null || StoreGui.instance == null)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_ledger_shut"));
player.Message(MessageHud.MessageType.Center, "The ledger is shut.");
return false;
}
@ -144,7 +140,7 @@ namespace RacesOfValheim
if (CountGroups() >= DvergarBanco.MaxTroops)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_five_contracts_all_ledger_holds"));
player.Message(MessageHud.MessageType.Center, "Five contracts is all the ledger holds.");
return;
}
@ -157,13 +153,13 @@ namespace RacesOfValheim
if (CountCoins(inventory) < price)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_not_enough_coins"));
player.Message(MessageHud.MessageType.Center, "$msg_notenoughmoney");
return;
}
TakeCoins(inventory, price);
m_nview.InvokeRPC("RoV_DvergarHire", troop.Id);
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_signs", troop.Display));
player.Message(MessageHud.MessageType.Center, $"{troop.Display} signs on.");
}
private const string CoinsPrefab = "Coins";
@ -277,16 +273,16 @@ namespace RacesOfValheim
private string Hover()
{
string body = ModText.Get("rov_hover_dvergar_contracts", CountGroups(), DvergarBanco.MaxTroops);
string body = $"contracts {CountGroups()}/{DvergarBanco.MaxTroops}";
// Said in as many words: a player who cannot see their own discount will read the lower
// number in the window as a mistake.
float discount = Mathf.Clamp01(DvergarProgression.Current.TraderBuyDiscount);
if (discount > 0f) body += ModText.Get("rov_hover_dvergar_seal_worth_off", Mathf.RoundToInt(discount * 100f));
if (discount > 0f) body += $"\nyour seal is worth {Mathf.RoundToInt(discount * 100f)}% off";
if (!IsUpgraded()) body += ModText.Get("rov_hover_dvergar_what_queen_left_behind_buys");
if (!IsUpgraded()) body += "\n(what the Queen left behind buys two more crews)";
body += ModText.Get("rov_hover_dvergar_read_ledger");
body += "\n[<color=yellow><b>$KEY_Use</b></color>] Read the ledger";
return Localization.instance.Localize($"{DvergarBanco.PieceDisplayName} ({body})");
}

View file

@ -123,14 +123,14 @@ namespace RacesOfValheim
else Jotunn.Logger.LogWarning($"[Dvergar] No icon on '{troop.Icon}' for {troop.Display}; the row " +
"keeps whatever the cloned element was showing.");
element.transform.Find("name").GetComponent<TMP_Text>().text = Localization.instance.Localize(troop.Display);
element.transform.Find("name").GetComponent<TMP_Text>().text = troop.Display;
// The DISCOUNTED price, because that is what will actually leave the player's pocket.
TMP_Text price = FindDescendant<TMP_Text>(element.transform, "price");
if (price != null) price.text = DvergarBanco.PriceFor(troop).ToString();
UITooltip tooltip = element.GetComponent<UITooltip>();
if (tooltip != null) tooltip.Set(Localization.instance.Localize(troop.Display), Composition(troop), gui.m_tooltipAnchor, default(Vector2));
if (tooltip != null) tooltip.Set(troop.Display, Composition(troop), gui.m_tooltipAnchor, default(Vector2));
string id = troop.Id;
element.GetComponent<Button>().onClick.AddListener(() =>
@ -154,9 +154,10 @@ namespace RacesOfValheim
int full = troop.Price;
int paid = DvergarBanco.PriceFor(troop);
if (paid < full) text.Append("\n\n").Append(ModText.Get("rov_troop_dvergar_seal_price", full, paid));
if (paid < full) text.Append("\n\nList price ").Append(full).Append(" - your seal takes it to ").Append(paid).Append('.');
text.Append("\n\n").Append(ModText.Get("rov_troop_dvergar_terms"));
text.Append("\n\nThey answer the follow command, knit their own wounds shut, keep your truce with " +
"the mountain's dvergr, drop nothing, and do not come back. A dead crew is money spent.");
return text.ToString();
}

View file

@ -33,7 +33,7 @@ namespace RacesOfValheim
public static class DvergarBotte
{
public const string PieceName = "DvergarRuneBarrel";
public const string PieceDisplayName = "$rov_piece_dvergar_runebarrel_name";
public const string PieceDisplayName = "Rune Barrel";
public const string RaceId = DvergarConfig.RaceId;
/// <summary>How many drinks it holds. One dose is one mercenary served, so twenty is four
@ -90,12 +90,8 @@ namespace RacesOfValheim
piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplayName;
piece.m_canBeRemoved = true;
// Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch
// the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's
// mesh floor - so players saw no ghost at all and could not tell why. A station belongs
// in a house or a cave as much as outside.
piece.m_groundPiece = false;
piece.m_groundOnly = false;
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_icon = BorrowIcon("MeadHealthMinor") ?? BorrowIcon("TrophyDvergr");
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
@ -105,7 +101,8 @@ namespace RacesOfValheim
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = PieceDisplayName,
Description = "$rov_piece_dvergar_runebarrel_desc",
Description = "Pour a brew in and the crew drinks. What it does to them is whatever it " +
"would have done to you - if they have the parts for it.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = BorrowIcon("MeadHealthMinor") ?? BorrowIcon("TrophyDvergr"),
@ -195,10 +192,8 @@ namespace RacesOfValheim
}
}
// Valheim 1.0 appended a 'bool cheated' parameter to this overload. The type array has to
// match it exactly or the patch silently fails to bind and PatchAll throws.
[HarmonyPatch(typeof(Player), "PlacePiece",
new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool), typeof(bool) })]
new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })]
public static class DvergarBotteRaceLockPatch
{
public static bool Prefix(Player __instance, Piece __0)
@ -207,7 +202,7 @@ namespace RacesOfValheim
if (Utils.GetPrefabName(__0.gameObject) != DvergarBotte.PieceName) return true;
if (DvergarRace.IsDvergar()) return true;
__instance.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_do_not_know_what_goes"));
__instance.Message(MessageHud.MessageType.Center, "You do not know what goes in it.");
return false;
}
}

View file

@ -63,12 +63,9 @@ namespace RacesOfValheim
if (!DvergarBotte.IsBrew(prefabName))
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return true;
return false;
}
// Always true from an item use, refusals included: false makes Humanoid.UseItem
// cover Fill's own message with the generic $msg_cantuseon.
Fill(player, inventory, item, prefabName);
return true;
return Fill(player, inventory, item, prefabName);
}
// Bare hands: pour a round if there is one, otherwise go looking for something to pour.
@ -77,7 +74,7 @@ namespace RacesOfValheim
ItemDrop.ItemData found = FindAnyBrew(inventory);
if (found == null)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_empty_so_are"));
player.Message(MessageHud.MessageType.Center, "It is empty, and so are you.");
return false;
}
@ -106,7 +103,7 @@ namespace RacesOfValheim
if (!string.IsNullOrEmpty(current) && current != prefabName && GetDoses() > 0)
{
player.Message(MessageHud.MessageType.Center,
ModText.Get("rov_msg_dvergar_there_still", DvergarBotte.BrewDisplayName(current)));
$"There is still {DvergarBotte.BrewDisplayName(current)} in it.");
return false;
}
@ -151,14 +148,14 @@ namespace RacesOfValheim
StatusEffect effect = DvergarBotte.BrewEffect(brew);
if (effect == null)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_whatever_does_nothing_anyone"));
player.Message(MessageHud.MessageType.Center, "Whatever is in it does nothing to anyone.");
return false;
}
List<RaisedThrall> drinkers = InRange();
if (drinkers.Count == 0)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_nobody_at_barrel"));
player.Message(MessageHud.MessageType.Center, "Nobody is at the barrel.");
return false;
}
@ -173,14 +170,16 @@ namespace RacesOfValheim
if (served == 0)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_not_drop_went_down"));
player.Message(MessageHud.MessageType.Center, "Not a drop went down.");
return false;
}
m_nview.InvokeRPC("RoV_DvergarBotteSpend", served);
string what = DvergarBotte.BrewDisplayName(brew);
player.Message(MessageHud.MessageType.Center, (served < drinkers.Count ? ModText.Get("rov_msg_dvergar_drink_barrel_runs_dry", served, what) : ModText.Get("rov_msg_dvergar_drink", served, what)));
player.Message(MessageHud.MessageType.Center, served < drinkers.Count
? $"{served} drink {what}. The barrel runs dry."
: $"{served} drink {what}.");
return true;
}
@ -252,12 +251,14 @@ namespace RacesOfValheim
string body;
if (doses <= 0 || string.IsNullOrEmpty(brew))
{
body = ModText.Get("rov_hover_dvergar_empty_pour_brew");
body = "empty\n[<color=yellow><b>$KEY_Use</b></color>] Pour a brew in";
}
else
{
int waiting = InRange().Count;
body = ModText.Get("rov_hover_dvergar_at_barrel_pour_round", DvergarBotte.BrewDisplayName(brew), doses, DvergarBotte.MaxDoses, waiting);
body = $"{DvergarBotte.BrewDisplayName(brew)} {doses}/{DvergarBotte.MaxDoses}" +
$"\n{waiting} at the barrel" +
$"\n[<color=yellow><b>$KEY_Use</b></color>] Pour a round";
}
return Localization.instance.Localize($"{DvergarBotte.PieceDisplayName} ({body})");

View file

@ -1,275 +0,0 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
/// <summary>
/// A Dvergar builds the black marble and Yggdrasil wood building pieces with stone and fine
/// wood (Wargles' suggestion). Only structural pieces: stations, furniture, containers and
/// fires keep their cost, so nothing with a progression role gets cheaper.
///
/// The swap is done on the piece prefabs of the Dvergar's own client. The build menu, the
/// "known piece" check and ConsumeResources all read the prefab's m_resources, so the menu
/// lists the pieces once stone or fine wood is known, and the player pays the swapped cost.
///
/// The refund is the catch. Piece.DropResources gives back whatever m_resources says on the
/// machine that destroys the piece; vanilla never records what was paid. Without help a human
/// deconstructing a Dvergar's stone wall would get black marble, and a Dvergar deconstructing a
/// vanilla wall would get stone. So a cheap piece is tagged on its ZDO when placed, with the
/// ratios it was paid at, and DropResources is given the matching cost on every client.
/// </summary>
public static class DvergarCheapBuilding
{
// The ratios a cheap piece was paid at. Absent (0) on every piece placed at full cost.
public const string StoneRatioZdoKey = "RacesOfValheim_DvergarCheapStone";
public const string WoodRatioZdoKey = "RacesOfValheim_DvergarCheapWood";
private const string BlackMarble = "BlackMarble";
private const string YggdrasilWood = "YggdrasilWood";
private const string Stone = "Stone";
private const string FineWood = "FineWood";
private const string LabelName = "rov_dvergar_cheap";
private const Piece.UsageTagFlags StructuralTags =
Piece.UsageTagFlags.Building | Piece.UsageTagFlags.Floor | Piece.UsageTagFlags.Wall |
Piece.UsageTagFlags.Roof | Piece.UsageTagFlags.Architecture | Piece.UsageTagFlags.Stairs |
Piece.UsageTagFlags.Doors;
// Piece prefab name -> its vanilla cost. Collected once and kept: the prefabs live for the
// whole session, and the originals must survive every swap.
private static Dictionary<string, Piece.Requirement[]> originals;
private static Dictionary<string, Piece> prefabs;
private static ItemDrop stoneItem, fineWoodItem;
// "" while the prefabs carry their vanilla cost, otherwise the ratios they were swapped at.
private static string appliedKey = "";
private static bool Collect()
{
if (originals != null) return true;
if (ObjectDB.instance == null) return false;
GameObject hammer = ObjectDB.instance.GetItemPrefab("Hammer");
PieceTable table = hammer != null ? hammer.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_buildPieces : null;
stoneItem = ObjectDB.instance.GetItemPrefab(Stone)?.GetComponent<ItemDrop>();
fineWoodItem = ObjectDB.instance.GetItemPrefab(FineWood)?.GetComponent<ItemDrop>();
if (table == null || stoneItem == null || fineWoodItem == null) return false;
originals = new Dictionary<string, Piece.Requirement[]>();
prefabs = new Dictionary<string, Piece>();
foreach (GameObject go in table.m_pieces)
{
Piece piece = go != null ? go.GetComponent<Piece>() : null;
if (piece == null || piece.m_resources == null || !UsesSwappedMaterial(piece) || !IsBuildingPiece(piece)) continue;
originals[go.name] = piece.m_resources;
prefabs[go.name] = piece;
// The list to read once in game: every piece that changes cost, and where it is built.
Jotunn.Logger.LogInfo($"[Dvergar] Cheap building: {go.name} at {(piece.m_craftingStation != null ? piece.m_craftingStation.name : "no station")}, {Describe(piece.m_resources)} -> {Describe(BuildCheap(piece.m_resources, 3, 2))} (at 3/2)");
}
Jotunn.Logger.LogInfo($"[Dvergar] Cheap building: {originals.Count} pieces.");
return true;
}
private static bool UsesSwappedMaterial(Piece piece)
{
foreach (Piece.Requirement req in piece.m_resources)
{
if (req.m_resItem == null) continue;
string name = req.m_resItem.name;
if (name == BlackMarble || name == YggdrasilWood) return true;
}
return false;
}
private static bool IsBuildingPiece(Piece piece)
{
bool structural = piece.m_category == Piece.PieceCategory.BuildingWorkbench
|| piece.m_category == Piece.PieceCategory.BuildingStonecutter
|| (piece.m_usage & StructuralTags) != 0;
if (!structural) return false;
if ((piece.m_usage & Piece.UsageTagFlags.Crafting) != 0) return false;
// Anything that does a job keeps its cost, whatever its tags say.
return piece.GetComponentInChildren<CraftingStation>() == null
&& piece.GetComponentInChildren<StationExtension>() == null
&& piece.GetComponentInChildren<Container>() == null
&& piece.GetComponentInChildren<Fireplace>() == null
&& piece.GetComponentInChildren<Smelter>() == null
&& piece.m_comfort <= 0;
}
/// <summary>
/// The cost with black marble and Yggdrasil wood swapped out. New Requirement objects
/// throughout: the originals are shared with the prefab and must stay untouched. A
/// material the piece already had (some marble pieces also ask for stone) is merged.
/// </summary>
private static Piece.Requirement[] BuildCheap(Piece.Requirement[] original, int stoneRatio, int woodRatio)
{
var result = new List<Piece.Requirement>();
foreach (Piece.Requirement req in original)
{
ItemDrop item = req.m_resItem;
int amount = req.m_amount;
if (item != null && item.name == BlackMarble) { item = stoneItem; amount *= stoneRatio; }
else if (item != null && item.name == YggdrasilWood) { item = fineWoodItem; amount *= woodRatio; }
Piece.Requirement same = item != null ? result.Find(r => r.m_resItem == item) : null;
if (same != null)
{
same.m_amount += amount;
continue;
}
result.Add(new Piece.Requirement
{
m_resItem = item,
m_amount = amount,
m_extraAmountOnlyOneIngredient = req.m_extraAmountOnlyOneIngredient,
m_amountPerLevel = req.m_amountPerLevel,
m_upgraderResource = req.m_upgraderResource,
m_recover = req.m_recover,
});
}
return result.ToArray();
}
private static string Describe(Piece.Requirement[] reqs)
{
var parts = new List<string>();
foreach (Piece.Requirement req in reqs)
{
if (req.m_resItem != null) parts.Add($"{req.m_amount} {req.m_resItem.name}");
}
return string.Join(", ", parts);
}
/// <summary>
/// Puts the cost the local player should see on the prefabs. Returns whether anything
/// changed, so the caller knows to refresh the build menu.
/// </summary>
private static bool Apply(bool cheap)
{
int stone = DvergarConfigManagement.CheapStonePerBlackMarble.Value;
int wood = DvergarConfigManagement.CheapFineWoodPerYggdrasil.Value;
string key = cheap ? stone + "/" + wood : "";
if (key == appliedKey) return false;
foreach (var pair in originals)
{
if (!prefabs.TryGetValue(pair.Key, out Piece prefab) || prefab == null) continue;
prefab.m_resources = cheap ? BuildCheap(pair.Value, stone, wood) : pair.Value;
}
appliedKey = key;
return true;
}
private static bool IsSwapped(Piece piece)
{
return appliedKey != "" && piece != null && originals != null
&& originals.ContainsKey(Utils.GetPrefabName(piece.gameObject.name));
}
/// <summary>
/// Keeps the prefabs in step with the local player: a Dvergar with the option on sees the
/// cheap cost, anyone else the vanilla one. Checked every frame because the race can change
/// mid-session (resetrace) and the ratios with the server's config; the check is a string
/// compare unless something changed.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class Dvergar_CheapBuildingSync_Patch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer || !Collect()) return;
bool cheap = DvergarConfigManagement.CheapBuildingEnabled.Value && DvergarRace.IsDvergar();
if (Apply(cheap)) Traverse.Create(__instance).Method("UpdateAvailablePiecesList").GetValue();
}
}
/// <summary>
/// Tags a piece placed at the cheap cost. SetCreator is called once, by PlacePiece, on the
/// placing client, right after the piece was paid for from the same prefab cost.
/// </summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.SetCreator))]
public static class Dvergar_CheapBuildingTag_Patch
{
public static void Postfix(Piece __instance)
{
if (!IsSwapped(__instance)) return;
ZNetView nview = __instance.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
nview.GetZDO().Set(StoneRatioZdoKey, DvergarConfigManagement.CheapStonePerBlackMarble.Value);
nview.GetZDO().Set(WoodRatioZdoKey, DvergarConfigManagement.CheapFineWoodPerYggdrasil.Value);
}
}
/// <summary>
/// Gives back what the piece cost: the cheap materials at the ratios it was paid at for a
/// tagged piece, the vanilla cost for every other one, whoever destroys it and whatever
/// cost this client's prefab carries right now.
/// </summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.DropResources))]
public static class Dvergar_CheapBuildingRefund_Patch
{
public static void Prefix(Piece __instance)
{
if (!Collect()) return;
if (!originals.TryGetValue(Utils.GetPrefabName(__instance.gameObject.name), out Piece.Requirement[] original)) return;
ZNetView nview = __instance.GetComponent<ZNetView>();
ZDO zdo = nview != null && nview.IsValid() ? nview.GetZDO() : null;
int stone = zdo != null ? zdo.GetInt(StoneRatioZdoKey, 0) : 0;
int wood = zdo != null ? zdo.GetInt(WoodRatioZdoKey, 0) : 0;
__instance.m_resources = stone > 0 && wood > 0 ? BuildCheap(original, stone, wood) : original;
}
}
/// <summary>
/// The Dvergar icon on every swapped piece in the hammer menu. Valheim 1.0
/// draws that menu with BuildUi, one pooled BuildUiPieceButton per piece, and Setup is
/// where a button takes its piece. The old Hud.UpdatePieceList grid still runs but is
/// hidden, so a label there is never seen.
/// </summary>
[HarmonyPatch(typeof(BuildUiPieceButton), nameof(BuildUiPieceButton.Setup))]
public static class Dvergar_CheapBuildingLabel_Patch
{
public static void Postfix(BuildUiPieceButton __instance, Piece pieceInfo)
{
bool cheap = IsSwapped(pieceInfo);
Transform label = __instance.transform.Find(LabelName);
if (label == null)
{
if (!cheap) return;
label = CreateLabel(__instance.transform);
}
if (label.gameObject.activeSelf != cheap) label.gameObject.SetActive(cheap);
}
private static Transform CreateLabel(Transform button)
{
var obj = new GameObject(LabelName, typeof(RectTransform));
obj.transform.SetParent(button, false);
// The race's own icon in the bottom-right corner, as the race menu and the build
// panel's race requirement show it: no text, so it fits in every language.
var rect = (RectTransform)obj.transform;
rect.anchorMin = rect.anchorMax = rect.pivot = new Vector2(1f, 0f);
rect.anchoredPosition = new Vector2(-2f, 2f);
rect.sizeDelta = new Vector2(22f, 22f);
var image = obj.AddComponent<Image>();
image.sprite = RacesOfValheim.RaceIcon(DvergarConfig.RaceId);
image.preserveAspect = true;
image.raycastTarget = false;
return obj.transform;
}
}
}
}

View file

@ -124,11 +124,9 @@ namespace RacesOfValheim
// still clearing by about 2mm. Same size of eye, sitting deeper, and the cap is flatter
// for it - which is what reads as set into the skull rather than resting on it.
public static readonly float EyeSeparation = 0.032f; // half the distance between them
public static readonly float EyeForward = 0.085f; // 0.081 left the smaller ball buried
public static readonly float EyeForward = 0.081f; // centre ~63mm out
public static readonly float EyeHeight = 0.181f; // ~15mm lower than before
// Then cut down after playtest: at 0.062 the cap read as two lamps covering the face. An
// 18mm radius at the same depth leaves a cap of about 22mm on a 0.78 Dvergar.
public static readonly float EyeSize = 0.036f;
public static readonly float EyeSize = 0.062f; // ~48mm across, so a 24mm radius
// How hard the eyes burn. The colours the game gives a starred dverger are HDR - one star
// is (0, 4, 3.3) - and anything past 1 clips to white on the way to the bloom pass, which
@ -256,7 +254,7 @@ namespace RacesOfValheim
FlatDamageType = HitData.DamageType.Blunt,
FlatDamage = 0f, DamagePercent = 0.15f,
StaminaPercent = 0.20f, StaminaFlat = 0f,
DisplayName = "$rov_compendium_dvergar_weapon_hammer"
DisplayName = "Hammer"
},
new WeaponAffinity
{
@ -264,7 +262,7 @@ namespace RacesOfValheim
FlatDamageType = HitData.DamageType.Pierce,
FlatDamage = 0f, DamagePercent = 0.15f,
StaminaPercent = 0.20f, StaminaFlat = 0f,
DisplayName = "$rov_compendium_dvergar_weapon_bow"
DisplayName = "Bow"
},
new WeaponAffinity
{
@ -272,7 +270,7 @@ namespace RacesOfValheim
FlatDamageType = HitData.DamageType.Slash,
FlatDamage = 0f, DamagePercent = 0.15f,
StaminaPercent = 0.20f, StaminaFlat = 0f,
DisplayName = "$rov_compendium_dvergar_weapon_axe"
DisplayName = "Axe"
},
new WeaponAffinity
{
@ -280,7 +278,7 @@ namespace RacesOfValheim
FlatDamageType = HitData.DamageType.Pierce,
FlatDamage = 0f, DamagePercent = 0.15f,
StaminaPercent = 0.20f, StaminaFlat = 0f,
DisplayName = "$rov_compendium_dvergar_weapon_crossbow"
DisplayName = "Crossbow"
}
};

View file

@ -57,11 +57,6 @@ namespace RacesOfValheim
public static ConfigEntry<float> RunicOverchargeWindow;
public static ConfigEntry<float> RunicOverchargeCooldown;
// ─── Cheap Building ───────────────────────────────────────────────────────
public static ConfigEntry<bool> CheapBuildingEnabled;
public static ConfigEntry<int> CheapStonePerBlackMarble;
public static ConfigEntry<int> CheapFineWoodPerYggdrasil;
public static void Bind(ConfigFile config)
{
const string keybinds = "Dvergar - Keybinds";
@ -111,14 +106,6 @@ namespace RacesOfValheim
new ConfigDescription("Seconds a loaded charge is held before it lapses unused.", new AcceptableValueRange<float>(1f, 60f)));
RunicOverchargeCooldown = config.Bind(overcharge, "Cooldown", 60f,
new ConfigDescription("Seconds between casts.", new AcceptableValueRange<float>(0f, 300f)));
const string building = "Dvergar - Cheap Building";
CheapBuildingEnabled = config.Bind(building, "Enabled", true,
new ConfigDescription("A Dvergar builds the black marble and Yggdrasil wood building pieces (walls, floors, beams, roofs, arches, stairs) with stone and fine wood instead. Stations and furniture keep their cost. A deconstructed piece gives back what was paid for it."));
CheapStonePerBlackMarble = config.Bind(building, "Stone per Black Marble", 3,
new ConfigDescription("Stone a Dvergar pays for each black marble in a piece's cost.", new AcceptableValueRange<int>(1, 10)));
CheapFineWoodPerYggdrasil = config.Bind(building, "Fine Wood per Yggdrasil Wood", 2,
new ConfigDescription("Fine wood a Dvergar pays for each Yggdrasil wood in a piece's cost.", new AcceptableValueRange<int>(1, 10)));
}
}
}

View file

@ -1,6 +1,5 @@
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib;
using UnityEngine;
@ -111,7 +110,7 @@ namespace RacesOfValheim
DvergarAbilities.ConsumeOvercharge(Player.m_localPlayer))
{
ScalePhysical(hit, DvergarConfig.RunicOverchargeMultiplier);
Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, ModText.Get("rov_msg_dvergar_runic_overcharge_discharges"));
Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "Runic Overcharge discharges");
}
}
@ -221,13 +220,9 @@ namespace RacesOfValheim
// ─── Smithing and jewelry ────────────────────────────────────────────
/// <summary>
/// Metal saved when crafting, upgrading and building. Requirement.GetAmount is what the
/// crafting panel, the build menu and Player.ConsumeResources all read, so the figure the
/// player is quoted and the figure they are charged can never drift apart.
///
/// Two vanilla paths read m_amount directly and skip GetAmount, both for build pieces:
/// Player.HaveRequirements(Piece) and Piece.DropResources. The two transpilers below route
/// them through the discount too.
/// Metal saved when crafting and upgrading. Requirement.GetAmount is the single point both
/// the crafting panel and Player.ConsumeResources go through, so the figure the player is
/// quoted and the figure they are charged can never drift apart.
///
/// Scoped to the metals and gems in DvergarConfig.DiscountedResourceNames, which is what
/// keeps this a smithing perk rather than a blanket discount on every wooden wall.
@ -237,137 +232,26 @@ namespace RacesOfValheim
{
public static void Postfix(Piece.Requirement __instance, ref int __result)
{
if (Player.m_localPlayer == null) return;
if (!DvergarRace.IsDvergar()) return;
__result = DiscountedAmount(__instance, __result, DvergarProgression.Current.SmithingDiscount);
}
}
/// <summary>
/// The single rounding rule for the smithing discount. The price a Dvergar pays and the
/// refund their piece drops both go through here, so they can't end up one ingot apart.
/// </summary>
internal static int DiscountedAmount(Piece.Requirement requirement, int amount, float discount)
{
if (amount <= 1 || discount <= 0f) return amount;
if (requirement == null || requirement.m_resItem == null) return amount;
if (!IsDiscounted(requirement.m_resItem.gameObject.name)) return amount;
return Mathf.Max(1, Mathf.RoundToInt(amount * (1f - discount)));
}
private static bool IsDiscounted(string prefabName)
{
string lower = prefabName.ToLower();
foreach (string resource in DvergarConfig.DiscountedResourceNames)
{
if (lower == resource || lower.Contains(resource)) return true;
}
return false;
}
private static readonly FieldInfo RequirementAmountField =
AccessTools.Field(typeof(Piece.Requirement), nameof(Piece.Requirement.m_amount));
/// <summary>
/// The build check. Vanilla compares the inventory against requirement.m_amount here, so
/// the menu quoted 6 tin for a cauldron while the hammer still refused to place it with
/// fewer than 10. Every m_amount read becomes GetAmount(1), which returns m_amount for
/// everyone else and the discounted figure for a Dvergar.
/// </summary>
[HarmonyPatch(typeof(Player), nameof(Player.HaveRequirements), typeof(Piece), typeof(Player.RequirementMode))]
public static class Dvergar_HaveRequirements_Piece_Patch
{
private static readonly MethodInfo GetAmountMethod =
AccessTools.Method(typeof(Piece.Requirement), nameof(Piece.Requirement.GetAmount));
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
int replaced = 0;
foreach (CodeInstruction instruction in instructions)
{
if (instruction.LoadsField(RequirementAmountField))
{
replaced++;
yield return new CodeInstruction(OpCodes.Ldc_I4_1).MoveLabelsFrom(instruction);
yield return new CodeInstruction(OpCodes.Callvirt, GetAmountMethod);
continue;
}
yield return instruction;
}
if (replaced == 0)
Jotunn.Logger.LogWarning("[Dvergar] HaveRequirements(Piece) no longer reads m_amount; build discount check not patched.");
}
}
/// <summary>
/// ZDO key holding the discount a Dvergar paid for a piece. Stored rather than read off
/// the builder at teardown, because anyone can smash the piece and the builder's discount
/// grows with progression.
/// </summary>
private const string PaidDiscountKey = "Dvergar_PaidDiscount";
/// <summary>
/// Stamps the discount on a piece the local Dvergar just placed. Player.PlacePiece calls
/// SetCreator on the new instance right after spawning it, and ConsumeResources charges
/// the discounted price straight after.
/// </summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.SetCreator))]
public static class Dvergar_Piece_SetCreator_Patch
{
public static void Postfix(Piece __instance, long uid)
{
Player player = Player.m_localPlayer;
if (player == null || uid != player.GetPlayerID()) return;
if (__result <= 1 || Player.m_localPlayer == null) return;
if (!DvergarRace.IsDvergar()) return;
float discount = DvergarProgression.Current.SmithingDiscount;
if (discount <= 0f) return;
ZNetView nview = __instance.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
nview.GetZDO().Set(PaidDiscountKey, discount);
if (__instance == null || __instance.m_resItem == null) return;
if (!IsDiscounted(__instance.m_resItem.gameObject.name)) return;
__result = Mathf.Max(1, Mathf.RoundToInt(__result * (1f - discount)));
}
}
/// <summary>
/// The refund. Vanilla drops requirement.m_amount when a piece is removed or destroyed,
/// which handed a Dvergar back 10 tin for a cauldron that cost 6: build, smash, repeat.
/// The drop now uses the discount stamped on the piece, so it returns what was paid.
/// </summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.DropResources))]
public static class Dvergar_Piece_DropResources_Patch
{
private static readonly MethodInfo PaidAmountMethod =
AccessTools.Method(typeof(Dvergar_Piece_DropResources_Patch), nameof(PaidAmount));
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
private static bool IsDiscounted(string prefabName)
{
int replaced = 0;
foreach (CodeInstruction instruction in instructions)
string lower = prefabName.ToLower();
foreach (string resource in DvergarConfig.DiscountedResourceNames)
{
if (instruction.LoadsField(RequirementAmountField))
{
replaced++;
yield return new CodeInstruction(OpCodes.Ldarg_0).MoveLabelsFrom(instruction);
yield return new CodeInstruction(OpCodes.Call, PaidAmountMethod);
continue;
}
yield return instruction;
if (lower == resource || lower.Contains(resource)) return true;
}
if (replaced == 0)
Jotunn.Logger.LogWarning("[Dvergar] DropResources no longer reads m_amount; build discount refund not patched.");
}
public static int PaidAmount(Piece.Requirement requirement, Piece piece)
{
int amount = requirement.m_amount;
ZNetView nview = piece.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return amount;
float discount = nview.GetZDO().GetFloat(PaidDiscountKey, 0f);
return DiscountedAmount(requirement, amount, discount);
return false;
}
}
@ -397,19 +281,17 @@ namespace RacesOfValheim
{
if (item == null) continue;
// A full copy, not a hand-picked one: Valheim 1.0 hangs name, tooltip, icon,
// buy/increment keys and buy effects off TradeItem, and StoreGui reads some
// of them without null checks. Only the price is ours to change.
var copy = (Trader.TradeItem)MemberwiseCloneMethod.Invoke(item, null);
copy.m_price = Mathf.Max(1, Mathf.RoundToInt(item.m_price * (1f - discount)));
discounted.Add(copy);
discounted.Add(new Trader.TradeItem
{
m_prefab = item.m_prefab,
m_stack = item.m_stack,
m_price = Mathf.Max(1, Mathf.RoundToInt(item.m_price * (1f - discount))),
m_requiredGlobalKey = item.m_requiredGlobalKey
});
}
__result = discounted;
}
private static readonly System.Reflection.MethodInfo MemberwiseCloneMethod =
AccessTools.Method(typeof(object), "MemberwiseClone");
}
/// <summary>

View file

@ -16,8 +16,8 @@ namespace RacesOfValheim
{
base.Setup(character);
name = DvergarConfig.StatsSE;
m_name = "$rov_se_dvergar_stats_name";
m_tooltip = "$rov_se_dvergar_stats_tooltip";
m_name = "Stone and Forge";
m_tooltip = "Small, sturdy, and born to the anvil.";
}
public override void ModifyAttackStaminaUsage(float baseStaminaUse, ref float staminaUse)
@ -80,7 +80,7 @@ namespace RacesOfValheim
var stats = ScriptableObject.CreateInstance<SE_DvergarStats>();
stats.name = DvergarConfig.StatsSE;
stats.m_name = "$rov_se_dvergar_stats_name";
stats.m_name = "Stone and Forge";
stats.m_icon = icon;
CustomStatusEffect customStats = new CustomStatusEffect(stats, fixReference: false);
ItemManager.Instance.AddStatusEffect(customStats);
@ -88,22 +88,22 @@ namespace RacesOfValheim
var overcharge = ScriptableObject.CreateInstance<SE_DvergarOvercharge>();
overcharge.name = DvergarConfig.OverchargeSE;
overcharge.m_name = "$rov_se_dvergar_overcharge_name";
overcharge.m_tooltip = "$rov_se_dvergar_overcharge_tooltip";
overcharge.m_name = "Runic Overcharge";
overcharge.m_tooltip = "Your next blow with a favoured weapon carries the whole of the charge.";
overcharge.m_icon = GetItemIcon("Eitr") ?? icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(overcharge, fixReference: false));
var pingCd = ScriptableObject.CreateInstance<SE_DvergarAbilityCooldown>();
pingCd.name = DvergarConfig.RunicPingCdSE;
pingCd.m_name = "$rov_se_dvergar_pingcd_name";
pingCd.m_tooltip = "$rov_se_dvergar_pingcd_tooltip";
pingCd.m_name = "Runic Ping";
pingCd.m_tooltip = "The runes must settle before you may call on them again.";
pingCd.m_icon = GetItemIcon("DvergrKeyFragment") ?? icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(pingCd, fixReference: false));
var overchargeCd = ScriptableObject.CreateInstance<SE_DvergarAbilityCooldown>();
overchargeCd.name = DvergarConfig.OverchargeCdSE;
overchargeCd.m_name = "$rov_se_dvergar_overchargecd_name";
overchargeCd.m_tooltip = "$rov_se_dvergar_overchargecd_tooltip";
overchargeCd.m_name = "Overcharge Cooldown";
overchargeCd.m_tooltip = "The runes are spent.";
overchargeCd.m_icon = GetItemIcon("Eitr") ?? icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(overchargeCd, fixReference: false));
}

View file

@ -159,19 +159,7 @@ namespace RacesOfValheim
return;
}
if (eyes == null)
{
// See AswidVisuals.ApplyEyes for the full reasoning - BuildEyes takes a one-time
// reading of the head bone's pose to work out which way the skull faces, and
// caches it for as long as the eyes exist. Sitting, attached, mid-attack or asleep,
// the head can be turned away from the body's own forward at that instant, which is
// how the snap-to-axis picked the wrong side and left the eyes behind the skull.
if (player.IsAttached() || player.IsAttachedToShip() || player.InAttack() || player.IsSleeping())
{
return;
}
eyes = BuildEyes(player, headBone);
}
if (eyes == null) eyes = BuildEyes(player, headBone);
if (eyes == null) return; // already logged once by the resolver
PlaceEyes(player, headBone, eyes);
@ -277,11 +265,10 @@ namespace RacesOfValheim
// metre was the entire drift: the offsets below are under a centimetre in local units
// and never stood a chance of mattering next to it.
float raceScale = GetVisualScale(player);
Vector3 baseLocal = localForward * (DvergarConfig.EyeForward * raceScale * toLocal)
+ localUp * (DvergarConfig.EyeHeight * raceScale * toLocal);
float height = DvergarConfig.EyeHeight;
float separation = DvergarConfig.EyeSeparation;
float eyeSize = DvergarConfig.EyeSize;
PlayerFace.AdjustEyes(player, ref height, ref separation, ref eyeSize);
float eyeLocalSize = DvergarConfig.EyeSize * raceScale * toLocal;
for (int i = 0; i < holder.childCount; i++)
{
@ -292,29 +279,27 @@ namespace RacesOfValheim
// curved and the two sides do not present the same surface to a ball of this
// radius.
float side = i == 0 ? -1f : 1f;
float size = i == 0 ? eyeLocalSize * DvergarConfig.LeftEyeSizeMultiplier : eyeLocalSize;
// This eye's hand corrections (RaceEyeTuning).
float forward = DvergarConfig.EyeForward;
float eyeHeight = height;
float eyeSeparation = separation;
float size = eyeSize * raceScale * toLocal;
RaceEyeTuning.Eye tuning = RaceEyeTuning.For(DvergarConfig.RaceId, player, side);
if (tuning != null)
{
forward += tuning.Forward;
eyeHeight += tuning.Height;
eyeSeparation += tuning.Separation;
size *= tuning.Size;
}
if (i == 0) size *= DvergarConfig.LeftEyeSizeMultiplier;
eye.localPosition = localForward * (forward * raceScale * toLocal)
+ localUp * (eyeHeight * raceScale * toLocal)
+ localRight * (side * eyeSeparation * raceScale * toLocal);
eye.localPosition = baseLocal + localRight * (side * DvergarConfig.EyeSeparation * raceScale * toLocal);
eye.localScale = Vector3.one * size;
}
}
/// <summary>
/// Rounds a direction to the nearest of the six axis directions. Whichever component is
/// largest wins, sign included.
/// </summary>
private static Vector3 SnapToAxis(Vector3 direction)
{
float x = Mathf.Abs(direction.x);
float y = Mathf.Abs(direction.y);
float z = Mathf.Abs(direction.z);
if (x >= y && x >= z) return new Vector3(Mathf.Sign(direction.x), 0f, 0f);
if (y >= z) return new Vector3(0f, Mathf.Sign(direction.y), 0f);
return new Vector3(0f, 0f, Mathf.Sign(direction.z));
}
private static Transform BuildEyes(Player player, Transform headBone)
{
@ -330,15 +315,22 @@ namespace RacesOfValheim
holder.transform.localRotation = Quaternion.identity;
holder.transform.localScale = Vector3.one;
// Which way the rig faces, rounded to the skull's own square axes - and taken from the
// BIND POSE rather than from whatever pose the head holds on this frame. See
// RigBindPose: read live, the rounding lands on the neighbouring axis whenever the head
// is caught mid-turn, and a race change rebuilds at exactly such a moment. That is why
// a Dvergar could come out of a reset with its eyes misplaced and be right again after
// a logout - the logout was simply a rebuild at a calmer moment, not a fix.
// Ask the rig which way it faces, once - and then round the answer to the skull's own
// axes. The raw measurement is taken at whatever pose the head happens to be in on
// this frame, so it arrives tilted: a "forward" leaning 20 degrees down put the eyes
// at the jaw instead of the eye line. A bone's real axes are square, and the tilt is
// nothing but the pose at the moment of asking, so it is rounded away.
Transform root = player.transform;
EyeFrame frame = holder.AddComponent<EyeFrame>();
RigBindPose.MeasureHeadFrame(player, headBone, "Dvergar",
out frame.LocalForward, out frame.LocalUp, out frame.LocalRight);
frame.LocalForward = SnapToAxis(headBone.InverseTransformDirection(root.forward));
frame.LocalUp = SnapToAxis(headBone.InverseTransformDirection(root.up));
// Right is derived, never snapped. Rounding all three independently guarantees
// nothing about the angles between them, and a "right" that shares an axis with
// forward stops being sideways: the separation then pushes one eye out of the face
// and pulls the other into it, which is one eye sitting proud of a forehead while its
// twin sits correctly. A cross product cannot be anything but perpendicular.
frame.LocalRight = Vector3.Cross(frame.LocalUp, frame.LocalForward).normalized;
for (int i = 0; i < 2; i++)
{

View file

@ -1,6 +1,5 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
@ -24,15 +23,8 @@ namespace RacesOfValheim
// is the same as no truce at all - the unexempted Fulings open fire, the player defends
// themselves, and every Berserker in earshot joins in through damage retaliation, which
// IsEnemy has no say over. Verified against the asset manifest, not the wiki's display names.
// Matching is by exact prefab name, so every variant of a creature has to be named here in
// its own right - a family left half-listed is what made the truce look random by biome
// (see PaludeMobs below for the report that turned this up). "Greyling" is the Meadows
// greydwarf and was missing outright: a Trol or a Furling was at peace with the whole
// Black Forest and still fought the smallest thing in it. The Trenta never noticed,
// because its own list in RaceHostilityManager matches on substrings instead.
private static readonly HashSet<string> NeraForestaMobs = new HashSet<string>
{
"Greyling",
"Greydwarf", "Greydwarf_Elite", "Greydwarf_Shaman",
"Goblin", "GoblinArcher", "GoblinBrute", "GoblinShaman",
"Troll",
@ -45,27 +37,10 @@ namespace RacesOfValheim
"Dverger", "DvergerMageFire", "DvergerMageIce", "DvergerMageSupport", "DvergerAshlands",
};
// Skeleton_NoArcher and Draugr_Ranged are the two that were missing, and they are why an
// Aswid reported skeletons that were peaceful in one biome and hostile in another: it was
// never the biome, it was which variant that particular spawner places. Skeleton_NoArcher
// is vanilla's guaranteed-melee skeleton (the same one SkeletonBonePile borrows), so a
// spawner using it produced hostile skeletons standing next to peaceful ones. Draugr_Ranged
// is the bow draugr, left out while the melee and elite ones were exempt.
//
// Skeleton_Hildir stays out deliberately, on the same rule that keeps GoblinKing and the
// Hildir brothers out of the Black Forest set: a quest boss is not somebody's kin.
//
// Valheim 1.0 added a skeleton per region (the green swamp ones and the blue mountain ones
// players noticed first), each with a melee-only twin, and spawners place those instead
// of the plain Skeleton. Left out, they fought a Skeleton player the plain ones ignored.
private static readonly HashSet<string> PaludeMobs = new HashSet<string>
{
"Ghost", "Skeleton", "Skeleton_NoArcher", "Skeleton_Poison", // Skeleton, Rancid remains
"Skeleton_Meadows", "Skeleton_Meadows_noarcher",
"Skeleton_Swamps", "Skeleton_Swamps_noarcher",
"Skeleton_Mountains", "Skeleton_Mountains_noarcher",
"Skeleton_DeepNorth",
"Draugr", "Draugr_Elite", "Draugr_Ranged",
"Ghost", "Skeleton", "Skeleton_Poison", // Skeleton, Rancid remains
"Draugr", "Draugr_Elite",
"Wraith", "Leech", "Abomination",
"Blob", "BlobElite", "BlobTar", // Blob, Oozer, Growth
};
@ -94,192 +69,26 @@ namespace RacesOfValheim
public static bool IsSameFaction(Player player, Character monster)
{
if (player == null || monster == null) return false;
return IsFactionMob(GetPlayerRace(player), monster.gameObject.name);
}
// The same answer by name alone, for callers that only have a prefab and no live creature -
// the raid filter reads RandomEvent.m_spawn, which holds prefabs that were never spawned.
public static bool IsFactionMob(string race, string prefabName)
{
if (race == null || prefabName == null) return false;
if (!player.m_customData.TryGetValue("Race", out string race)) return false;
if (!RaceFactionMobs.TryGetValue(race, out HashSet<string> mobs)) return false;
return mobs.Contains(prefabName.Replace("(Clone)", "").Trim());
}
// Faction set or per-race list, whichever says yes: the two questions IsEnemy is asked
// through these two files, answered without a Character. Grudges are not in here - a grudge
// is held by one creature, not by a prefab.
public static bool IsAlliedMob(string race, string prefabName)
{
if (race == null || prefabName == null) return false;
return IsFactionMob(race, prefabName) || RaceHostilityManager.IsRaceKin(race, prefabName);
}
// m_customData is the local save file's dictionary: it is only ever populated for
// the client's own m_localPlayer, so IsEnemy running on a remote AI owner (a
// dedicated server, or any other nearby player who ends up owning the mob's ZDO)
// read an empty dictionary here and treated every truce as hostile. Every other
// race-aware patch in this project reads "RacesOfValheim_Race" off the ZDO instead
// because that field actually replicates - check it first, and only fall back to
// m_customData for the single-player/local-owner case where the ZDO hasn't been
// written yet (e.g. brand new character before the race pick's Set() call runs).
public static string GetPlayerRace(Player player)
{
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
string zdoRace = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(zdoRace)) return zdoRace;
}
return player.m_customData.TryGetValue("Race", out string race) ? race : null;
}
// The truce used to cover the player only. A thrall is tamed, so it sits in the Players
// faction, and a wild mob of the player's own faction still saw it as fair game: a wild
// Rancid Remains walked up to a Skeleton's bone pile, ignored the Skeleton and tore into
// the garrison. The thrall's own race is on the prefab (m_commandingRace), so the same
// faction sets answer for it without needing its owner nearby.
//
// The truce breaks the moment that wild mob holds a grudge against any player: it is
// fighting the thralls' master, and the thralls should fight back.
private static bool IsThrallTruce(Character thrallSide, Character wildSide)
{
if (wildSide.IsPlayer() || wildSide.IsTamed()) return false;
RaisedThrall thrall = thrallSide.GetComponent<RaisedThrall>();
if (thrall == null || string.IsNullOrEmpty(thrall.m_commandingRace)) return false;
if (wildSide.GetComponent<RaisedThrall>() != null) return false;
if (!IsAlliedMob(thrall.m_commandingRace, wildSide.gameObject.name)) return false;
foreach (Player player in Player.GetAllPlayers())
{
if (RaceGrudge.Holds(wildSide, player)) return false;
}
return true;
string prefabName = monster.gameObject.name.Replace("(Clone)", "").Trim();
return mobs.Contains(prefabName);
}
public static void Postfix(Character a, Character b, ref bool __result)
{
if (!FactionsConfig.Hostility) return;
if (!__result) return; // already not enemies, nothing to add
if (a == null || b == null) return;
// The player's own blow. Peace is the creature's choice, not a shield. See
// RaceGrudge.StrikeScope.
if (RaceGrudge.PlayerStrikes(a)) return;
if (IsThrallTruce(a, b) || IsThrallTruce(b, a))
{
__result = false;
return;
}
Character playerCharacter = a.IsPlayer() ? a : (b.IsPlayer() ? b : null);
Character monster = a.IsPlayer() ? b : (b.IsPlayer() ? a : null);
if (!(playerCharacter is Player p) || monster == null) return;
// Same stand-down as the per-race truces get: hit your own faction and it hits back
// until the grudge runs out. See RaceGrudge.
if (RaceGrudge.Holds(monster, p)) return;
if (IsSameFaction(p, monster))
{
__result = false;
}
}
}
/// <summary>
/// The truce above only ever touches BaseAI.IsEnemy - a mob's decision to smash a nearby
/// piece runs on a completely separate track. MonsterAI.UpdateTarget gates that on
/// m_attackPlayerObjects (a flag baked into the prefab, true for Troll among others) and
/// never once calls IsEnemy: a Troll with nothing to fight picks a m_targetStatic and
/// swings at it regardless of who is standing next to it. That is how a Trol player,
/// exempt from that very Troll's hostility, could still watch it flatten a workbench built
/// two seconds earlier in its own cave.
///
/// A postfix on UpdateTarget rather than trying to intercept FindClosestStaticPriorityTarget
/// or FindRandomStaticTarget (both private, both called from more than one branch inside it):
/// simpler to let vanilla pick whatever it wants and veto the pick once, right after, than to
/// duplicate its target-selection logic to stop it picking in the first place.
/// </summary>
[HarmonyPatch(typeof(MonsterAI), "UpdateTarget")]
public static class FactionStaticTargetPatch
{
// This used to be 20 m, sized against FindRandomStaticTarget's 10 m search. The other pick,
// FindClosestStaticPriorityTarget, searches the mob's whole m_viewRange, so a skeleton 25 m
// from an Aswid could still lock onto a piece and the veto never ran - and it never ran at
// all once the player stepped away from the base mid-raid. The rule is now "an ally is
// around, the whole base is safe": 100 m is roughly a raid's own area (RandomEvent's
// m_eventRange), so anyone still inside the raid covers every piece in it, whoever built it.
private const float FactionCheckRange = 100f;
public static void Postfix(MonsterAI __instance)
{
if (!FactionsConfig.Hostility) return;
Traverse targetStatic = Traverse.Create(__instance).Field("m_targetStatic");
// GetValue() hands back a plain object, and object == null skips Unity's destroyed
// check: a piece smashed or removed while targeted stays non-null here, and touching
// its gameObject throws. That throw escapes into MonoUpdaters.FixedUpdate and stops
// every AI after this one for the frame, every frame, until the field changes.
Component target = targetStatic.GetValue() as Component;
if (target == null)
{
if (targetStatic.GetValue() != null) targetStatic.SetValue(null);
return;
}
Character monster = Traverse.Create(__instance).Field<Character>("m_character").Value;
if (monster == null) return;
// A piece an allied race built is never a target, with or without anyone around.
// See FactionPieceTruce.
if (FactionPieceTruce.Protects(target.gameObject, monster))
{
targetStatic.SetValue(null);
return;
}
foreach (Player player in Player.GetAllPlayers())
{
if (Vector3.Distance(player.transform.position, monster.transform.position) > FactionCheckRange) continue;
// A player this creature holds a grudge against is no ally of it right now.
if (RaceGrudge.Holds(monster, player)) continue;
if (!FactionHostilityPatch.IsAlliedMob(FactionHostilityPatch.GetPlayerRace(player), monster.gameObject.name)) continue;
targetStatic.SetValue(null);
return;
}
}
}
// IsEnemy is not the only way a mob picks the player, and the other way ignores it
// completely. BaseAI.FindEnemy() walks every character asking IsEnemy - which both truce
// patches above answer - but when that walk comes up empty and the creature HuntPlayer()s,
// it falls through to Player.GetClosestPlayer(transform.position, 200f) and returns whoever
// it finds, without asking anything about factions.
//
// That fall-through is why the Black Forest truce looked broken to the Trol's testers:
// MonsterAI.UpdateAI turns hunting on for every IsEventCreature() while an event is running,
// and the events that reach a Trol are "the forest is moving" (Greydwarves), "you are being
// hunted" (Trolls) and the Fuling army - the exact three they named. Anything a SpawnSystem
// entry or a TriggerSpawner flags with huntPlayer arrives by the same door.
//
// Filtering the RESULT rather than restating the rule keeps one source of truth: the public
// instance IsEnemy(Character) calls the static overload both postfixes above hook, so this
// honours whatever the faction sets and RaceHostilityManager's per-race lists already agree
// on. Retaliation does not come through here either way - a mob the player hits is targeted
// through BaseAI.OnDamaged/SetTarget, which never goes near FindEnemy. That target only
// SURVIVES because of RaceGrudge, though: UpdateTarget drops anything IsEnemy refuses.
[HarmonyPatch(typeof(BaseAI), "FindEnemy")]
public static class FactionHuntPlayerPatch
{
public static void Postfix(BaseAI __instance, ref Character __result)
{
if (!FactionsConfig.Hostility) return;
if (__result == null || !__result.IsPlayer()) return;
if (!__instance.IsEnemy(__result)) __result = null;
}
}
}

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