diff --git a/JotunnModStub/Alfar/AlfarArchon.cs b/JotunnModStub/Alfar/AlfarArchon.cs
index 0be4415..079d7a6 100644
--- a/JotunnModStub/Alfar/AlfarArchon.cs
+++ b/JotunnModStub/Alfar/AlfarArchon.cs
@@ -119,7 +119,10 @@ namespace RacesOfValheim
if (Time.time >= nextPulse)
{
nextPulse = Time.time + AlfarPowerConfig.ArchonPulseInterval.Value;
- AlfarPowers.Pulse(player, AlfarPowerConfig.ArchonPulseRadius.Value, AlfarPowerConfig.ArchonPulseDamage.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);
}
}
diff --git a/JotunnModStub/Alfar/AlfarChestGlow.cs b/JotunnModStub/Alfar/AlfarChestGlow.cs
new file mode 100644
index 0000000..dc529ff
--- /dev/null
+++ b/JotunnModStub/Alfar/AlfarChestGlow.cs
@@ -0,0 +1,79 @@
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// The light on the two Alfar chests, which says whether the drones have work there: the fire
+ /// chest's grate burns while it holds wood they may burn, the entry chest's inlay shines while it
+ /// holds anything but the sigil. Every client asks its own copy of the inventory, which Container
+ /// keeps in step with the ZDO, so nothing travels over the network for it.
+ ///
+ public class AlfarChestGlow : MonoBehaviour
+ {
+ public Renderer[] Glows;
+ public ParticleSystem Embers;
+ public Color GlowColor;
+ public bool WoodOnly;
+
+ private Container m_container;
+ private Material m_lit;
+ private Material m_cold;
+ private bool? m_shown;
+ private float m_nextCheck;
+
+ private void Awake()
+ {
+ m_container = GetComponent();
+ if (Glows == null || Glows.Length == 0 || Glows[0] == null) return;
+
+ m_cold = Glows[0].sharedMaterial;
+ m_lit = new Material(m_cold) { name = m_cold.name + "_lit" };
+ m_lit.color = Color.black;
+ m_lit.EnableKeyword("_EMISSION");
+ m_lit.SetColor("_EmissionColor", GlowColor);
+ }
+
+ private void Update()
+ {
+ if (Time.time < m_nextCheck) return;
+ m_nextCheck = Time.time + 1f;
+
+ bool lit = HasWork();
+ if (m_shown == lit) return;
+ m_shown = lit;
+
+ if (m_lit != null)
+ {
+ foreach (Renderer glow in Glows)
+ {
+ if (glow != null) glow.sharedMaterial = lit ? m_lit : m_cold;
+ }
+ }
+ if (Embers != null)
+ {
+ if (lit) Embers.Play(true);
+ else Embers.Stop(true, ParticleSystemStopBehavior.StopEmitting);
+ }
+ }
+
+ private bool HasWork()
+ {
+ Inventory inventory = m_container != null ? m_container.GetInventory() : null;
+ if (inventory == null) return false;
+
+ foreach (ItemDrop.ItemData item in inventory.GetAllItems())
+ {
+ if (item == null || item.m_dropPrefab == null) continue;
+
+ string name = item.m_dropPrefab.name;
+ if (WoodOnly ? AlfarDroneAI.IsWood(name) : name != AlfarSigil.PrefabName) return true;
+ }
+ return false;
+ }
+
+ private void OnDestroy()
+ {
+ if (m_lit != null) Destroy(m_lit);
+ }
+ }
+}
diff --git a/JotunnModStub/Alfar/AlfarChests.cs b/JotunnModStub/Alfar/AlfarChests.cs
index e8fc1d9..9efa86a 100644
--- a/JotunnModStub/Alfar/AlfarChests.cs
+++ b/JotunnModStub/Alfar/AlfarChests.cs
@@ -61,12 +61,15 @@ namespace RacesOfValheim
public static void Register()
{
RegisterOne(EntryName, "$rov_piece_alfar_inngangskista_name", "$rov_piece_alfar_inngangskista_desc",
- new Color(0.62f, 0.80f, 1f, 1f));
+ "$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",
- new Color(0.85f, 0.62f, 0.36f, 1f));
+ "$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, Color tint)
+ private static void RegisterOne(string pieceName, string display, string description, string hoverName, Color tint,
+ System.Func build, string iconResource)
{
GameObject source = PrefabManager.Cache.GetPrefab("piece_chest_wood");
if (source == null)
@@ -91,15 +94,19 @@ namespace RacesOfValheim
}
requirements.Add(new RequirementConfig("GreydwarfEye", AlfarNexusConfig.ChestEyes.Value, 0, true));
+ // The hover and the chest window say what the chest is for, not only its name.
Container container = prefab.GetComponent();
- if (container != null) container.m_name = display;
+ if (container != null) container.m_name = hoverName;
Piece piece = prefab.GetComponent();
if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The chest has no Piece: " + pieceName); return; }
piece.m_name = display;
piece.m_description = description;
- AlfarConstructs.Tint(prefab, tint);
+ // 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
{
@@ -107,7 +114,7 @@ namespace RacesOfValheim
Description = description,
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
- Icon = piece.m_icon,
+ Icon = icon,
Requirements = requirements.ToArray(),
}));
@@ -130,5 +137,12 @@ namespace RacesOfValheim
AlfarPieces.Extra.Add(pieceName);
}
+
+ internal static Sprite IconFrom(string resource)
+ {
+ Texture2D texture = PieceLook.LoadTexture(resource);
+ if (texture == null) return null;
+ return Sprite.Create(texture, new Rect(0f, 0f, texture.width, texture.height), new Vector2(0.5f, 0.5f));
+ }
}
}
diff --git a/JotunnModStub/Alfar/AlfarConfig.cs b/JotunnModStub/Alfar/AlfarConfig.cs
index 1769a1a..558c0a7 100644
--- a/JotunnModStub/Alfar/AlfarConfig.cs
+++ b/JotunnModStub/Alfar/AlfarConfig.cs
@@ -39,17 +39,26 @@ namespace RacesOfValheim
public static ConfigEntry WidthScale;
///
- /// 1 is the Sverm's size, which is what the design asked to try first ("se non va li
- /// allarghiamo"). Raise it to enlarge the eyes: 1.6 is roughly a grey from the films.
+ /// Scales the almond eyes (EyeExtent). The default 0.8 is the tuned grey look; raise it for
+ /// bigger eyes.
///
public static ConfigEntry EyeSizeMultiplier;
- // The eye geometry is the Sverm's, unchanged (SvermVisuals): offsets are metres in the head
- // bone's OWN frame, so they land on the same part of the face at any body scale.
- public const float EyeSeparation = 0.032f;
- public const float EyeForward = 0.081f;
- public const float EyeHeight = 0.181f;
- public const float EyeSize = 0.062f;
+ // 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 ───────────────────────────────────
@@ -152,7 +161,7 @@ namespace RacesOfValheim
new AcceptableValueRange(0.7f, 1.2f)));
EyeSizeMultiplier = config.Bind(look, "Eye Size Multiplier", 0.8f,
- new ConfigDescription("1 = the Sverm's eye size; 0.8 is slightly smaller. Raise to enlarge the black eyes.",
+ new ConfigDescription("Scales the black almond eyes. 0.8 is the default look; raise it for bigger eyes.",
new AcceptableValueRange(0.5f, 3f)));
}
}
diff --git a/JotunnModStub/Alfar/AlfarDroneAI.cs b/JotunnModStub/Alfar/AlfarDroneAI.cs
index 59d8fea..b319ceb 100644
--- a/JotunnModStub/Alfar/AlfarDroneAI.cs
+++ b/JotunnModStub/Alfar/AlfarDroneAI.cs
@@ -58,6 +58,13 @@ namespace RacesOfValheim
public const string KeyStatus = "RoV_alfarStatus";
public const string KeyDest = "RoV_alfarDest";
+ // What the drone last said: a counter every client watches, the text key and the item.
+ // Each client builds the line in its own language, so only the token travels.
+ public const string KeySaySeq = "RoV_alfarSaySeq";
+ public const string KeySayKey = "RoV_alfarSayKey";
+ public const string KeySayItem = "RoV_alfarSayItem";
+ public const string KeySayStation = "RoV_alfarSayStation";
+
/// Every drone alive in the loaded zones: the repairs look at each other through it.
public static readonly List All = new List();
@@ -141,6 +148,7 @@ namespace RacesOfValheim
private float m_nextFightScan;
private float m_fightUntil;
+ private bool m_fighting;
private ZNetView m_nview;
private Character m_character;
@@ -168,6 +176,11 @@ namespace RacesOfValheim
private ZDOID m_sortDest;
private float m_scannedAt = -99f;
+ // Speech: the last line this client showed, and when to look for a new one.
+ private int m_heardSeq;
+ private float m_nextListen;
+ private float m_nextKilnCheck;
+
private Job m_job;
private float m_nextPlan;
private float m_jobDeadline;
@@ -200,6 +213,16 @@ namespace RacesOfValheim
All.Add(this);
ReadPayload();
+
+ // A line said before this object loaded is old news: do not replay it on a zone reload.
+ if (m_nview != null && m_nview.IsValid()) m_heardSeq = m_nview.GetZDO().GetInt(KeySaySeq, 0);
+ }
+
+ private void Update()
+ {
+ if (Time.time < m_nextListen) return;
+ m_nextListen = Time.time + 0.5f;
+ Listen();
}
private void OnDestroy()
@@ -293,7 +316,17 @@ namespace RacesOfValheim
if (!m_fightsBack || m_ai == null || m_character == null || m_character.IsDead()) return false;
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false;
+ // A tamed MonsterAI with no patrol point and no follow target never drops its target for
+ // distance (UpdateTarget, IL): only after 30 s unsensed or 60 s without a swing. The drone
+ // hears far, so an enemy that ran off kept "being sensed" and held the tick for vanilla.
+ // Past the leash it is no longer this drone's fight.
Character target = m_ai.GetTargetCreature();
+ if (target != null && !target.IsDead() && !InFightReach(target))
+ {
+ m_ai.MakeTame();
+ target = null;
+ }
+
if (target != null && !target.IsDead())
{
m_fightUntil = Time.time + FightLinger;
@@ -301,20 +334,43 @@ namespace RacesOfValheim
else if (Time.time >= m_nextFightScan)
{
m_nextFightScan = Time.time + FightScanInterval;
- if (BaseAI.FindClosestEnemy(m_character, transform.position, FightRange) != null)
+ // FindClosestEnemy takes its first match at ANY distance (it only compares against
+ // maxDistance once it holds one), so with a deer anywhere in the loaded zones it never
+ // returned null and vanilla kept the tick: the drone idled about instead of working.
+ Character enemy = BaseAI.FindClosestEnemy(m_character, transform.position, FightRange);
+ if (enemy != null && Vector3.Distance(enemy.transform.position, transform.position) <= FightRange)
{
m_fightUntil = Time.time + FightLinger;
}
}
- if (Time.time >= m_fightUntil) return false;
+ if (Time.time >= m_fightUntil)
+ {
+ // The fight is over: clear what vanilla still holds (target, alert), or the next
+ // GetTargetCreature hands the tick straight back to it. MakeTame is the public door
+ // that nulls both targets and the alert in one call; the drone is tamed already.
+ if (m_fighting) { m_fighting = false; m_ai.MakeTame(); }
+ return false;
+ }
+ m_fighting = true;
m_job = null;
m_nextPlan = 0f; // the fight moved it; plan afresh the moment it hands back
SetStatus("Fighting.");
return true;
}
+ /// Close to the drone, and not past the edge of the base it works.
+ private bool InFightReach(Character enemy)
+ {
+ Vector3 at = enemy.transform.position;
+ if (Vector3.Distance(at, transform.position) > FightRange * 2f) return false;
+
+ Vector3? anchor = Anchor;
+ float leash = AlfarNexusConfig.NexusRadius.Value + m_radiusBonus + FightRange;
+ return anchor == null || Vector3.Distance(at, anchor.Value) <= leash;
+ }
+
// ================================================================ the tick
/// Everything. Returns what MonsterAI.UpdateAI would have returned.
@@ -389,17 +445,34 @@ namespace RacesOfValheim
Scan(anchor.Value);
ExpirePenalties();
+ CheckIdleKiln();
// A harvest is in progress: wait for the drops to land, then gather them and replant.
+ Job job;
if (m_farmSpot != null)
{
- m_job = Time.time < m_farmReadyAt
+ job = Time.time < m_farmReadyAt
? new Job { Kind = "wait", Point = transform.position, Label = "Waiting" }
: new Job { Kind = "farm_finish", Point = m_farmSpot.Value, Label = "Gathering" };
- return;
}
+ // A delivery is a job like any other and gets its own clock. It used to return early here
+ // and inherit the load's deadline: a slow trip, or a fight on the way, left it already late,
+ // so it timed out on the first tick, was planned again, timed out again, every frame - the
+ // drone froze with wood in hand next to the kiln (10790 timeouts in one player's log).
+ else if (m_payload.Count > 0) job = PlanDelivery(anchor.Value);
+ else job = PlanWork(anchor.Value);
- if (m_payload.Count > 0) { m_job = PlanDelivery(anchor.Value); return; }
+ if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target))
+ {
+ m_jobDeadline = Time.time + JobTimeout;
+ }
+ if (m_job != null && !ReferenceEquals(m_job, job)) Release(m_job.Claim);
+ if (job != null) Claim(job.Claim);
+ m_job = job;
+ }
+
+ private Job PlanWork(Vector3 anchor)
+ {
// The forge has no clock: a smelter holds its ore indefinitely and puts its own output on
// the floor, so PlanRescue would ask a question whose answer is always no. The smith is a
@@ -415,15 +488,7 @@ namespace RacesOfValheim
// base: repairs, the fields, and last the tidying of the entry chest.
Job job = PlanRescue();
job = job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad();
- job = job ?? PlanRepair(anchor.Value) ?? PlanFarm(anchor.Value) ?? PlanSort();
-
- if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target))
- {
- m_jobDeadline = Time.time + JobTimeout;
- }
- if (m_job != null && !ReferenceEquals(m_job, job)) Release(m_job.Claim);
- if (job != null) Claim(job.Claim);
- m_job = job;
+ return job ?? PlanRepair(anchor) ?? PlanFarm(anchor) ?? PlanSort();
}
///
@@ -552,7 +617,7 @@ namespace RacesOfValheim
Kind = "collect",
Target = best.Id,
Claim = best.Id,
- Point = best.Position,
+ Point = ApproachPoint(best),
Hurry = true,
Label = "Saving the food",
};
@@ -583,7 +648,7 @@ namespace RacesOfValheim
Kind = "collect",
Target = best.Id,
Claim = best.Id,
- Point = best.Position,
+ Point = ApproachPoint(best),
Label = "Collecting",
};
}
@@ -713,20 +778,37 @@ namespace RacesOfValheim
// coal, so gating the delivery on free slots sent the servant back to the chest with
// the coal it had just fetched - and then PlanFuel sent it out for the same coal again,
// forever. AcceptsAnything already asks the right question of both doors.
+ // A station it could not reach is in the penalty box: asking it again straight away
+ // is the same failed trip.
+ bool unreachable = IsPenalised(target);
ButlerStation station = StationById(target);
- if (station != null && station.Alive && station.Operable && AcceptsAnything(station))
+ if (station != null && station.Alive && station.Operable && AcceptsAnything(station) && !unreachable)
{
return new Job
{
Kind = "deposit_station",
Target = target,
- Point = station.Position,
+ Point = ApproachPoint(station),
Label = "Loading " + Describe(),
};
}
// The station is gone, full or cold. The goods are ours to put back, not to hold.
m_nview.GetZDO().Set(KeyTarget, ZDOID.None);
+
+ // Out of reach, the load goes back where it came from: the Eldividarkista's wood stays
+ // fuel instead of landing in the entry chest and being sorted away into storage.
+ Container source = unreachable ? ContainerById(m_nview.GetZDO().GetZDOID(KeySource)) : null;
+ if (source != null && !IsMarkedOff(source) && !IsPenalised(ZdoOf(source)) && HasRoomFor(source))
+ {
+ return new Job
+ {
+ Kind = "deposit",
+ Target = ZdoOf(source),
+ Point = source.transform.position,
+ Label = "Storing " + Describe(),
+ };
+ }
}
Container chest = ChestForProduct();
@@ -759,7 +841,7 @@ namespace RacesOfValheim
{
Kind = "deposit_station",
Target = consumer.Id,
- Point = consumer.Position,
+ Point = ApproachPoint(consumer),
Label = "Loading " + Describe(),
};
}
@@ -1418,16 +1500,25 @@ namespace RacesOfValheim
if (inventory == null) return null;
string sigil = AlfarSigil.PrefabName;
+ bool spoke = false;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item == null || item.m_dropPrefab == null) continue;
string name = item.m_dropPrefab.name;
if (name == sigil) continue;
- if (!IsWood(name) && AnyStationAccepts(name)) continue;
+ if (!IsWood(name) && AnyStationAccepts(name))
+ {
+ if (!spoke) spoke = Say("rov_msg_alfar_drone_sort_keep", name, KeepRepeatSeconds);
+ continue;
+ }
Container destination = DestinationFor(name);
- if (destination == null) continue;
+ if (destination == null)
+ {
+ if (!spoke) spoke = Say("rov_msg_alfar_drone_sort_nowhere", name, NowhereRepeatSeconds);
+ continue;
+ }
m_sortItem = name;
m_sortDest = ZdoOf(destination);
@@ -1443,6 +1534,119 @@ namespace RacesOfValheim
return null;
}
+ // ================================================================ speech
+
+ /// When each item may be mentioned again, shared by every drone on this client, so
+ /// five drones looking at the same stone say it once and not five times.
+ private static readonly Dictionary s_nextMention = new Dictionary();
+ private const float NowhereRepeatSeconds = 300f;
+ private const float KeepRepeatSeconds = 1800f;
+ private const float SpeechRange = 40f;
+
+ /// Owner side: says the line once per cooldown per item, by writing it into the ZDO
+ /// where every client in range picks it up. Returns whether it spoke, so one plan says one
+ /// line and the bubbles do not overwrite each other.
+ private bool Say(string key, string item, float repeatSeconds, string station = "")
+ {
+ string mention = key + "|" + item;
+ float next;
+ if (s_nextMention.TryGetValue(mention, out next) && Time.time < next) return false;
+ s_nextMention[mention] = Time.time + repeatSeconds;
+
+ ZDO zdo = m_nview.GetZDO();
+ zdo.Set(KeySayKey, key);
+ zdo.Set(KeySayItem, item);
+ zdo.Set(KeySayStation, station);
+ zdo.Set(KeySaySeq, zdo.GetInt(KeySaySeq, 0) + 1);
+ return true;
+ }
+
+ /// Every client: a new line in the ZDO goes over the drone's head, the way vanilla's
+ /// NPCs talk, and into the chat window, for players close enough to care.
+ private void Listen()
+ {
+ if (m_nview == null || !m_nview.IsValid()) return;
+
+ ZDO zdo = m_nview.GetZDO();
+ int seq = zdo.GetInt(KeySaySeq, 0);
+ if (seq == m_heardSeq) return;
+ m_heardSeq = seq;
+
+ Player player = Player.m_localPlayer;
+ if (player == null || Chat.instance == null) return;
+ if (Vector3.Distance(player.transform.position, transform.position) > SpeechRange) return;
+
+ string item = zdo.GetString(KeySayItem, "");
+ GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(item) : null;
+ ItemDrop drop = prefab != null ? prefab.GetComponent() : null;
+ string itemName = drop != null ? drop.m_itemData.m_shared.m_name : item;
+
+ string text = ModText.Get(zdo.GetString(KeySayKey, ""), itemName,
+ "$rov_piece_alfar_inngangskista_name", "$rov_piece_alfar_eldividarkista_name",
+ zdo.GetString(KeySayStation, ""));
+ string speaker = m_character != null ? Localization.instance.Localize(m_character.m_name) : "";
+
+ Chat.instance.SetNpcText(gameObject, Vector3.up * 1.5f, SpeechRange, 8f, speaker, text, false);
+ Chat.instance.AddString(speaker, text, Talker.Type.Normal);
+ }
+
+ ///
+ /// The mistake players make with the kiln: the wood is in a plain chest (vanilla even calls
+ /// one "Wood chest"), and only the Eldividarkista's wood is ever burnt. A station that takes
+ /// wood, standing idle with nothing for it in the Eldividarkista while the right wood sits in
+ /// another chest, gets a line explaining that. Every 30 s is plenty for something the player
+ /// fixes by hand.
+ ///
+ private void CheckIdleKiln()
+ {
+ if (Time.time < m_nextKilnCheck) return;
+ m_nextKilnCheck = Time.time + 30f;
+
+ foreach (ButlerStation station in m_stations)
+ {
+ if (!station.Alive || !station.Operable || station.HasWork || station.FreeSlots <= 0) continue;
+ if (m_wood != null && FirstAccepted(station, m_wood) != null) continue;
+
+ string misplaced = WoodElsewhereFor(station);
+ if (misplaced == null) continue;
+
+ // The station's own name token, so every language says "kiln" the game's way.
+ Piece piece = station.Behaviour.GetComponent();
+ string stationName = piece != null ? piece.m_name : "";
+ if (Say("rov_msg_alfar_drone_kiln_wood", misplaced, NowhereRepeatSeconds, stationName)) return;
+ }
+ }
+
+ /// Wood the station would take, lying in the entry chest or a storage chest.
+ private string WoodElsewhereFor(ButlerStation station)
+ {
+ if (m_entry != null)
+ {
+ string found = WoodIn(m_entry, station);
+ if (found != null) return found;
+ }
+ foreach (Container chest in m_chests)
+ {
+ string found = WoodIn(chest, station);
+ if (found != null) return found;
+ }
+ return null;
+ }
+
+ private static string WoodIn(Container chest, ButlerStation station)
+ {
+ Inventory inventory = chest != null ? chest.GetInventory() : null;
+ if (inventory == null) return null;
+
+ foreach (ItemDrop.ItemData item in inventory.GetAllItems())
+ {
+ if (item == null || item.m_dropPrefab == null) continue;
+ string name = item.m_dropPrefab.name;
+ if (IsWood(name) && station.Accepts(name)) return name;
+ }
+ return null;
+ }
+
private bool DoSortFetch()
{
if (m_sortItem == null || m_sortDest == ZDOID.None) return false;
@@ -1463,6 +1667,169 @@ namespace RacesOfValheim
// ================================================================ moving
/// Vanilla pathing, through the private MoveTo. True the moment it has arrived.
+ /// F8 readout: what each worker within 60 m is doing and what vanilla still holds, and
+ /// for the nearest one, why each thing in the entry chest is (or is not) being sorted.
+ public static void DebugReport(Player player)
+ {
+ var lines = new List();
+ AlfarDroneAI nearest = null;
+ float nearestDistance = 60f;
+
+ foreach (AlfarDroneAI drone in All)
+ {
+ if (drone == null || drone.m_ai == null) continue;
+ float distance = Vector3.Distance(drone.transform.position, player.transform.position);
+ if (distance > 60f) continue;
+ if (distance < nearestDistance) { nearestDistance = distance; nearest = drone; }
+
+ Character target = drone.m_ai.GetTargetCreature();
+ string targetText = target != null
+ ? $"{Utils.GetPrefabName(target.gameObject)} {Vector3.Distance(target.transform.position, drone.transform.position):0}m"
+ : "none";
+ lines.Add($"[RoV drone] {distance:0}m: '{drone.Status}' job {(drone.m_job != null ? drone.m_job.Kind : "none")} " +
+ $"carry {drone.PayloadCount()} fight {drone.m_fighting} vanilla target {targetText} " +
+ $"alerted {drone.m_ai.IsAlerted()} flying {drone.m_character.IsFlying()} owner {drone.m_nview.IsOwner()}");
+
+ // The other half of what holds a fight: the 12 m sweep, and how long the linger has left.
+ Character near = BaseAI.FindClosestEnemy(drone.m_character, drone.transform.position, FightRange);
+ string nearText = near != null
+ ? $"{Utils.GetPrefabName(near.gameObject)} {Vector3.Distance(near.transform.position, drone.transform.position):0}m"
+ : "none";
+ lines.Add($"[RoV drone] fight left {Mathf.Max(0f, drone.m_fightUntil - Time.time):0.0}s, " +
+ $"closest enemy {nearText}, in reach {(target != null && drone.InFightReach(target))}");
+ }
+
+ if (nearest == null) lines.Add("[RoV drone] no worker drone within 60m");
+ else
+ {
+ lines.AddRange(nearest.SortReport());
+ lines.AddRange(nearest.StationReport());
+ }
+
+ foreach (string line in lines)
+ {
+ Debug.Log(line);
+ player.Message(MessageHud.MessageType.TopLeft, line);
+ }
+ }
+
+ /// Why a station is (or is not) fed: what the last scan saw, the wood chest, and every
+ /// smelter, hearth or fermenter within the radius - and the ones just past it, by how much.
+ private IEnumerable StationReport()
+ {
+ Vector3? anchor = Anchor;
+ if (anchor == null) { yield return "[RoV station] no anchor"; yield break; }
+
+ float radius = AlfarNexusConfig.NexusRadius.Value + m_radiusBonus;
+ yield return $"[RoV station] anchor {Vector3.Distance(transform.position, anchor.Value):0}m from drone, " +
+ $"radius {radius:0}, scanned {Time.time - m_scannedAt:0}s ago, {m_stations.Count} stations, {m_chests.Count} chests";
+
+ if (m_wood == null) yield return "[RoV station] no Eldividarkista in range (or it is open, or holds the sigil)";
+ else
+ {
+ var wood = new List();
+ Inventory inventory = m_wood.GetInventory();
+ if (inventory != null)
+ {
+ foreach (ItemDrop.ItemData item in inventory.GetAllItems())
+ {
+ wood.Add(item.m_dropPrefab != null ? $"{item.m_dropPrefab.name}x{item.m_stack}" : $"{item.m_shared.m_name}(no prefab)");
+ }
+ }
+ yield return $"[RoV station] Eldividarkista {Vector3.Distance(m_wood.transform.position, anchor.Value):0}m from anchor, " +
+ $"open {m_wood.IsInUse()}, penalty {IsPenalised(ZdoOf(m_wood))}, holds [{string.Join(", ", wood.ToArray())}]";
+ }
+
+ foreach (ButlerStation station in m_stations)
+ {
+ if (!station.Alive) { yield return "[RoV station] (a station that is gone)"; continue; }
+
+ Container chest;
+ string material = FindMaterialFor(station, out chest);
+ string from = material == null ? "nothing" : $"{material} from {(chest == m_wood ? "Eldividarkista" : "entry")}";
+ yield return $"[RoV station] {Utils.GetPrefabName(station.Behaviour.gameObject)} " +
+ $"{Vector3.Distance(station.Position, anchor.Value):0}m: operable {station.Operable} free {station.FreeSlots} " +
+ $"work {station.HasWork} wood {station.Accepts("Wood")} penalty {IsPenalised(station.Id)} " +
+ $"claimed {ClaimedByOther(station.Id)} fuel {station.FuelPrefab ?? "-"}/{station.FuelWanted} | load: {from}";
+ }
+
+ // A station the scan cannot see because it stands past the edge.
+ List pieces = AllPiecesField != null ? AllPiecesField.GetValue(null) as List : null;
+ if (pieces == null) yield break;
+ foreach (Piece piece in pieces)
+ {
+ if (piece == null) continue;
+ float distance = Vector3.Distance(piece.transform.position, anchor.Value);
+ if (distance <= radius || distance > radius + 15f) continue;
+ if (ButlerStation.From(piece.gameObject) == null) continue;
+ yield return $"[RoV station] {Utils.GetPrefabName(piece.gameObject)} {distance:0}m: OUTSIDE the radius by {distance - radius:0.0}m";
+ }
+ }
+
+ private IEnumerable SortReport()
+ {
+ if (m_entry == null) { yield return "[RoV sort] no entry chest in range"; yield break; }
+ if (m_entry.IsInUse()) yield return "[RoV sort] entry chest is open";
+ if (IsPenalised(ZdoOf(m_entry))) yield return "[RoV sort] entry chest is set aside (penalty)";
+
+ Inventory inventory = m_entry.GetInventory();
+ if (inventory == null) yield break;
+
+ var seen = new HashSet();
+ foreach (ItemDrop.ItemData item in inventory.GetAllItems())
+ {
+ if (item == null) continue;
+ if (item.m_dropPrefab == null) { yield return $"[RoV sort] {item.m_shared.m_name}: no drop prefab"; continue; }
+
+ string name = item.m_dropPrefab.name;
+ if (!seen.Add(name)) continue;
+
+ string verdict;
+ if (name == AlfarSigil.PrefabName) verdict = "sigil, stays";
+ else if (!IsWood(name) && AnyStationAccepts(name)) verdict = "a station takes it, stays as work";
+ else
+ {
+ Container destination = DestinationFor(name);
+ verdict = destination != null
+ ? $"goes to chest at {Vector3.Distance(destination.transform.position, m_entry.transform.position):0}m"
+ : $"nowhere: no storage chest holds it and none is empty ({m_chests.Count} chests)";
+ }
+ yield return $"[RoV sort] {name}: {verdict}";
+ }
+ }
+
+ ///
+ /// Where the drone flies to serve a station: beside it, a metre past its colliders on the side
+ /// the drone comes from. Vanilla lifts a flyer's goal to m_flyAltitudeMin over the ground under
+ /// it (BaseAI.MoveTo, IL), and under a charcoal kiln's origin that is inside the dome: the drone
+ /// pressed against the stone, never came within ArriveDistance, and the kiln went into the
+ /// penalty box (snakey's log, "Could not reach collect target"). Beside it is open air, and it
+ /// stays under a roof indoors, where aiming over the top would not. The loading and the sweep
+ /// still work from the station's own position.
+ ///
+ private Vector3 ApproachPoint(ButlerStation station)
+ {
+ Vector3 centre = station.Position;
+ bool any = false;
+ Bounds bounds = new Bounds(centre, Vector3.zero);
+ foreach (Collider collider in station.Behaviour.GetComponentsInChildren())
+ {
+ if (collider == null || !collider.enabled || collider.isTrigger) continue;
+ if (any) bounds.Encapsulate(collider.bounds);
+ else { bounds = collider.bounds; any = true; }
+ }
+ if (!any) return centre;
+
+ Vector3 away = transform.position - bounds.center;
+ away.y = 0f;
+ if (away.sqrMagnitude < 0.01f) away = station.Transform.forward;
+ float reach = Mathf.Max(bounds.extents.x, bounds.extents.z) + 1f;
+
+ Vector3 point = bounds.center + away.normalized * reach;
+ point.y = centre.y;
+ return point;
+ }
+
private bool MoveToPoint(float dt, Vector3 point, float distance, bool run)
{
if (m_ai == null || MoveToMethod == null) return true; // cannot walk: act in place
@@ -1633,7 +2000,7 @@ namespace RacesOfValheim
"Wood", "FineWood", "RoundLog", "ElderBark", "YggdrasilWood", "Blackwood",
};
- private static bool IsWood(string prefabName) => s_woodFamily.Contains(prefabName);
+ internal static bool IsWood(string prefabName) => s_woodFamily.Contains(prefabName);
///
/// The first thing a station will take, and the chest it is in: raw material from the ENTRY chest
diff --git a/JotunnModStub/Alfar/AlfarDrones.cs b/JotunnModStub/Alfar/AlfarDrones.cs
index 7cef524..669d0c0 100644
--- a/JotunnModStub/Alfar/AlfarDrones.cs
+++ b/JotunnModStub/Alfar/AlfarDrones.cs
@@ -105,6 +105,10 @@ namespace RacesOfValheim
BaseAI ai = prefab.GetComponent();
if (ai != null) ai.m_randomMoveRange = 5f;
+ // A flyer's MoveTo lifts its goal to m_flyAltitudeMin above whatever solid is under it,
+ // the rock top included: at the vanilla height the miners hovered over a deposit out of
+ // reach and never struck.
+ if (ai != null && miner) { ai.m_flyAltitudeMin = 0.5f; ai.m_flyAltitudeMax = 2f; }
foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true))
{
@@ -251,34 +255,100 @@ namespace RacesOfValheim
public float Radius = 12f;
public float LiveSeconds = 120f;
- private float born;
+ // The job lives in the drone's ZDO, not only in these fields: Valheim destroys a creature
+ // when its zone unloads and builds a fresh one when the zone comes back, and the fresh
+ // one had a zero Centre, so it searched around the world origin and stood idle. The
+ // birth time is network time, so a rebuilt drone does not get a new two minutes either.
+ private static readonly int CentreKey = "rov_graf_centre".GetStableHashCode();
+ private static readonly int RadiusKey = "rov_graf_radius".GetStableHashCode();
+ private static readonly int LifeKey = "rov_graf_life".GetStableHashCode();
+ private static readonly int BornKey = "rov_graf_born".GetStableHashCode();
+
+ private const float Reach = 4f;
+
+ private bool loaded;
+ private double bornAt;
private float nextStrike;
private Component target;
+ private float lastDistance = -1f;
+ private int strikes;
+ private string lastHit = "none";
+
+ public static readonly List All = new List();
+
+ private void OnEnable() { All.Add(this); }
+ private void OnDisable() { All.Remove(this); }
private static readonly System.Reflection.MethodInfo MoveToMethod =
AccessTools.Method(typeof(BaseAI), "MoveTo", new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) });
- private void Start()
+ private static double Now => ZNet.instance != null ? ZNet.instance.GetTimeSeconds() : Time.time;
+
+ /// Called by the throw right after the drone is made: the job, into the ZDO.
+ public void Assign(Vector3 centre, float radius, float liveSeconds)
{
- born = Time.time;
+ Centre = centre;
+ Radius = radius;
+ LiveSeconds = liveSeconds;
+ bornAt = Now;
+ loaded = true;
+
+ ZNetView nview = GetComponent();
+ if (nview == null || !nview.IsValid()) return;
+ ZDO zdo = nview.GetZDO();
+ zdo.Set(CentreKey, centre);
+ zdo.Set(RadiusKey, radius);
+ zdo.Set(LifeKey, liveSeconds);
+ zdo.Set(BornKey, (long)(bornAt * 1000.0));
+ }
+
+ ///
+ /// A drone rebuilt from its ZDO reads its job back. One with no job at all (thrown by an
+ /// older build) digs around where it stands, which is where it was thrown.
+ ///
+ private void Load()
+ {
+ loaded = true;
+ ZNetView nview = GetComponent();
+ ZDO zdo = nview != null && nview.IsValid() ? nview.GetZDO() : null;
+ long born = zdo != null ? zdo.GetLong(BornKey, 0L) : 0L;
+ if (born == 0L)
+ {
+ Centre = transform.position;
+ bornAt = Now;
+ return;
+ }
+ Centre = zdo.GetVec3(CentreKey, transform.position);
+ Radius = zdo.GetFloat(RadiusKey, Radius);
+ LiveSeconds = zdo.GetFloat(LifeKey, LiveSeconds);
+ bornAt = born / 1000.0;
}
public bool Tick(MonsterAI ai, float dt)
{
- if (Time.time - born >= LiveSeconds)
+ if (!loaded) Load();
+
+ if (Now - bornAt >= LiveSeconds)
{
ZNetView nview = GetComponent();
if (nview != null && nview.IsValid() && nview.IsOwner()) ZNetScene.instance.Destroy(gameObject);
return true;
}
- if (target == null || !target.gameObject.activeInHierarchy) target = FindDeposit();
- if (target == null) { ai.StopMoving(); return true; }
+ // 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; }
- Vector3 point = target.transform.position;
+ // 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 > 3.5f)
+ if (distance > Reach)
{
if (MoveToMethod != null) MoveToMethod.Invoke(ai, new object[] { dt, point + Vector3.up * 1.5f, 2f, true });
return true;
@@ -287,15 +357,30 @@ namespace RacesOfValheim
ai.StopMoving();
if (Time.time < nextStrike) return true;
nextStrike = Time.time + 1f;
- Strike(target);
+ Strike(target, area, point);
+ strikes++;
return true;
}
private static string[] names;
- private static string[] Deposits => names ?? (names = AlfarNexusConfig.MinerDeposits.Value.Split(
- new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries));
+ private static string namesSource;
- private bool IsPrecious(string prefabName)
+ // 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)
{
@@ -310,12 +395,11 @@ namespace RacesOfValheim
float bestDistance = float.MaxValue;
foreach (Collider collider in Physics.OverlapSphere(Centre, Radius, ~0, QueryTriggerInteraction.Ignore))
{
- Component deposit = collider.GetComponentInParent();
- if (deposit == null) deposit = collider.GetComponentInParent();
- if (deposit == null) deposit = collider.GetComponentInParent();
+ Component deposit = DepositOf(collider);
if (deposit == null) continue;
- string prefabName = Utils.GetPrefabName(deposit.gameObject);
+ if (!Live(deposit)) continue;
+ string prefabName = DepositName(deposit);
if (!IsPrecious(prefabName)) continue;
float distance = Vector3.Distance(transform.position, deposit.transform.position);
@@ -324,28 +408,289 @@ namespace RacesOfValheim
return best;
}
- private void Strike(Component deposit)
+ ///
+ /// The live hit area of the deposit closest to the drone, and the closest point on it.
+ /// MineRock and MineRock5 only take a hit on one of their own areas; a MineRock with an area
+ /// root (tin) keeps its base model collider apart, and a hit on that one is thrown away.
+ /// Broken areas are switched off, so only active colliders count.
+ ///
+ private Collider NearestArea(Component deposit, out Vector3 point)
+ {
+ point = Vector3.zero;
+ MineRock rock = deposit as MineRock;
+ GameObject root = rock != null && rock.m_areaRoot != null ? rock.m_areaRoot : deposit.gameObject;
+
+ Collider best = null;
+ float bestDistance = float.MaxValue;
+ foreach (Collider collider in root.GetComponentsInChildren())
+ {
+ if (collider == null || !collider.enabled) continue;
+ Vector3 closest = collider.bounds.ClosestPoint(transform.position);
+ float distance = Vector3.Distance(transform.position, closest);
+ if (distance < bestDistance) { best = collider; bestDistance = distance; point = closest; }
+ }
+ return best;
+ }
+
+ private void Strike(Component deposit, Collider area, Vector3 point)
{
IDestructible destructible = deposit as IDestructible;
- if (destructible == null) return;
+ 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_point = deposit.transform.position;
- hit.m_dir = (deposit.transform.position - transform.position).normalized;
+ 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());
- // MineRock5 picks the piece of the rock to hurt from the collider that was hit.
- Collider collider = deposit.GetComponentInChildren();
- if (collider != null)
+ // 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
{
- hit.m_hitCollider = collider;
- hit.m_point = collider.bounds.center;
+ destructible.Damage(hit);
+
+ // The F8 readout showed the hit entering Damage with every gate open and this
+ // machine owning the deposit, and the RPC handler never running: the routed call
+ // left for the network instead of being handled here. When we own the deposit,
+ // call its own handler directly - the same resistance, tier and break logic, only
+ // without the routing.
+ if (!rpcRan && OwnsDeposit(deposit)) StrikeDirect(deposit, area, hit);
+ }
+ finally { striking = null; }
+ }
+
+ private static bool rpcRan;
+
+ private static readonly System.Reflection.MethodInfo DestructibleRpc = AccessTools.Method(typeof(Destructible), "RPC_Damage");
+ private static readonly System.Reflection.MethodInfo MineRockRpc = AccessTools.Method(typeof(MineRock), "RPC_Hit");
+ private static readonly System.Reflection.MethodInfo MineRockArea = AccessTools.Method(typeof(MineRock), "GetAreaIndex");
+ private static readonly System.Reflection.MethodInfo MineRock5Rpc = AccessTools.Method(typeof(MineRock5), "RPC_Damage");
+ private static readonly System.Reflection.MethodInfo MineRock5Area = AccessTools.Method(typeof(MineRock5), "GetAreaIndex");
+ private static readonly System.Reflection.FieldInfo RpcIdField = AccessTools.Field(typeof(ZRoutedRpc), "m_id");
+
+ private static bool OwnsDeposit(Component deposit)
+ {
+ ZNetView nview = deposit.GetComponent();
+ return nview != null && nview.IsValid() && nview.IsOwner();
+ }
+
+ private void StrikeDirect(Component deposit, Collider area, HitData hit)
+ {
+ long sender = ZDOMan.GetSessionID();
+ string entry = lastHit;
+ try
+ {
+ if (deposit is Destructible && DestructibleRpc != null)
+ {
+ DestructibleRpc.Invoke(deposit, new object[] { sender, hit });
+ }
+ else if (deposit is MineRock && MineRockRpc != null && MineRockArea != null)
+ {
+ int index = (int)MineRockArea.Invoke(deposit, new object[] { area });
+ if (index < 0) { lastHit = "direct: collider is not a MineRock area"; return; }
+ MineRockRpc.Invoke(deposit, new object[] { sender, hit, index });
+ }
+ else if (deposit is MineRock5 && MineRock5Rpc != null && MineRock5Area != null)
+ {
+ int index = (int)MineRock5Area.Invoke(deposit, new object[] { area });
+ if (index < 0) { lastHit = "direct: collider is not a MineRock5 area"; return; }
+ MineRock5Rpc.Invoke(deposit, new object[] { sender, hit, index });
+ }
+ else
+ {
+ lastHit = $"direct: no handler for {deposit.GetType().Name}";
+ return;
+ }
+ lastHit = $"direct, {lastHit} | before: {entry}";
+ }
+ catch (System.Exception ex)
+ {
+ System.Exception inner = ex.InnerException ?? ex;
+ lastHit = $"direct failed: {inner.GetType().Name}: {inner.Message}";
+ Jotunn.Logger.LogWarning($"[Alfar] Grafvaettir direct hit failed: {inner}");
+ }
+ }
+
+ // ─── F8 diagnostics: what each hit did on arrival ──────────────────────
+
+ private static AlfarMiner striking;
+
+ private static AlfarMiner MinerOf(HitData hit)
+ {
+ if (striking != null) return striking;
+ Character attacker = hit != null ? hit.GetAttacker() : null;
+ return attacker != null ? attacker.GetComponent() : null;
+ }
+
+ private static readonly System.Reflection.FieldInfo FirstFrameField = AccessTools.Field(typeof(Destructible), "m_firstFrame");
+
+ /// The gates in front of the RPC: whose deposit it is and whether the view is live.
+ private static void RecordEntry(Component deposit, string extra)
+ {
+ if (striking == null) return;
+ ZNetView nview = deposit.GetComponent();
+ bool valid = nview != null && nview.IsValid();
+ long owner = valid ? nview.GetZDO().GetOwner() : -1L;
+ long me = ZDOMan.GetSessionID();
+ Character attacker = striking.GetComponent();
+ object rpcId = RpcIdField != null && ZRoutedRpc.instance != null ? RpcIdField.GetValue(ZRoutedRpc.instance) : null;
+ striking.lastHit = $"Damage entered{extra} valid={valid} owner={owner} session={me} rpcId={rpcId} " +
+ $"attackerZdo={(attacker != null ? attacker.GetZDOID().ToString() : "none")}, no RPC";
+ }
+
+ [HarmonyPatch(typeof(Destructible), nameof(Destructible.Damage))]
+ public static class Alfar_Miner_DestructibleEnter_Patch
+ {
+ public static void Prefix(Destructible __instance)
+ {
+ object first = FirstFrameField != null ? FirstFrameField.GetValue(__instance) : null;
+ RecordEntry(__instance, $" firstFrame={first}");
+ }
+ }
+
+ [HarmonyPatch(typeof(MineRock), nameof(MineRock.Damage))]
+ public static class Alfar_Miner_MineRockEnter_Patch
+ {
+ public static void Prefix(MineRock __instance) => RecordEntry(__instance, "");
+ }
+
+ [HarmonyPatch(typeof(MineRock5), nameof(MineRock5.Damage))]
+ public static class Alfar_Miner_MineRock5Enter_Patch
+ {
+ public static void Prefix(MineRock5 __instance) => RecordEntry(__instance, "");
+ }
+
+ private static void Record(HitData hit, string kind, float before, float after, int minTier)
+ {
+ AlfarMiner miner = MinerOf(hit);
+ if (miner == null) return;
+ if (miner == striking) rpcRan = true;
+ miner.lastHit = $"{kind} hp {before:0.#}->{after:0.#} dmg {hit.GetTotalDamage():0.#} " +
+ $"pick {hit.m_damage.m_pickaxe:0.#} tier {hit.m_toolTier}/{minTier}";
+ }
+
+ [HarmonyPatch(typeof(Destructible), "RPC_Damage")]
+ public static class Alfar_Miner_DestructibleHit_Patch
+ {
+ private static float Health(Destructible d)
+ {
+ ZNetView nview = d.GetComponent();
+ return nview != null && nview.IsValid() ? nview.GetZDO().GetFloat(ZDOVars.s_health, d.m_health) : -1f;
}
- destructible.Damage(hit);
+ public static void Prefix(Destructible __instance, HitData hit, out float __state)
+ {
+ __state = MinerOf(hit) != null ? Health(__instance) : -1f;
+ }
+
+ public static void Postfix(Destructible __instance, HitData hit, float __state)
+ {
+ if (MinerOf(hit) == null) return;
+ Record(hit, "Destructible", __state, Health(__instance), __instance.m_minToolTier);
+ }
+ }
+
+ [HarmonyPatch(typeof(MineRock), "RPC_Hit")]
+ public static class Alfar_Miner_MineRockHit_Patch
+ {
+ private static float Health(MineRock rock, int area)
+ {
+ ZNetView nview = rock.GetComponent();
+ return nview != null && nview.IsValid() ? nview.GetZDO().GetFloat("Health" + area, rock.GetHealth()) : -1f;
+ }
+
+ public static void Prefix(MineRock __instance, HitData hit, int hitAreaIndex, out float __state)
+ {
+ __state = MinerOf(hit) != null ? Health(__instance, hitAreaIndex) : -1f;
+ }
+
+ public static void Postfix(MineRock __instance, HitData hit, int hitAreaIndex, float __state)
+ {
+ if (MinerOf(hit) == null) return;
+ Record(hit, $"MineRock area {hitAreaIndex}", __state, Health(__instance, hitAreaIndex), __instance.m_minToolTier);
+ }
+ }
+
+ [HarmonyPatch(typeof(MineRock5), "DamageArea")]
+ public static class Alfar_Miner_MineRock5Hit_Patch
+ {
+ public static void Postfix(MineRock5 __instance, int hitAreaIndex, HitData hit, bool __result)
+ {
+ if (MinerOf(hit) == null) return;
+ Record(hit, $"MineRock5 area {hitAreaIndex} damaged={__result}", -1f, -1f, __instance.m_minToolTier);
+ }
+ }
+
+ private static bool Live(Component deposit)
+ {
+ ZNetView nview = deposit.GetComponent();
+ return nview != null && nview.IsValid();
+ }
+
+ ///
+ /// The deposit's prefab name, read from its ZDO. Not from the GameObject: MineRock5 renames
+ /// its own object to "___MineRock5 m_meshFilter" in Awake, so a broken copper vein
+ /// (rock4_copper_frac) never matched the list and the drones stopped after the first blow.
+ ///
+ private static string DepositName(Component deposit)
+ {
+ ZNetView nview = deposit.GetComponent();
+ if (nview != null && nview.IsValid() && ZNetScene.instance != null)
+ {
+ GameObject prefab = ZNetScene.instance.GetPrefab(nview.GetZDO().GetPrefab());
+ if (prefab != null) return prefab.name;
+ }
+ return Utils.GetPrefabName(deposit.gameObject);
+ }
+
+ private static Component DepositOf(Collider collider)
+ {
+ Component deposit = collider.GetComponentInParent();
+ if (deposit == null) deposit = collider.GetComponentInParent();
+ if (deposit == null) deposit = collider.GetComponentInParent();
+ return deposit;
+ }
+
+ ///
+ /// F8 readout: what the camera looks at (is it a deposit, of which kind, on the list?) and
+ /// what each live miner is doing (its target, how far, how many strikes).
+ ///
+ public static void DebugReport(Player player)
+ {
+ var lines = new List();
+ Transform aim = GameCamera.instance != null ? GameCamera.instance.transform : player.transform;
+ if (Physics.Raycast(aim.position, aim.forward, out RaycastHit hit, 50f, ~0, QueryTriggerInteraction.Ignore))
+ {
+ Component deposit = DepositOf(hit.collider);
+ string prefabName = deposit != null ? DepositName(deposit) : Utils.GetPrefabName(hit.collider.transform.root.gameObject);
+ lines.Add($"[RoV graf] look: {hit.collider.name} on {prefabName} " +
+ (deposit != null ? $"{deposit.GetType().Name} listed={IsPrecious(prefabName)}" : "not a deposit"));
+ }
+ else lines.Add("[RoV graf] look: nothing within 50m");
+
+ foreach (AlfarMiner miner in All)
+ {
+ if (miner == null) continue;
+ string targetName = miner.target != null ? DepositName(miner.target) : "none";
+ lines.Add($"[RoV graf] miner {Vector3.Distance(miner.transform.position, player.transform.position):0}m away: " +
+ $"target {targetName} dist {miner.lastDistance:0.0} strikes {miner.strikes} " +
+ $"age {Now - miner.bornAt:0}s centre {miner.Centre} r {miner.Radius:0} | last hit: {miner.lastHit}");
+ }
+
+ foreach (string line in lines)
+ {
+ Debug.Log(line);
+ player.Message(MessageHud.MessageType.TopLeft, line);
+ }
}
[HarmonyPatch(typeof(MonsterAI), "UpdateAI")]
diff --git a/JotunnModStub/Alfar/AlfarFireChest.cs b/JotunnModStub/Alfar/AlfarFireChest.cs
new file mode 100644
index 0000000..ffff98a
--- /dev/null
+++ b/JotunnModStub/Alfar/AlfarFireChest.cs
@@ -0,0 +1,166 @@
+using System.Collections.Generic;
+using Jotunn.Managers;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// The Eldividarkista's own body. Players kept mistaking a plain "Wood chest" for it, so it must
+ /// not look like any chest they can build: the box and lid are the Mistlands dvergr crate (a prop
+ /// nobody can place), repainted as blackened iron with an aged-bronze frame
+ /// (scripts/paint_fire_chest.py), with an iron grate on the front.
+ ///
+ /// Behind the grate the fire shows only while the chest holds wood the drones may burn: a dark
+ /// grate means empty. No light source, on purpose - a base full of chests must not glow.
+ ///
+ public static class AlfarFireChest
+ {
+ private const string CrateName = "dvergrprops_crate";
+ private const string EmbersSource = "fx_Torch_Carried";
+
+ // The crate is a 1.02 m cube, stretched into a chest about the size of the vanilla one:
+ // 1.6 m wide, 0.8 m deep. Its front face (+z, away from the lid's hinge) ends up here.
+ private static readonly Vector3 Stretch = new Vector3(1.6f, 1f, 0.8f);
+ private const float FrontZ = 0.515f * 0.8f;
+ private const float LidY = 0.81f;
+ private const float GrateWidth = 0.62f * 1.6f;
+ private const int GrateGaps = 10;
+ private const float GrateHeight = 0.36f;
+ private const float GrateY = 0.42f;
+
+ private static readonly Color Ember = new Color(1f, 0.42f, 0.1f);
+
+ /// Swaps the cloned wood chest's meshes for the fire chest. False leaves the wood
+ /// chest's look in place, with a warning, rather than an invisible chest.
+ public static bool Build(GameObject prefab)
+ {
+ GameObject crate = PrefabManager.Cache.GetPrefab(CrateName);
+ Transform crateNew = crate != null ? crate.transform.Find("new") : null;
+ Transform visual = prefab.transform.Find("New");
+ if (crateNew == null || crateNew.childCount < 3 || visual == null)
+ {
+ Jotunn.Logger.LogWarning("[Alfar] No dvergr crate to build the Eldividarkista from; it keeps the wood chest's look.");
+ return false;
+ }
+
+ // The wood chest's box, lids and LOD group go; "New" itself stays, because WearNTear
+ // switches it as the piece's healthy look.
+ for (int i = visual.childCount - 1; i >= 0; i--) Object.DestroyImmediate(visual.GetChild(i).gameObject);
+ LODGroup lod = visual.GetComponent();
+ if (lod != null) Object.DestroyImmediate(lod);
+
+ // The crate's high meshes, in the order the prefab keeps them: box, contents, lid. The
+ // contents are the glowing dvergr cargo and stay behind.
+ GameObject body = Object.Instantiate(crateNew.GetChild(0).gameObject, visual, false);
+ body.name = "body";
+ body.transform.localScale = Vector3.Scale(body.transform.localScale, Stretch);
+ GameObject lidClosed = Object.Instantiate(crateNew.GetChild(2).gameObject, visual, false);
+ lidClosed.name = "lid_closed";
+ lidClosed.transform.localScale = Vector3.Scale(lidClosed.transform.localScale, Stretch);
+
+ // The open lid: the closed one turned up 100 degrees about its back edge.
+ GameObject lidOpen = Object.Instantiate(lidClosed, visual, false);
+ lidOpen.name = "lid_open";
+ foreach (Collider collider in lidOpen.GetComponentsInChildren(true)) Object.DestroyImmediate(collider);
+ Vector3 hinge = new Vector3(0f, LidY, -FrontZ);
+ Quaternion turn = Quaternion.Euler(-100f, 0f, 0f);
+ lidOpen.transform.localPosition = hinge + turn * (lidClosed.transform.localPosition - hinge);
+ lidOpen.transform.localRotation = turn * lidClosed.transform.localRotation;
+ lidOpen.SetActive(false);
+
+ Container container = prefab.GetComponent();
+ if (container != null)
+ {
+ container.m_open = lidOpen;
+ container.m_closed = lidClosed;
+ }
+
+ // Only a retextured material is a copy; without the paint, writing to it would change every
+ // dvergr crate in the Mistlands too.
+ Texture2D paint = PieceLook.LoadTexture("AlfarFireChest_d.png");
+ if (paint != null) PieceLook.Retexture(visual, new Dictionary { { "Crate_d", paint } });
+ Material iron = paint != null ? body.GetComponent()?.sharedMaterial : null;
+ if (iron != null)
+ {
+ // The crate's normal map is wood planks; on plates it would draw seams that are not there.
+ if (iron.HasProperty("_BumpMap")) iron.SetTexture("_BumpMap", null);
+ if (iron.HasProperty("_Metallic")) iron.SetFloat("_Metallic", 0.6f);
+ if (iron.HasProperty("_Glossiness")) iron.SetFloat("_Glossiness", 0.45f);
+ }
+
+ Transform grate = BuildGrate(visual, iron, out Renderer glow);
+ ParticleSystem embers = AddEmbers(grate);
+
+ AlfarChestGlow look = prefab.AddComponent();
+ look.Glows = new[] { glow };
+ look.Embers = embers;
+ look.GlowColor = Ember * 2f;
+ look.WoodOnly = true;
+ return true;
+ }
+
+ /// The grate: a glowing plate just off the front face, a frame and bars in front of it.
+ private static Transform BuildGrate(Transform visual, Material iron, out Renderer glow)
+ {
+ Transform grate = new GameObject("grate").transform;
+ grate.SetParent(visual, false);
+ grate.gameObject.layer = visual.gameObject.layer;
+
+ Material bars = iron != null ? new Material(iron) { name = "AlfarFireChest_bars" } : null;
+ if (bars != null)
+ {
+ bars.SetTexture("_MainTex", null);
+ bars.color = new Color(0.16f, 0.15f, 0.15f);
+ }
+
+ glow = Block(grate, "glow", new Vector3(0f, GrateY, FrontZ + 0.005f), new Vector3(GrateWidth, GrateHeight, 0.01f), bars).GetComponent();
+
+ const float frame = 0.035f;
+ foreach (float x in new[] { -GrateWidth / 2f, GrateWidth / 2f })
+ Block(grate, "frame", new Vector3(x, GrateY, FrontZ + 0.02f), new Vector3(frame, GrateHeight + frame, 0.04f), bars);
+ foreach (float y in new[] { GrateY - GrateHeight / 2f, GrateY + GrateHeight / 2f })
+ Block(grate, "frame", new Vector3(0f, y, FrontZ + 0.02f), new Vector3(GrateWidth + frame, frame, 0.04f), bars);
+
+ for (int i = 1; i < GrateGaps; i++)
+ {
+ float x = -GrateWidth / 2f + GrateWidth * i / GrateGaps;
+ Block(grate, "bar", new Vector3(x, GrateY, FrontZ + 0.02f), new Vector3(0.022f, GrateHeight, 0.03f), bars);
+ }
+ Block(grate, "bar", new Vector3(0f, GrateY, FrontZ + 0.022f), new Vector3(GrateWidth, 0.022f, 0.03f), bars);
+
+ return grate;
+ }
+
+ /// A plain box with no collider, for trim the borrowed meshes do not have.
+ internal static GameObject Block(Transform parent, string name, Vector3 position, Vector3 size, Material material)
+ {
+ GameObject block = GameObject.CreatePrimitive(PrimitiveType.Cube);
+ Object.DestroyImmediate(block.GetComponent());
+ block.name = name;
+ block.layer = parent.gameObject.layer;
+ block.transform.SetParent(parent, false);
+ block.transform.localPosition = position;
+ block.transform.localScale = size;
+ if (material != null) block.GetComponent().sharedMaterial = material;
+ return block;
+ }
+
+ /// The carried torch's embers, rising off the top of the grate.
+ private static ParticleSystem AddEmbers(Transform grate)
+ {
+ GameObject torch = PrefabManager.Cache.GetPrefab(EmbersSource);
+ Transform source = torch != null ? torch.transform.Find("Embers") : null;
+ if (source == null)
+ {
+ Jotunn.Logger.LogWarning("[Alfar] No torch embers for the Eldividarkista; its grate glows without sparks.");
+ return null;
+ }
+
+ GameObject embers = Object.Instantiate(source.gameObject, grate, false);
+ embers.name = "embers";
+ embers.transform.localPosition = new Vector3(0f, GrateY + GrateHeight / 2f, FrontZ + 0.05f);
+ embers.transform.localRotation = Quaternion.identity;
+ return embers.GetComponent();
+ }
+ }
+}
diff --git a/JotunnModStub/Alfar/AlfarInputChest.cs b/JotunnModStub/Alfar/AlfarInputChest.cs
new file mode 100644
index 0000000..6f4ea39
--- /dev/null
+++ b/JotunnModStub/Alfar/AlfarInputChest.cs
@@ -0,0 +1,137 @@
+using System.Collections.Generic;
+using Jotunn.Managers;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// The Inngangskista's own body, the cold twin of : the dvergr loot
+ /// chest of the Mistlands towns (seen, never built), its panels repainted navy steel
+ /// (scripts/paint_input_chest.py) and its copper trim turned silver. A cyan line set into the
+ /// lid shines while the chest holds anything for the drones, and goes dark once they have
+ /// emptied it.
+ ///
+ public static class AlfarInputChest
+ {
+ private const string SourceName = "TreasureChest_dvergrtown";
+
+ // The town chest is placed at 1.2 and its meshes at 1.5 on top: 1.66 m wide, a vanilla chest's size.
+ private const float SourceScale = 1.2f;
+ private const float MeshScale = 1.5f * SourceScale;
+ private const float LidTop = 0.48f * MeshScale;
+ private const float LidHalfX = 0.42f * MeshScale;
+ private const float LidHalfZ = 0.24f * MeshScale;
+ private const float InlayInset = 0.10f;
+ private const float InlayWidth = 0.03f;
+
+ private static readonly Color Trim = new Color(0.9f, 0.95f, 1f);
+ private static readonly Color Inlay = new Color(0.35f, 0.9f, 1f);
+
+ /// Swaps the cloned wood chest's meshes for the input chest. False leaves the wood
+ /// chest's look in place, with a warning.
+ public static bool Build(GameObject prefab)
+ {
+ GameObject source = PrefabManager.Cache.GetPrefab(SourceName);
+ Transform sourceNew = source != null ? source.transform.Find("New") : null;
+ Transform box = sourceNew != null ? sourceNew.Find("stonechest") : null;
+ Transform closed = sourceNew != null ? sourceNew.Find("stonechesttop_closed") : null;
+ Transform open = sourceNew != null ? sourceNew.Find("stonechesttop_open") : null;
+ Transform visual = prefab.transform.Find("New");
+ if (box == null || closed == null || open == null || visual == null)
+ {
+ Jotunn.Logger.LogWarning("[Alfar] No dvergr chest to build the Inngangskista from; it keeps the wood chest's look.");
+ return false;
+ }
+
+ for (int i = visual.childCount - 1; i >= 0; i--) Object.DestroyImmediate(visual.GetChild(i).gameObject);
+ LODGroup lod = visual.GetComponent();
+ if (lod != null) Object.DestroyImmediate(lod);
+
+ GameObject body = Copy(box, visual, "body");
+ GameObject lidClosed = Copy(closed, visual, "lid_closed");
+ GameObject lidOpen = Copy(open, visual, "lid_open");
+ lidOpen.SetActive(false);
+
+ Container container = prefab.GetComponent();
+ if (container != null)
+ {
+ container.m_open = lidOpen;
+ container.m_closed = lidClosed;
+ }
+
+ Texture2D paint = PieceLook.LoadTexture("AlfarInputChest_d.png");
+ if (paint == null) return true; // the dvergr chest as it is: still not a vanilla chest
+ PieceLook.Retexture(visual, new Dictionary { { "dvergrchestWorn_d", paint } });
+
+ // The trim shares the anvil's texture, so it is recoloured on a copy instead; the panels'
+ // material is already a copy from Retexture.
+ var copies = new Dictionary();
+ Material panel = null;
+ foreach (Renderer renderer in visual.GetComponentsInChildren(true))
+ {
+ Material[] materials = renderer.sharedMaterials;
+ for (int i = 0; i < materials.Length; i++)
+ {
+ Material material = materials[i];
+ if (material == null) continue;
+ if (material.name.EndsWith("_rov")) { panel = panel ?? material; continue; }
+ if (!material.name.StartsWith("dvergr_metal_furnmiture")) continue;
+
+ if (!copies.TryGetValue(material, out Material trim))
+ {
+ trim = new Material(material) { name = material.name + "_rov" };
+ trim.color = Trim;
+ if (trim.HasProperty("_MetalColor")) trim.SetColor("_MetalColor", Trim);
+ copies[material] = trim;
+ }
+ materials[i] = trim;
+ }
+ renderer.sharedMaterials = materials;
+ }
+
+ AlfarChestGlow look = prefab.AddComponent();
+ look.Glows = BuildInlay(lidClosed.transform, panel);
+ look.GlowColor = Inlay * 1.6f;
+ look.WoodOnly = false;
+ return true;
+ }
+
+ /// A copy of one of the town chest's parts, at the town chest's size and on the piece layer.
+ private static GameObject Copy(Transform part, Transform parent, string name)
+ {
+ GameObject copy = Object.Instantiate(part.gameObject, parent, false);
+ copy.name = name;
+ copy.transform.localPosition = part.localPosition * SourceScale;
+ copy.transform.localScale = part.localScale * SourceScale;
+ foreach (Transform t in copy.GetComponentsInChildren(true)) t.gameObject.layer = parent.gameObject.layer;
+ return copy;
+ }
+
+ /// The cyan line on the lid: four thin strips just above it, inset from the edge. They
+ /// hang off the closed lid, so they go with it when the chest opens. The lid is scaled, so the
+ /// sizes are divided back out of it.
+ private static Renderer[] BuildInlay(Transform lid, Material panel)
+ {
+ Material cold = panel != null ? new Material(panel) { name = "AlfarInputChest_inlay" } : null;
+ if (cold != null)
+ {
+ cold.SetTexture("_MainTex", null);
+ cold.color = new Color(0.08f, 0.12f, 0.16f);
+ }
+
+ float k = 1f / lid.localScale.x;
+ float x = LidHalfX - InlayInset, z = LidHalfZ - InlayInset, y = LidTop + 0.004f;
+ var strips = new List();
+ foreach (float side in new[] { -z, z })
+ strips.Add(Strip(lid, new Vector3(0f, y, side) * k, new Vector3(2f * x + InlayWidth, 0.01f, InlayWidth) * k, cold));
+ foreach (float side in new[] { -x, x })
+ strips.Add(Strip(lid, new Vector3(side, y, 0f) * k, new Vector3(InlayWidth, 0.01f, 2f * z) * k, cold));
+ return strips.ToArray();
+ }
+
+ private static Renderer Strip(Transform lid, Vector3 position, Vector3 size, Material material)
+ {
+ return AlfarFireChest.Block(lid, "inlay", position, size, material).GetComponent();
+ }
+ }
+}
diff --git a/JotunnModStub/Alfar/AlfarLevitation.cs b/JotunnModStub/Alfar/AlfarLevitation.cs
index 77f6b9d..206c8c7 100644
--- a/JotunnModStub/Alfar/AlfarLevitation.cs
+++ b/JotunnModStub/Alfar/AlfarLevitation.cs
@@ -48,7 +48,7 @@ namespace RacesOfValheim
float target = 0f;
if (Time.time - AlfarArchon.StartedAt < 0.6f) target = 4f; // lift off
else if (RaceInput.Allowed && JumpHeld()) target = speed;
- else if (RaceInput.Allowed && ZInput.GetButton("Crouch")) target = -speed;
+ else if (RaceInput.Allowed && CrouchHeld()) target = -speed;
Vector3 velocity = flyer.linearVelocity;
velocity.y = Mathf.Lerp(velocity.y, target, 0.25f);
@@ -97,9 +97,15 @@ namespace RacesOfValheim
private static bool JumpHeld()
{
- // ZInput's "Jump" covers the space bar and the pad's jump button alike, and respects the
- // controls the player picked in the settings.
- return ZInput.GetButton("Jump");
+ // "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)
diff --git a/JotunnModStub/Alfar/AlfarMiners.cs b/JotunnModStub/Alfar/AlfarMiners.cs
index 59b3b22..b2c5a95 100644
--- a/JotunnModStub/Alfar/AlfarMiners.cs
+++ b/JotunnModStub/Alfar/AlfarMiners.cs
@@ -22,7 +22,11 @@ namespace RacesOfValheim
public static void Throw(Player player)
{
- if (Time.time < readyAt) return;
+ 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;
@@ -76,12 +80,7 @@ namespace RacesOfValheim
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity);
AlfarMiner miner = spawned.GetComponent();
- if (miner != null)
- {
- miner.Centre = point;
- miner.Radius = AlfarPowerConfig.GrafRadius.Value;
- miner.LiveSeconds = AlfarPowerConfig.GrafSeconds.Value;
- }
+ 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();
diff --git a/JotunnModStub/Alfar/AlfarNexus.cs b/JotunnModStub/Alfar/AlfarNexus.cs
index 8ba5ac9..26024f5 100644
--- a/JotunnModStub/Alfar/AlfarNexus.cs
+++ b/JotunnModStub/Alfar/AlfarNexus.cs
@@ -46,7 +46,9 @@ namespace RacesOfValheim
Object.DestroyImmediate(behaviour);
}
- AlfarConstructs.Tint(prefab, new Color(0.62f, 0.8f, 1f, 1f));
+ // The floating pyramid; the blue table stays as the fallback if it cannot be built.
+ bool pyramid = AlfarNexusLook.Build(prefab);
+ if (!pyramid) AlfarConstructs.Tint(prefab, new Color(0.62f, 0.8f, 1f, 1f));
AlfarNexusBehaviour nexus = prefab.AddComponent();
nexus.m_switch = prefab.AddComponent();
@@ -71,7 +73,7 @@ namespace RacesOfValheim
trader.m_randomUseItemAlreadyRecieved = new List();
trader.m_randomTalkConditionals = new List();
- Sprite icon = BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore");
+ Sprite icon = (pyramid ? AlfarChests.IconFrom("AlfarNexus_icon.png") : null) ?? BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore");
Piece piece = prefab.GetComponent() ?? prefab.AddComponent();
piece.m_craftingStation = null;
diff --git a/JotunnModStub/Alfar/AlfarNexusConfig.cs b/JotunnModStub/Alfar/AlfarNexusConfig.cs
index 59c4020..84ffd4c 100644
--- a/JotunnModStub/Alfar/AlfarNexusConfig.cs
+++ b/JotunnModStub/Alfar/AlfarNexusConfig.cs
@@ -89,8 +89,13 @@ namespace RacesOfValheim
DroneZapDamage = config.Bind(drone, "Zap Damage", 1f, new ConfigDescription("Lightning damage of a drone's defensive zap.", new AcceptableValueRange(0f, 100f)));
DroneZapInterval = config.Bind(drone, "Zap Interval", 2f, new ConfigDescription("Seconds between a drone's zaps.", new AcceptableValueRange(0.2f, 30f)));
- MinerDeposits = config.Bind(drone, "Mining Targets", "MineRock_Copper,MineRock_Tin,MineRock_Iron,silvervein,rock3_silver,giant_brain",
+ // Copper deposits are rock4_copper (and rock4_copper_frac once hit), crypt scrap is mudpile;
+ // the first default missed both, so a config still holding it is moved to the new one.
+ const string oldTargets = "MineRock_Copper,MineRock_Tin,MineRock_Iron,silvervein,rock3_silver,giant_brain";
+ const string targets = "rock4_copper,MineRock_Copper,MineRock_Tin,MineRock_Iron,mudpile,silvervein,rock3_silver,giant_brain";
+ MinerDeposits = config.Bind(drone, "Mining Targets", targets,
new ConfigDescription("Comma separated parts of prefab names the mining drones dig (case does not matter). Soft tissue comes from giant_brain."));
+ if (MinerDeposits.Value == oldTargets) MinerDeposits.Value = targets;
MinerDamage = config.Bind(drone, "Mining Damage", 40f, new ConfigDescription("Pickaxe damage each mining drone does per second to a deposit.", new AcceptableValueRange(1f, 1000f)));
WildPickables = config.Bind(drone, "Wild Plants Harvested", "Pickable_Mushroom,Pickable_Dandelion,Pickable_Thistle,RaspberryBush,BlueberryBush,CloudberryBush",
diff --git a/JotunnModStub/Alfar/AlfarNexusLook.cs b/JotunnModStub/Alfar/AlfarNexusLook.cs
new file mode 100644
index 0000000..34c1fe7
--- /dev/null
+++ b/JotunnModStub/Alfar/AlfarNexusLook.cs
@@ -0,0 +1,217 @@
+using Jotunn.Managers;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// The Ljoskjarne's body: a stone pyramid, 2 m to a side and 2 m tall, floating 0.8 m above the
+ /// ground. Dark steel carved with Valheim's own runes (the Ashlands rune tile's glyphs, laid out by
+ /// scripts/paint_nexus.py), and a cyan seam down the middle of each face.
+ ///
+ /// The seam is painted into the faces' glow map, not built. Bars standing on the faces, lit or
+ /// unlit, lost part of their length to the face on whichever side looked one way in the world,
+ /// as the pyramid turned; a line in the face's own pixels has nothing to hide behind.
+ ///
+ /// Only the look moves. The piece keeps one still collider from the ground up, so building on it,
+ /// support, hovering and the E key behave as before; the pyramid bobs and turns on each client by
+ /// itself, nothing over the network. The seam breathes, and burns brighter while crystals wait.
+ ///
+ public static class AlfarNexusLook
+ {
+ private const float Height = 2f;
+ private const float HalfBase = 1f;
+ private const float Lift = 0.8f;
+ private const string SourceMaterialPrefab = "piece_cartographytable";
+ private const string EmbersSource = "fx_Torch_Carried";
+
+ private static readonly Color Seam = new Color(0.35f, 0.75f, 1f);
+
+ /// Strips the cartography table's body and puts the pyramid in its place. False leaves
+ /// the table, with a warning, so the Nexus is never invisible.
+ public static bool Build(GameObject prefab)
+ {
+ Texture2D face = PieceLook.LoadTexture("AlfarNexus_face.png");
+ Texture2D glow = PieceLook.LoadTexture("AlfarNexus_glow.png");
+ Texture2D bumps = PieceLook.LoadTexture("AlfarNexus_n.png", true);
+ Renderer tableRenderer = prefab.transform.Find("new/high")?.GetComponent();
+ if (face == null || glow == null || tableRenderer == null || tableRenderer.sharedMaterial == null)
+ {
+ Jotunn.Logger.LogWarning("[Alfar] Could not build the Ljoskjarne's pyramid; it keeps the cartography table's look.");
+ return false;
+ }
+
+ Material stone = new Material(tableRenderer.sharedMaterial) { name = "AlfarNexus_stone" };
+ stone.color = Color.white;
+ stone.SetTexture("_MainTex", face);
+ // Forged, not polished: the plate's own grain in the normal map, and a dull sheen.
+ stone.SetTexture("_BumpMap", bumps);
+ if (bumps != null) stone.EnableKeyword("_NORMALMAP");
+ else stone.DisableKeyword("_NORMALMAP");
+ if (stone.HasProperty("_MetallicGlossMap")) stone.SetTexture("_MetallicGlossMap", null);
+ if (stone.HasProperty("_Metallic")) stone.SetFloat("_Metallic", 0.6f);
+ if (stone.HasProperty("_Glossiness")) stone.SetFloat("_Glossiness", 0.3f);
+ // Custom/Piece samples its noise in world space unless told the object moves, as boats and
+ // carts do; on a turning pyramid the blotches would slide across the faces.
+ stone.EnableKeyword("_MOVEABLEOBJECT_ON");
+ if (stone.HasProperty("_MoveableObject")) stone.SetFloat("_MoveableObject", 1f);
+ stone.SetTexture("_EmissionMap", glow);
+ stone.EnableKeyword("_EMISSION");
+ stone.SetColor("_EmissionColor", Seam);
+
+ // The table goes whole: its meshes, its damage states, its fragments and its four colliders.
+ for (int i = prefab.transform.childCount - 1; i >= 0; i--)
+ Object.DestroyImmediate(prefab.transform.GetChild(i).gameObject);
+ WearNTear wear = prefab.GetComponent();
+ if (wear != null)
+ {
+ wear.m_new = null;
+ wear.m_worn = null;
+ wear.m_broken = null;
+ wear.m_fragmentRoots = new GameObject[0];
+ }
+
+ // One still collider, from the ground to the tip, a little inside the faces.
+ GameObject solid = new GameObject("collider") { layer = prefab.layer };
+ solid.transform.SetParent(prefab.transform, false);
+ BoxCollider box = solid.AddComponent();
+ box.center = new Vector3(0f, (Lift + Height) / 2f, 0f);
+ box.size = new Vector3(HalfBase * 1.4f, Lift + Height, HalfBase * 1.4f);
+
+ Transform floating = new GameObject("float").transform;
+ floating.SetParent(prefab.transform, false);
+ floating.gameObject.layer = prefab.layer;
+
+ MeshRenderer pyramid = Part(floating, "pyramid", PyramidMesh(), stone).GetComponent();
+
+ NexusLook look = prefab.AddComponent();
+ look.Float = floating;
+ look.SeamRenderer = pyramid;
+ look.Motes = AddMotes(prefab.transform);
+ return true;
+ }
+
+ private static GameObject Part(Transform parent, string name, Mesh mesh, Material material)
+ {
+ GameObject part = new GameObject(name) { layer = parent.gameObject.layer };
+ part.transform.SetParent(parent, false);
+ part.AddComponent().sharedMesh = mesh;
+ part.AddComponent().sharedMaterial = material;
+ return part;
+ }
+
+ private static Vector3 Apex => new Vector3(0f, Lift + Height, 0f);
+
+ private static Vector3[] BaseCorners => new[]
+ {
+ new Vector3(-HalfBase, Lift, -HalfBase), new Vector3(HalfBase, Lift, -HalfBase),
+ new Vector3(HalfBase, Lift, HalfBase), new Vector3(-HalfBase, Lift, HalfBase),
+ };
+
+ /// Four faces, each with its own three corners so the shading stays flat and every face
+ /// shows the whole carving (u along the base, v = 1 at the tip), and the underside.
+ private static Mesh PyramidMesh()
+ {
+ Vector3[] c = BaseCorners;
+ var vertices = new Vector3[16];
+ var uvs = new Vector2[16];
+ var triangles = new int[18];
+ for (int i = 0; i < 4; i++)
+ {
+ // Wound clockwise seen from outside, which is Unity's front face.
+ vertices[i * 3] = c[(i + 1) % 4];
+ vertices[i * 3 + 1] = c[i];
+ vertices[i * 3 + 2] = Apex;
+ uvs[i * 3] = new Vector2(1f, 0f);
+ uvs[i * 3 + 1] = new Vector2(0f, 0f);
+ uvs[i * 3 + 2] = new Vector2(0.5f, 1f);
+ triangles[i * 3] = i * 3;
+ triangles[i * 3 + 1] = i * 3 + 1;
+ triangles[i * 3 + 2] = i * 3 + 2;
+ }
+ for (int i = 0; i < 4; i++) { vertices[12 + i] = c[i]; uvs[12 + i] = new Vector2(0.1f, 0.02f); }
+ int[] under = { 12, 13, 14, 12, 14, 15 };
+ System.Array.Copy(under, 0, triangles, 12, 6);
+
+ Mesh mesh = new Mesh { name = "AlfarNexus_pyramid", vertices = vertices, uv = uvs, triangles = triangles };
+ mesh.RecalculateNormals();
+ mesh.RecalculateBounds();
+ return mesh;
+ }
+
+ /// A few cyan motes drifting up from the ground under it: the torch's embers, recoloured,
+ /// spread over the pyramid's shadow and slowed down.
+ private static ParticleSystem AddMotes(Transform root)
+ {
+ GameObject torch = PrefabManager.Cache.GetPrefab(EmbersSource);
+ Transform source = torch != null ? torch.transform.Find("Embers") : null;
+ if (source == null) return null;
+
+ GameObject motes = Object.Instantiate(source.gameObject, root, false);
+ motes.name = "motes";
+ motes.transform.localPosition = new Vector3(0f, 0.05f, 0f);
+ motes.transform.localRotation = Quaternion.identity;
+ PieceLook.Rehue(motes.transform, Seam * 2f);
+
+ ParticleSystem particles = motes.GetComponent();
+ if (particles != null)
+ {
+ ParticleSystem.ShapeModule shape = particles.shape;
+ shape.enabled = true;
+ shape.shapeType = ParticleSystemShapeType.Circle;
+ shape.radius = HalfBase;
+ shape.rotation = new Vector3(-90f, 0f, 0f);
+ ParticleSystem.MainModule main = particles.main;
+ main.simulationSpeed = 0.5f;
+ }
+ return particles;
+ }
+
+ /// The motion and the seam's light, per client.
+ public class NexusLook : MonoBehaviour
+ {
+ public Transform Float;
+ public Renderer SeamRenderer;
+ public ParticleSystem Motes;
+
+ private const float BobHeight = 0.08f;
+ private const float BobSeconds = 4.5f;
+ private const float TurnSeconds = 40f;
+ private const float BreathSeconds = 3.5f;
+
+ private AlfarNexusBehaviour m_nexus;
+ private Material m_seam;
+ private float m_phase;
+ private float m_ready; // eases between 0 (no crystals) and 1, so the brightening is not a jump
+
+ private void Awake()
+ {
+ m_nexus = GetComponent();
+ if (SeamRenderer != null) m_seam = SeamRenderer.material; // this one's own copy, to animate
+ // Two Nexuses side by side must not bob in step.
+ m_phase = (Mathf.Abs(transform.position.x * 0.37f + transform.position.z * 0.71f)) % 10f;
+ }
+
+ private void Update()
+ {
+ float t = Time.time + m_phase;
+ if (Float != null)
+ {
+ Float.localPosition = new Vector3(0f, Mathf.Sin(t * 2f * Mathf.PI / BobSeconds) * BobHeight, 0f);
+ Float.localRotation = Quaternion.Euler(0f, t * 360f / TurnSeconds, 0f);
+ }
+
+ if (m_seam == null) return;
+ bool ready = m_nexus != null && m_nexus.Crystals > 0;
+ m_ready = Mathf.MoveTowards(m_ready, ready ? 1f : 0f, Time.deltaTime * 0.5f);
+ float breath = 0.75f + 0.25f * Mathf.Sin(t * 2f * Mathf.PI / BreathSeconds);
+ Color glow = Seam * breath * Mathf.Lerp(1f, 2.2f, m_ready);
+ m_seam.SetColor("_EmissionColor", glow);
+ }
+
+ private void OnDestroy()
+ {
+ if (m_seam != null) Destroy(m_seam);
+ }
+ }
+ }
+}
diff --git a/JotunnModStub/Alfar/AlfarPatches.cs b/JotunnModStub/Alfar/AlfarPatches.cs
index 5d5e5ea..73864de 100644
--- a/JotunnModStub/Alfar/AlfarPatches.cs
+++ b/JotunnModStub/Alfar/AlfarPatches.cs
@@ -38,6 +38,37 @@ namespace RacesOfValheim
}
}
+ ///
+ /// 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.
+ ///
+ [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();
+ return player != null && AlfarVisuals.IsAlfarPlayer(player);
+ }
+
///
/// 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,
diff --git a/JotunnModStub/Alfar/AlfarPowers.cs b/JotunnModStub/Alfar/AlfarPowers.cs
index dc7c52b..8a02b61 100644
--- a/JotunnModStub/Alfar/AlfarPowers.cs
+++ b/JotunnModStub/Alfar/AlfarPowers.cs
@@ -148,12 +148,17 @@ namespace RacesOfValheim
}
/// A pulse of lightning on every hostile creature within a radius of the Alfr.
- public static void Pulse(Player player, float radius, float damage)
+ /// True if it struck at least one creature.
+ 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)) Strike(player, character, damage, character.GetCenterPoint());
+ if (!IsHostile(player, character)) continue;
+ Strike(player, character, damage, character.GetCenterPoint());
+ struck = true;
}
+ return struck;
}
private static IEnumerable CharactersIn(Vector3 center, float radius)
@@ -177,35 +182,64 @@ namespace RacesOfValheim
Vector3 direction = aim.forward;
float distance = AlfarPowerConfig.SkridDistance.Value;
- if (!Pay(player, AlfarPowerConfig.SkridCost.Value)) return;
-
// Stop short of whatever is in the way, so the blink never ends inside a wall.
Vector3 destination = origin + direction * distance;
- RaycastHit[] hits = Physics.RaycastAll(origin, direction, distance, ~0, QueryTriggerInteraction.Ignore);
- float nearest = float.MaxValue;
- foreach (RaycastHit hit in hits)
+ if (NearestHit(player, origin, direction, distance, out RaycastHit wall))
{
- if (hit.collider.GetComponentInParent() == player) continue;
- if (hit.distance < nearest)
+ 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)
{
- nearest = hit.distance;
- destination = hit.point - direction * 0.6f;
+ // 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;
}
}
- // Back down to the player's own height: the origin was at the chest.
- destination.y -= 1.0f;
- if (ZoneSystem.instance != null)
- {
- float ground = ZoneSystem.instance.GetSolidHeight(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);
}
+ /// The nearest solid hit along a ray, skipping the caster's own colliders.
+ 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) continue;
+ if (!found || hit.distance < nearest.distance)
+ {
+ nearest = hit;
+ found = true;
+ }
+ }
+ return found;
+ }
+
///
/// 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.
@@ -305,6 +339,34 @@ namespace RacesOfValheim
// ─── Geisli: the beam ────────────────────────────────────────────────
+ ///
+ /// 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.
+ ///
+ private static bool PadBeamHeld(Player player) =>
+ !RaceInput.RadialOpen && RaceInput.PadAttackHeld(2) &&
+ (AlfarArchon.Active || RaceInput.EmptyHanded(player));
+
+ ///
+ /// Swallows the unarmed secondary (the kick) while the pad's secondary attack is the beam,
+ /// the same way SkadiAttackPatch does for the Cold Spell.
+ ///
+ [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 beamArcs = new List();
private static GameObject beamFx;
@@ -324,7 +386,7 @@ namespace RacesOfValheim
private static void TickBeam(Player player)
{
bool wanted = RaceInput.Allowed && !player.IsDead() && Unlocked(AlfarPowerConfig.GeisliState) &&
- AlfarPowerConfig.GeisliKey.Value.IsPressedIgnoringHeldKeys();
+ (AlfarPowerConfig.GeisliKey.Value.IsPressedIgnoringHeldKeys() || PadBeamHeld(player));
if (!wanted)
{
@@ -368,7 +430,11 @@ namespace RacesOfValheim
AlfarEitr.Spend(player, cost);
}
- if (IsHostile(player, target)) Strike(player, target, AlfarPowerConfig.BeamDps.Value * tick, end);
+ 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)
@@ -520,14 +586,19 @@ namespace RacesOfValheim
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();
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));
}
diff --git a/JotunnModStub/Alfar/AlfarVisuals.cs b/JotunnModStub/Alfar/AlfarVisuals.cs
index 51d4cd1..aa6df6e 100644
--- a/JotunnModStub/Alfar/AlfarVisuals.cs
+++ b/JotunnModStub/Alfar/AlfarVisuals.cs
@@ -161,35 +161,67 @@ namespace RacesOfValheim
}
if (eyes == null) return;
- PlaceEyes(headBone, eyes);
+ PlaceEyes(player, eyes);
}
- private static void PlaceEyes(Transform headBone, Transform holder)
+ ///
+ /// 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.
+ ///
+ private static void PlaceEyes(Player player, Transform holder)
{
- Vector3 lossy = headBone.lossyScale;
- if (Mathf.Abs(lossy.x) < 0.0001f || Mathf.Abs(lossy.y) < 0.0001f || Mathf.Abs(lossy.z) < 0.0001f) return;
-
EyeFrame frame = holder.GetComponent();
if (frame == null) return;
- // The Visual is scaled non-uniformly (thinner than tall), so lossyScale has three
- // different components and a single divisor would squash the spheres. Each axis is
- // divided by its own.
- Vector3 toLocal = new Vector3(1f / lossy.x, 1f / lossy.y, 1f / lossy.z);
- float eyeSize = AlfarConfig.EyeSize * AlfarConfig.EyeSizeMultiplier.Value;
+ const float toLocal = PlayerFace.MetresToHeadLocal;
- Vector3 baseOffset = frame.LocalForward * AlfarConfig.EyeForward + frame.LocalUp * AlfarConfig.EyeHeight;
+ 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.
+ // 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;
- Vector3 offset = baseOffset + frame.LocalRight * (side * AlfarConfig.EyeSeparation);
- eye.localPosition = Vector3.Scale(offset, toLocal);
- eye.localScale = Vector3.Scale(Vector3.one * eyeSize, toLocal);
+ // 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);
}
}
@@ -234,9 +266,8 @@ namespace RacesOfValheim
}
///
- /// Matte black, and nothing else: the colour is black, the emission is black, and the two
- /// properties that make a lit shader shine are zeroed where the shader has them. The
- /// Sverm's eyes burn; these must read as holes.
+ /// 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.
///
private static Material BlackMaterial(Shader shader)
{
@@ -244,10 +275,9 @@ namespace RacesOfValheim
material.color = Color.black;
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Color.black);
- if (material.HasProperty("_Glossiness")) material.SetFloat("_Glossiness", 0f);
- if (material.HasProperty("_Smoothness")) material.SetFloat("_Smoothness", 0f);
+ 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);
- if (material.HasProperty("_SpecColor")) material.SetColor("_SpecColor", Color.black);
return material;
}
diff --git a/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_d.png b/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_d.png
new file mode 100644
index 0000000..6f380b1
Binary files /dev/null and b/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_d.png differ
diff --git a/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_icon.png b/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_icon.png
new file mode 100644
index 0000000..8a4077f
Binary files /dev/null and b/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_icon.png differ
diff --git a/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_d.png b/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_d.png
new file mode 100644
index 0000000..6ede24f
Binary files /dev/null and b/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_d.png differ
diff --git a/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_icon.png b/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_icon.png
new file mode 100644
index 0000000..761ff83
Binary files /dev/null and b/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_icon.png differ
diff --git a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_face.png b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_face.png
new file mode 100644
index 0000000..2dff3cb
Binary files /dev/null and b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_face.png differ
diff --git a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_glow.png b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_glow.png
new file mode 100644
index 0000000..d88a980
Binary files /dev/null and b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_glow.png differ
diff --git a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_icon.png b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_icon.png
new file mode 100644
index 0000000..a85c891
Binary files /dev/null and b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_icon.png differ
diff --git a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_n.png b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_n.png
new file mode 100644
index 0000000..1940c2a
Binary files /dev/null and b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_n.png differ
diff --git a/JotunnModStub/Assets/CookCloth/CookCloth_d.png b/JotunnModStub/Assets/CookCloth/CookCloth_d.png
new file mode 100644
index 0000000..905ec99
Binary files /dev/null and b/JotunnModStub/Assets/CookCloth/CookCloth_d.png differ
diff --git a/JotunnModStub/Assets/CookCloth/CookCloth_n.png b/JotunnModStub/Assets/CookCloth/CookCloth_n.png
new file mode 100644
index 0000000..7603df9
Binary files /dev/null and b/JotunnModStub/Assets/CookCloth/CookCloth_n.png differ
diff --git a/JotunnModStub/Assets/CookCloth/CookCloth_worn_d.png b/JotunnModStub/Assets/CookCloth/CookCloth_worn_d.png
new file mode 100644
index 0000000..d36ee7c
Binary files /dev/null and b/JotunnModStub/Assets/CookCloth/CookCloth_worn_d.png differ
diff --git a/JotunnModStub/Assets/Hammers/ShrinkHammer_icon.png b/JotunnModStub/Assets/Hammers/ShrinkHammer_icon.png
new file mode 100644
index 0000000..a7328f5
Binary files /dev/null and b/JotunnModStub/Assets/Hammers/ShrinkHammer_icon.png differ
diff --git a/JotunnModStub/Assets/Hammers/TrolsHammer_icon.png b/JotunnModStub/Assets/Hammers/TrolsHammer_icon.png
new file mode 100644
index 0000000..99e1761
Binary files /dev/null and b/JotunnModStub/Assets/Hammers/TrolsHammer_icon.png differ
diff --git a/JotunnModStub/Assets/SmithMail/SmithMail_d.png b/JotunnModStub/Assets/SmithMail/SmithMail_d.png
new file mode 100644
index 0000000..5ecb47d
Binary files /dev/null and b/JotunnModStub/Assets/SmithMail/SmithMail_d.png differ
diff --git a/JotunnModStub/Assets/SmithMail/SmithMail_m.png b/JotunnModStub/Assets/SmithMail/SmithMail_m.png
new file mode 100644
index 0000000..0227d0f
Binary files /dev/null and b/JotunnModStub/Assets/SmithMail/SmithMail_m.png differ
diff --git a/JotunnModStub/Assets/SmithMail/SmithMail_n.png b/JotunnModStub/Assets/SmithMail/SmithMail_n.png
new file mode 100644
index 0000000..9198ee1
Binary files /dev/null and b/JotunnModStub/Assets/SmithMail/SmithMail_n.png differ
diff --git a/JotunnModStub/Assets/SmithMail/SmithMail_worn_d.png b/JotunnModStub/Assets/SmithMail/SmithMail_worn_d.png
new file mode 100644
index 0000000..a90bd1c
Binary files /dev/null and b/JotunnModStub/Assets/SmithMail/SmithMail_worn_d.png differ
diff --git a/JotunnModStub/Aswid/AswidBatForm.cs b/JotunnModStub/Aswid/AswidBatForm.cs
index dcf985b..2ac80c7 100644
--- a/JotunnModStub/Aswid/AswidBatForm.cs
+++ b/JotunnModStub/Aswid/AswidBatForm.cs
@@ -6,11 +6,22 @@ namespace RacesOfValheim
///
/// Whether a player is a bat, on any client.
///
- /// This file used to be AswidBatAggro: while the bat flew on vanilla's debug-fly flag, vanilla
- /// read that flag as "this player is not really here" - no monster could see, hear or wake for
- /// it, and every hit on it was dropped - and six patches here lied about the flag in exactly
- /// those places. The bat now flies on m_flying (DirectedFlight.cs), which vanilla's AI and
- /// damage never look at, so monsters notice and hurt it with no help, and the lie went.
+ /// 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.
///
public static class AswidBatForm
{
@@ -22,6 +33,14 @@ namespace RacesOfValheim
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--; }
+
///
/// 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
@@ -40,6 +59,98 @@ namespace RacesOfValheim
}
}
+ /// Free Flight: monsters see and hear a bat. See AswidBatForm for why this one is safe flat.
+ [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;
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ [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;
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ [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();
+ }
+ }
+
+ /// The networked half of the same thing: a hit sent by another machine.
+ [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();
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ [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;
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ [HarmonyPatch(typeof(MonsterAI), "UpdateSleep")]
+ public static class Aswid_BatWakesSleepers_Patch
+ {
+ public static void Prefix() { AswidBatForm.PushUnmask(); }
+ public static void Finalizer() { AswidBatForm.PopUnmask(); }
+ }
+
///
/// 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
diff --git a/JotunnModStub/Aswid/AswidBloodRefinery.cs b/JotunnModStub/Aswid/AswidBloodRefinery.cs
index c119d53..a127b5a 100644
--- a/JotunnModStub/Aswid/AswidBloodRefinery.cs
+++ b/JotunnModStub/Aswid/AswidBloodRefinery.cs
@@ -338,8 +338,6 @@ namespace RacesOfValheim
// The raw -> cooked table the Draugh already maintains is the source of truth.
meatToCooked = new Dictionary(DraughFoodPatches.rawToCookedMapping);
meatToCooked.Remove("GreydwarfEye"); // stew ingredient, not flesh
- meatToCooked["AsksvinMeat"] = "CookedAsksvinMeat";
- meatToCooked["BoneMawSerpentMeat"] = "CookedBoneMawSerpentMeat";
foreach (string stationName in CookingStationPrefabs)
{
diff --git a/JotunnModStub/Aswid/AswidConfig.cs b/JotunnModStub/Aswid/AswidConfig.cs
index 1cf197b..57bc11a 100644
--- a/JotunnModStub/Aswid/AswidConfig.cs
+++ b/JotunnModStub/Aswid/AswidConfig.cs
@@ -74,8 +74,24 @@ namespace RacesOfValheim
// 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. None of that is left.
+ // 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 FreeBatFlight;
+ public static ConfigEntry BatFlightRule;
+
+ /// Which flight a bat taken now gets: the server's rule first, then the player's own pick.
+ public static bool UsesFreeBatFlight()
+ {
+ switch (BatFlightRule.Value)
+ {
+ case BatFlightRuleMode.AlwaysStaminaFlight: return false;
+ case BatFlightRuleMode.AlwaysFreeFlight: return true;
+ default: return FreeBatFlight.Value;
+ }
+ }
public static ConfigEntry BatTurnSpeed;
public static ConfigEntry BatGlideSpeed;
@@ -91,6 +107,7 @@ namespace RacesOfValheim
public static ConfigEntry BatMaxDuration;
public static ConfigEntry BatDurationPerState;
public static ConfigEntry BatCooldown;
+ public static ConfigEntry BatCombatLock;
// ─── Vampiric Aura (passive, always active) ──────────────────────────────
public static ConfigEntry AuraTickInterval;
@@ -240,6 +257,10 @@ namespace RacesOfValheim
new ConfigDescription("How far the camera rolls. 1 is about 4 degrees. Local.", new AcceptableValueRange(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,
@@ -272,6 +293,8 @@ namespace RacesOfValheim
new ConfigDescription("Seconds added to the max duration per progression state. Does nothing while the max duration is 0.", new AcceptableValueRange(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(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(0f, 30f)));
const string aura = "Aswid - Vampiric Aura";
AuraTickInterval = config.Bind(aura, "Tick Interval", 0.25f,
@@ -453,7 +476,7 @@ namespace RacesOfValheim
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(-180f, 180f), new ConfigurationManagerAttributes { Order = 58 }));
- EyeSmoke = config.Bind(eyes, "Eye Smoke", true,
+ 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,
diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs
index b799936..b607ad9 100644
--- a/JotunnModStub/Aswid/AswidPatches.cs
+++ b/JotunnModStub/Aswid/AswidPatches.cs
@@ -931,6 +931,30 @@ namespace RacesOfValheim
}
}
+ ///
+ /// 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.
+ ///
+ [HarmonyPatch(typeof(Player), "RemoveOneFood")]
+ public static class Aswid_PlayerRemoveOneFood_Patch
+ {
+ public static bool Prefix(Player __instance, System.Collections.Generic.List ___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;
+ }
+ }
+
[HarmonyPatch(typeof(Player), "ClearFood")]
public static class Aswid_Player_ClearFood_Patch
{
diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs
index 24ae745..8367a64 100644
--- a/JotunnModStub/Aswid/AswidRace.cs
+++ b/JotunnModStub/Aswid/AswidRace.cs
@@ -329,9 +329,6 @@ namespace RacesOfValheim
}
private float m_tintCheckTimer = 0f;
- private float sensesCheckTimer = 0f;
-
- private Dictionary activeSensesLight = new Dictionary();
public static float GetEnslaveCooldown()
{
@@ -373,6 +370,7 @@ namespace RacesOfValheim
{
seman.RemoveStatusEffect(myHash);
}
+ HunterSenses.Clear();
return;
}
@@ -381,64 +379,8 @@ namespace RacesOfValheim
seman.AddStatusEffect(myHash, true);
}
- sensesCheckTimer -= Time.deltaTime;
- if (sensesCheckTimer <= 0f)
- {
- sensesCheckTimer = AswidConfig.SensesRefreshInterval.Value; // TTL is 2s
-
- List allChars = Character.GetAllCharacters();
- Vector3 myPos = Player.m_localPlayer.transform.position;
-
- int markHash = "SE_AswidSensesMark".GetStableHashCode();
- HashSet inRangeChars = new HashSet();
-
- foreach (var c in allChars)
- {
- if (c == null || c == Player.m_localPlayer || c.IsDead() || c.IsTamed()) continue;
-
- float dist = Vector3.Distance(c.transform.position, myPos);
- if (dist <= AswidConfig.SensesRadius.Value)
- {
- try
- {
- inRangeChars.Add(c);
- c.GetSEMan().AddStatusEffect(markHash, true); // Keep the malus as requested
-
- // Locally generate the visual
- if (!activeSensesLight.ContainsKey(c))
- {
- GameObject lightObj = new GameObject("AswidSensesLight");
- lightObj.transform.SetParent(c.transform);
- lightObj.transform.position = c.GetCenterPoint();
-
- Light pLight = lightObj.AddComponent();
- pLight.type = LightType.Point;
- pLight.color = Color.green;
- pLight.range = AswidConfig.SensesLightRange.Value;
- pLight.intensity = AswidConfig.SensesLightIntensity.Value;
- pLight.shadows = LightShadows.None;
-
- activeSensesLight[c] = lightObj;
- }
- }
- catch (Exception ex)
- {
- Jotunn.Logger.LogError($"[Aswid] Error processing mob {c.name}: {ex}");
- }
- }
- }
-
- List keysToRemove = new List();
- foreach (var kvp in activeSensesLight)
- {
- if (kvp.Key == null || kvp.Key.IsDead() || !inRangeChars.Contains(kvp.Key))
- {
- if (kvp.Value != null) Destroy(kvp.Value);
- keysToRemove.Add(kvp.Key);
- }
- }
- foreach (var k in keysToRemove) activeSensesLight.Remove(k);
- }
+ int markHash = "SE_AswidSensesMark".GetStableHashCode();
+ HunterSenses.Tick(AswidConfig.SensesRadius.Value, c => c.GetSEMan().AddStatusEffect(markHash, true));
}
catch (Exception ex)
{
@@ -446,15 +388,6 @@ namespace RacesOfValheim
}
}
- private void ClearSuperhumanSenses()
- {
- foreach (var kvp in activeSensesLight)
- {
- if (kvp.Value != null) Destroy(kvp.Value);
- }
- activeSensesLight.Clear();
- }
-
private bool? wasNight = null;
private void Update()
@@ -682,6 +615,14 @@ namespace RacesOfValheim
return;
}
+ // No escaping a fight by taking wing mid-blow: the form waits until the hits stop.
+ float hurtLeft = AswidConfig.BatCombatLock.Value - (Time.time - LastHurtTime);
+ if (hurtLeft > 0f)
+ {
+ Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_combat_lock", Mathf.CeilToInt(hurtLeft)));
+ return;
+ }
+
float cooldownLeft = AswidConfig.BatCooldown.Value - (Time.time - lastBatEndTime);
if (cooldownLeft > 0f)
{
@@ -696,6 +637,10 @@ namespace RacesOfValheim
// fresh session never begins on cooldown.
private float lastBatEndTime = -100000f;
+ // When the local player last lost health, for the bat's combat lock. Written by
+ // Aswid_BatCombatLock_Patch for every race; only the Aswid reads it.
+ public static float LastHurtTime = -100000f;
+
// The one bat or mist routine in flight, if any. Kept so ResetRace can stop it: a
// TransformIntoBatRoutine left running through a reset finishes its 1.1s gesture and
// turns a freshly reset Human into a bat.
@@ -1246,6 +1191,7 @@ namespace RacesOfValheim
int layerMask = LayerMask.GetMask("character", "character_net", "character_ghost");
var colliders = Physics.OverlapSphere(center, radius, layerMask);
+ bool hitCreature = false;
foreach (var col in colliders)
{
@@ -1296,10 +1242,16 @@ namespace RacesOfValheim
// kill). ApplyDamage() skipped all of that: it edited the local copy of a
// character we usually do not own, and the owner overwrote it on the next sync.
c.Damage(hd);
+ hitCreature = true;
SpawnBloodVFX(c);
}
}
+
+ // The aura scales with Blood Magic but called Damage directly, so it never paid
+ // the skill back. Passive and always on, so it earns what the Skadi's Frost Aura
+ // does: a tenth of a hit per second of draining, once per tick, not per victim.
+ if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.BloodMagic, 0.1f * AswidConfig.AuraTickInterval.Value);
}
catch (Exception ex)
{
diff --git a/JotunnModStub/Aswid/AswidVisuals.cs b/JotunnModStub/Aswid/AswidVisuals.cs
index b118424..c0822ad 100644
--- a/JotunnModStub/Aswid/AswidVisuals.cs
+++ b/JotunnModStub/Aswid/AswidVisuals.cs
@@ -58,6 +58,12 @@ namespace RacesOfValheim
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 ─────────────────────────────────────────────────────
///
@@ -99,6 +105,10 @@ namespace RacesOfValheim
// 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;
}
/// The pose an eye was authored at on the creature. Everything else is a delta on this.
@@ -180,7 +190,8 @@ namespace RacesOfValheim
EyeFrame existing = eyes.GetComponent();
if (existing == null ||
existing.SourceModel != AswidConfig.EyeSourceModel.Value ||
- existing.FlatShader != AswidConfig.EyeFlatColorShader.Value)
+ existing.FlatShader != AswidConfig.EyeFlatColorShader.Value ||
+ existing.Female != PlayerFace.IsFemale(player))
{
eyes.name = EyesName + "_Removed";
Object.Destroy(eyes.gameObject);
@@ -309,9 +320,6 @@ namespace RacesOfValheim
float scale = GetPlayerScale(player) * toLocal;
- Vector3 shift = frame.LocalForward * (AswidConfig.EyeForwardOffset.Value * scale)
- + frame.LocalUp * (AswidConfig.EyeHeightOffset.Value * scale);
-
for (int i = 0; i < holder.childCount; i++)
{
Transform eye = holder.GetChild(i);
@@ -324,6 +332,16 @@ namespace RacesOfValheim
float side = Mathf.Sign(Vector3.Dot(authored.Position, frame.LocalRight));
if (side == 0f) side = i == 0 ? -1f : 1f;
+ // 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
@@ -332,15 +350,31 @@ namespace RacesOfValheim
//
// 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 * AswidConfig.EyeSeparationOffset.Value * scale);
- eye.localRotation = twist * authored.Rotation;
- eye.localScale = authored.Scale * AswidConfig.EyeSizeMultiplier.Value;
+ frame.LocalRight * (side * separation * scale);
+ eye.localRotation = nudge * twist * authored.Rotation;
+ eye.localScale = authored.Scale * size;
}
}
@@ -424,6 +458,12 @@ namespace RacesOfValheim
MeasureFrame(player, headBone, frame);
frame.SourceModel = modelName;
frame.FlatShader = AswidConfig.EyeFlatColorShader.Value;
+ frame.Female = PlayerFace.IsFemale(player);
+
+ 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
@@ -458,8 +498,8 @@ namespace RacesOfValheim
float toLocal = 1f / headBone.lossyScale.x;
Vector3 basePosition = frame.LocalForward * (BaseEyeForward * toLocal)
- + frame.LocalUp * (BaseEyeHeight * toLocal)
- + frame.LocalRight * (side * BaseEyeSeparation * 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
@@ -481,7 +521,7 @@ namespace RacesOfValheim
// 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;
+ Vector3 baseScale = source.lossyScale * (toLocal * baseSize);
// Remembered before anything moves it, because everything the config does is
// expressed as a delta on this.
diff --git a/JotunnModStub/Aswid/BatFormBehavior.cs b/JotunnModStub/Aswid/BatFormBehavior.cs
index 75646d6..e712fec 100644
--- a/JotunnModStub/Aswid/BatFormBehavior.cs
+++ b/JotunnModStub/Aswid/BatFormBehavior.cs
@@ -14,17 +14,25 @@ namespace RacesOfValheim
///
/// 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.
///
public class BatFormBehavior : MonoBehaviour, IDirectedFlyer
{
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)
{
@@ -73,8 +81,9 @@ namespace RacesOfValheim
anim = GetComponentInChildren();
startTime = Time.time;
LastPoweredTime = Time.time;
- DirectedFlight.Register(this);
- SetFlying(true);
+ free = AswidConfig.UsesFreeBatFlight();
+ if (!free) DirectedFlight.Register(this);
+ Hold();
}
private void Update()
@@ -85,16 +94,20 @@ namespace RacesOfValheim
// 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.
- SetFlying(true);
+ Hold();
- if (!CanPower && !warnedTooHeavy)
+ // Free Flight ignores weight, so only Stamina Flight warns about it.
+ if (!free)
{
- warnedTooHeavy = true;
- player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_too_heavy_to_beat"));
- }
- else if (CanPower)
- {
- warnedTooHeavy = false;
+ 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();
@@ -120,15 +133,37 @@ namespace RacesOfValheim
SetFlying(false);
}
+ private void Hold()
+ {
+ if (free) SetDebugFly(true);
+ else SetFlying(true);
+ }
+
///
- /// The local half of flight. The remote half is the Aswid_IsBatForm ZDO flag AswidRace
- /// already writes, so there is nothing to replicate here.
+ /// 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.
///
public static void SetFlying(bool flying)
{
Player player = Player.m_localPlayer;
- if (player == null || FlyingField == null) return;
- FlyingField.SetValue(player, flying);
+ if (player == null) return;
+ if (FlyingField != null) FlyingField.SetValue(player, flying);
+ if (!flying) SetDebugFly(false);
+ }
+
+ ///
+ /// 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.
+ ///
+ 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();
+ if (nview != null && nview.IsValid() && nview.IsOwner()) nview.GetZDO().Set(ZDOVars.s_debugFly, flying);
}
}
}
diff --git a/JotunnModStub/Audio/trolsbuilding.ogg b/JotunnModStub/Audio/trolsbuilding.ogg
new file mode 100644
index 0000000..697f323
Binary files /dev/null and b/JotunnModStub/Audio/trolsbuilding.ogg differ
diff --git a/JotunnModStub/Audio/trolsdeath.ogg b/JotunnModStub/Audio/trolsdeath.ogg
new file mode 100644
index 0000000..9f5ea11
Binary files /dev/null and b/JotunnModStub/Audio/trolsdeath.ogg differ
diff --git a/JotunnModStub/Butler/BoneServant.cs b/JotunnModStub/Butler/BoneServant.cs
index 714016f..59ef5d7 100644
--- a/JotunnModStub/Butler/BoneServant.cs
+++ b/JotunnModStub/Butler/BoneServant.cs
@@ -218,6 +218,7 @@ namespace RacesOfValheim
}
prefab.transform.localScale = Vector3.one * TableScale;
+ Dress(prefab, family);
ServantTableBehaviour table = prefab.AddComponent();
table.m_switch = prefab.AddComponent();
@@ -255,6 +256,65 @@ namespace RacesOfValheim
}));
}
+ // 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;
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ private static void LayCover(GameObject prefab, string set, bool metal)
+ {
+ var cover = new System.Collections.Generic.Dictionary();
+ 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 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;
diff --git a/JotunnModStub/Butler/BoneServantAI.cs b/JotunnModStub/Butler/BoneServantAI.cs
index db77b6d..2c165db 100644
--- a/JotunnModStub/Butler/BoneServantAI.cs
+++ b/JotunnModStub/Butler/BoneServantAI.cs
@@ -270,7 +270,11 @@ namespace RacesOfValheim
else if (Time.time >= m_nextFightScan)
{
m_nextFightScan = Time.time + FightScanInterval;
- if (BaseAI.FindClosestEnemy(m_character, transform.position, FightRange) != null)
+ // FindClosestEnemy takes its first match at ANY distance (it only compares against
+ // maxDistance once it holds one), so with a deer anywhere in the loaded zones it never
+ // returned null and vanilla kept the tick: the worker idled about instead of working.
+ Character enemy = BaseAI.FindClosestEnemy(m_character, transform.position, FightRange);
+ if (enemy != null && Vector3.Distance(enemy.transform.position, transform.position) <= FightRange)
{
m_fightUntil = Time.time + FightLinger;
}
@@ -359,8 +363,22 @@ namespace RacesOfValheim
Scan(anchor.Value);
ExpirePenalties();
- if (m_payload.Count > 0) { m_job = PlanDelivery(anchor.Value); return; }
+ // A delivery gets its own clock like any other job. Returning early here left it with the
+ // load's deadline: a slow trip, or a fight on the way, made it late before it started, and
+ // it timed out and was planned again on every tick, frozen with the goods in hand.
+ Job job;
+ if (m_payload.Count > 0) job = PlanDelivery(anchor.Value);
+ else job = PlanWork();
+ if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target))
+ {
+ m_jobDeadline = Time.time + JobTimeout;
+ }
+ m_job = job;
+ }
+
+ private Job PlanWork()
+ {
// The forge has no clock: a smelter holds its ore indefinitely and puts its own output on
// the floor, so PlanRescue would ask a question whose answer is always no. The smith is a
// four-state machine and the cook is a five-state one, and that is the whole of the
@@ -372,13 +390,7 @@ namespace RacesOfValheim
// in return, because FuelWanted is zero for a station with no work: an empty furnace asks
// for no coal, gets filled, and only then becomes worth stoking.
Job job = m_family == ButlerFamily.Kitchen ? PlanRescue() : null;
- job = job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad();
-
- if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target))
- {
- m_jobDeadline = Time.time + JobTimeout;
- }
- m_job = job;
+ return job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad();
}
///
@@ -630,8 +642,10 @@ namespace RacesOfValheim
// coal, so gating the delivery on free slots sent the servant back to the chest with
// the coal it had just fetched - and then PlanFuel sent it out for the same coal again,
// forever. AcceptsAnything already asks the right question of both doors.
+ // A station it could not reach is in the penalty box: asking it again straight away
+ // is the same failed trip.
ButlerStation station = StationById(target);
- if (station != null && station.Alive && station.Operable && AcceptsAnything(station))
+ if (station != null && station.Alive && station.Operable && AcceptsAnything(station) && !IsPenalised(target))
{
return new Job
{
diff --git a/JotunnModStub/Butler/ServantTableBehaviour.cs b/JotunnModStub/Butler/ServantTableBehaviour.cs
index e4964e6..44346b0 100644
--- a/JotunnModStub/Butler/ServantTableBehaviour.cs
+++ b/JotunnModStub/Butler/ServantTableBehaviour.cs
@@ -143,7 +143,8 @@ namespace RacesOfValheim
string status = servant.Status;
if (string.IsNullOrEmpty(status)) status = ModText.Get("rov_hover_butler_waiting");
- return m_title + "\n" + status;
+ // 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;
}
///
diff --git a/JotunnModStub/ConfigSync.cs b/JotunnModStub/ConfigSync.cs
index abbad38..fbf16b6 100644
--- a/JotunnModStub/ConfigSync.cs
+++ b/JotunnModStub/ConfigSync.cs
@@ -31,6 +31,8 @@ namespace RacesOfValheim
"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",
@@ -47,6 +49,8 @@ namespace RacesOfValheim
// 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)
diff --git a/JotunnModStub/DebugConfig.cs b/JotunnModStub/DebugConfig.cs
new file mode 100644
index 0000000..ae763e0
--- /dev/null
+++ b/JotunnModStub/DebugConfig.cs
@@ -0,0 +1,32 @@
+using UnityEngine;
+using BepInEx.Configuration;
+
+namespace RacesOfValheim
+{
+ ///
+ /// 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.
+ ///
+ public static class DebugConfig
+ {
+ public static ConfigEntry EnableDebugKey;
+ public static ConfigEntry DebugKey;
+ public static ConfigEntry 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."));
+ }
+ }
+}
diff --git a/JotunnModStub/DirectedFlight.cs b/JotunnModStub/DirectedFlight.cs
index 49d2b5d..f68a094 100644
--- a/JotunnModStub/DirectedFlight.cs
+++ b/JotunnModStub/DirectedFlight.cs
@@ -112,12 +112,13 @@ namespace RacesOfValheim
// 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();
- bool forward = input && (Input.GetKey(KeyCode.W) || stick > StickThreshold);
+ // 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 && (Input.GetKey(KeyCode.S) || stick < -StickThreshold);
+ 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 && (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift) ||
- ZInput.GetButton("JoyRun"));
+ 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
diff --git a/JotunnModStub/Draugh/DraughFoodPatches.cs b/JotunnModStub/Draugh/DraughFoodPatches.cs
index ea56d5c..a527830 100644
--- a/JotunnModStub/Draugh/DraughFoodPatches.cs
+++ b/JotunnModStub/Draugh/DraughFoodPatches.cs
@@ -24,11 +24,16 @@ namespace RacesOfValheim
{ "HareMeat", "CookedHareMeat" },
{ "ChickenMeat", "CookedChickenMeat" },
{ "BugMeat", "CookedBugMeat" },
- { "VoltureMeat", "RoastedVoltureMeat" },
+ { "VoltureMeat", "CookedVoltureMeat" },
{ "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" }
diff --git a/JotunnModStub/Dvergar/DvergarBanco.cs b/JotunnModStub/Dvergar/DvergarBanco.cs
index a912a2d..8f24220 100644
--- a/JotunnModStub/Dvergar/DvergarBanco.cs
+++ b/JotunnModStub/Dvergar/DvergarBanco.cs
@@ -76,6 +76,12 @@ 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;
@@ -276,6 +282,12 @@ 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();
foreach (Switch existing in prefab.GetComponentsInChildren(true))
diff --git a/JotunnModStub/Dvergar/DvergarCheapBuilding.cs b/JotunnModStub/Dvergar/DvergarCheapBuilding.cs
new file mode 100644
index 0000000..9fa25ec
--- /dev/null
+++ b/JotunnModStub/Dvergar/DvergarCheapBuilding.cs
@@ -0,0 +1,275 @@
+using System.Collections.Generic;
+using HarmonyLib;
+using UnityEngine;
+using UnityEngine.UI;
+
+namespace RacesOfValheim
+{
+ ///
+ /// 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.
+ ///
+ 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 originals;
+ private static Dictionary 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()?.m_itemData?.m_shared?.m_buildPieces : null;
+ stoneItem = ObjectDB.instance.GetItemPrefab(Stone)?.GetComponent();
+ fineWoodItem = ObjectDB.instance.GetItemPrefab(FineWood)?.GetComponent();
+ if (table == null || stoneItem == null || fineWoodItem == null) return false;
+
+ originals = new Dictionary();
+ prefabs = new Dictionary();
+ foreach (GameObject go in table.m_pieces)
+ {
+ Piece piece = go != null ? go.GetComponent() : 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() == null
+ && piece.GetComponentInChildren() == null
+ && piece.GetComponentInChildren() == null
+ && piece.GetComponentInChildren() == null
+ && piece.GetComponentInChildren() == null
+ && piece.m_comfort <= 0;
+ }
+
+ ///
+ /// 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.
+ ///
+ private static Piece.Requirement[] BuildCheap(Piece.Requirement[] original, int stoneRatio, int woodRatio)
+ {
+ var result = new List();
+ 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();
+ foreach (Piece.Requirement req in reqs)
+ {
+ if (req.m_resItem != null) parts.Add($"{req.m_amount} {req.m_resItem.name}");
+ }
+ return string.Join(", ", parts);
+ }
+
+ ///
+ /// Puts the cost the local player should see on the prefabs. Returns whether anything
+ /// changed, so the caller knows to refresh the build menu.
+ ///
+ 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));
+ }
+
+ ///
+ /// 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.
+ ///
+ [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();
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ [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();
+ if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
+
+ nview.GetZDO().Set(StoneRatioZdoKey, DvergarConfigManagement.CheapStonePerBlackMarble.Value);
+ nview.GetZDO().Set(WoodRatioZdoKey, DvergarConfigManagement.CheapFineWoodPerYggdrasil.Value);
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ [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();
+ 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;
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ [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.sprite = RacesOfValheim.RaceIcon(DvergarConfig.RaceId);
+ image.preserveAspect = true;
+ image.raycastTarget = false;
+ return obj.transform;
+ }
+ }
+ }
+}
diff --git a/JotunnModStub/Dvergar/DvergarConfig.cs b/JotunnModStub/Dvergar/DvergarConfig.cs
index 745c748..03f0bad 100644
--- a/JotunnModStub/Dvergar/DvergarConfig.cs
+++ b/JotunnModStub/Dvergar/DvergarConfig.cs
@@ -124,9 +124,11 @@ 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.081f; // centre ~63mm out
+ public static readonly float EyeForward = 0.085f; // 0.081 left the smaller ball buried
public static readonly float EyeHeight = 0.181f; // ~15mm lower than before
- public static readonly float EyeSize = 0.062f; // ~48mm across, so a 24mm radius
+ // 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;
// 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
diff --git a/JotunnModStub/Dvergar/DvergarConfigManagement.cs b/JotunnModStub/Dvergar/DvergarConfigManagement.cs
index b9be848..3a6d43f 100644
--- a/JotunnModStub/Dvergar/DvergarConfigManagement.cs
+++ b/JotunnModStub/Dvergar/DvergarConfigManagement.cs
@@ -57,6 +57,11 @@ namespace RacesOfValheim
public static ConfigEntry RunicOverchargeWindow;
public static ConfigEntry RunicOverchargeCooldown;
+ // ─── Cheap Building ───────────────────────────────────────────────────────
+ public static ConfigEntry CheapBuildingEnabled;
+ public static ConfigEntry CheapStonePerBlackMarble;
+ public static ConfigEntry CheapFineWoodPerYggdrasil;
+
public static void Bind(ConfigFile config)
{
const string keybinds = "Dvergar - Keybinds";
@@ -106,6 +111,14 @@ namespace RacesOfValheim
new ConfigDescription("Seconds a loaded charge is held before it lapses unused.", new AcceptableValueRange(1f, 60f)));
RunicOverchargeCooldown = config.Bind(overcharge, "Cooldown", 60f,
new ConfigDescription("Seconds between casts.", new AcceptableValueRange(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(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(1, 10)));
}
}
}
diff --git a/JotunnModStub/Dvergar/DvergarVisuals.cs b/JotunnModStub/Dvergar/DvergarVisuals.cs
index a6a694a..c654a3a 100644
--- a/JotunnModStub/Dvergar/DvergarVisuals.cs
+++ b/JotunnModStub/Dvergar/DvergarVisuals.cs
@@ -277,10 +277,11 @@ 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 eyeLocalSize = DvergarConfig.EyeSize * raceScale * toLocal;
+ float height = DvergarConfig.EyeHeight;
+ float separation = DvergarConfig.EyeSeparation;
+ float eyeSize = DvergarConfig.EyeSize;
+ PlayerFace.AdjustEyes(player, ref height, ref separation, ref eyeSize);
for (int i = 0; i < holder.childCount; i++)
{
@@ -291,9 +292,25 @@ 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;
- eye.localPosition = baseLocal + localRight * (side * DvergarConfig.EyeSeparation * raceScale * toLocal);
+ // 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.localScale = Vector3.one * size;
}
}
diff --git a/JotunnModStub/Factions/FactionHostilityPatch.cs b/JotunnModStub/Factions/FactionHostilityPatch.cs
index 7fee617..2bc10ce 100644
--- a/JotunnModStub/Factions/FactionHostilityPatch.cs
+++ b/JotunnModStub/Factions/FactionHostilityPatch.cs
@@ -54,9 +54,17 @@ namespace RacesOfValheim
//
// 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 PaludeMobs = new HashSet
{
"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",
"Wraith", "Leech", "Abomination",
"Blob", "BlobElite", "BlobTar", // Blob, Oozer, Growth
@@ -157,6 +165,10 @@ namespace RacesOfValheim
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;
diff --git a/JotunnModStub/Factions/FactionMerchantCatalog.cs b/JotunnModStub/Factions/FactionMerchantCatalog.cs
index e4db2cb..93a0b71 100644
--- a/JotunnModStub/Factions/FactionMerchantCatalog.cs
+++ b/JotunnModStub/Factions/FactionMerchantCatalog.cs
@@ -337,7 +337,16 @@ namespace RacesOfValheim
{ "Draugr_Elite", DraugrShop },
{ "Skeleton", SkeletonShop },
+ { "Skeleton_NoArcher", SkeletonShop },
{ "Skeleton_Poison", SkeletonShop },
+ // Valheim 1.0's regional skeletons, the ones its spawners actually place.
+ { "Skeleton_Meadows", SkeletonShop },
+ { "Skeleton_Meadows_noarcher", SkeletonShop },
+ { "Skeleton_Swamps", SkeletonShop },
+ { "Skeleton_Swamps_noarcher", SkeletonShop },
+ { "Skeleton_Mountains", SkeletonShop },
+ { "Skeleton_Mountains_noarcher", SkeletonShop },
+ { "Skeleton_DeepNorth", SkeletonShop },
{ "Ghost", GhostShop },
{ "Wraith", WraithShop },
diff --git a/JotunnModStub/Factions/FactionsConfig.cs b/JotunnModStub/Factions/FactionsConfig.cs
index 2448192..6535e12 100644
--- a/JotunnModStub/Factions/FactionsConfig.cs
+++ b/JotunnModStub/Factions/FactionsConfig.cs
@@ -21,6 +21,8 @@ namespace RacesOfValheim
public static ConfigEntry HostilityEnabled;
public static ConfigEntry MerchantsEnabled;
public static ConfigEntry GrudgeDuration;
+ public static ConfigEntry GrudgeSpreadEnabled;
+ public static ConfigEntry GrudgeSpreadRadius;
// Null-safe, defaulting to ON, for the same reason WarVultureConfig guards its own reads:
// a patch that somehow runs before Bind() should behave like the shipped default rather
@@ -28,6 +30,8 @@ namespace RacesOfValheim
public static bool Hostility => HostilityEnabled?.Value ?? true;
public static bool Merchants => MerchantsEnabled?.Value ?? true;
public static float GrudgeSeconds => GrudgeDuration?.Value ?? 60f;
+ public static bool GrudgeSpreads => GrudgeSpreadEnabled?.Value ?? false;
+ public static float GrudgeSpreadMeters => GrudgeSpreadRadius?.Value ?? 20f;
public static void Bind(ConfigFile config)
{
@@ -55,11 +59,24 @@ namespace RacesOfValheim
"Without this the truce is absolute in both directions: MonsterAI.UpdateTarget " +
"throws away any target BaseAI.IsEnemy calls a non-enemy, so a truced mob could " +
"not fight back even after being struck - it stood still, or fled because it " +
- "was hurt and had no enemy it was allowed to have. The grudge is per attacker " +
- "and per creature, on whichever machine runs that creature's AI. 0 restores the " +
+ "was hurt and had no enemy it was allowed to have. Each creature holds one " +
+ "grudge, against the last player who hit it, and keeps it when another player's " +
+ "game takes over running that creature. 0 restores the " +
"old absolute truce.",
new AcceptableValueRange(0f, 600f)));
+ // Joacwoo's request: the truce made the swamp and the crypts a walk for a Skeleton,
+ // since only the one creature you hit ever fought back.
+ GrudgeSpreadEnabled = config.Bind(factions, "Grudge spreads to kin", false,
+ new ConfigDescription("Off: only the creature you hit fights back. On: hit a creature of your " +
+ "own faction and every creature of that faction near it turns on you too, " +
+ "for the same Faction grudge time, the way vanilla's Dvergr treat a human. " +
+ "Peace still holds until you strike first."));
+ GrudgeSpreadRadius = config.Bind(factions, "Grudge spread radius", 20f,
+ new ConfigDescription("Meters around the creature you hit within which its kin join the fight, " +
+ "with Grudge spreads to kin on.",
+ new AcceptableValueRange(5f, 60f)));
+
MerchantsEnabled = config.Bind(factions, "Faction merchants", true,
new ConfigDescription("Certain mobs of your own faction can be traded with - 'E - Talk' opens a shop " +
"where you sell them what their kind wants. Turn this off and they are ordinary " +
diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs
index e1df615..d0dd0cd 100644
--- a/JotunnModStub/Fenrir/FenrirBehaviors.cs
+++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs
@@ -323,17 +323,72 @@ namespace RacesOfValheim
GameObject fireVfx = ZNetScene.instance.GetPrefab("fx_fenring_flames");
if (fireVfx == null) return null;
- GameObject instance = Object.Instantiate(fireVfx, player.transform.position + Vector3.up * 1.5f + player.transform.forward, player.transform.rotation, player.transform);
+ GameObject instance = Object.Instantiate(fireVfx, MouthPoint(player), player.transform.rotation, player.transform);
+ instance.AddComponent().Player = player;
+
+ // The vanilla effect is one throw, not a held breath: its emitters do not loop (2 s) and
+ // a TimedDestruction removes it after 5 s, so a long hold went on draining eitr with no
+ // fire. It loops here and lives until StopFire takes it down.
+ TimedDestruction timer = instance.GetComponent();
+ if (timer != null)
+ {
+ timer.CancelInvoke();
+ Object.Destroy(timer);
+ }
// Aumentiamo la durata delle particelle del 20%
foreach (ParticleSystem ps in instance.GetComponentsInChildren())
{
var main = ps.main;
main.startLifetimeMultiplier *= 1.2f;
+ main.loop = true;
+ }
+
+ // The roar of the fire, the same one-throw story: set before its ZSFX first plays.
+ foreach (ZSFX sfx in instance.GetComponentsInChildren())
+ {
+ sfx.m_fadeOutOnAwake = false;
+ AudioSource source = sfx.GetComponent();
+ if (source != null) source.loop = true;
}
return instance;
}
+ // Bone names the breath leaves from, mouth first. Matched by name anywhere under the form.
+ private static readonly string[] MouthBones = { "Jaw", "Head" };
+
+ ///
+ /// Where the Cultist's breath starts: just ahead of the form's jaw (or head), so it leaves the
+ /// mouth at whatever size the form stands. It used to be a fixed 1.5 m above the player's
+ /// feet, chest height on a Cultist, which is the "fire starts too low" report. Falls back on
+ /// that fixed point if the form has neither bone.
+ ///
+ public static Vector3 MouthPoint(Player player) => MouthPoint(player, FindMouth(player));
+
+ public static Vector3 MouthPoint(Player player, Transform bone)
+ {
+ Transform body = player.transform;
+ return bone != null
+ ? bone.position + body.forward * 0.3f
+ : body.position + Vector3.up * 1.5f + body.forward;
+ }
+
+ public static Transform FindMouth(Player player)
+ {
+ foreach (string wanted in MouthBones)
+ {
+ foreach (Transform child in player.transform)
+ {
+ if (child.name == "Visual" || !child.gameObject.activeInHierarchy) continue;
+ foreach (Transform t in child.GetComponentsInChildren())
+ {
+ if (string.Equals(t.name, wanted, System.StringComparison.OrdinalIgnoreCase)) return t;
+ }
+ }
+ }
+ return null;
+ }
+
public static void PublishFire(bool on)
{
Player player = Player.m_localPlayer;
@@ -393,6 +448,8 @@ namespace RacesOfValheim
private ZNetView nview;
private string lastAttack;
private GameObject flames;
+ private bool breathing;
+ private float breathStarted;
private readonly FormLocomotion locomotion = new FormLocomotion();
// The flames hang off the player, not this model, so they outlive it unless taken down.
@@ -433,18 +490,31 @@ namespace RacesOfValheim
bool fire = nview.GetZDO().GetBool(FenrirAttackSync.FireKey, false);
- // The breath itself: up while the flag is, gone when it drops. Only the cultist ever
- // sets the flag, so no other form can grow flames here.
- if (fire && flames == null)
+ // The flag is up for the whole hold, wind-up included, as on the owner's side; the
+ // flames come at the same point of the same clip (CultistBreathClip). Only the cultist
+ // ever sets the flag, so no other form can grow flames here.
+ if (fire && !breathing)
{
- flames = FenrirAttackSync.SpawnFlames(player);
+ breathing = true;
+ breathStarted = Time.time;
// The roar that opens the breath, once per start, the same cue the owner hears.
// "sfx_cultist_attack_fire_start" was asked for here and there is no sfx_cultist_*
// prefab in the game at all; the fenring's own fire-claw snarl is the real one.
FenrirCreatureSound.PlayFireRoar(player.transform.position);
}
- else if (!fire && flames != null) { Destroy(flames); flames = null; }
+ if (fire)
+ {
+ CultistBreathClip.Hold(formAnim);
+ if (flames == null && CultistBreathClip.FlamesDue(formAnim, breathStarted))
+ flames = FenrirAttackSync.SpawnFlames(player);
+ }
+ else if (breathing)
+ {
+ breathing = false;
+ CultistBreathClip.Release(formAnim, player);
+ if (flames != null) { Destroy(flames); flames = null; }
+ }
foreach (AnimatorControllerParameter p in formAnim.parameters)
{
@@ -550,15 +620,15 @@ namespace RacesOfValheim
{
StartCoroutine(HowlRoutine());
}
- else if (RaceInput.AttackDown(1)) // Tasto destro (Heavy Claw)
+ else if (RaceInput.AttackDown(1) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.FenringHeavyClawStamina.Value, Skills.SkillType.Unarmed)) // Tasto destro (Heavy Claw)
{
StartCoroutine(ClawRoutine("attack_claw1", FenrirConfig.FenringHeavyClawDamage.Value, 1.2f, 0.5f));
}
- else if (RaceInput.AttackDown(0)) // Tasto sinistro
+ else if (RaceInput.AttackDown(0) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.FenringLightClawStamina.Value, Skills.SkillType.Unarmed)) // Tasto sinistro
{
StartCoroutine(ClawRoutine("attack_claw0", FenrirConfig.FenringLightClawDamage.Value, 1.0f, 0.4f));
}
- else if (RaceInput.AttackDown(2)) // Tasto centrale
+ else if (RaceInput.AttackDown(2) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.FenringJumpAttackStamina.Value, Skills.SkillType.Unarmed)) // Tasto centrale
{
StartCoroutine(JumpAttackRoutine());
}
@@ -690,7 +760,7 @@ namespace RacesOfValheim
private void ExecuteClawDamage(float baseDamage)
{
- if (Player.m_localPlayer == null) return;
+ if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 1f;
@@ -704,6 +774,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet hitObjects = new System.Collections.Generic.HashSet();
+ bool hitCreature = false;
foreach (Collider hit in hits)
{
@@ -753,10 +824,13 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData);
FormMelee.GrantAdrenaline(target);
+ if (target is Character) hitCreature = true;
}
}
}
}
+
+ if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
}
}
@@ -805,47 +879,40 @@ namespace RacesOfValheim
// still falls through to StopFire() instead of leaving the flames running.
bool canAct = RaceInput.Allowed;
- // Fire attack on Right Click
- if (canAct && RaceInput.AttackHeld(1))
+ // Fire attack on Right Click, held.
+ bool wantFire = canAct && RaceInput.AttackHeld(1) && !Player.m_localPlayer.IsStaggering();
+ if (wantFire && Player.m_localPlayer.GetEitr() <= 0f)
{
- if (Player.m_localPlayer.GetEitr() > 0)
- {
- if (!isShootingFire)
- {
- StartFire();
- }
- else
- {
- UpdateFire();
- }
- }
- else
- {
- // Held with an empty pool. Until now this did nothing whatsoever: no
- // flames, no sound, no reason given - and the form's own tier is Yagluth
- // while eitr is a Mistlands thing, so a Cultist meets this before it ever
- // meets the fire.
- SayNoEitr();
- if (isShootingFire) StopFire();
- }
+ // Held with an empty pool. Until now this did nothing whatsoever: no
+ // flames, no sound, no reason given - and the form's own tier is Yagluth
+ // while eitr is a Mistlands thing, so a Cultist meets this before it ever
+ // meets the fire.
+ SayNoEitr();
+ wantFire = false;
+ }
+
+ if (wantFire)
+ {
+ if (!isShootingFire) StartFire();
+ else UpdateFire();
}
else if (isShootingFire)
{
StopFire();
}
- if (canAct && FenrirConfig.HowlKey.Value.IsDownIgnoringHeldKeys())
+ if (canAct && !isShootingFire && FenrirConfig.HowlKey.Value.IsDownIgnoringHeldKeys())
{
StartCoroutine(HowlRoutine());
}
// Attacks on Left Click
- if (canAct && RaceInput.AttackDown(0) && !isShootingFire)
+ if (canAct && RaceInput.AttackDown(0) && !isShootingFire && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.CultistClawStamina.Value, Skills.SkillType.Unarmed))
{
StartCoroutine(ClawRoutine()); // Single claw
}
// Double claw on Middle Click
- else if (canAct && RaceInput.AttackDown(2) && !isShootingFire)
+ else if (canAct && RaceInput.AttackDown(2) && !isShootingFire && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.CultistDoubleClawStamina.Value, Skills.SkillType.Unarmed))
{
StartCoroutine(DoubleClawRoutine());
}
@@ -907,31 +974,54 @@ namespace RacesOfValheim
ModText.Get("rov_msg_fenrir_only_breath_comes_out_fire"));
}
+ // The breath runs on the flame clip (CultistBreathClip): pressed, the clip starts; the flames,
+ // the eitr drain and the damage begin at its own Hit point; released, the clip is cut.
+ private bool flaming;
+ private float fireStarted;
+
+ /// True while the local Cultist holds its breath attack, wind-up included. Read by
+ /// Cultist_BreathFacesCamera_Patch.
+ public static bool LocalBreathing { get; private set; }
+
private void StartFire()
{
if (Player.m_localPlayer == null || isShootingFire) return;
isShootingFire = true;
+ LocalBreathing = true;
+ // Planted while it breathes, as the vanilla Cultist is: its controller has no walking
+ // version of the cast, so a moving Cultist slid along in the casting pose.
+ // Fenrir_FormHoldStill_Patch holds the player; turning to the camera still works.
+ FenrirForms.LocalAttacking = true;
+ flaming = false;
+ fireStarted = Time.time;
+ fireTimer = 0f;
FormAnimGuard.LeaveHowl(cultistAnim);
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
- cultistAnim.SetBool("attack_fire", true);
FenrirAttackSync.PublishFire(true);
-
+
// Same cue the remote mirror plays - see the fire branch in the sync behaviour above.
FenrirCreatureSound.PlayFireRoar(Player.m_localPlayer.transform.position);
cultistAnim.SetTrigger("attack_flames");
FenrirAttackSync.Publish("attack_flames");
-
- if (fireEffectInstance == null) fireEffectInstance = FenrirAttackSync.SpawnFlames(Player.m_localPlayer);
}
private void UpdateFire()
{
- Player.m_localPlayer.UseEitr(FenrirConfig.CultistFireEitrDrainPerSecond.Value * Time.deltaTime);
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
-
+ CultistBreathClip.Hold(cultistAnim);
+
+ if (!flaming)
+ {
+ if (!CultistBreathClip.FlamesDue(cultistAnim, fireStarted)) return;
+ flaming = true;
+ if (fireEffectInstance == null) fireEffectInstance = FenrirAttackSync.SpawnFlames(Player.m_localPlayer);
+ }
+
+ Player.m_localPlayer.UseEitr(FenrirConfig.CultistFireEitrDrainPerSecond.Value * Time.deltaTime);
+
fireTimer += Time.deltaTime;
if (fireTimer >= 0.2f) // Damage tick every 0.2s
{
@@ -944,14 +1034,20 @@ namespace RacesOfValheim
private void OnDestroy()
{
if (isShootingFire) FenrirAttackSync.PublishFire(false);
+ if (isShootingFire) FenrirForms.LocalAttacking = false;
+ LocalBreathing = false;
}
private void StopFire()
{
isShootingFire = false;
+ LocalBreathing = false;
+ FenrirForms.LocalAttacking = false;
+ flaming = false;
cultistAnim.ResetTrigger("attack_flames");
FenrirAttackSync.PublishFire(false);
-
+ CultistBreathClip.Release(cultistAnim, Player.m_localPlayer);
+
if (fireEffectInstance != null)
{
Destroy(fireEffectInstance);
@@ -975,6 +1071,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet hitObjects = new System.Collections.Generic.HashSet();
+ bool hitCreature = false;
foreach (Collider hit in hits)
{
@@ -1014,6 +1111,7 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData);
FormMelee.GrantAdrenaline(target, 0.2f); // one 0.2s tick: a full hit per second of breath
+ if (target is Character) hitCreature = true;
if (ZNetScene.instance != null)
{
@@ -1023,6 +1121,8 @@ namespace RacesOfValheim
}
}
}
+
+ if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, 0.2f); // one 0.2s tick: a full swing's worth per second of breath
}
private IEnumerator ClawRoutine()
@@ -1034,25 +1134,30 @@ namespace RacesOfValheim
cultistAnim.SetFloat("sideway_speed", 0f);
// Per il Cultista usiamo esplicitamente il trigger dell'artigliata
+ int baseline = FenrirForms.AttackEvents;
+ float started = Time.time;
cultistAnim.SetTrigger("attack_claw");
FenrirAttackSync.Publish("attack_claw", "sfx_fenring_claw_start");
- yield return new WaitForSeconds(0.4f);
+ // The blow lands on the clip's own Hit event (ClawAttackCultist: 0.64 s of 1.33 s), and
+ // the lock holds until the clip is over. A fixed 0.4 s hit and a 0.5 s lock used to land
+ // the damage before the claw swung and let the next click start a new one mid-swing.
+ yield return null;
+ float length = ClipLength(1.33f);
+ yield return WaitForHit(baseline, started);
PlaySFX("sfx_fenring_claw_start");
-
ExecuteClawDamage(FenrirConfig.CultistClawDamage.Value);
- float remainingTimeToIdle = 0.5f - 0.4f;
- if (remainingTimeToIdle > 0)
- {
- yield return new WaitForSeconds(remainingTimeToIdle);
- }
-
+ yield return WaitUntilClipEnds(length, started);
cultistAnim.ResetTrigger("attack_claw");
isAttacking = false;
}
+ // Each swipe of the double claw deals this share of Double Claw Damage. Two swipes give
+ // 120% of what the old single hit dealt: a little more, for a slower swing that can be cut short.
+ private const float DoubleClawHitShare = 0.6f;
+
private IEnumerator DoubleClawRoutine()
{
isAttacking = true;
@@ -1061,27 +1166,66 @@ namespace RacesOfValheim
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
+ int baseline = FenrirForms.AttackEvents;
+ float started = Time.time;
cultistAnim.SetTrigger("attack_claw_double");
FenrirAttackSync.Publish("attack_claw_double", "sfx_fenring_claw_start");
- // L'animazione double claw è più lunga, facciamo il danno un po' dopo
- yield return new WaitForSeconds(0.6f);
+ // DoubleClawAttackCultist carries two Hit events (0.64 s and 1.21 s of 1.83 s), one per
+ // swipe. It used to deal one hit at a fixed 0.6 s, so the second swipe did nothing.
+ yield return null;
+ float length = ClipLength(1.83f);
+ float damage = FenrirConfig.CultistDoubleClawDamage.Value * DoubleClawHitShare;
+ yield return WaitForHit(baseline, started);
PlaySFX("sfx_fenring_claw_start");
+ ExecuteClawDamage(damage);
- ExecuteClawDamage(FenrirConfig.CultistDoubleClawDamage.Value);
-
- // Attendiamo che l'animazione finisca (locking del giocatore)
- // L'animazione doppia del cultista dura circa 1.5 - 2 secondi
- yield return new WaitForSeconds(1.2f);
+ yield return WaitForHit(baseline + 1, started, HitEventTimeout + 0.6f);
+ PlaySFX("sfx_fenring_claw_start");
+ ExecuteClawDamage(damage);
+ yield return WaitUntilClipEnds(length, started);
cultistAnim.ResetTrigger("attack_claw_double");
isAttacking = false;
}
+ // Longest a swipe waits for its Hit event before landing anyway, measured from the trigger:
+ // a clip that never sends one must not leave the Cultist swinging at nothing.
+ private const float HitEventTimeout = 1.5f;
+
+ /// Waits until the clip has sent more than hit events since
+ /// the trigger, or until the timeout.
+ private IEnumerator WaitForHit(int seen, float started, float timeout = HitEventTimeout)
+ {
+ while (FenrirForms.AttackEvents <= seen && Time.time - started < timeout)
+ {
+ yield return null;
+ }
+ }
+
+ /// The attack clip's length, read a frame after its trigger, when the transition
+ /// into it has begun. is the clip's length in the game files.
+ private float ClipLength(float fallback)
+ {
+ AnimatorClipInfo[] clips = cultistAnim.IsInTransition(0)
+ ? cultistAnim.GetNextAnimatorClipInfo(0)
+ : cultistAnim.GetCurrentAnimatorClipInfo(0);
+ if (clips != null && clips.Length > 0 && clips[0].clip != null) return clips[0].clip.length;
+ return fallback;
+ }
+
+ /// Holds the lock until the clip has played out, clamped so a wrong reading can
+ /// neither cut a swing short nor freeze the form.
+ private IEnumerator WaitUntilClipEnds(float length, float started)
+ {
+ float remaining = Mathf.Clamp(length, 0.6f, 3f) - (Time.time - started);
+ if (remaining > 0f) yield return new WaitForSeconds(remaining);
+ }
+
private void ExecuteClawDamage(float baseDamage)
{
- if (Player.m_localPlayer == null) return;
+ if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 1f;
@@ -1095,6 +1239,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet hitObjects = new System.Collections.Generic.HashSet();
+ bool hitCreature = false;
foreach (Collider hit in hits)
{
@@ -1144,10 +1289,13 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData);
FormMelee.GrantAdrenaline(target);
+ if (target is Character) hitCreature = true;
}
}
}
}
+
+ if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
}
}
@@ -1194,15 +1342,15 @@ namespace RacesOfValheim
{
StartCoroutine(WolfHowlRoutine());
}
- else if (RaceInput.AttackDown(0)) // Left Click
+ else if (RaceInput.AttackDown(0) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.WolfAttack1Stamina.Value, Skills.SkillType.Unarmed)) // Left Click
{
StartCoroutine(WolfAttackRoutine("attack1", FenrirConfig.WolfAttack1Damage.Value, 0.6f, 0.2f));
}
- else if (RaceInput.AttackDown(1)) // Right Click
+ else if (RaceInput.AttackDown(1) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.WolfAttack2Stamina.Value, Skills.SkillType.Unarmed)) // Right Click
{
StartCoroutine(WolfAttackRoutine("attack2", FenrirConfig.WolfAttack2Damage.Value, 0.8f, 0.3f));
}
- else if (RaceInput.AttackDown(2)) // Middle Click
+ else if (RaceInput.AttackDown(2) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.WolfAttack3Stamina.Value, Skills.SkillType.Unarmed)) // Middle Click
{
StartCoroutine(WolfAttackRoutine("attack3", FenrirConfig.WolfAttack3Damage.Value, 1.0f, 0.4f));
}
@@ -1295,7 +1443,7 @@ namespace RacesOfValheim
private void ExecuteBiteDamage(float baseDamage)
{
- if (Player.m_localPlayer == null) return;
+ if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position;
// Il lupo è basso, abbassiamo l'altezza dell'attacco
@@ -1310,6 +1458,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet hitObjects = new System.Collections.Generic.HashSet();
+ bool hitCreature = false;
foreach (Collider hit in hits)
{
@@ -1359,10 +1508,13 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData);
FormMelee.GrantAdrenaline(target);
+ if (target is Character) hitCreature = true;
}
}
}
}
+
+ if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
}
}
@@ -1410,16 +1562,16 @@ namespace RacesOfValheim
{
StartCoroutine(UlvHowlRoutine());
}
- else if (RaceInput.AttackDown(0)) // Left Click
+ else if (RaceInput.AttackDown(0) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.UlvBiteStamina.Value, Skills.SkillType.Unarmed)) // Left Click
{
StartCoroutine(UlvAttackRoutine("attack_bite", FenrirConfig.UlvBiteDamage.Value, 0.6f, 0.2f));
}
- else if (RaceInput.AttackDown(1)) // Right Click
+ else if (RaceInput.AttackDown(1) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.UlvHeavyBiteStamina.Value, Skills.SkillType.Unarmed)) // Right Click
{
// Right click uses bite but as a heavier attack since slash is moved to jump
StartCoroutine(UlvAttackRoutine("attack_bite", FenrirConfig.UlvHeavyBiteDamage.Value, 0.8f, 0.3f));
}
- else if (RaceInput.AttackDown(2)) // Middle Click
+ else if (RaceInput.AttackDown(2) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.UlvJumpAttackStamina.Value, Skills.SkillType.Unarmed)) // Middle Click
{
StartCoroutine(UlvJumpAttackRoutine());
}
@@ -1504,7 +1656,7 @@ namespace RacesOfValheim
private void ExecuteBiteDamage(float baseDamage)
{
- if (Player.m_localPlayer == null) return;
+ if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 0.5f;
@@ -1518,6 +1670,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet hitObjects = new System.Collections.Generic.HashSet();
+ bool hitCreature = false;
foreach (Collider hit in hits)
{
@@ -1567,10 +1720,13 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData);
FormMelee.GrantAdrenaline(target);
+ if (target is Character) hitCreature = true;
}
}
}
}
+
+ if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
}
private IEnumerator UlvJumpAttackRoutine()
@@ -1621,4 +1777,160 @@ namespace RacesOfValheim
}
}
+ ///
+ /// The Cultist's breath, timed by its own clip. fenring_cultist_animator's attack_flames state
+ /// plays "Flame Spell Attack" (read offline with UnityPy, bundle c4210710): 3.5 s, the hands
+ /// light at 1.094 s (TrailOn), the vanilla flames come at 1.245 s (Hit) and are taken down at
+ /// 3.193 s. The state leaves for Movement only when the clip ends, so a short click used to
+ /// leave the Cultist standing with its arms up for the rest of the 3.5 s, breathing nothing.
+ ///
+ /// Now the flames wait for the clip's Hit point, the arms are held in the casting pose for as
+ /// long as the button is, and letting go blends straight back to Movement. Shared by the
+ /// owner's Cultist and every onlooker's copy, so both play the same breath.
+ ///
+ internal static class CultistBreathClip
+ {
+ private static readonly int State = Animator.StringToHash("Base Layer.attack_flames");
+ private const string MovementState = "Base Layer.Movement";
+
+ // The clip's Hit event, where the vanilla Cultist's flames come out.
+ private const float FlamesAt = 1.245f;
+
+ // The throw itself: the Animator stops here while held. After it the vanilla Cultist lowers
+ // its arms while its fire flies on alone, so a pin at 2.6 s held an idle-looking pose.
+ private const float PinAt = 1.3f;
+
+ private const float Fade = 0.25f;
+
+ /// Seconds into the flame clip, or -1 while the Animator is in another state.
+ private static float ClipTime(Animator anim)
+ {
+ AnimatorStateInfo info = anim.IsInTransition(0) ? anim.GetNextAnimatorStateInfo(0) : anim.GetCurrentAnimatorStateInfo(0);
+ return info.fullPathHash == State ? info.normalizedTime * info.length : -1f;
+ }
+
+ /// True once the clip has reached its Hit point. If the clip never started (another
+ /// state took the Animator), the same delay counted from the press stands in for it.
+ public static bool FlamesDue(Animator anim, float started)
+ {
+ float t = ClipTime(anim);
+ return t >= FlamesAt || (t < 0f && Time.time - started >= FlamesAt + 0.2f);
+ }
+
+ ///
+ /// Holds the arms in the casting pose: once the clip reaches PinAt it is put back there every
+ /// frame. Not with Animator.speed = 0, which is what the troll's pin uses: the creature's own
+ /// CharacterAnimEvent sits on this model and sets speed back to 1 on every physics step while
+ /// the player is not in a vanilla attack, so the clip ran on to its end and the Cultist went
+ /// back to idle with the fire still pouring out.
+ ///
+ public static void Hold(Animator anim)
+ {
+ if (anim.IsInTransition(0)) return;
+ AnimatorStateInfo info = anim.GetCurrentAnimatorStateInfo(0);
+ if (info.fullPathHash != State || info.length <= 0f) return;
+ if (info.normalizedTime * info.length >= PinAt) anim.Play(State, 0, PinAt / info.length);
+ }
+
+ /// Blends out of the clip, unless a stagger has taken over (FormStagger has fired
+ /// the form's own).
+ public static void Release(Animator anim, Player player)
+ {
+ if (anim == null) return;
+ if (ClipTime(anim) >= 0f && (player == null || !player.IsStaggering()))
+ anim.CrossFadeInFixedTime(MovementState, Fade, 0);
+ }
+ }
+
+ ///
+ /// Keeps the Cultist's breath in its hands, where the vanilla Cultist casts it from. fx_fenring_flames
+ /// has two emitters, "flames_world left" and "flames_world right", set 1.2 to 1.6 m ahead of
+ /// its own origin; spawned at the creature, the fire began that far in front of it. Each
+ /// emitter goes on its hand bone (fenring_cultist rig: .../LeftForeArm/LeftHand and the right
+ /// one), pointing where the player faces, so the two streams leave the palms and run forward.
+ /// The embers and the light sit between the hands. Placed every LateUpdate, after the form's
+ /// Animator has moved the arms. The same on every client's copy.
+ ///
+ /// A form without hand bones keeps the whole effect at its mouth, as before.
+ ///
+ internal class CultistFlameFollow : MonoBehaviour
+ {
+ // Ahead of the palm, so the stream does not start inside the hand.
+ private const float AheadOfHand = 0.15f;
+
+ // The light, further ahead along the stream.
+ private const float LightAhead = 1.5f;
+
+ public Player Player;
+ private Transform mouth, leftHand, rightHand;
+ private Transform leftFlames, rightFlames, embers, light;
+ private bool partsFound;
+ private float nextLook;
+
+ private void LateUpdate()
+ {
+ if (Player == null) return;
+
+ if (!partsFound)
+ {
+ partsFound = true;
+ leftFlames = transform.Find("flames_world left");
+ rightFlames = transform.Find("flames_world right");
+ embers = transform.Find("FireEmbers");
+ light = transform.Find("Point light");
+ }
+
+ // The form can be rebuilt under the same flames; look again now and then if lost.
+ if ((leftHand == null || rightHand == null || mouth == null) && Time.time >= nextLook)
+ {
+ nextLook = Time.time + 0.5f;
+ leftHand = FindBone(Player, "LeftHand");
+ rightHand = FindBone(Player, "RightHand");
+ mouth = FenrirAttackSync.FindMouth(Player);
+ }
+
+ Quaternion facing = Player.transform.rotation;
+ transform.SetPositionAndRotation(FenrirAttackSync.MouthPoint(Player, mouth), facing);
+ if (leftHand == null || rightHand == null || leftFlames == null || rightFlames == null) return;
+
+ Vector3 forward = Player.transform.forward;
+ Vector3 left = leftHand.position + forward * AheadOfHand;
+ Vector3 right = rightHand.position + forward * AheadOfHand;
+ leftFlames.SetPositionAndRotation(left, facing);
+ rightFlames.SetPositionAndRotation(right, facing);
+
+ Vector3 between = (left + right) * 0.5f;
+ if (embers != null) embers.SetPositionAndRotation(between, facing);
+ if (light != null) light.position = between + forward * LightAhead;
+ }
+
+ private static Transform FindBone(Player player, string name)
+ {
+ foreach (Transform child in player.transform)
+ {
+ if (child.name == "Visual" || !child.gameObject.activeInHierarchy) continue;
+ foreach (Transform t in child.GetComponentsInChildren())
+ {
+ if (t.name == name) return t;
+ }
+ }
+ return null;
+ }
+ }
+
+ ///
+ /// Turns the Cultist toward the camera while it breathes fire, as vanilla turns a player who
+ /// blocks or draws a bow: Player.AlwaysRotateCamera answers true for those, and Character then
+ /// turns the body to the look direction at its own turn speed. The breath is not a vanilla
+ /// attack, so the body stayed facing wherever the movement keys had left it.
+ ///
+ [HarmonyPatch(typeof(Player), "AlwaysRotateCamera")]
+ public static class Cultist_BreathFacesCamera_Patch
+ {
+ public static void Postfix(Player __instance, ref bool __result)
+ {
+ if (!__result && __instance == Player.m_localPlayer && CultistFormBehavior.LocalBreathing) __result = true;
+ }
+ }
+
}
diff --git a/JotunnModStub/Fenrir/FenrirConfig.cs b/JotunnModStub/Fenrir/FenrirConfig.cs
index e9dd6e5..2190a36 100644
--- a/JotunnModStub/Fenrir/FenrirConfig.cs
+++ b/JotunnModStub/Fenrir/FenrirConfig.cs
@@ -38,15 +38,33 @@ namespace RacesOfValheim
public static ConfigEntry SpeedBonusPerState;
public static ConfigEntry JumpBonusPerState;
public static ConfigEntry SunSicknessDuration;
+ public static ConfigEntry SensesRadius;
// ─── Form buffs (applied while transformed) ───────────────────────────
public static ConfigEntry FullFormSpeedBonus;
public static ConfigEntry FullFormJumpBonus;
public static ConfigEntry FullFormFallDamageReduction;
public static ConfigEntry WolfFormSpeedBonus;
+ public static ConfigEntry UlvFormSpeedBonus;
+ public static ConfigEntry FenringDamageReduction;
+ public static ConfigEntry CultistExtraDamageTaken;
public static ConfigEntry WolfFormFallDamageReduction;
public static ConfigEntry FormStaminaRegenMultiplier;
public static ConfigEntry FormStaminaDrainReduction;
+ public static ConfigEntry FormAdrenalineMultiplier;
+
+ // ─── Form attack stamina (base cost, before the Unarmed skill discount) ─
+ public static ConfigEntry FenringLightClawStamina;
+ public static ConfigEntry FenringHeavyClawStamina;
+ public static ConfigEntry FenringJumpAttackStamina;
+ public static ConfigEntry CultistClawStamina;
+ public static ConfigEntry CultistDoubleClawStamina;
+ public static ConfigEntry WolfAttack1Stamina;
+ public static ConfigEntry WolfAttack2Stamina;
+ public static ConfigEntry WolfAttack3Stamina;
+ public static ConfigEntry UlvBiteStamina;
+ public static ConfigEntry UlvHeavyBiteStamina;
+ public static ConfigEntry UlvJumpAttackStamina;
// ─── Fenring form attacks ─────────────────────────────────────────────
public static ConfigEntry FenringHeavyClawDamage;
@@ -82,9 +100,6 @@ namespace RacesOfValheim
public static ConfigEntry UlvAttackRadius;
public static ConfigEntry UlvPushForce;
- // ─── Debug ─────────────────────────────────────────────────────────────
- public static ConfigEntry DebugFormHits;
-
// ─── Appearance (per player, never synced) ──────────────────────────────
public static ConfigEntry ReadyMessage;
public static ConfigEntry EyeGlow;
@@ -117,16 +132,30 @@ namespace RacesOfValheim
SunSicknessDuration = config.Bind(combat, "Sun Sickness Duration", 60f,
new ConfigDescription("Seconds of forced human form after being reverted by sunrise.", new AcceptableValueRange(0f, 300f)));
+ const string senses = "Fenrir - Superhuman Senses";
+ SensesRadius = config.Bind(senses, "Detection Radius", 100f,
+ new ConfigDescription("Meters within which nearby creatures glow green while you are in any form. The light itself follows the Aswid's Marker Light settings.", new AcceptableValueRange(10f, 300f)));
+
const string buffs = "Fenrir - Form Buffs";
BindNote(config, buffs, "Note: these values need a relog to take effect.");
- FullFormSpeedBonus = config.Bind(buffs, "Full Form Speed Bonus", 1.0f,
- new ConfigDescription("Speed multiplier bonus while in Fenring or Cultist form.", new AcceptableValueRange(0f, 3f)));
+ // Each form has a job once all three are unlocked (Lexsonn's suggestion): the Ulv
+ // travels, the Fenring holds the line, the Cultist burns. The speed keys were renamed
+ // from "Full Form Speed Bonus" and "Wolf Form Speed Bonus" so a saved .cfg cannot keep
+ // the old order, where the Fenring outran the Ulv.
+ FullFormSpeedBonus = config.Bind(buffs, "Fenring And Cultist Speed Bonus", 0.5f,
+ new ConfigDescription("Speed multiplier bonus while in Fenring or Cultist form. 0.5 = 50% faster.", new AcceptableValueRange(0f, 3f)));
FullFormJumpBonus = config.Bind(buffs, "Full Form Jump Bonus", 1.0f,
new ConfigDescription("Jump multiplier bonus while in Fenring or Cultist form.", new AcceptableValueRange(0f, 3f)));
FullFormFallDamageReduction = config.Bind(buffs, "Full Form Fall Damage Reduction", 1.0f,
new ConfigDescription("Fall damage reduction while in Fenring or Cultist form (1 = immune).", new AcceptableValueRange(0f, 1f)));
- WolfFormSpeedBonus = config.Bind(buffs, "Wolf Form Speed Bonus", 0.5f,
- new ConfigDescription("Speed multiplier bonus while in Wolf or Ulv form.", new AcceptableValueRange(0f, 3f)));
+ WolfFormSpeedBonus = config.Bind(buffs, "Wolf Speed Bonus", 0.5f,
+ new ConfigDescription("Speed multiplier bonus while in Wolf form, the G form before Moder.", new AcceptableValueRange(0f, 3f)));
+ UlvFormSpeedBonus = config.Bind(buffs, "Ulv Speed Bonus", 1.0f,
+ new ConfigDescription("Speed multiplier bonus while in Ulv form. The fastest form by default: the one to travel in.", new AcceptableValueRange(0f, 3f)));
+ FenringDamageReduction = config.Bind(buffs, "Fenring Damage Reduction", 0.3f,
+ new ConfigDescription("Share of every hit the Fenring shrugs off. 0.3 = 30% less damage taken.", new AcceptableValueRange(0f, 0.9f)));
+ CultistExtraDamageTaken = config.Bind(buffs, "Cultist Extra Damage Taken", 0.25f,
+ new ConfigDescription("How much harder hits land on the Cultist. 0.25 = 25% more damage taken.", new AcceptableValueRange(0f, 2f)));
WolfFormFallDamageReduction = config.Bind(buffs, "Wolf Form Fall Damage Reduction", 0.5f,
new ConfigDescription("Fall damage reduction while in Wolf or Ulv form.", new AcceptableValueRange(0f, 1f)));
FormStaminaRegenMultiplier = config.Bind(buffs, "Stamina Regen Multiplier", 1.3f,
@@ -154,7 +183,7 @@ namespace RacesOfValheim
CultistClawDamage = config.Bind(cultist, "Claw Damage", 85f,
new ConfigDescription("Base damage of the single claw (Left Mouse), before the Unarmed skill bonus.", new AcceptableValueRange(0f, 500f)));
CultistDoubleClawDamage = config.Bind(cultist, "Double Claw Damage", 140f,
- new ConfigDescription("Base damage of the double claw (Middle Mouse), before the Unarmed skill bonus.", new AcceptableValueRange(0f, 500f)));
+ new ConfigDescription("Base damage of the double claw (Middle Mouse), before the Unarmed skill bonus. Each of its two swipes deals 60% of it.", new AcceptableValueRange(0f, 500f)));
CultistAttackRadius = config.Bind(cultist, "Claw Attack Radius", 2.5f,
new ConfigDescription("Hit-sweep radius for both claw attacks.", new AcceptableValueRange(1f, 10f)));
CultistPushForce = config.Bind(cultist, "Claw Push Force", 30f,
@@ -194,6 +223,35 @@ namespace RacesOfValheim
UlvPushForce = config.Bind(ulv, "Push Force", 25f,
new ConfigDescription("Knockback applied on a hit.", new AcceptableValueRange(0f, 100f)));
+ // Form attack stamina, beside each form's damage. Lower than a weapon's on purpose: the
+ // forms pay less per swing and fill the adrenaline bar faster instead (Form Adrenaline
+ // Multiplier). For scale, vanilla fists cost 4, Bjorn claws 6, Fenris claws 10.
+ const string staminaNote = " Base stamina, cut by up to a third with the Unarmed skill as a weapon's is. 0 makes it free.";
+ FormAdrenalineMultiplier = config.Bind(buffs, "Form Adrenaline Multiplier", 1.5f,
+ new ConfigDescription("Adrenaline per form hit, times the bare-handed amount, in any Fenrir form.", new AcceptableValueRange(0f, 5f)));
+ FenringLightClawStamina = config.Bind(fenring, "Light Claw Stamina", 6f,
+ new ConfigDescription("Stamina for the light claw (Left Mouse)." + staminaNote, new AcceptableValueRange(0f, 50f)));
+ FenringHeavyClawStamina = config.Bind(fenring, "Heavy Claw Stamina", 10f,
+ new ConfigDescription("Stamina for the heavy claw (Right Mouse)." + staminaNote, new AcceptableValueRange(0f, 50f)));
+ FenringJumpAttackStamina = config.Bind(fenring, "Jump Attack Stamina", 16f,
+ new ConfigDescription("Stamina for the leaping attack (Middle Mouse)." + staminaNote, new AcceptableValueRange(0f, 50f)));
+ CultistClawStamina = config.Bind(cultist, "Claw Stamina", 6f,
+ new ConfigDescription("Stamina for the single claw (Left Mouse)." + staminaNote, new AcceptableValueRange(0f, 50f)));
+ CultistDoubleClawStamina = config.Bind(cultist, "Double Claw Stamina", 12f,
+ new ConfigDescription("Stamina for the double claw (Middle Mouse)." + staminaNote, new AcceptableValueRange(0f, 50f)));
+ WolfAttack1Stamina = config.Bind(wolf, "Attack 1 Stamina", 4f,
+ new ConfigDescription("Stamina for the Left Mouse attack." + staminaNote, new AcceptableValueRange(0f, 50f)));
+ WolfAttack2Stamina = config.Bind(wolf, "Attack 2 Stamina", 6f,
+ new ConfigDescription("Stamina for the Right Mouse attack." + staminaNote, new AcceptableValueRange(0f, 50f)));
+ WolfAttack3Stamina = config.Bind(wolf, "Attack 3 Stamina", 10f,
+ new ConfigDescription("Stamina for the Middle Mouse attack." + staminaNote, new AcceptableValueRange(0f, 50f)));
+ UlvBiteStamina = config.Bind(ulv, "Bite Stamina", 5f,
+ new ConfigDescription("Stamina for the Left Mouse bite." + staminaNote, new AcceptableValueRange(0f, 50f)));
+ UlvHeavyBiteStamina = config.Bind(ulv, "Heavy Bite Stamina", 8f,
+ new ConfigDescription("Stamina for the Right Mouse bite." + staminaNote, new AcceptableValueRange