Merge pull request 'feat(trenta): add the Trenta race' (#10) from create-trenta-race into main
Reviewed-on: #10
This commit is contained in:
commit
e7860cfcab
14 changed files with 2430 additions and 2 deletions
|
|
@ -54,12 +54,33 @@ namespace RacesOfValheim
|
|||
if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == "Draugh")
|
||||
{
|
||||
string prefabName = monster.gameObject.name.ToLower();
|
||||
if (prefabName.Contains("skeleton") || prefabName.Contains("draugr") ||
|
||||
if (prefabName.Contains("skeleton") || prefabName.Contains("draugr") ||
|
||||
prefabName.Contains("ghost") || prefabName.Contains("wraith"))
|
||||
{
|
||||
__result = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Trenta Race Logic - base passive, live from the start (no progression
|
||||
// gate, unlike Aswid's escalating list above).
|
||||
//
|
||||
// IsEnemy=false is the only lever this patch has, and it produces one
|
||||
// behaviour: the mob never initiates. It reads as two different relationships
|
||||
// only in flavour text - Greyling/Greydwarf/Leech/Deathsquito "don't see" a
|
||||
// Trenta as prey (root-kin, or simply nothing with blood to sense), while
|
||||
// Fuling/Troll "choose" not to fight one - but there is no third state to code
|
||||
// for: vanilla's own damage-response AI already makes any of them retaliate if
|
||||
// the Trenta strikes first, same as it does for Fenrir's wolves above.
|
||||
if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == TrentaConfig.RaceId)
|
||||
{
|
||||
string prefabName = monster.gameObject.name.ToLower();
|
||||
if (prefabName.Contains("greyling") || prefabName.Contains("greydwarf") ||
|
||||
prefabName.Contains("fuling") || prefabName.Contains("troll") ||
|
||||
prefabName.Contains("leech") || prefabName.Contains("deathsquito"))
|
||||
{
|
||||
__result = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,7 +19,8 @@ namespace RacesOfValheim
|
|||
{
|
||||
"Trol",
|
||||
"Furling",
|
||||
DvergarConfig.RaceId
|
||||
DvergarConfig.RaceId,
|
||||
TrentaConfig.RaceId
|
||||
};
|
||||
|
||||
public static bool ManagesOwnScale(string race)
|
||||
|
|
|
|||
|
|
@ -33,12 +33,14 @@ namespace RacesOfValheim
|
|||
gameObject.AddComponent<TrolRace>();
|
||||
gameObject.AddComponent<DraughRace>();
|
||||
gameObject.AddComponent<DvergarRace>();
|
||||
gameObject.AddComponent<TrentaRace>();
|
||||
PrefabManager.OnVanillaPrefabsAvailable += CreateAllModAssets;
|
||||
CommandManager.Instance.AddConsoleCommand(new ResetRaceCommand());
|
||||
CommandManager.Instance.AddConsoleCommand(new CheckProgressionCommand());
|
||||
CommandManager.Instance.AddConsoleCommand(new IncreaseProgressionCommand());
|
||||
CommandManager.Instance.AddConsoleCommand(new ResetProgressionCommand());
|
||||
CommandManager.Instance.AddConsoleCommand(new DumpDvergerCommand());
|
||||
CommandManager.Instance.AddConsoleCommand(new DumpElderCommand());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -76,6 +78,7 @@ namespace RacesOfValheim
|
|||
player.GetSEMan().RemoveStatusEffect("SE_SkadiCooldown".GetStableHashCode());
|
||||
player.GetSEMan().RemoveStatusEffect(DvergarConfig.StatsSE.GetStableHashCode());
|
||||
player.GetSEMan().RemoveStatusEffect(DvergarConfig.OverchargeSE.GetStableHashCode());
|
||||
player.GetSEMan().RemoveStatusEffect(TrentaConfig.StatsSE.GetStableHashCode());
|
||||
|
||||
ZNetView nview = player.GetComponent<ZNetView>();
|
||||
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Human");
|
||||
|
|
@ -98,6 +101,7 @@ namespace RacesOfValheim
|
|||
TrolRace.Instance.CreateModAssets();
|
||||
DraughRace.Instance.CreateModAssets();
|
||||
DvergarRace.Instance.CreateModAssets();
|
||||
TrentaRace.Instance.CreateModAssets();
|
||||
}
|
||||
// --- RACE SELECTION UI ---
|
||||
public void ShowRaceSelectionMenu()
|
||||
|
|
@ -240,6 +244,7 @@ namespace RacesOfValheim
|
|||
|
||||
// Row 3 (y = -140)
|
||||
CreateRaceButtonWithConfirm("Dvergar", new Vector2(-450, -140), GetDvergarIcon(), "Small, stubborn smiths of the deep. Frail of frame, but masters of metal, mine and market.", SelectDvergar);
|
||||
CreateRaceButtonWithConfirm("Trenta", new Vector2(-150, -140), GetTrentaIcon(), "Tree-born folk, kin to root and leaf. Patient and hard to fell.", SelectTrenta);
|
||||
|
||||
GUIManager.BlockInput(true);
|
||||
}
|
||||
|
|
@ -622,6 +627,44 @@ namespace RacesOfValheim
|
|||
return null;
|
||||
}
|
||||
|
||||
private void SelectTrenta()
|
||||
{
|
||||
if (Player.m_localPlayer != null)
|
||||
{
|
||||
Player.m_localPlayer.m_customData["Race"] = TrentaConfig.RaceId;
|
||||
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
|
||||
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", TrentaConfig.RaceId);
|
||||
|
||||
Player.m_localPlayer.GetSEMan().AddStatusEffect(TrentaConfig.StatsSE.GetStableHashCode(), true);
|
||||
|
||||
// No SetSkinColor here: the tint is written onto the material by the UpdateColors
|
||||
// postfix in TrentaPatches, which keys off the race and so needs nothing saved.
|
||||
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
|
||||
if (visEq != null)
|
||||
{
|
||||
visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
|
||||
}
|
||||
|
||||
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Trenta.");
|
||||
CloseRaceSelectionMenu();
|
||||
}
|
||||
}
|
||||
|
||||
private Sprite GetTrentaIcon()
|
||||
{
|
||||
GameObject prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyGreydwarfBrute")?.gameObject;
|
||||
if (prefab == null) prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("Wood")?.gameObject;
|
||||
if (prefab != null)
|
||||
{
|
||||
ItemDrop drop = prefab.GetComponent<ItemDrop>();
|
||||
if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0)
|
||||
{
|
||||
return drop.m_itemData.m_shared.m_icons[0];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void CloseRaceSelectionMenu()
|
||||
{
|
||||
if (raceSelectionMenu != null)
|
||||
|
|
@ -872,6 +915,152 @@ namespace RacesOfValheim
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// [DEBUG] Built for Muspell (Trenta/Fader): dumps everything about "gd_king" (The Elder) that
|
||||
/// Mono.Cecil cannot see, since that only reveals field/method *names*, never the actual
|
||||
/// values baked into the prefab asset. Three things a transformation ability needs and can
|
||||
/// only get from a live prefab reference:
|
||||
/// - the full hierarchy (same as DumpDvergerCommand), to see whether "Visual" actually
|
||||
/// carries the Animator our clone needs, or whether it lives somewhere else;
|
||||
/// - every Animator's real parameter list, since a wrong trigger name passed to
|
||||
/// Animator.SetTrigger doesn't throw or warn, it just silently does nothing;
|
||||
/// - the real attack animation trigger names, read directly off Humanoid.m_defaultItems'
|
||||
/// weapon SharedData (confirmed via IL that Attack.Start feeds m_attackAnimation straight
|
||||
/// into ZSyncAnimation.SetTrigger, so this is the actual string The Elder itself uses,
|
||||
/// not a guess).
|
||||
/// None of this instantiates the prefab, so nothing here can trigger its AI/Awake logic.
|
||||
/// </summary>
|
||||
public class DumpElderCommand : ConsoleCommand
|
||||
{
|
||||
public override string Name => "dumpelder";
|
||||
public override string Help => "[DEBUG] Logs The Elder's hierarchy, Animator parameters and real attack animation names";
|
||||
|
||||
public override void Run(string[] args)
|
||||
{
|
||||
string prefabName = args.Length > 0 ? args[0] : TrentaConfig.MuspellFormPrefab;
|
||||
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
|
||||
if (prefab == null)
|
||||
{
|
||||
Console.instance.Print($"Prefab '{prefabName}' not found.");
|
||||
return;
|
||||
}
|
||||
|
||||
Jotunn.Logger.LogInfo($"=== {prefabName} HIERARCHY ===");
|
||||
DumpTransform(prefab.transform, "");
|
||||
|
||||
Jotunn.Logger.LogInfo($"=== {prefabName} ANIMATORS ===");
|
||||
bool anyAnimator = false;
|
||||
foreach (Animator animator in prefab.GetComponentsInChildren<Animator>(true))
|
||||
{
|
||||
anyAnimator = true;
|
||||
Jotunn.Logger.LogInfo($" Animator on '{GetPath(animator.transform)}' controller='{(animator.runtimeAnimatorController != null ? animator.runtimeAnimatorController.name : "null")}'");
|
||||
if (animator.runtimeAnimatorController == null) continue;
|
||||
|
||||
foreach (AnimatorControllerParameter param in animator.parameters)
|
||||
{
|
||||
Jotunn.Logger.LogInfo($" param: {param.name} ({param.type})");
|
||||
}
|
||||
}
|
||||
if (!anyAnimator) Jotunn.Logger.LogInfo(" (no Animator found anywhere in the hierarchy)");
|
||||
|
||||
Jotunn.Logger.LogInfo($"=== {prefabName} ATTACKS (from Humanoid.m_defaultItems) ===");
|
||||
Humanoid humanoid = prefab.GetComponent<Humanoid>();
|
||||
if (humanoid == null)
|
||||
{
|
||||
Jotunn.Logger.LogInfo(" (no Humanoid component on the prefab root)");
|
||||
}
|
||||
else
|
||||
{
|
||||
GameObject[] defaultItems = Traverse.Create(humanoid).Field<GameObject[]>("m_defaultItems").Value;
|
||||
if (defaultItems == null || defaultItems.Length == 0)
|
||||
{
|
||||
Jotunn.Logger.LogInfo(" (m_defaultItems is empty)");
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (GameObject itemPrefab in defaultItems)
|
||||
{
|
||||
if (itemPrefab == null) continue;
|
||||
DumpWeaponAttacks(itemPrefab);
|
||||
}
|
||||
}
|
||||
|
||||
ItemDrop unarmed = Traverse.Create(humanoid).Field<ItemDrop>("m_unarmedWeapon").Value;
|
||||
if (unarmed != null) DumpWeaponAttacks(unarmed.gameObject);
|
||||
}
|
||||
|
||||
Console.instance.Print($"Dumped '{prefabName}' to the BepInEx log.");
|
||||
}
|
||||
|
||||
private static void DumpWeaponAttacks(GameObject itemPrefab)
|
||||
{
|
||||
ItemDrop drop = itemPrefab.GetComponent<ItemDrop>();
|
||||
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return;
|
||||
|
||||
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
|
||||
Jotunn.Logger.LogInfo($" weapon '{itemPrefab.name}' ({shared.m_name}): damages={DumpDamageTypes(shared.m_damages)}");
|
||||
DumpAttack("primary", shared.m_attack);
|
||||
DumpAttack("secondary", shared.m_secondaryAttack);
|
||||
}
|
||||
|
||||
private static void DumpAttack(string label, Attack attack)
|
||||
{
|
||||
if (attack == null) return;
|
||||
Jotunn.Logger.LogInfo(
|
||||
$" {label}: animation='{attack.m_attackAnimation}' randomAnimations={attack.m_attackRandomAnimations} " +
|
||||
$"chainLevels={attack.m_attackChainLevels} damageMultiplier={attack.m_damageMultiplier} " +
|
||||
$"type={attack.m_attackType} range={attack.m_attackRange} angle={attack.m_attackAngle} " +
|
||||
$"spawnOnTrigger='{(attack.m_spawnOnTrigger != null ? attack.m_spawnOnTrigger.name : "none")}' " +
|
||||
$"projectile='{(attack.m_attackProjectile != null ? attack.m_attackProjectile.name : "none")}'");
|
||||
|
||||
if (attack.m_attackProjectile != null)
|
||||
{
|
||||
Projectile proj = attack.m_attackProjectile.GetComponent<Projectile>();
|
||||
if (proj == null) proj = attack.m_attackProjectile.GetComponentInChildren<Projectile>(true);
|
||||
if (proj != null)
|
||||
{
|
||||
Jotunn.Logger.LogInfo($" projectile '{attack.m_attackProjectile.name}' damage={DumpDamageTypes(proj.m_damage)} aoe={proj.m_aoe}");
|
||||
}
|
||||
else
|
||||
{
|
||||
Jotunn.Logger.LogInfo($" projectile '{attack.m_attackProjectile.name}' has no Projectile component");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string DumpDamageTypes(HitData.DamageTypes d)
|
||||
{
|
||||
if (d == null) return "none";
|
||||
return $"blunt={d.m_blunt} slash={d.m_slash} pierce={d.m_pierce} chop={d.m_chop} pickaxe={d.m_pickaxe} " +
|
||||
$"fire={d.m_fire} frost={d.m_frost} lightning={d.m_lightning} poison={d.m_poison} spirit={d.m_spirit}";
|
||||
}
|
||||
|
||||
private static void DumpTransform(Transform t, string indent)
|
||||
{
|
||||
if (t == null) return;
|
||||
|
||||
System.Text.StringBuilder components = new System.Text.StringBuilder();
|
||||
foreach (Component c in t.GetComponents<Component>())
|
||||
{
|
||||
if (c != null) components.Append(c.GetType().Name).Append(" ");
|
||||
}
|
||||
|
||||
Jotunn.Logger.LogInfo($"{indent}{t.name} [{components}]");
|
||||
for (int i = 0; i < t.childCount; i++) DumpTransform(t.GetChild(i), indent + " ");
|
||||
}
|
||||
|
||||
private static string GetPath(Transform t)
|
||||
{
|
||||
string path = t.name;
|
||||
while (t.parent != null)
|
||||
{
|
||||
t = t.parent;
|
||||
path = t.name + "/" + path;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
public class ResetProgressionCommand : ConsoleCommand
|
||||
{
|
||||
public override string Name => "resetprogression";
|
||||
|
|
|
|||
328
JotunnModStub/Trenta/TrentaAbilities.cs
Normal file
328
JotunnModStub/Trenta/TrentaAbilities.cs
Normal file
|
|
@ -0,0 +1,328 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using HarmonyLib;
|
||||
using Jotunn.Managers;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// The Trenta's active abilities, driven from TrentaRace.Update. Each one reads its cost,
|
||||
/// radius, duration and cooldown out of TrentaConfig.
|
||||
/// </summary>
|
||||
public static class TrentaAbilities
|
||||
{
|
||||
public static void Tick(Player player, int state)
|
||||
{
|
||||
// Photosynthesis is a passive trigger, not a keypress, so it runs unconditionally -
|
||||
// unlike the keybound abilities below it is not gated on RaceInput.Allowed. Standing
|
||||
// still with an inventory screen open is still standing still.
|
||||
TickPhotosynthesis(player, state);
|
||||
|
||||
// Ability input is gated exactly like every other race's: RaceInput mirrors
|
||||
// Player.TakeInput, so nothing fires while a map, chest or chat window has focus.
|
||||
if (!RaceInput.Allowed) return;
|
||||
|
||||
if (state >= TrentaConfig.PurpleRainUnlockState && Input.GetKeyDown(TrentaConfig.PurpleRainKey))
|
||||
{
|
||||
TryPurpleRain(player);
|
||||
}
|
||||
|
||||
if (state >= TrentaConfig.PortalUnlockState && Input.GetKeyDown(TrentaConfig.PortalKey))
|
||||
{
|
||||
TryOpenPortal(player);
|
||||
}
|
||||
|
||||
if (state >= TrentaConfig.MuspellUnlockState && Input.GetKeyDown(TrentaConfig.MuspellKey))
|
||||
{
|
||||
TrentaMuspell.Toggle(player);
|
||||
}
|
||||
|
||||
// TODO: any further keybound perks, one `if (... && Input.GetKeyDown(...))` each.
|
||||
}
|
||||
|
||||
// ─── Hornet's Nest ──────────────────────────────────────────────────
|
||||
|
||||
private static GameObject hornetSwarm;
|
||||
|
||||
/// <summary>
|
||||
/// Called unconditionally from TrentaRace.Update, not from Tick above - a permanent
|
||||
/// companion has to be torn down the moment it should stop existing (race change, tier
|
||||
/// drop, death), and Tick only ever runs while the local player still qualifies as a
|
||||
/// Queen-tier Trenta, which is exactly the case this needs to catch.
|
||||
/// </summary>
|
||||
public static void TickHornetsNest(Player player, bool shouldExist)
|
||||
{
|
||||
if (shouldExist && hornetSwarm == null)
|
||||
{
|
||||
hornetSwarm = TrentaHornetSwarm.Spawn(player);
|
||||
}
|
||||
else if (!shouldExist && hornetSwarm != null)
|
||||
{
|
||||
Object.Destroy(hornetSwarm);
|
||||
hornetSwarm = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Photosynthesis ──────────────────────────────────────────────────
|
||||
|
||||
// Seconds of unbroken stillness accumulated so far, and the state of the heal-over-time
|
||||
// window once a grant has fired. Static because only ever ticked for the local player.
|
||||
private static float stillTimer = 0f;
|
||||
private static bool healPhaseActive = false;
|
||||
private static float healPhaseTimer = 0f;
|
||||
private static int healTicksApplied = 0;
|
||||
|
||||
/// <summary>
|
||||
/// Daylight, out from under a roof, ten unbroken seconds of standing still: the Trenta
|
||||
/// gets a Rested buff (Player.SetSleeping's own duration-less grant, given a duration here
|
||||
/// instead - see the long comment on Trenta_Player_EatFood_Patch-adjacent code style,
|
||||
/// mirrors DvergarStatusEffects.ApplyCooldownIcon exactly) plus 10% of max health healed
|
||||
/// once a second for 8 seconds.
|
||||
///
|
||||
/// Movement cancels whichever phase is running, on the spot, with no partial credit -
|
||||
/// including movement from being knocked back by an attack, since this only ever looks at
|
||||
/// whether the character actually moved, never at why. A hit that does not move the Trenta
|
||||
/// does not touch either phase.
|
||||
/// </summary>
|
||||
private static void TickPhotosynthesis(Player player, int state)
|
||||
{
|
||||
bool moving = player.GetVelocity().magnitude > TrentaConfig.PhotosynthesisVelocityEpsilon;
|
||||
|
||||
if (healPhaseActive)
|
||||
{
|
||||
if (moving)
|
||||
{
|
||||
healPhaseActive = false;
|
||||
healPhaseTimer = 0f;
|
||||
healTicksApplied = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
healPhaseTimer += Time.deltaTime;
|
||||
int targetTicks = Mathf.Min(Mathf.FloorToInt(healPhaseTimer), TrentaConfig.PhotosynthesisHealSeconds);
|
||||
while (healTicksApplied < targetTicks)
|
||||
{
|
||||
player.Heal(player.GetMaxHealth() * TrentaConfig.PhotosynthesisHealPercentPerSecond, true);
|
||||
healTicksApplied++;
|
||||
}
|
||||
|
||||
if (healTicksApplied >= TrentaConfig.PhotosynthesisHealSeconds)
|
||||
{
|
||||
healPhaseActive = false;
|
||||
healPhaseTimer = 0f;
|
||||
healTicksApplied = 0;
|
||||
}
|
||||
|
||||
return; // A new stillness channel cannot start while a grant is still healing
|
||||
}
|
||||
|
||||
bool eligible = EnvMan.instance != null && EnvMan.IsDay() &&
|
||||
!Traverse.Create(player).Field<bool>("m_underRoof").Value;
|
||||
|
||||
if (!eligible || moving)
|
||||
{
|
||||
stillTimer = 0f;
|
||||
return;
|
||||
}
|
||||
|
||||
stillTimer += Time.deltaTime;
|
||||
if (stillTimer < TrentaConfig.PhotosynthesisStillnessSeconds) return;
|
||||
|
||||
stillTimer = 0f;
|
||||
|
||||
float restMinutes = TrentaConfig.PhotosynthesisRestBaseMinutes +
|
||||
TrentaConfig.PhotosynthesisRestMinutesPerBoss * (state - BossProgressionManager.MinState);
|
||||
|
||||
SEMan seman = player.GetSEMan();
|
||||
seman.AddStatusEffect(SEMan.s_statusEffectRested, true);
|
||||
StatusEffect rested = seman.GetStatusEffect(SEMan.s_statusEffectRested);
|
||||
if (rested != null) rested.m_ttl = restMinutes * 60f;
|
||||
|
||||
healPhaseActive = true;
|
||||
healPhaseTimer = 0f;
|
||||
healTicksApplied = 0;
|
||||
}
|
||||
|
||||
// ─── Purple Rain ─────────────────────────────────────────────────────
|
||||
|
||||
private static float lastPurpleRainTime = -1000f;
|
||||
private static Material cachedVfxMaterial;
|
||||
private static bool vfxMaterialResolved;
|
||||
|
||||
/// <summary>
|
||||
/// A burst of toxic-purple pollen centred on the Trenta: heals everything that isn't its
|
||||
/// enemy, poisons everything that is. "Ally" and "enemy" are read straight off
|
||||
/// BaseAI.IsEnemy - the same check RaceHostilityManager's Trenta block feeds - so this
|
||||
/// automatically covers players, tamed companions and the neutral Greyling/Greydwarf/
|
||||
/// Fuling/Troll/Leech/Deathsquito list without a second, separate species list to keep in
|
||||
/// sync with the first one.
|
||||
/// </summary>
|
||||
private static void TryPurpleRain(Player player)
|
||||
{
|
||||
// Muspell (state 8) shortens Purple Rain's own cooldown while transformed - read here
|
||||
// rather than baked into PurpleRainCooldown, since the normal-form value still applies
|
||||
// the instant the player reverts.
|
||||
float cooldown = TrentaMuspell.IsTransformed ? TrentaConfig.MuspellPurpleRainCooldown : TrentaConfig.PurpleRainCooldown;
|
||||
if (Time.time - lastPurpleRainTime < cooldown) return;
|
||||
|
||||
lastPurpleRainTime = Time.time;
|
||||
TrentaStatusEffects.ApplyCooldownIcon(TrentaConfig.PurpleRainCdSE, cooldown);
|
||||
|
||||
// While transformed, The Elder's own root-summon gesture plays on the transformation
|
||||
// clone's Animator instead - TryPlayRootSummonAnimation returns false (and does
|
||||
// nothing) when not transformed, so the normal staff_summon path below still covers
|
||||
// every other case unchanged.
|
||||
if (!TrentaMuspell.TryPlayRootSummonAnimation())
|
||||
{
|
||||
var zanim = Traverse.Create(player).Field("m_zanim").GetValue<ZSyncAnimation>();
|
||||
if (zanim != null)
|
||||
{
|
||||
// "galdr_cast" was never real, and "gpower" turned out to read as the vanilla
|
||||
// Guardian Power raise (Forsaken Power), not a staff cast - both dead ends, now
|
||||
// documented so nobody re-walks them. "staff_summon" is the Dead Raiser's own
|
||||
// attack animation, the actual "raise the staff and call something forth" clip -
|
||||
// confirmed against WeaponsAttackAnimationManager's own dump of vanilla weapon
|
||||
// attack animations, since it is weapon data rather than anything hard-coded in
|
||||
// the assembly's IL the way "gpower" is. Unlike gpower it is not expected to carry
|
||||
// a baked side effect (per-weapon attack clips resolve their game logic through
|
||||
// Humanoid.StartAttack, not through Animation Events on the clip), so no suppress
|
||||
// call before it - flag it if this instead spawns a real skeleton ally.
|
||||
zanim.SetTrigger("staff_summon");
|
||||
}
|
||||
}
|
||||
|
||||
SpawnPurpleRainVfx(player);
|
||||
|
||||
HashSet<Character> hit = new HashSet<Character>();
|
||||
foreach (Collider collider in Physics.OverlapSphere(player.transform.position, TrentaConfig.PurpleRainRadius))
|
||||
{
|
||||
if (collider == null) continue;
|
||||
|
||||
Character character = collider.GetComponentInParent<Character>();
|
||||
if (character == null || character == player || character.IsDead() || !hit.Add(character)) continue;
|
||||
|
||||
if (BaseAI.IsEnemy(player, character))
|
||||
{
|
||||
HitData hitData = new HitData();
|
||||
hitData.m_damage.m_poison = TrentaConfig.PurpleRainPoisonDamage;
|
||||
hitData.SetAttacker(player);
|
||||
hitData.m_dir = Vector3.zero;
|
||||
character.Damage(hitData);
|
||||
}
|
||||
else
|
||||
{
|
||||
character.Heal(TrentaConfig.PurpleRainHealAmount, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the rain burst from scratch - mirrors SkeletonRace.EnsureFireAuraVFX, which
|
||||
/// borrows only a *material* off an existing prefab and drives everything else (shape,
|
||||
/// emission, gradient) itself, rather than cloning a specific child particle system
|
||||
/// wholesale. The clone-a-child approach tried first came up empty: whatever the Shaman's
|
||||
/// actual spit VFX is, it is not a particle system living permanently on its model (most
|
||||
/// likely a separate projectile prefab spawned by its attack code instead), so there was
|
||||
/// nothing there to find. Borrowing just the material sidesteps needing to know that at
|
||||
/// all - it fails safe to Unity's default particle material if even that comes up empty,
|
||||
/// so this always renders *something*.
|
||||
/// </summary>
|
||||
private static void SpawnPurpleRainVfx(Player player)
|
||||
{
|
||||
if (!vfxMaterialResolved)
|
||||
{
|
||||
vfxMaterialResolved = true;
|
||||
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(TrentaConfig.PurpleRainVfxSourcePrefab)
|
||||
?? PrefabManager.Cache.GetPrefab<GameObject>("vfx_smoke");
|
||||
if (source != null)
|
||||
{
|
||||
ParticleSystemRenderer sourceRenderer = source.GetComponentInChildren<ParticleSystemRenderer>(true);
|
||||
if (sourceRenderer != null) cachedVfxMaterial = sourceRenderer.material;
|
||||
}
|
||||
}
|
||||
|
||||
GameObject vfx = new GameObject("TrentaPurpleRainVFX");
|
||||
vfx.transform.SetParent(player.transform, false);
|
||||
vfx.transform.localPosition = new Vector3(0, 3f, 0);
|
||||
|
||||
ParticleSystem ps = vfx.AddComponent<ParticleSystem>();
|
||||
var main = ps.main;
|
||||
main.loop = false;
|
||||
main.duration = 1.2f;
|
||||
main.startLifetime = new ParticleSystem.MinMaxCurve(1.5f, 2.5f);
|
||||
main.startSpeed = new ParticleSystem.MinMaxCurve(0.5f, 1.5f);
|
||||
main.startSize = new ParticleSystem.MinMaxCurve(0.03f, 0.09f); // cherry-sized, not watermelon-sized
|
||||
main.gravityModifier = 1.2f; // falls like rain rather than hanging in the air
|
||||
main.simulationSpace = ParticleSystemSimulationSpace.World;
|
||||
main.maxParticles = 400;
|
||||
|
||||
var emission = ps.emission;
|
||||
emission.rateOverTime = 250f;
|
||||
|
||||
var shape = ps.shape;
|
||||
shape.shapeType = ParticleSystemShapeType.Sphere;
|
||||
shape.radius = TrentaConfig.PurpleRainRadius * 0.6f;
|
||||
|
||||
ParticleSystemRenderer renderer = ps.GetComponent<ParticleSystemRenderer>();
|
||||
if (cachedVfxMaterial != null) renderer.material = cachedVfxMaterial;
|
||||
|
||||
var colorOverLifetime = ps.colorOverLifetime;
|
||||
colorOverLifetime.enabled = true;
|
||||
Gradient grad = new Gradient();
|
||||
grad.SetKeys(
|
||||
new GradientColorKey[] { new GradientColorKey(TrentaConfig.PurpleRainVfxColor, 0f), new GradientColorKey(TrentaConfig.PurpleRainVfxColor, 1f) },
|
||||
new GradientAlphaKey[] { new GradientAlphaKey(0f, 0f), new GradientAlphaKey(0.85f, 0.2f), new GradientAlphaKey(0.85f, 0.7f), new GradientAlphaKey(0f, 1f) }
|
||||
);
|
||||
colorOverLifetime.color = grad;
|
||||
|
||||
ps.Play();
|
||||
|
||||
if (TrentaRace.Instance != null)
|
||||
{
|
||||
TrentaRace.Instance.StartCoroutine(DestroyAfter(vfx, 4f));
|
||||
}
|
||||
else
|
||||
{
|
||||
Object.Destroy(vfx, 4f);
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerator DestroyAfter(GameObject obj, float seconds)
|
||||
{
|
||||
yield return new WaitForSeconds(seconds);
|
||||
if (obj != null) Object.Destroy(obj);
|
||||
}
|
||||
|
||||
// ─── Homecoming Portal ──────────────────────────────────────────────
|
||||
|
||||
private static float lastPortalTime = -100000f;
|
||||
|
||||
/// <summary>
|
||||
/// Opens a linked portal pair (TrentaPortal.Open does the actual spawning): one where the
|
||||
/// Trenta is standing, one at their respawn point - a custom spawn point if they have set
|
||||
/// one by sleeping in a bed, otherwise the world's starting temple, exactly mirroring the
|
||||
/// choice vanilla respawn itself makes.
|
||||
/// </summary>
|
||||
private static void TryOpenPortal(Player player)
|
||||
{
|
||||
if (Time.time - lastPortalTime < TrentaConfig.PortalCooldown) return;
|
||||
|
||||
PlayerProfile profile = Game.instance != null ? Game.instance.GetPlayerProfile() : null;
|
||||
if (profile == null) return;
|
||||
|
||||
// m_originalSpawnPoint is static on PlayerProfile - one starting temple per world,
|
||||
// not per profile - unlike everything else read off profile here.
|
||||
Vector3 homePoint = profile.HaveCustomSpawnPoint() ? profile.GetCustomSpawnPoint() : PlayerProfile.m_originalSpawnPoint;
|
||||
|
||||
lastPortalTime = Time.time;
|
||||
TrentaStatusEffects.ApplyCooldownIcon(TrentaConfig.PortalCdSE, TrentaConfig.PortalCooldown);
|
||||
|
||||
var zanim = Traverse.Create(player).Field("m_zanim").GetValue<ZSyncAnimation>();
|
||||
if (zanim != null) zanim.SetTrigger("staff_summon"); // same cast as Purple Rain - see its comment for why
|
||||
|
||||
Vector3 castPoint = player.transform.position + player.transform.forward * TrentaConfig.PortalSpawnDistance;
|
||||
TrentaPortal.Open(player, castPoint, homePoint);
|
||||
}
|
||||
}
|
||||
}
|
||||
378
JotunnModStub/Trenta/TrentaConfig.cs
Normal file
378
JotunnModStub/Trenta/TrentaConfig.cs
Normal file
|
|
@ -0,0 +1,378 @@
|
|||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// Every tunable number the Trenta uses, in one place.
|
||||
///
|
||||
/// Same arrangement as DvergarConfig: TrentaProgression reads these to build its per-tier
|
||||
/// rules and the patches read the rules, never a literal. Retuning the race means editing
|
||||
/// this file only.
|
||||
///
|
||||
/// Nothing here is final - the values are placeholders so the race compiles and runs while
|
||||
/// the design is still open.
|
||||
/// </summary>
|
||||
public static class TrentaConfig
|
||||
{
|
||||
// ─── Identity ────────────────────────────────────────────────────────
|
||||
// Anagram of "Treant": the Trenta are the tree-born.
|
||||
//
|
||||
// This is the value stored in m_customData["Race"] and in the ZDO, so renaming it after
|
||||
// players have chosen the race would orphan their characters. Decide it now.
|
||||
public const string RaceId = "Trenta";
|
||||
|
||||
public const string StatsSE = "SE_TrentaStats";
|
||||
|
||||
// Mirrors the ZDO key layout the other races use, so remote clients can read the tier
|
||||
// without having the local player's progression state.
|
||||
public const string StateZdoKey = "RacesOfValheim_TrentaState";
|
||||
|
||||
// Title of the compendium entry, once RaceCompendium learns about the race.
|
||||
public const string CompendiumTitle = "Trenta Secrets";
|
||||
|
||||
// ─── Model ───────────────────────────────────────────────────────────
|
||||
// Applied to the player's "Visual" child rather than the root transform, the way Furling
|
||||
// and Dvergar do it: scaling the root would drag the collider and camera pivot along.
|
||||
//
|
||||
// Tuning knobs are static readonly rather than const throughout: a const folds at compile
|
||||
// time, which turns "is this perk switched off?" guards into dead code the moment a knob
|
||||
// is set to zero.
|
||||
public static readonly float VisualScale = 1f; // TODO: taller than a human?
|
||||
|
||||
// ─── Skin ────────────────────────────────────────────────────────────
|
||||
// Written straight onto the body material's _SkinColor by an UpdateColors postfix, which
|
||||
// is the only thing that actually tints a player.
|
||||
//
|
||||
// This is a multiplier over the human skin texture, not a replacement, so a value near
|
||||
// (1,1,1) changes nothing anyone can see. Every race that reads clearly commits to a
|
||||
// channel - Trol (0.1, 0.6, 0.7), Furling (0.3, 0.8, 0.3) - so the Trenta does too:
|
||||
// the pale green of a young leaf for skin, dark foliage green for hair and beard.
|
||||
public static readonly Color SkinColor = new Color(0.55f, 0.85f, 0.35f, 1f);
|
||||
|
||||
public static readonly Color HairColor = new Color(0.06f, 0.28f, 0.08f, 1f);
|
||||
|
||||
// ─── Progression tables ──────────────────────────────────────────────
|
||||
// Indexed by progression state; index 0 is unused so the state number indexes directly.
|
||||
// 1 Base, 2 Eikthyr, 3 The Elder, 4 Bonemass, 5 Moder, 6 Yagluth, 7 The Queen, 8 Fader.
|
||||
public static readonly float[] HealthBonusByState =
|
||||
{
|
||||
0f, // (unused)
|
||||
0f, // 1 Base TODO
|
||||
0f, // 2 Eikthyr TODO
|
||||
0f, // 3 The Elder TODO
|
||||
0f, // 4 Bonemass TODO
|
||||
0f, // 5 Moder TODO
|
||||
0f, // 6 Yagluth TODO
|
||||
0f, // 7 The Queen TODO
|
||||
0f // 8 Fader TODO
|
||||
};
|
||||
|
||||
// ─── Photosynthesis ──────────────────────────────────────────────────
|
||||
// Base passive, live from state 1: stand motionless in daylight, out from under a roof,
|
||||
// and the Trenta puts down roots. TrentaAbilities.TickPhotosynthesis reads every number
|
||||
// below; nothing is hard-coded in the patch itself.
|
||||
public const float PhotosynthesisStillnessSeconds = 10f; // channel time before it fires
|
||||
public const int PhotosynthesisHealSeconds = 8; // number of 1-second heal ticks
|
||||
public const float PhotosynthesisHealPercentPerSecond = 0.10f; // % of max health per tick
|
||||
public const float PhotosynthesisRestBaseMinutes = 5f; // Rested duration at Base
|
||||
public const float PhotosynthesisRestMinutesPerBoss = 1f; // + this, per boss defeated
|
||||
|
||||
// Character.GetVelocity() never reads exactly zero even standing still - a bit of
|
||||
// physics jitter is normal. Below this, the Trenta counts as motionless.
|
||||
public const float PhotosynthesisVelocityEpsilon = 0.01f;
|
||||
|
||||
// ─── Purple Rain (The Elder) ─────────────────────────────────────────
|
||||
// A spray of toxic-purple pollen: heals everything the Trenta doesn't fight, poisons
|
||||
// everything that fights the Trenta. "Ally" is deliberately not a hardcoded species list -
|
||||
// TrentaAbilities checks the same BaseAI.IsEnemy the mod's own hostility rules use, so it
|
||||
// lines up with RaceHostilityManager's Trenta block (Greyling/Greydwarf/Fuling/Troll/
|
||||
// Leech/Deathsquito) and with every tamed companion and teammate, for free.
|
||||
public const int PurpleRainUnlockState = 3; // The Elder dead
|
||||
public const KeyCode PurpleRainKey = KeyCode.G;
|
||||
|
||||
public const float PurpleRainCooldown = 20f;
|
||||
public const float PurpleRainRadius = 8f; // TODO: tune
|
||||
public const float PurpleRainHealAmount = 40f; // TODO: tune - flat heal per ally hit
|
||||
public const float PurpleRainPoisonDamage = 40f; // TODO: tune - a Poison-type hit; vanilla's
|
||||
// own poison-on-hit handling takes over
|
||||
// from there, same as SkeletonRace's fire
|
||||
// aura just deals Fire damage and lets
|
||||
// the burn status follow from that.
|
||||
|
||||
public const string PurpleRainCdSE = "SE_TrentaPurpleRainCooldown";
|
||||
|
||||
// Source of the spray particle system Purple Rain clones and retints. "Greydwarf_Shaman"
|
||||
// is the same prefab name AswidRace's own raw-food mapping already keys off, so it is
|
||||
// known-correct rather than guessed.
|
||||
public const string PurpleRainVfxSourcePrefab = "Greydwarf_Shaman";
|
||||
public static readonly Color PurpleRainVfxColor = new Color(0.55f, 0.1f, 0.85f, 1f); // toxic purple
|
||||
|
||||
// ─── Bonemass passives ───────────────────────────────────────────────
|
||||
// Three flat unlocks, all live from the same boss kill: swimming costs no stamina, and
|
||||
// Poison and Wet can no longer touch a Trenta. A body that runs on sunlight and rain
|
||||
// rather than blood has nothing left for the swamp to spoil.
|
||||
public const int BonemassDefeatedState = 4;
|
||||
|
||||
// ─── Moder passives ──────────────────────────────────────────────────
|
||||
public const int ModerDefeatedState = 5;
|
||||
|
||||
// Last Stand: always-on armor bonus that scales with health already lost, so it does
|
||||
// nothing at full health and its most at the edge of death. SE_TrentaStats.ModifyArmorMods
|
||||
// reads this every time armor is computed - there is no timer or trigger to it.
|
||||
public const float LastStandMaxArmorBonus = 0.5f; // +50% armor at ~0 health remaining
|
||||
|
||||
// Thorns: reflects this fraction of every hit taken back at whoever landed it.
|
||||
// Trenta_Character_Damage_Thorns_Patch reads it fresh on every hit - no timer, no charge,
|
||||
// no cooldown, it just always applies. Replaces Camouflage, which never worked reliably.
|
||||
public const float ThornsReflectPercent = 0.2f;
|
||||
|
||||
// ─── Homecoming Portal (Yagluth) ─────────────────────────────────────
|
||||
// Opens a linked pair of portals - one where the Trenta is standing, one at their
|
||||
// respawn point - for everyone to walk through, no item-carry restriction, for 30
|
||||
// seconds. The visual is deliberately just the swirl, not the vanilla wooden frame -
|
||||
// "solo la componente VFX del portale normale" - and the teleport itself is entirely
|
||||
// custom (TrentaPortal.cs), not a re-skinned vanilla TeleportWorld, which is exactly why
|
||||
// it can skip the raw-ore restriction the real thing carries.
|
||||
public const int PortalUnlockState = 6; // Yagluth dead
|
||||
public const KeyCode PortalKey = KeyCode.H;
|
||||
|
||||
public const float PortalCooldown = 300f; // 5 minutes
|
||||
public const float PortalLifetime = 30f;
|
||||
public const float PortalSpawnDistance = 2f; // meters in front of the player, where it opens
|
||||
|
||||
// Source of the swirl visual the portal clones and retints. "portal_wood" is the
|
||||
// confirmed internal ID of the vanilla portal piece (verified against a live source
|
||||
// rather than guessed, the same standard as every other prefab name in this file).
|
||||
public const string PortalVfxSourcePrefab = "portal_wood";
|
||||
public static readonly Color PortalVfxColor = new Color(0.55f, 0.1f, 0.85f, 1f); // same toxic purple as Purple Rain
|
||||
|
||||
public const string PortalCdSE = "SE_TrentaPortalCooldown";
|
||||
|
||||
// ─── Hornet's Nest (The Queen) ───────────────────────────────────────
|
||||
// A permanent, passive companion rather than a keybound ability: once the Queen is dead
|
||||
// it simply exists, hovering on the Trenta, and stays until the state that granted it no
|
||||
// longer holds. TrentaRace.Update ticks its lifecycle unconditionally (not gated behind
|
||||
// the usual "still Trenta" early return) so it is torn down the instant a race change,
|
||||
// a drop in tier or death would otherwise leave it orphaned with nothing left to update it.
|
||||
public const int HornetsNestUnlockState = 7; // The Queen dead
|
||||
|
||||
// Matches the wild Bee Nest's own sting - 10 poison damage every 4 seconds - rather than
|
||||
// an invented number, on the read that "as if constantly stung by bees" means using the
|
||||
// real thing's own numbers. Not found as a tunable field on the Beehive class itself
|
||||
// (probably scene data on the wild instance, not code), so this one rests on the wiki's
|
||||
// account of live behaviour rather than the assembly's own IL the way most numbers in
|
||||
// this file do - flag it if it reads as too strong or too weak once tried.
|
||||
public const float HornetsNestDamagePerTick = 10f;
|
||||
public const float HornetsNestTickInterval = 4f;
|
||||
|
||||
public const float HornetsNestEngageRadius = 6f; // TODO: tune - how close a foe has to get
|
||||
public const float HornetsNestFollowSpeed = 8f; // TODO: tune
|
||||
public const float HornetsNestOrbitRadius = 0.6f; // how tightly it hugs the Trenta at rest
|
||||
public const float HornetsNestAttackHeight = 1.5f; // hovers this high over a target it is stinging - the "from above" for the pierce half of each tick
|
||||
|
||||
// The flies only, not the smoke or the drip, off the same "Draugr" prefab
|
||||
// DraughRace.EnsureVFX already reads for its own aura - same source, same filtering rule,
|
||||
// just discarding the two effects Draugh keeps instead of the one it discards.
|
||||
public const string HornetsNestFliesSourcePrefab = "Draugr";
|
||||
|
||||
// Source of the buzz: the ambient bee-swarm effect a placed Beehive plays, read for its
|
||||
// AudioClip only - never instantiated, so nothing about how it looks ever enters this
|
||||
// ability, matching "la sua unica componente visiva sarà le mosche" literally.
|
||||
public const string HornetsNestBeehivePrefab = "Beehive";
|
||||
|
||||
// ─── Muspell (Fader) ─────────────────────────────────────────────────
|
||||
// A toggled transformation, the same shape as FenrirRace's own G/H/J forms: press J to
|
||||
// become a half-size The Elder, press J again to revert. The permanent-fire half of the
|
||||
// original design (Burning VFX + ignite-on-hit) was tried and dropped - the flame glitched
|
||||
// with no reliable fix in reach, so it was removed rather than chased further.
|
||||
// TrentaMuspell.cs mirrors FenrirRace.cs (transform/revert routines, ExecuteTransformation/
|
||||
// ExecuteReversion) and FenrirBehaviors.cs (per-form Animator + mouse-button attack
|
||||
// pattern) about as closely as two independent races' code can - both are read, not
|
||||
// guessed, so the shape of this is trustworthy even where individual numbers below are not.
|
||||
public const int MuspellUnlockState = 8; // Fader dead
|
||||
public const KeyCode MuspellKey = KeyCode.J;
|
||||
|
||||
// "gd_king" is The Elder's own internal prefab name, confirmed against a live source
|
||||
// (not guessed) the same way "portal_wood" and "Draugr" were.
|
||||
public const string MuspellFormPrefab = "gd_king";
|
||||
public const float MuspellScale = 0.5f;
|
||||
|
||||
// Stomp's damage/radius are still this mod's own numbers - TODO: replace with
|
||||
// gd_king_stomp's own SharedData.m_damages once dumpelder reports it, the same way the
|
||||
// trigger name below was replaced with a read value instead of a guess.
|
||||
public const float MuspellStompDamage = 60f;
|
||||
public const float MuspellStompRadius = 2.5f; // TODO: tune
|
||||
|
||||
// The ranged attack is a real Projectile (type=Projectile, range 8-24), not an instant
|
||||
// cone hit - "gdking_root_projectile", The Elder's own vine/spike shot, spawned and set up
|
||||
// exactly the way Attack.FireProjectileBurst does it (Instantiate, new HitData, IProjectile
|
||||
// .Setup), for "identico" rather than an approximation.
|
||||
public const string MuspellSpikeProjectilePrefab = "gdking_root_projectile";
|
||||
public const float MuspellSpikeDamage = 35f; // TODO: replace with the projectile's own m_damage once dumpelder reports it
|
||||
public const float MuspellSpikeVelocity = 20f; // TODO: tune - m_projectileVel isn't in this dump yet either
|
||||
|
||||
// Read straight off gd_king's own default weapons via the "dumpelder" console command
|
||||
// (RacesOfValheim.DumpElderCommand) rather than guessed - confirmed by IL that
|
||||
// Attack.m_attackAnimation feeds directly into ZSyncAnimation.SetTrigger, so these are the
|
||||
// exact strings The Elder itself uses:
|
||||
// gd_king_stomp (jaws) -> primary animation "stomp", m_attackRandomAnimations=2
|
||||
// gd_king_shoot (shaman attack) -> primary animation "shoot", spawns gdking_root_projectile
|
||||
// gd_king_rootspawn (spawn) -> primary animation "spawn"
|
||||
// Stomp's randomAnimations=2 means the real trigger fired is "stomp0" or "stomp1", picked
|
||||
// at random each swing, mirroring Attack.Start's own random-suffix branch.
|
||||
public const string MuspellStompTrigger = "stomp";
|
||||
public const int MuspellStompTriggerVariants = 2;
|
||||
public const string MuspellSpikeTrigger = "shoot";
|
||||
public const string MuspellRootSummonTrigger = "spawn";
|
||||
|
||||
// Purple Rain's own cooldown while Muspell is active - read by TryPurpleRain instead of
|
||||
// PurpleRainCooldown whenever TrentaMuspell.IsTransformed is true.
|
||||
public const float MuspellPurpleRainCooldown = 10f;
|
||||
|
||||
// ─── Diet ────────────────────────────────────────────────────────────
|
||||
// The Trenta are strict vegans: no meat, fish, egg or honey, in any dish that contains
|
||||
// even a trace of one. TrentaFoodPatches blocks eating anything whose prefab is not in
|
||||
// this set - meads are untouched, since those never carry m_food/m_foodStamina/m_foodEitr
|
||||
// and so never look like "food" to that check in the first place.
|
||||
//
|
||||
// Every entry here is the game's actual internal prefab ID (verified against the item's
|
||||
// wiki infobox one at a time - the display name does not reliably predict it: Blueberries
|
||||
// is "Blueberries" but Raspberries is "Raspberry", Magecap is "MushroomMagecap", Fiddlehead
|
||||
// is "Fiddleheadfern"). Get one of these wrong and that food silently stops being
|
||||
// recognised as vegan-safe rather than throwing, so this list must never be hand-guessed.
|
||||
//
|
||||
// Deliberately excludes every dish that touches Honey, Egg, Royal jelly or Volture egg
|
||||
// (Cooked egg, Mushroom omelette, Frosted sweetbread, Yggdrasil porridge, Spicy marmalade,
|
||||
// Roasted crust pie) even though none of those are meat - a vegan diet is "no animal
|
||||
// product", not "no meat", and the player asked for the former.
|
||||
public static readonly HashSet<string> VeganFoodPrefabNames = new HashSet<string>
|
||||
{
|
||||
// Meadows / Black Forest
|
||||
"Raspberry", // Raspberries
|
||||
"Mushroom", // Mushroom
|
||||
"Blueberries", // Blueberries
|
||||
"MushroomYellow", // Yellow mushroom
|
||||
"Carrot", // Carrot
|
||||
"QueensJam", // Queen's jam
|
||||
"CarrotSoup", // Carrot soup
|
||||
|
||||
// Mountain
|
||||
"Onion", // Onion
|
||||
"OnionSoup", // Onion soup
|
||||
|
||||
// Plains
|
||||
"Cloudberry", // Cloudberries
|
||||
"Bread", // Bread
|
||||
|
||||
// Mistlands
|
||||
"MushroomMagecap", // Magecap
|
||||
"MushroomJotunPuffs", // Jotun puffs
|
||||
"Salad", // Salad
|
||||
|
||||
// Ashlands
|
||||
"MushroomSmokePuff", // Smoke puff
|
||||
"Fiddleheadfern", // Fiddlehead
|
||||
"Vineberry", // Vineberry cluster
|
||||
"ScorchingMedley", // Scorching medley
|
||||
"SizzlingBerryBroth", // Sizzling berry broth
|
||||
"SparklingShroomshake", // Sparkling shroomshake
|
||||
"MarinatedGreens" // Marinated greens
|
||||
};
|
||||
|
||||
// Digestion runs twice as long for a Trenta eating any of the foods above.
|
||||
public const float FoodDurationMultiplier = 2f;
|
||||
|
||||
// ─── Awakened seeds ──────────────────────────────────────────────────
|
||||
// Once a Trenta has felled Eikthyr, every seed, cone, acorn and self-seeding mushroom in
|
||||
// the game wakes up: eating the raw item on the spot consumes it and grants the strongest
|
||||
// health/eitr dish its own biome has to offer (see the biome-pairing table worked out with
|
||||
// the player - eitr food wins the tie-break wherever a biome has one, otherwise health
|
||||
// wins by default). Before that boss falls the same click does nothing special - the seed
|
||||
// just behaves like the ordinary planting material it already is.
|
||||
//
|
||||
// A handful of judgment calls, all defaults rather than answers pulled from the player:
|
||||
// - Fir cone spans Black Forest/Swamp/Mountain and Birch seeds spans Meadows/Plains;
|
||||
// each is given one fixed stat block drawn from the highest-tier biome it grows in
|
||||
// (Mountain, Plains) rather than varying by where it happened to be picked up.
|
||||
// - Flax has no seed-to-food entry: it produces fibre, never food, in vanilla, so there
|
||||
// is nothing sensible to "awaken" it into.
|
||||
// - Magecap and Jotun puffs are self-seeding (the raw item you plant is the same one you
|
||||
// already eat raw at the base tier), so their entry represents an *upgrade* on the same
|
||||
// item rather than turning an inedible material into a first meal.
|
||||
public const int EikthyrDefeatedState = 2; // BossProgressionManager state 2 = Eikthyr dead
|
||||
|
||||
// Prefix shared by every generated awakened-food prefab, so patches can recognise one on
|
||||
// sight (Trenta_Player_EatFood_DuplicateGuard_Patch) without re-deriving the raw-name map.
|
||||
public const string AwakenedSeedPrefabPrefix = "TrentaAwakened_";
|
||||
|
||||
public struct AwakenedSeedFood
|
||||
{
|
||||
public string RawPrefabName; // the seed/cone/acorn/mushroom item this replaces on eating
|
||||
public float Health;
|
||||
public float Stamina;
|
||||
public float Eitr;
|
||||
public float Duration; // seconds
|
||||
public float Healing; // hp/tick
|
||||
|
||||
public string AwakenedPrefabName => AwakenedSeedPrefabPrefix + RawPrefabName;
|
||||
}
|
||||
|
||||
public static readonly AwakenedSeedFood[] AwakenedSeedFoods =
|
||||
{
|
||||
// Meadows - no eitr food in the biome, so health wins by default (Cooked deer meat).
|
||||
new AwakenedSeedFood { RawPrefabName = "BeechSeeds", Health = 35, Stamina = 12, Eitr = 0, Duration = 1200, Healing = 2 },
|
||||
new AwakenedSeedFood { RawPrefabName = "Acorn", Health = 35, Stamina = 12, Eitr = 0, Duration = 1200, Healing = 2 },
|
||||
|
||||
// Black Forest - no eitr food, health wins (Deer stew).
|
||||
new AwakenedSeedFood { RawPrefabName = "CarrotSeeds", Health = 45, Stamina = 15, Eitr = 0, Duration = 1500, Healing = 3 },
|
||||
new AwakenedSeedFood { RawPrefabName = "PineCone", Health = 45, Stamina = 15, Eitr = 0, Duration = 1500, Healing = 3 },
|
||||
|
||||
// Fir cone also grows in Swamp and Mountain; Mountain is its highest tier (Wolf skewer).
|
||||
new AwakenedSeedFood { RawPrefabName = "FirCone", Health = 65, Stamina = 21, Eitr = 0, Duration = 1500, Healing = 3 },
|
||||
|
||||
// Swamp - no eitr food, health wins (Serpent stew).
|
||||
new AwakenedSeedFood { RawPrefabName = "TurnipSeeds", Health = 80, Stamina = 26, Eitr = 0, Duration = 1800, Healing = 4 },
|
||||
|
||||
// Mountain - no eitr food, health wins (Wolf skewer).
|
||||
new AwakenedSeedFood { RawPrefabName = "OnionSeeds", Health = 65, Stamina = 21, Eitr = 0, Duration = 1500, Healing = 3 },
|
||||
|
||||
// Plains - no eitr food, health wins (Lox meat pie). Birch seeds also grows in
|
||||
// Meadows; Plains is its higher tier.
|
||||
new AwakenedSeedFood { RawPrefabName = "Barley", Health = 75, Stamina = 24, Eitr = 0, Duration = 1800, Healing = 4 },
|
||||
new AwakenedSeedFood { RawPrefabName = "BirchSeeds", Health = 75, Stamina = 24, Eitr = 0, Duration = 1800, Healing = 4 },
|
||||
|
||||
// Mistlands - Seeker aspic has the biome's highest eitr, so it wins the tie-break over
|
||||
// Misthare supreme's higher health.
|
||||
new AwakenedSeedFood { RawPrefabName = "MushroomMagecap", Health = 28, Stamina = 14, Eitr = 85, Duration = 1800, Healing = 3 },
|
||||
new AwakenedSeedFood { RawPrefabName = "MushroomJotunPuffs", Health = 28, Stamina = 14, Eitr = 85, Duration = 1800, Healing = 3 },
|
||||
|
||||
// Ashlands - Marinated greens has the biome's highest eitr, wins the tie-break over
|
||||
// Piquant pie's higher health.
|
||||
new AwakenedSeedFood { RawPrefabName = "VineberrySeeds", Health = 32, Stamina = 16, Eitr = 95, Duration = 1800, Healing = 4 }
|
||||
};
|
||||
|
||||
// Built once from the array above so the Humanoid.UseItem patch can look a clicked
|
||||
// prefab up in O(1) instead of scanning the array on every item use.
|
||||
public static readonly Dictionary<string, AwakenedSeedFood> AwakenedSeedFoodByRawPrefab = BuildAwakenedSeedFoodLookup();
|
||||
|
||||
private static Dictionary<string, AwakenedSeedFood> BuildAwakenedSeedFoodLookup()
|
||||
{
|
||||
var lookup = new Dictionary<string, AwakenedSeedFood>();
|
||||
foreach (AwakenedSeedFood food in AwakenedSeedFoods)
|
||||
{
|
||||
lookup[food.RawPrefabName] = food;
|
||||
}
|
||||
return lookup;
|
||||
}
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────
|
||||
/// <summary>Clamped table lookup, so a state outside 1..8 can never index out of range.</summary>
|
||||
public static float Lookup(float[] table, int state)
|
||||
{
|
||||
if (table == null || table.Length == 0) return 0f;
|
||||
int index = Mathf.Clamp(state, BossProgressionManager.MinState, table.Length - 1);
|
||||
return table[index];
|
||||
}
|
||||
}
|
||||
}
|
||||
205
JotunnModStub/Trenta/TrentaFoodPatches.cs
Normal file
205
JotunnModStub/Trenta/TrentaFoodPatches.cs
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
using HarmonyLib;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// Every hook the Trenta's diet needs. Mirrors DraughFoodPatches.cs - the Draugh's own
|
||||
/// "restricted diet" file - closely enough that the two are worth reading side by side:
|
||||
/// the Draugh only eats raw flesh and swaps a raw material for a custom edible on the spot;
|
||||
/// the Trenta only eats plants and, after Eikthyr falls, does the same raw-material swap for
|
||||
/// every seed, cone, acorn and self-seeding mushroom in the game.
|
||||
/// </summary>
|
||||
public static class TrentaFoodPatches
|
||||
{
|
||||
// Awakened-seed foods go through Player.EatFood the same way Draugh's EdibleUncooked_
|
||||
// items do: called directly from inside a UseItem prefix rather than through the normal
|
||||
// right-click flow. Native EatFood's own duplicate-slot handling does not reliably
|
||||
// refresh a food added this way, so - exactly as DraughFoodPatches.hiddenFoods does -
|
||||
// any existing slot with a matching name is pulled out of m_foods before the call and
|
||||
// put back afterwards, forcing EatFood to always see room for a fresh entry.
|
||||
private static List<object> hiddenFoods = new List<object>();
|
||||
|
||||
/// <summary>
|
||||
/// Blocks a Trenta from eating anything that is not vegan, and - once Eikthyr is dead -
|
||||
/// turns eating a raw seed, cone, acorn or self-seeding mushroom into eating the dish it
|
||||
/// awakens into instead.
|
||||
///
|
||||
/// The seed check runs first and, if it matches, owns the whole outcome: before Eikthyr
|
||||
/// it falls through to normal item behaviour (a seed has nothing to do with the vegan
|
||||
/// check below, it isn't food yet), and after Eikthyr it always returns false, win or
|
||||
/// lose, because a failed eat should not fall through into planting the seed instead.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(Humanoid), "UseItem")]
|
||||
public static class Trenta_Humanoid_UseItem_Patch
|
||||
{
|
||||
public static bool Prefix(Humanoid __instance, Inventory inventory, ItemDrop.ItemData item)
|
||||
{
|
||||
Player player = __instance as Player;
|
||||
if (player == null || player != Player.m_localPlayer) return true;
|
||||
if (!TrentaRace.IsTrenta()) return true;
|
||||
if (item == null || item.m_dropPrefab == null) return true;
|
||||
|
||||
string prefabName = item.m_dropPrefab.name;
|
||||
|
||||
if (TrentaConfig.AwakenedSeedFoodByRawPrefab.TryGetValue(prefabName, out TrentaConfig.AwakenedSeedFood seedFood))
|
||||
{
|
||||
if (BossProgressionManager.GetCurrentProgressionState() < TrentaConfig.EikthyrDefeatedState)
|
||||
{
|
||||
return true; // Not woken yet - let the seed behave normally (i.e. plant it)
|
||||
}
|
||||
|
||||
GameObject customPrefab = ObjectDB.instance.GetItemPrefab(seedFood.AwakenedPrefabName);
|
||||
if (customPrefab == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[Trenta] Missing awakened seed prefab: {seedFood.AwakenedPrefabName}");
|
||||
return true;
|
||||
}
|
||||
|
||||
ItemDrop customDrop = customPrefab.GetComponent<ItemDrop>();
|
||||
if (customDrop == null) return true;
|
||||
|
||||
bool ate = player.EatFood(customDrop.m_itemData);
|
||||
if (ate)
|
||||
{
|
||||
inventory.RemoveItem(item, 1);
|
||||
|
||||
var consumeEffects = Traverse.Create(player).Field("m_consumeItemEffects").GetValue<EffectList>();
|
||||
if (consumeEffects != null) consumeEffects.Create(player.transform.position, Quaternion.identity, player.transform, 1f, -1);
|
||||
|
||||
var zanim = Traverse.Create(player).Field("m_zanim").GetValue<ZSyncAnimation>();
|
||||
if (zanim != null) zanim.SetTrigger("eat");
|
||||
}
|
||||
return false; // Skip native UseItem either way
|
||||
}
|
||||
|
||||
if (item.m_shared == null) return true;
|
||||
|
||||
bool isFood = item.m_shared.m_food > 0f || item.m_shared.m_foodStamina > 0f || item.m_shared.m_foodEitr > 0f;
|
||||
if (!isFood) return true;
|
||||
|
||||
if (TrentaConfig.VeganFoodPrefabNames.Contains(prefabName)) return true;
|
||||
|
||||
player.Message(MessageHud.MessageType.Center, "The Trenta eat only what grows from root and leaf - no meat, fish, egg or honey.");
|
||||
return false; // Block consumption
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Doubles the digestion time of whatever vegan food a Trenta just ate - the whitelisted
|
||||
/// vanilla dishes and the awakened seed foods alike.
|
||||
///
|
||||
/// item.m_shared is a reference shared by every instance of that food across every
|
||||
/// player - the same fact SkeletonRace.GetBestRealFoods works around when it scales a
|
||||
/// food's HP. Multiplying m_foodBurnTime on it directly would double the duration for
|
||||
/// every race eating a Carrot soup, not just the Trenta. So this clones the item, then
|
||||
/// MemberwiseClones m_shared off of that clone, and only then doubles the burn time -
|
||||
/// the clone is what Player.EatFood goes on to store in m_foods, the original prefab
|
||||
/// data is never touched.
|
||||
///
|
||||
/// A Prefix rather than a Postfix because the doubled burn time has to be in place
|
||||
/// *before* EatFood builds the Food entry it puts in m_foods; a Postfix would be
|
||||
/// rewriting state EatFood had already finished computing from the old value.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(Player), "EatFood")]
|
||||
public static class Trenta_Player_EatFood_Patch
|
||||
{
|
||||
public static void Prefix(Player __instance, ref ItemDrop.ItemData item)
|
||||
{
|
||||
if (__instance == null || __instance != Player.m_localPlayer) return;
|
||||
if (!TrentaRace.IsTrenta()) return;
|
||||
if (item == null || item.m_dropPrefab == null) return;
|
||||
|
||||
string prefabName = item.m_dropPrefab.name;
|
||||
bool isDietFood = TrentaConfig.VeganFoodPrefabNames.Contains(prefabName)
|
||||
|| prefabName.StartsWith(TrentaConfig.AwakenedSeedPrefabPrefix);
|
||||
if (!isDietFood) return;
|
||||
|
||||
ItemDrop.ItemData doubled = item.Clone();
|
||||
doubled.m_shared = (ItemDrop.ItemData.SharedData)typeof(object)
|
||||
.GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
|
||||
.Invoke(doubled.m_shared, null);
|
||||
doubled.m_shared.m_foodBurnTime *= TrentaConfig.FoodDurationMultiplier;
|
||||
|
||||
item = doubled;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The duplicate-slot workaround an awakened seed food needs because it is handed to
|
||||
/// EatFood directly from the UseItem prefix above rather than through the native
|
||||
/// right-click path - see DraughFoodPatches.EatFood_Prefix/Postfix for the original of
|
||||
/// this exact trick and why it exists. Scoped to awakened-seed prefabs only: the 21
|
||||
/// whitelisted vanilla foods already go through native UseItem normally and have never
|
||||
/// needed this.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(Player), "EatFood")]
|
||||
public static class Trenta_Player_EatFood_DuplicateGuard_Patch
|
||||
{
|
||||
public static bool Prefix(Player __instance, ItemDrop.ItemData item)
|
||||
{
|
||||
hiddenFoods.Clear();
|
||||
|
||||
if (__instance != Player.m_localPlayer || !TrentaRace.IsTrenta()) return true;
|
||||
if (item == null || item.m_dropPrefab == null) return true;
|
||||
if (!item.m_dropPrefab.name.StartsWith(TrentaConfig.AwakenedSeedPrefabPrefix)) return true;
|
||||
|
||||
var m_foods = Traverse.Create(__instance).Field("m_foods").GetValue<System.Collections.IList>();
|
||||
if (m_foods == null) return true;
|
||||
|
||||
if (m_foods.Count >= 3)
|
||||
{
|
||||
foreach (object foodObj in m_foods)
|
||||
{
|
||||
Player.Food f = foodObj as Player.Food;
|
||||
if (f != null && f.m_item.m_shared.m_name == item.m_shared.m_name && f.CanEatAgain())
|
||||
{
|
||||
f.m_time = 0f;
|
||||
f.m_item = item.Clone();
|
||||
|
||||
var consumeEffects = Traverse.Create(__instance).Field("m_consumeItemEffects").GetValue<EffectList>();
|
||||
if (consumeEffects != null) consumeEffects.Create(__instance.transform.position, Quaternion.identity, __instance.transform, 1f, -1);
|
||||
|
||||
var zanim = Traverse.Create(__instance).Field("m_zanim").GetValue<ZSyncAnimation>();
|
||||
if (zanim != null) zanim.SetTrigger("eat");
|
||||
|
||||
if (item.m_shared.m_food > 0f) __instance.Heal(item.m_shared.m_food, true);
|
||||
|
||||
return false; // Refreshed ourselves - skip native EatFood
|
||||
}
|
||||
}
|
||||
|
||||
return false; // Full, and nothing to refresh
|
||||
}
|
||||
|
||||
// Temporarily hide any existing slot with the same name to force native EatFood
|
||||
// to add a fresh entry instead of trying (and failing) to extend this one.
|
||||
for (int i = m_foods.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var foodObj = m_foods[i];
|
||||
var foodItem = Traverse.Create(foodObj).Field("m_item").GetValue<ItemDrop.ItemData>();
|
||||
if (foodItem != null && foodItem.m_shared.m_name == item.m_shared.m_name)
|
||||
{
|
||||
hiddenFoods.Add(foodObj);
|
||||
m_foods.RemoveAt(i);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void Postfix(Player __instance)
|
||||
{
|
||||
if (hiddenFoods.Count == 0) return;
|
||||
|
||||
var m_foods = Traverse.Create(__instance).Field("m_foods").GetValue<System.Collections.IList>();
|
||||
if (m_foods != null)
|
||||
{
|
||||
foreach (var h in hiddenFoods) m_foods.Add(h);
|
||||
}
|
||||
hiddenFoods.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
185
JotunnModStub/Trenta/TrentaHornetsNest.cs
Normal file
185
JotunnModStub/Trenta/TrentaHornetsNest.cs
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
using HarmonyLib;
|
||||
using Jotunn.Managers;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// The swarm itself. Not a Character - it has no health, no hitbox anything else can target,
|
||||
/// so "indistruttibile" falls out of what it simply isn't rather than needing invulnerability
|
||||
/// code of its own. Idles in a slow orbit around the Trenta; the instant an enemy comes within
|
||||
/// range it breaks off, hovers over that enemy instead, and sting-ticks it on a timer until it
|
||||
/// dies or leaves range, then returns to orbiting.
|
||||
/// </summary>
|
||||
public class TrentaHornetSwarm : MonoBehaviour
|
||||
{
|
||||
private Player owner;
|
||||
private Character target;
|
||||
private float tickTimer;
|
||||
private float orbitAngle;
|
||||
private AudioSource buzz;
|
||||
|
||||
public static GameObject Spawn(Player player)
|
||||
{
|
||||
GameObject go = new GameObject("TrentaHornetsNest");
|
||||
go.transform.position = player.transform.position + Vector3.up;
|
||||
|
||||
TrentaHornetSwarm swarm = go.AddComponent<TrentaHornetSwarm>();
|
||||
swarm.owner = player;
|
||||
|
||||
BuildFliesVfx(go.transform);
|
||||
swarm.buzz = BuildBuzzAudio(go.transform);
|
||||
|
||||
return go;
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (owner == null || owner.IsDead())
|
||||
{
|
||||
Destroy(gameObject);
|
||||
return;
|
||||
}
|
||||
|
||||
if (target != null && (target.IsDead() || Vector3.Distance(target.transform.position, owner.transform.position) > TrentaConfig.HornetsNestEngageRadius * 1.5f))
|
||||
{
|
||||
target = null;
|
||||
}
|
||||
|
||||
if (target == null)
|
||||
{
|
||||
target = FindTarget();
|
||||
}
|
||||
|
||||
if (target != null)
|
||||
{
|
||||
Vector3 hoverPoint = target.transform.position + Vector3.up * TrentaConfig.HornetsNestAttackHeight;
|
||||
transform.position = Vector3.MoveTowards(transform.position, hoverPoint, TrentaConfig.HornetsNestFollowSpeed * Time.deltaTime);
|
||||
|
||||
if (!buzz.isPlaying) buzz.Play();
|
||||
|
||||
tickTimer += Time.deltaTime;
|
||||
if (tickTimer >= TrentaConfig.HornetsNestTickInterval)
|
||||
{
|
||||
tickTimer = 0f;
|
||||
Sting(target);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (buzz.isPlaying) buzz.Stop();
|
||||
tickTimer = 0f;
|
||||
|
||||
// A slow, lazy orbit around the Trenta rather than sitting dead-still on top of
|
||||
// them - reads as "trying to stay on him" without looking glued in place.
|
||||
orbitAngle += Time.deltaTime * 60f;
|
||||
Vector3 orbitOffset = new Vector3(Mathf.Cos(orbitAngle * Mathf.Deg2Rad), 0.3f, Mathf.Sin(orbitAngle * Mathf.Deg2Rad)) * TrentaConfig.HornetsNestOrbitRadius;
|
||||
Vector3 restPoint = owner.transform.position + Vector3.up + orbitOffset;
|
||||
transform.position = Vector3.MoveTowards(transform.position, restPoint, TrentaConfig.HornetsNestFollowSpeed * Time.deltaTime);
|
||||
}
|
||||
}
|
||||
|
||||
private Character FindTarget()
|
||||
{
|
||||
Character nearest = null;
|
||||
float nearestDist = float.MaxValue;
|
||||
|
||||
foreach (Collider collider in Physics.OverlapSphere(owner.transform.position, TrentaConfig.HornetsNestEngageRadius))
|
||||
{
|
||||
if (collider == null) continue;
|
||||
|
||||
Character character = collider.GetComponentInParent<Character>();
|
||||
if (character == null || character == owner || character.IsDead()) continue;
|
||||
if (!BaseAI.IsEnemy(owner, character)) continue;
|
||||
|
||||
float dist = Vector3.Distance(character.transform.position, owner.transform.position);
|
||||
if (dist < nearestDist)
|
||||
{
|
||||
nearestDist = dist;
|
||||
nearest = character;
|
||||
}
|
||||
}
|
||||
|
||||
return nearest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Two hits, matching "come se il giocatore fosse costantemente avvelenato dalle api, più
|
||||
/// lo stesso danno ma perforante da sopra" literally: one Poison hit at the wild Bee
|
||||
/// Nest's own numbers, and one Pierce hit of the same size, its direction pointed straight
|
||||
/// down since the swarm is hovering above the target when it lands.
|
||||
/// </summary>
|
||||
private void Sting(Character victim)
|
||||
{
|
||||
HitData poison = new HitData();
|
||||
poison.m_damage.m_poison = TrentaConfig.HornetsNestDamagePerTick;
|
||||
poison.SetAttacker(owner);
|
||||
poison.m_point = victim.GetCenterPoint();
|
||||
poison.m_dir = Vector3.zero;
|
||||
victim.Damage(poison);
|
||||
|
||||
HitData pierce = new HitData();
|
||||
pierce.m_damage.m_pierce = TrentaConfig.HornetsNestDamagePerTick;
|
||||
pierce.SetAttacker(owner);
|
||||
pierce.m_point = victim.GetCenterPoint();
|
||||
pierce.m_dir = Vector3.down;
|
||||
victim.Damage(pierce);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clones only the "flies" particle system off the Draugr prefab, discarding smoke and
|
||||
/// drip - the exact filtering rule DraughRace.EnsureVFX already uses for its own aura, off
|
||||
/// the same prefab, just keeping the opposite subset.
|
||||
/// </summary>
|
||||
private static void BuildFliesVfx(Transform parent)
|
||||
{
|
||||
GameObject draugrPrefab = PrefabManager.Cache.GetPrefab<GameObject>(TrentaConfig.HornetsNestFliesSourcePrefab);
|
||||
if (draugrPrefab == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[Trenta] Hornet's Nest: could not find VFX source prefab '{TrentaConfig.HornetsNestFliesSourcePrefab}'.");
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (ParticleSystem ps in draugrPrefab.GetComponentsInChildren<ParticleSystem>(true))
|
||||
{
|
||||
if (!ps.main.loop) continue;
|
||||
if (!ps.gameObject.name.ToLower().Contains("flies")) continue;
|
||||
|
||||
GameObject copy = Object.Instantiate(ps.gameObject, parent);
|
||||
copy.name = ps.gameObject.name;
|
||||
copy.SetActive(true);
|
||||
copy.transform.localPosition = Vector3.zero;
|
||||
copy.transform.localRotation = ps.transform.localRotation;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Borrows only the AudioClip off the Beehive's ambient bee-swarm effect - read straight
|
||||
/// off the prefab asset, never instantiated, so none of that effect's own visuals or
|
||||
/// scripts ever come along with it.
|
||||
/// </summary>
|
||||
private static AudioSource BuildBuzzAudio(Transform parent)
|
||||
{
|
||||
AudioSource source = parent.gameObject.AddComponent<AudioSource>();
|
||||
source.loop = true;
|
||||
source.spatialBlend = 1f; // 3D - it should sound like it is coming from the swarm
|
||||
source.volume = 0.6f;
|
||||
|
||||
GameObject beehivePrefab = PrefabManager.Cache.GetPrefab<GameObject>(TrentaConfig.HornetsNestBeehivePrefab);
|
||||
Beehive beehive = beehivePrefab != null ? beehivePrefab.GetComponent<Beehive>() : null;
|
||||
GameObject beeEffect = beehive != null ? Traverse.Create(beehive).Field<GameObject>("m_beeEffect").Value : null;
|
||||
AudioSource sourceClipHolder = beeEffect != null ? beeEffect.GetComponentInChildren<AudioSource>(true) : null;
|
||||
|
||||
if (sourceClipHolder != null && sourceClipHolder.clip != null)
|
||||
{
|
||||
source.clip = sourceClipHolder.clip;
|
||||
}
|
||||
else
|
||||
{
|
||||
Jotunn.Logger.LogWarning("[Trenta] Hornet's Nest: could not find a buzzing AudioClip on the Beehive's bee effect.");
|
||||
}
|
||||
|
||||
return source;
|
||||
}
|
||||
}
|
||||
}
|
||||
382
JotunnModStub/Trenta/TrentaMuspell.cs
Normal file
382
JotunnModStub/Trenta/TrentaMuspell.cs
Normal file
|
|
@ -0,0 +1,382 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using HarmonyLib;
|
||||
using Jotunn.Managers;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// Muspell (Fader): toggle with J into a half-size The Elder and back. Structured as closely
|
||||
/// as possible on FenrirRace.cs's own transform/revert routines - poof, clone the target's
|
||||
/// "Visual" child onto the player, shrink the player's own Visual to nothing, drive the clone
|
||||
/// with its own per-form Animator-reading MonoBehaviour (MuspellFormBehavior, the same shape
|
||||
/// as FenrirFormBehavior). The permanent-Burning/ignite-attacker fire mechanic was tried and
|
||||
/// dropped - the flame VFX glitched with no reliable fix in reach, and the player asked for it
|
||||
/// (and the fire damage that rode along with it) removed rather than chased further.
|
||||
/// </summary>
|
||||
public static class TrentaMuspell
|
||||
{
|
||||
public static bool IsTransformed { get; private set; }
|
||||
|
||||
private static GameObject currentTransformation;
|
||||
private static bool isTransformingSequence;
|
||||
|
||||
public static void Toggle(Player player)
|
||||
{
|
||||
if (isTransformingSequence) return;
|
||||
|
||||
if (IsTransformed)
|
||||
{
|
||||
TrentaRace.Instance.StartCoroutine(RevertRoutine(player));
|
||||
}
|
||||
else
|
||||
{
|
||||
TrentaRace.Instance.StartCoroutine(TransformRoutine(player));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Called from TrentaRace.Update unconditionally, the same way Hornet's Nest is -
|
||||
/// a race change, a tier drop or death has to end the transformation even though nothing
|
||||
/// would otherwise be left running to notice.</summary>
|
||||
public static void ForceRevert(Player player)
|
||||
{
|
||||
if (IsTransformed && !isTransformingSequence)
|
||||
{
|
||||
TrentaRace.Instance.StartCoroutine(RevertRoutine(player));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called by Purple Rain instead of its usual staff_summon trigger whenever Muspell is
|
||||
/// active - The Elder's own root-summon gesture, played on the transformation clone's
|
||||
/// Animator rather than the player's. Returns false (and does nothing) if not transformed,
|
||||
/// so TryPurpleRain's own fallback to staff_summon still covers the normal case.
|
||||
/// </summary>
|
||||
public static bool TryPlayRootSummonAnimation()
|
||||
{
|
||||
if (!IsTransformed || currentTransformation == null) return false;
|
||||
|
||||
Animator formAnim = currentTransformation.GetComponent<Animator>() ?? currentTransformation.GetComponentInChildren<Animator>();
|
||||
if (formAnim == null) return false;
|
||||
|
||||
try { formAnim.SetTrigger(TrentaConfig.MuspellRootSummonTrigger); } catch { }
|
||||
return true;
|
||||
}
|
||||
|
||||
private static IEnumerator TransformRoutine(Player player)
|
||||
{
|
||||
isTransformingSequence = true;
|
||||
|
||||
var zanim = Traverse.Create(player).Field("m_zanim").GetValue<ZSyncAnimation>();
|
||||
if (zanim != null)
|
||||
{
|
||||
// The transformation poof itself, not an ability cast - "gpower" (the arms-raised
|
||||
// Guardian Power clip, borrowed the same way FenrirRace's own TransformIntoWolfRoutine
|
||||
// borrows it for its transformation) rather than staff_summon, which is reserved for
|
||||
// Purple Rain.
|
||||
RaceInput.SuppressGuardianPowerBriefly();
|
||||
zanim.SetTrigger("gpower");
|
||||
}
|
||||
|
||||
yield return new WaitForSeconds(1.1f);
|
||||
|
||||
SpawnPoofEffect(player);
|
||||
yield return new WaitForSeconds(0.1f);
|
||||
|
||||
ExecuteTransformation(player);
|
||||
|
||||
// Grows in from small rather than popping straight to 50%, the same tween
|
||||
// FenrirRace uses for its own non-wolf forms.
|
||||
float elapsed = 0f;
|
||||
float duration = 0.5f;
|
||||
Vector3 startScale = Vector3.one * (TrentaConfig.MuspellScale * 0.2f);
|
||||
Vector3 endScale = Vector3.one * TrentaConfig.MuspellScale;
|
||||
if (currentTransformation != null) currentTransformation.transform.localScale = startScale;
|
||||
|
||||
while (elapsed < duration)
|
||||
{
|
||||
if (currentTransformation == null) break;
|
||||
currentTransformation.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration);
|
||||
elapsed += Time.deltaTime;
|
||||
yield return null;
|
||||
}
|
||||
if (currentTransformation != null) currentTransformation.transform.localScale = endScale;
|
||||
|
||||
isTransformingSequence = false;
|
||||
}
|
||||
|
||||
private static IEnumerator RevertRoutine(Player player)
|
||||
{
|
||||
isTransformingSequence = true;
|
||||
|
||||
if (currentTransformation != null)
|
||||
{
|
||||
MuspellFormBehavior behavior = currentTransformation.GetComponent<MuspellFormBehavior>();
|
||||
if (behavior != null) behavior.enabled = false;
|
||||
|
||||
float elapsed = 0f;
|
||||
float duration = 0.5f;
|
||||
Vector3 startScale = currentTransformation.transform.localScale;
|
||||
Vector3 endScale = Vector3.one * (TrentaConfig.MuspellScale * 0.2f);
|
||||
|
||||
while (elapsed < duration)
|
||||
{
|
||||
if (currentTransformation == null) break;
|
||||
currentTransformation.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration);
|
||||
elapsed += Time.deltaTime;
|
||||
yield return null;
|
||||
}
|
||||
}
|
||||
|
||||
SpawnPoofEffect(player);
|
||||
yield return new WaitForSeconds(0.1f);
|
||||
|
||||
ExecuteReversion(player);
|
||||
isTransformingSequence = false;
|
||||
}
|
||||
|
||||
private static void SpawnPoofEffect(Player player)
|
||||
{
|
||||
if (player == null) return;
|
||||
Vector3 pos = player.transform.position + Vector3.up;
|
||||
|
||||
GameObject smoke = PrefabManager.Cache.GetPrefab<GameObject>("vfx_corpse_destruction");
|
||||
if (smoke != null) Object.Instantiate(smoke, pos, Quaternion.identity);
|
||||
}
|
||||
|
||||
private static void ExecuteTransformation(Player player)
|
||||
{
|
||||
Transform playerVisual = player.transform.Find("Visual");
|
||||
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(TrentaConfig.MuspellFormPrefab);
|
||||
if (prefab == null || playerVisual == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[Trenta] Muspell: could not find form prefab '{TrentaConfig.MuspellFormPrefab}'.");
|
||||
return;
|
||||
}
|
||||
|
||||
playerVisual.localScale = Vector3.one * 0.001f;
|
||||
|
||||
Transform visual = prefab.transform.Find("Visual") ?? prefab.transform;
|
||||
currentTransformation = Object.Instantiate(visual.gameObject, player.transform);
|
||||
currentTransformation.transform.localPosition = Vector3.zero;
|
||||
currentTransformation.transform.localRotation = Quaternion.identity;
|
||||
|
||||
// Same reasoning as FenrirRace.ExecuteTransformation: the clone must never carry
|
||||
// whatever AI/gameplay component made the source a functioning boss.
|
||||
Component animEvent = currentTransformation.GetComponent("AnimEvent");
|
||||
if (animEvent != null) Object.Destroy(animEvent);
|
||||
foreach (Component ai in currentTransformation.GetComponentsInChildren<BaseAI>(true)) Object.Destroy(ai);
|
||||
foreach (Component character in currentTransformation.GetComponentsInChildren<Character>(true)) Object.Destroy(character);
|
||||
foreach (Component znet in currentTransformation.GetComponentsInChildren<ZNetView>(true)) Object.Destroy(znet);
|
||||
|
||||
currentTransformation.AddComponent<MuspellFormBehavior>();
|
||||
|
||||
ZNetView nview = player.GetComponent<ZNetView>();
|
||||
if (nview != null && nview.IsValid())
|
||||
{
|
||||
nview.GetZDO().Set("RacesOfValheim_MuspellForm", true);
|
||||
}
|
||||
|
||||
IsTransformed = true;
|
||||
|
||||
player.Message(MessageHud.MessageType.Center, "You are Muspell, ash and ember given shape.");
|
||||
}
|
||||
|
||||
private static void ExecuteReversion(Player player)
|
||||
{
|
||||
Transform playerVisual = player.transform.Find("Visual");
|
||||
if (currentTransformation != null) Object.Destroy(currentTransformation);
|
||||
currentTransformation = null;
|
||||
|
||||
ZNetView nview = player.GetComponent<ZNetView>();
|
||||
if (nview != null && nview.IsValid())
|
||||
{
|
||||
nview.GetZDO().Set("RacesOfValheim_MuspellForm", false);
|
||||
}
|
||||
|
||||
if (playerVisual != null)
|
||||
{
|
||||
playerVisual.localScale = Vector3.one;
|
||||
playerVisual.gameObject.SetActive(true);
|
||||
}
|
||||
|
||||
IsTransformed = false;
|
||||
|
||||
player.Message(MessageHud.MessageType.Center, "You return to your rooted form.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drives the transformation clone's Animator and its two mouse-button attacks - the same
|
||||
/// shape as FenrirBehaviors.cs's per-form classes (locomotion sync from the player's own
|
||||
/// Animator when idle, lock-and-trigger-and-damage coroutines per attack).
|
||||
/// </summary>
|
||||
public class MuspellFormBehavior : MonoBehaviour
|
||||
{
|
||||
private Animator playerAnim;
|
||||
private Animator formAnim;
|
||||
private Transform muzzle;
|
||||
private bool isAttacking;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
playerAnim = Player.m_localPlayer.transform.Find("Visual").GetComponent<Animator>();
|
||||
formAnim = GetComponent<Animator>();
|
||||
if (formAnim == null) formAnim = GetComponentInChildren<Animator>();
|
||||
|
||||
// The spike volley should leave from the Elder's own mouth, not the (now hidden)
|
||||
// player's eye point underneath it.
|
||||
muzzle = transform.Find("Armature/root/spine1/spine2/spine3/head");
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (playerAnim == null || formAnim == null || Player.m_localPlayer == null) return;
|
||||
if (isAttacking) return;
|
||||
|
||||
bool isGrounded = playerAnim.GetBool("onGround");
|
||||
TrySet(() => formAnim.SetBool("onGround", isGrounded));
|
||||
TrySet(() => formAnim.SetBool("inWater", playerAnim.GetBool("inWater")));
|
||||
|
||||
if (!isGrounded || Player.m_localPlayer.IsCrouching())
|
||||
{
|
||||
TrySet(() => formAnim.SetFloat("forward_speed", 0f));
|
||||
TrySet(() => formAnim.SetFloat("sideway_speed", 0f));
|
||||
}
|
||||
else
|
||||
{
|
||||
TrySet(() => formAnim.SetFloat("forward_speed", playerAnim.GetFloat("forward_speed")));
|
||||
TrySet(() => formAnim.SetFloat("sideway_speed", playerAnim.GetFloat("sideway_speed")));
|
||||
}
|
||||
|
||||
if (!isGrounded || !RaceInput.Allowed) return;
|
||||
|
||||
if (Input.GetMouseButtonDown(0)) // Stomp
|
||||
{
|
||||
StartCoroutine(StompRoutine());
|
||||
}
|
||||
else if (Input.GetMouseButtonDown(1)) // Spike volley
|
||||
{
|
||||
StartCoroutine(SpikeRoutine());
|
||||
}
|
||||
}
|
||||
|
||||
private static void TrySet(System.Action set)
|
||||
{
|
||||
try { set(); } catch { }
|
||||
}
|
||||
|
||||
private IEnumerator StompRoutine()
|
||||
{
|
||||
isAttacking = true;
|
||||
TrySet(() => formAnim.SetFloat("forward_speed", 0f));
|
||||
TrySet(() => formAnim.SetFloat("sideway_speed", 0f));
|
||||
|
||||
// gd_king_stomp's own attack has m_attackRandomAnimations=2 - The Elder itself picks
|
||||
// between "stomp0"/"stomp1" at random each swing, so this mirrors that instead of
|
||||
// always firing the same one.
|
||||
string trigger = TrentaConfig.MuspellStompTrigger + Random.Range(0, TrentaConfig.MuspellStompTriggerVariants);
|
||||
TrySet(() => formAnim.SetTrigger(trigger));
|
||||
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
|
||||
ExecuteMeleeDamage(TrentaConfig.MuspellStompDamage, TrentaConfig.MuspellStompRadius);
|
||||
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
TrySet(() => formAnim.ResetTrigger(trigger));
|
||||
isAttacking = false;
|
||||
}
|
||||
|
||||
private IEnumerator SpikeRoutine()
|
||||
{
|
||||
isAttacking = true;
|
||||
TrySet(() => formAnim.SetFloat("forward_speed", 0f));
|
||||
TrySet(() => formAnim.SetFloat("sideway_speed", 0f));
|
||||
TrySet(() => formAnim.SetTrigger(TrentaConfig.MuspellSpikeTrigger));
|
||||
|
||||
yield return new WaitForSeconds(0.4f);
|
||||
|
||||
FireSpikeProjectile();
|
||||
|
||||
yield return new WaitForSeconds(0.6f);
|
||||
TrySet(() => formAnim.ResetTrigger(TrentaConfig.MuspellSpikeTrigger));
|
||||
isAttacking = false;
|
||||
}
|
||||
|
||||
/// <summary>Close-range, all-around - matches Stomp being an area slam rather than a
|
||||
/// directional swing.</summary>
|
||||
private void ExecuteMeleeDamage(float baseDamage, float radius)
|
||||
{
|
||||
Player player = Player.m_localPlayer;
|
||||
if (player == null) return;
|
||||
|
||||
Vector3 center = player.transform.position + Vector3.up;
|
||||
float unarmedSkillLevel = player.GetSkillLevel(Skills.SkillType.Unarmed);
|
||||
float totalDamage = baseDamage + unarmedSkillLevel;
|
||||
|
||||
HashSet<GameObject> hit = new HashSet<GameObject>();
|
||||
foreach (Collider collider in Physics.OverlapSphere(center, radius))
|
||||
{
|
||||
Character target = collider.GetComponentInParent<Character>();
|
||||
if (target == null || target == player || target.IsDead() || !hit.Add(target.gameObject)) continue;
|
||||
if (!BaseAI.IsEnemy(player, target)) continue;
|
||||
|
||||
DealDamage(player, target, totalDamage, HitData.DamageType.Blunt, Vector3.zero);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The real ranged attack - "gdking_root_projectile", the same one gd_king_shoot fires -
|
||||
/// rather than an instant hitscan, so it travels, can be dodged and can miss the same way
|
||||
/// the boss's own volley does. Spawn/Setup shape copied from TrolRace's own rock throw,
|
||||
/// the established pattern for a custom projectile in this codebase.
|
||||
/// </summary>
|
||||
private void FireSpikeProjectile()
|
||||
{
|
||||
Player player = Player.m_localPlayer;
|
||||
if (player == null) return;
|
||||
|
||||
GameObject projPrefab = ZNetScene.instance.GetPrefab(TrentaConfig.MuspellSpikeProjectilePrefab);
|
||||
if (projPrefab == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[Trenta] Muspell: could not find projectile prefab '{TrentaConfig.MuspellSpikeProjectilePrefab}'.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Aim still follows the player's own look direction (mouse/camera), only the spawn
|
||||
// point moves to the Elder clone's mouth so the shot visibly comes from the model
|
||||
// that's on screen instead of the hidden player underneath it.
|
||||
Vector3 origin = muzzle != null ? muzzle.position : player.GetEyePoint();
|
||||
Vector3 spawnPos = origin + player.GetLookDir() * 1.5f;
|
||||
GameObject projInstance = Object.Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(player.GetLookDir()));
|
||||
|
||||
Projectile proj = projInstance.GetComponent<Projectile>();
|
||||
if (proj == null) return;
|
||||
|
||||
float unarmedSkillLevel = player.GetSkillLevel(Skills.SkillType.Unarmed);
|
||||
|
||||
HitData hitData = new HitData();
|
||||
hitData.m_damage.m_pierce = TrentaConfig.MuspellSpikeDamage + unarmedSkillLevel;
|
||||
hitData.m_skill = Skills.SkillType.Unarmed;
|
||||
hitData.SetAttacker(player);
|
||||
|
||||
proj.Setup(player, player.GetLookDir() * TrentaConfig.MuspellSpikeVelocity, -1f, hitData, null, null);
|
||||
}
|
||||
|
||||
private void DealDamage(Player attacker, Character target, float amount, HitData.DamageType type, Vector3 dir)
|
||||
{
|
||||
HitData hitData = new HitData();
|
||||
if (type == HitData.DamageType.Pierce) hitData.m_damage.m_pierce = amount;
|
||||
else hitData.m_damage.m_blunt = amount;
|
||||
|
||||
hitData.m_point = target.GetCenterPoint();
|
||||
hitData.m_dir = dir;
|
||||
hitData.m_skill = Skills.SkillType.Unarmed;
|
||||
hitData.m_hitType = HitData.HitType.PlayerHit;
|
||||
hitData.SetAttacker(attacker);
|
||||
|
||||
target.Damage(hitData);
|
||||
}
|
||||
}
|
||||
}
|
||||
190
JotunnModStub/Trenta/TrentaPatches.cs
Normal file
190
JotunnModStub/Trenta/TrentaPatches.cs
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
using HarmonyLib;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// Every hook the Trenta needs. The patches only ever decide *whether* a perk applies; *how
|
||||
/// much* it applies always comes from TrentaProgression, which in turn reads TrentaConfig.
|
||||
///
|
||||
/// Two rules the other races learned the hard way and that hold here too:
|
||||
///
|
||||
/// - Health is changed through Player.GetTotalFoodValue, never through
|
||||
/// Character.GetMaxHealth. Patching the getter makes it lie to the rest of the game and
|
||||
/// leaves current health unclamped and the bar flashing every food tick. See the long
|
||||
/// comment on Dvergar_GetTotalFoodValue_Patch.
|
||||
///
|
||||
/// - Every patch guards on `__instance == Player.m_localPlayer` before it guards on the
|
||||
/// race, so a remote player never trips the local player's perks.
|
||||
/// </summary>
|
||||
public static class TrentaPatches
|
||||
{
|
||||
// ─── Skin ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Tints the Trenta the pale green of a young leaf, with dark foliage-green hair and beard.
|
||||
///
|
||||
/// VisEquipment.SetSkinColor followed by UpdateColors does nothing on its own - UpdateColors
|
||||
/// rebuilds the body material from Valheim's own state on every refresh, so the tint has to
|
||||
/// be written *after* it runs. This postfix is that write; see the long comment on
|
||||
/// Dvergar_VisEquipment_UpdateColors_Patch for the full story of why.
|
||||
///
|
||||
/// No local-player check and no saved original: the race is read from the ZDO with a
|
||||
/// m_customData fallback so the main-menu preview and the first spawn frame are covered
|
||||
/// too, and the tint simply stops being applied once the player is no longer a Trenta.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
|
||||
public static class Trenta_VisEquipment_UpdateColors_Patch
|
||||
{
|
||||
public static void Postfix(VisEquipment __instance)
|
||||
{
|
||||
if (__instance == null || !__instance.m_isPlayer) return;
|
||||
|
||||
Player player = __instance.GetComponent<Player>();
|
||||
if (player == null || !TrentaVisuals.IsTrentaPlayer(player)) return;
|
||||
|
||||
if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null)
|
||||
{
|
||||
__instance.m_bodyModel.material.SetColor("_SkinColor", TrentaConfig.SkinColor);
|
||||
}
|
||||
|
||||
TintRenderers(Traverse.Create(__instance).Field("m_hairItemInstance").GetValue<GameObject>());
|
||||
TintRenderers(Traverse.Create(__instance).Field("m_beardItemInstance").GetValue<GameObject>());
|
||||
}
|
||||
|
||||
private static void TintRenderers(GameObject instance)
|
||||
{
|
||||
if (instance == null) return;
|
||||
foreach (Renderer renderer in instance.GetComponentsInChildren<Renderer>())
|
||||
{
|
||||
if (renderer.material != null) renderer.material.SetColor("_SkinColor", TrentaConfig.HairColor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Diet (vegan restriction, digestion doubling, awakened seeds) lives in
|
||||
// TrentaFoodPatches.cs, the way DraughFoodPatches.cs holds the Draugh's equivalent.
|
||||
|
||||
// ─── Bonemass passives ──────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Marks whether the current call into Player.UseStamina was reached from inside
|
||||
/// Player.OnSwimming, for a Bonemass-tier Trenta specifically. Player.OnSwimming is the
|
||||
/// only call site that spends stamina to swim - Character.UpdateSwimming itself never
|
||||
/// touches stamina at all, confirmed by reading its IL - but UseStamina is also the same
|
||||
/// method sprinting, jumping, blocking and attacking all spend through. Blocking it
|
||||
/// outright, the way Player_UseStamina_Patch does wholesale for Skeleton/Aswid/Draugh,
|
||||
/// would give the Trenta free sprint and free attacks along with free swimming. This flag
|
||||
/// is what keeps the waiver scoped to swimming alone.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(Player), "OnSwimming")]
|
||||
public static class Trenta_Player_OnSwimming_Patch
|
||||
{
|
||||
public static void Prefix(Player __instance)
|
||||
{
|
||||
if (__instance != Player.m_localPlayer) return;
|
||||
swimStaminaWaived = TrentaRace.IsTrenta() &&
|
||||
BossProgressionManager.GetCurrentProgressionState() >= TrentaConfig.BonemassDefeatedState;
|
||||
}
|
||||
|
||||
public static void Postfix(Player __instance)
|
||||
{
|
||||
if (__instance == Player.m_localPlayer) swimStaminaWaived = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool swimStaminaWaived = false;
|
||||
|
||||
[HarmonyPatch(typeof(Player), "UseStamina")]
|
||||
public static class Trenta_Player_UseStamina_SwimWaiver_Patch
|
||||
{
|
||||
public static bool Prefix(Player __instance)
|
||||
{
|
||||
if (!swimStaminaWaived) return true;
|
||||
if (__instance != Player.m_localPlayer) return true;
|
||||
return false; // Swimming - waived, everything else still costs stamina normally
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Blocks the Wet status effect from ever landing on a Bonemass-tier Trenta.
|
||||
///
|
||||
/// Wet has no damage type of its own, so unlike Poison this cannot go through
|
||||
/// SE_TrentaStats.m_mods - it has to be stopped at the door instead. Player.
|
||||
/// UpdateEnvStatusEffects (confirmed by reading its IL) is the only vanilla caller that
|
||||
/// ever adds Wet, always through this exact four-argument SEMan.AddStatusEffect overload,
|
||||
/// so patching that call is equivalent to patching every path Wet could arrive by.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(SEMan), "AddStatusEffect", new System.Type[] { typeof(int), typeof(bool), typeof(int), typeof(float) })]
|
||||
public static class Trenta_SEMan_AddStatusEffect_WetImmunity_Patch
|
||||
{
|
||||
public static bool Prefix(SEMan __instance, int nameHash)
|
||||
{
|
||||
if (nameHash != SEMan.s_statusEffectWet) return true;
|
||||
if (Player.m_localPlayer == null || __instance != Player.m_localPlayer.GetSEMan()) return true;
|
||||
if (!TrentaRace.IsTrenta()) return true;
|
||||
if (BossProgressionManager.GetCurrentProgressionState() < TrentaConfig.BonemassDefeatedState) return true;
|
||||
|
||||
return false; // Never gets wet
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Moder passives ─────────────────────────────────────────────────
|
||||
// Last Stand (the armor bonus that scales with missing health) lives in
|
||||
// SE_TrentaStats.ModifyArmorMods - nothing to intercept there either, same reasoning as
|
||||
// the damage m_mods above.
|
||||
//
|
||||
// Camouflage (stand still by a tree, become unsensable + fade to 50% alpha) was tried and
|
||||
// pulled: neither half worked out reliably even after two rebuilds - Valheim's own systems
|
||||
// kept fighting the visual fade, and the CanSenseTarget block never visibly stopped mobs
|
||||
// aggroing either, for a reason that was never pinned down given the tools at hand.
|
||||
// Replaced with something far simpler and much easier to trust: Thorns.
|
||||
|
||||
/// <summary>
|
||||
/// Thorns: reflects a flat percentage of every hit taken back at whoever landed it.
|
||||
///
|
||||
/// A Postfix, not a Prefix - it runs after Character.Damage has already applied the hit to
|
||||
/// the Trenta, so the reflected amount is read off the same HitData the Trenta itself just
|
||||
/// took rather than being computed separately. Guards against hitting a hit with no
|
||||
/// attacker (fall damage, drowning, environmental sources) and against reflecting a
|
||||
/// creature's damage back onto itself.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(Character), "Damage")]
|
||||
public static class Trenta_Character_Damage_Thorns_Patch
|
||||
{
|
||||
public static void Postfix(Character __instance, HitData hit)
|
||||
{
|
||||
if (__instance != Player.m_localPlayer) return;
|
||||
if (!TrentaRace.IsTrenta()) return;
|
||||
if (hit == null || !hit.HaveAttacker()) return;
|
||||
|
||||
Character attacker = hit.GetAttacker();
|
||||
if (attacker == null || attacker == __instance || attacker.IsDead()) return;
|
||||
|
||||
float reflected = hit.GetTotalDamage() * TrentaConfig.ThornsReflectPercent;
|
||||
if (reflected <= 0f) return;
|
||||
|
||||
HitData thorns = new HitData();
|
||||
thorns.m_damage.m_damage = reflected;
|
||||
thorns.SetAttacker(__instance);
|
||||
thorns.m_point = attacker.GetCenterPoint();
|
||||
thorns.m_dir = Vector3.zero;
|
||||
attacker.Damage(thorns);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: the race's remaining perks, one nested [HarmonyPatch] class per hook.
|
||||
//
|
||||
// [HarmonyPatch(typeof(Player), "GetTotalFoodValue")]
|
||||
// public static class Trenta_GetTotalFoodValue_Patch
|
||||
// {
|
||||
// public static void Postfix(Player __instance, ref float hp)
|
||||
// {
|
||||
// if (__instance == null || __instance != Player.m_localPlayer) return;
|
||||
// if (!TrentaRace.IsTrenta()) return;
|
||||
//
|
||||
// hp += TrentaProgression.Current.HealthBonus;
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
189
JotunnModStub/Trenta/TrentaPortal.cs
Normal file
189
JotunnModStub/Trenta/TrentaPortal.cs
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
using System.Collections;
|
||||
using HarmonyLib;
|
||||
using Jotunn.Managers;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// One end of a Homecoming Portal pair. Entirely custom - not a re-skinned vanilla
|
||||
/// TeleportWorld - which is exactly why it has none of the real portal's restrictions
|
||||
/// (raw ore, matching tags, needing to be built at all): it is a local, unregistered prop the
|
||||
/// ability spawns and despawns itself, with its own trigger and its own teleport call.
|
||||
/// </summary>
|
||||
public class TrentaPortalLink : MonoBehaviour
|
||||
{
|
||||
public TrentaPortalLink Other;
|
||||
|
||||
// Sidesteps a same-frame ping-pong: without it, a player who teleports in and is still
|
||||
// standing inside the destination's own trigger collider would be bounced straight back
|
||||
// out the way they came, forever.
|
||||
private float reentryBlockedUntil = -1f;
|
||||
|
||||
private void OnTriggerEnter(Collider other)
|
||||
{
|
||||
if (Other == null || Time.time < reentryBlockedUntil) return;
|
||||
|
||||
Player player = other.GetComponentInParent<Player>();
|
||||
if (player == null) return;
|
||||
|
||||
Vector3 destination = Other.transform.position + Other.transform.forward * 1.5f;
|
||||
player.TeleportTo(destination, Other.transform.rotation, true);
|
||||
|
||||
Other.reentryBlockedUntil = Time.time + 1.5f;
|
||||
}
|
||||
}
|
||||
|
||||
public static class TrentaPortal
|
||||
{
|
||||
private static Material cachedVfxMaterial;
|
||||
private static bool vfxMaterialResolved;
|
||||
|
||||
/// <summary>
|
||||
/// Spawns the linked pair - one at the cast point, one at the player's respawn point -
|
||||
/// and schedules both to close together after TrentaConfig.PortalLifetime.
|
||||
/// </summary>
|
||||
public static void Open(Player player, Vector3 castPoint, Vector3 homePoint)
|
||||
{
|
||||
GameObject castPortal = SpawnPortal(castPoint, player.transform.rotation);
|
||||
GameObject homePortal = SpawnPortal(homePoint, Quaternion.identity);
|
||||
|
||||
TrentaPortalLink castLink = castPortal.GetComponent<TrentaPortalLink>();
|
||||
TrentaPortalLink homeLink = homePortal.GetComponent<TrentaPortalLink>();
|
||||
castLink.Other = homeLink;
|
||||
homeLink.Other = castLink;
|
||||
|
||||
if (TrentaRace.Instance != null)
|
||||
{
|
||||
TrentaRace.Instance.StartCoroutine(CloseAfter(castPortal, homePortal, TrentaConfig.PortalLifetime));
|
||||
}
|
||||
else
|
||||
{
|
||||
Object.Destroy(castPortal, TrentaConfig.PortalLifetime);
|
||||
Object.Destroy(homePortal, TrentaConfig.PortalLifetime);
|
||||
}
|
||||
}
|
||||
|
||||
private static GameObject SpawnPortal(Vector3 position, Quaternion rotation)
|
||||
{
|
||||
GameObject portal = new GameObject("TrentaHomecomingPortal");
|
||||
portal.transform.position = position;
|
||||
portal.transform.rotation = rotation;
|
||||
|
||||
CapsuleCollider trigger = portal.AddComponent<CapsuleCollider>();
|
||||
trigger.isTrigger = true;
|
||||
trigger.height = 3f;
|
||||
trigger.radius = 1.2f;
|
||||
trigger.center = new Vector3(0, 1.5f, 0);
|
||||
|
||||
portal.AddComponent<TrentaPortalLink>();
|
||||
|
||||
BuildSwirlVfx(portal.transform);
|
||||
|
||||
return portal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The swirl only - deliberately not the vanilla wooden frame, since the player asked for
|
||||
/// just the VFX component. Built the same proven way as Purple Rain's rain burst: borrow a
|
||||
/// material off the real portal (read straight off the prefab asset, so this never
|
||||
/// instantiates - and never risks running - any of the real portal's own gameplay
|
||||
/// components), and drive shape/emission/colour here instead of cloning its hierarchy
|
||||
/// wholesale.
|
||||
/// </summary>
|
||||
private static void BuildSwirlVfx(Transform parent)
|
||||
{
|
||||
if (!vfxMaterialResolved)
|
||||
{
|
||||
vfxMaterialResolved = true;
|
||||
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(TrentaConfig.PortalVfxSourcePrefab);
|
||||
if (source != null)
|
||||
{
|
||||
ParticleSystemRenderer sourceRenderer = source.GetComponentInChildren<ParticleSystemRenderer>(true);
|
||||
if (sourceRenderer != null) cachedVfxMaterial = sourceRenderer.material;
|
||||
}
|
||||
if (cachedVfxMaterial == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[Trenta] Homecoming Portal: no particle material found on '{TrentaConfig.PortalVfxSourcePrefab}'; falling back to the default particle material.");
|
||||
}
|
||||
}
|
||||
|
||||
GameObject vfx = new GameObject("Swirl");
|
||||
vfx.transform.SetParent(parent, false);
|
||||
vfx.transform.localPosition = new Vector3(0, 1.2f, 0);
|
||||
|
||||
ParticleSystem ps = vfx.AddComponent<ParticleSystem>();
|
||||
var main = ps.main;
|
||||
main.loop = true;
|
||||
main.startLifetime = 1.5f;
|
||||
main.startSpeed = 0f;
|
||||
main.startSize = new ParticleSystem.MinMaxCurve(0.15f, 0.3f);
|
||||
main.maxParticles = 200;
|
||||
main.simulationSpace = ParticleSystemSimulationSpace.Local;
|
||||
|
||||
var emission = ps.emission;
|
||||
emission.rateOverTime = 80f;
|
||||
|
||||
var shape = ps.shape;
|
||||
shape.shapeType = ParticleSystemShapeType.Circle;
|
||||
shape.radius = 1f;
|
||||
shape.radiusThickness = 0.1f; // hollow ring, not a filled disc
|
||||
|
||||
var rotationOverLifetime = ps.rotationOverLifetime;
|
||||
rotationOverLifetime.enabled = true;
|
||||
rotationOverLifetime.z = new ParticleSystem.MinMaxCurve(90f); // the "swirl" - constant spin
|
||||
|
||||
ParticleSystemRenderer renderer = ps.GetComponent<ParticleSystemRenderer>();
|
||||
if (cachedVfxMaterial != null) renderer.material = cachedVfxMaterial;
|
||||
|
||||
var colorOverLifetime = ps.colorOverLifetime;
|
||||
colorOverLifetime.enabled = true;
|
||||
Gradient grad = new Gradient();
|
||||
grad.SetKeys(
|
||||
new GradientColorKey[] { new GradientColorKey(TrentaConfig.PortalVfxColor, 0f), new GradientColorKey(TrentaConfig.PortalVfxColor, 1f) },
|
||||
new GradientAlphaKey[] { new GradientAlphaKey(0f, 0f), new GradientAlphaKey(0.9f, 0.3f), new GradientAlphaKey(0.9f, 0.7f), new GradientAlphaKey(0f, 1f) }
|
||||
);
|
||||
colorOverLifetime.color = grad;
|
||||
|
||||
ps.Play();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes both ends together: the trigger and swirl come down first (so nothing can walk
|
||||
/// through mid-collapse), then a one-second shrink stands in for "the right closing
|
||||
/// animation" - vanilla portals never actually open or close, they are simply present or
|
||||
/// absent, so there is no real animation to borrow here the way Purple Rain could borrow
|
||||
/// staff_summon.
|
||||
/// </summary>
|
||||
private static IEnumerator CloseAfter(GameObject castPortal, GameObject homePortal, float seconds)
|
||||
{
|
||||
yield return new WaitForSeconds(seconds);
|
||||
|
||||
yield return CollapsePortal(castPortal);
|
||||
yield return CollapsePortal(homePortal);
|
||||
}
|
||||
|
||||
private static IEnumerator CollapsePortal(GameObject portal)
|
||||
{
|
||||
if (portal == null) yield break;
|
||||
|
||||
TrentaPortalLink link = portal.GetComponent<TrentaPortalLink>();
|
||||
if (link != null) Object.Destroy(link);
|
||||
|
||||
CapsuleCollider trigger = portal.GetComponent<CapsuleCollider>();
|
||||
if (trigger != null) Object.Destroy(trigger);
|
||||
|
||||
float t = 0f;
|
||||
Vector3 startScale = portal.transform.localScale;
|
||||
while (t < 1f)
|
||||
{
|
||||
if (portal == null) yield break;
|
||||
t += Time.deltaTime;
|
||||
portal.transform.localScale = Vector3.Lerp(startScale, Vector3.zero, t);
|
||||
yield return null;
|
||||
}
|
||||
|
||||
if (portal != null) Object.Destroy(portal);
|
||||
}
|
||||
}
|
||||
}
|
||||
45
JotunnModStub/Trenta/TrentaProgression.cs
Normal file
45
JotunnModStub/Trenta/TrentaProgression.cs
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// Turns a boss progression state into the set of Trenta perks active at that tier, the same
|
||||
/// way SkeletonProgression and DvergarProgression do for their races.
|
||||
///
|
||||
/// Nothing is decided here - every figure comes out of TrentaConfig - so the tuning pass can
|
||||
/// happen without touching a single patch.
|
||||
/// </summary>
|
||||
public static class TrentaProgression
|
||||
{
|
||||
public struct TrentaRules
|
||||
{
|
||||
/// <summary>Points added to max health at this tier.</summary>
|
||||
public float HealthBonus;
|
||||
|
||||
// TODO: one field per perk, each read by exactly one patch.
|
||||
}
|
||||
|
||||
// GetRules runs from Update loops and from damage patches, so the per-state result is
|
||||
// built once and handed back on every later call.
|
||||
private static readonly TrentaRules[] cache = new TrentaRules[BossProgressionManager.MaxState + 1];
|
||||
private static readonly bool[] cached = new bool[BossProgressionManager.MaxState + 1];
|
||||
|
||||
public static TrentaRules GetRules(int state)
|
||||
{
|
||||
state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState);
|
||||
if (cached[state]) return cache[state];
|
||||
|
||||
TrentaRules rules = new TrentaRules
|
||||
{
|
||||
HealthBonus = TrentaConfig.Lookup(TrentaConfig.HealthBonusByState, state)
|
||||
};
|
||||
|
||||
cache[state] = rules;
|
||||
cached[state] = true;
|
||||
return rules;
|
||||
}
|
||||
|
||||
/// <summary>Rules for whatever tier the local player is currently on.</summary>
|
||||
public static TrentaRules Current => GetRules(BossProgressionManager.GetCurrentProgressionState());
|
||||
}
|
||||
}
|
||||
126
JotunnModStub/Trenta/TrentaRace.cs
Normal file
126
JotunnModStub/Trenta/TrentaRace.cs
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// Driver for the Trenta: a tree-born folk, kin to the forest.
|
||||
///
|
||||
/// Only the per-frame upkeep lives here. The perks are Harmony patches in TrentaPatches, the
|
||||
/// active abilities are in TrentaAbilities, the looks are in TrentaVisuals, and every number
|
||||
/// they use comes from TrentaConfig by way of TrentaProgression.
|
||||
/// </summary>
|
||||
public class TrentaRace : MonoBehaviour
|
||||
{
|
||||
public static TrentaRace Instance;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
Instance = this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called from RacesOfValheim.CreateAllModAssets, once the vanilla prefabs exist. Anything
|
||||
/// that needs to look up a vanilla prefab or register a status effect belongs here, not in
|
||||
/// Awake.
|
||||
/// </summary>
|
||||
public void CreateModAssets()
|
||||
{
|
||||
TrentaStatusEffects.RegisterStatusEffects();
|
||||
CreateAwakenedSeedFoods();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates the "awakened" edible clone of every seed/cone/acorn/mushroom in
|
||||
/// TrentaConfig.AwakenedSeedFoods, one CustomItem per entry, cloned from the raw item
|
||||
/// itself so it keeps that item's icon and mesh - mirrors the loop in
|
||||
/// DraughRace.CreateModAssets that builds the Draugh's EdibleUncooked_ prefabs, just
|
||||
/// cloning from the raw material instead of from a cooked counterpart, since there is no
|
||||
/// existing "cooked seed" to borrow stats from.
|
||||
///
|
||||
/// The clone stays a Seed until Trenta_Humanoid_UseItem_Patch decides to eat it - only
|
||||
/// its stand-alone prefab (never seen in an inventory) needs to look like food.
|
||||
/// </summary>
|
||||
private void CreateAwakenedSeedFoods()
|
||||
{
|
||||
foreach (TrentaConfig.AwakenedSeedFood seedFood in TrentaConfig.AwakenedSeedFoods)
|
||||
{
|
||||
GameObject rawPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(seedFood.RawPrefabName);
|
||||
if (rawPrefab == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[Trenta] Could not find raw seed prefab: {seedFood.RawPrefabName}");
|
||||
continue;
|
||||
}
|
||||
|
||||
ItemDrop rawDrop = rawPrefab.GetComponent<ItemDrop>();
|
||||
if (rawDrop == null) continue;
|
||||
|
||||
Jotunn.Entities.CustomItem customItem = new Jotunn.Entities.CustomItem(seedFood.AwakenedPrefabName, seedFood.RawPrefabName);
|
||||
ItemDrop.ItemData.SharedData shared = customItem.ItemDrop.m_itemData.m_shared;
|
||||
|
||||
shared.m_name = rawDrop.m_itemData.m_shared.m_name;
|
||||
shared.m_description = rawDrop.m_itemData.m_shared.m_description;
|
||||
shared.m_icons = rawDrop.m_itemData.m_shared.m_icons;
|
||||
|
||||
shared.m_itemType = ItemDrop.ItemData.ItemType.Consumable;
|
||||
shared.m_food = seedFood.Health;
|
||||
shared.m_foodStamina = seedFood.Stamina;
|
||||
shared.m_foodEitr = seedFood.Eitr;
|
||||
shared.m_foodBurnTime = seedFood.Duration;
|
||||
shared.m_foodRegen = seedFood.Healing;
|
||||
|
||||
Jotunn.Managers.ItemManager.Instance.AddItem(customItem);
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsTrenta()
|
||||
{
|
||||
return Player.m_localPlayer != null &&
|
||||
Player.m_localPlayer.m_customData.ContainsKey("Race") &&
|
||||
Player.m_localPlayer.m_customData["Race"] == TrentaConfig.RaceId;
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
Player player = Player.m_localPlayer;
|
||||
if (player == null) return;
|
||||
|
||||
int state = BossProgressionManager.GetCurrentProgressionState();
|
||||
|
||||
// Unconditional, unlike everything below: Hornet's Nest is a permanent companion, not
|
||||
// a per-tick perk, so it has to be torn down the instant it no longer qualifies - a
|
||||
// race change, a tier drop, death - none of which the early return right below would
|
||||
// otherwise let this method see again to react to.
|
||||
TrentaAbilities.TickHornetsNest(player, IsTrenta() && !player.IsDead() && state >= TrentaConfig.HornetsNestUnlockState);
|
||||
|
||||
// Same reasoning for Muspell: a race change or death mid-transformation has to run the
|
||||
// real revert routine (restore scale, drop the permanent Burning), not just vanish.
|
||||
if (!IsTrenta() || player.IsDead() || state < TrentaConfig.MuspellUnlockState)
|
||||
{
|
||||
TrentaMuspell.ForceRevert(player);
|
||||
}
|
||||
|
||||
if (!IsTrenta() || player.IsDead()) return;
|
||||
|
||||
// Keep the passive carrier attached. It is re-added rather than assumed because a
|
||||
// respawn, a death or a world load all clear the player's status effects.
|
||||
if (TrentaStatusEffects.StatsSE != null)
|
||||
{
|
||||
int hash = TrentaConfig.StatsSE.GetStableHashCode();
|
||||
if (!player.GetSEMan().HaveStatusEffect(hash))
|
||||
{
|
||||
player.GetSEMan().AddStatusEffect(hash, true);
|
||||
}
|
||||
}
|
||||
|
||||
// Published for remote clients, matching how the Skeleton and the Dvergar replicate
|
||||
// their tier.
|
||||
ZNetView nview = player.GetComponent<ZNetView>();
|
||||
if (nview != null && nview.IsValid())
|
||||
{
|
||||
nview.GetZDO().Set(TrentaConfig.StateZdoKey, state);
|
||||
}
|
||||
|
||||
TrentaAbilities.Tick(player, state);
|
||||
}
|
||||
}
|
||||
}
|
||||
136
JotunnModStub/Trenta/TrentaStatusEffects.cs
Normal file
136
JotunnModStub/Trenta/TrentaStatusEffects.cs
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
using System.Collections.Generic;
|
||||
using Jotunn.Entities;
|
||||
using Jotunn.Managers;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// Passive carrier for the Trenta. Anything Valheim already routes through the status effects
|
||||
/// - damage modifiers, attack stamina cost, regeneration multipliers - belongs here rather
|
||||
/// than in a Harmony patch, because there is nothing to intercept.
|
||||
/// </summary>
|
||||
public class SE_TrentaStats : SE_Stats
|
||||
{
|
||||
public override void Setup(Character character)
|
||||
{
|
||||
base.Setup(character);
|
||||
name = TrentaConfig.StatsSE;
|
||||
m_name = "Heartwood";
|
||||
m_tooltip = "Rooted, patient, and hard to fell.";
|
||||
|
||||
// Resistant/Weak are exactly ±50% damage taken (0.5x / 1.5x) - verified against
|
||||
// HitData.ApplyModifier's own IL rather than assumed, since the enum names alone
|
||||
// don't say by how much. Live from the base tier, ungated by boss progression:
|
||||
// sap and heartwood conduct current and turn away the dead the same on day one as
|
||||
// on day eight, and kindling and the woodsman's axe never stop being kindling and
|
||||
// an axe.
|
||||
m_mods = new List<HitData.DamageModPair>
|
||||
{
|
||||
new HitData.DamageModPair { m_type = HitData.DamageType.Lightning, m_modifier = HitData.DamageModifier.Resistant },
|
||||
new HitData.DamageModPair { m_type = HitData.DamageType.Spirit, m_modifier = HitData.DamageModifier.Resistant },
|
||||
new HitData.DamageModPair { m_type = HitData.DamageType.Fire, m_modifier = HitData.DamageModifier.Weak },
|
||||
new HitData.DamageModPair { m_type = HitData.DamageType.Slash, m_modifier = HitData.DamageModifier.Weak }
|
||||
};
|
||||
|
||||
// Bonemass passive. Setup runs once per (re)application of this effect rather than
|
||||
// continuously, so - same as SkeletonRace's own PoisonImmunity check in
|
||||
// SE_SkeletonStats - a boss killed mid-life only takes effect from the next
|
||||
// respawn/re-add onward, not instantly. That already matches how every other
|
||||
// state-gated m_mods list in this mod behaves.
|
||||
if (BossProgressionManager.GetCurrentProgressionState() >= TrentaConfig.BonemassDefeatedState)
|
||||
{
|
||||
m_mods.Add(new HitData.DamageModPair { m_type = HitData.DamageType.Poison, m_modifier = HitData.DamageModifier.Immune });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Last Stand (Moder). Unlike the m_mods list above this cannot be computed once at Setup:
|
||||
/// it has to track current health, which changes every hit, so it is read fresh on every
|
||||
/// armor calculation instead - already-live boss-progression state included, so this one
|
||||
/// (unlike the Poison immunity above) does take effect the instant Moder falls, no
|
||||
/// respawn needed.
|
||||
/// </summary>
|
||||
public override void ModifyArmorMods(ref float armor)
|
||||
{
|
||||
base.ModifyArmorMods(ref armor);
|
||||
|
||||
if (!(m_character is Player player) || player != Player.m_localPlayer) return;
|
||||
if (!TrentaRace.IsTrenta()) return;
|
||||
if (BossProgressionManager.GetCurrentProgressionState() < TrentaConfig.ModerDefeatedState) return;
|
||||
|
||||
float maxHealth = player.GetMaxHealth();
|
||||
if (maxHealth <= 0f) return;
|
||||
|
||||
float missingFraction = Mathf.Clamp01(1f - player.GetHealth() / maxHealth);
|
||||
armor *= 1f + TrentaConfig.LastStandMaxArmorBonus * missingFraction;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Exists only so the HUD has something to count down, the way SE_DvergarAbilityCooldown and
|
||||
/// SE_SkadiAbilityCooldown do: Valheim prints the remaining time of any effect with a m_ttl.
|
||||
/// </summary>
|
||||
public class SE_TrentaAbilityCooldown : StatusEffect
|
||||
{
|
||||
}
|
||||
|
||||
public static class TrentaStatusEffects
|
||||
{
|
||||
public static SE_TrentaStats StatsSE { get; private set; }
|
||||
|
||||
public static void RegisterStatusEffects()
|
||||
{
|
||||
var stats = ScriptableObject.CreateInstance<SE_TrentaStats>();
|
||||
stats.name = TrentaConfig.StatsSE;
|
||||
stats.m_name = "Heartwood";
|
||||
stats.m_icon = GetItemIcon("Wood"); // TODO: pick the icon the race should carry
|
||||
|
||||
CustomStatusEffect customStats = new CustomStatusEffect(stats, fixReference: false);
|
||||
ItemManager.Instance.AddStatusEffect(customStats);
|
||||
StatsSE = customStats.StatusEffect as SE_TrentaStats;
|
||||
|
||||
var purpleRainCd = ScriptableObject.CreateInstance<SE_TrentaAbilityCooldown>();
|
||||
purpleRainCd.name = TrentaConfig.PurpleRainCdSE;
|
||||
purpleRainCd.m_name = "Purple Rain";
|
||||
purpleRainCd.m_tooltip = "The pollen must settle before you may call the rain again.";
|
||||
purpleRainCd.m_icon = GetItemIcon("TrophyGreydwarfShaman") ?? GetItemIcon("Wood");
|
||||
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(purpleRainCd, fixReference: false));
|
||||
|
||||
var portalCd = ScriptableObject.CreateInstance<SE_TrentaAbilityCooldown>();
|
||||
portalCd.name = TrentaConfig.PortalCdSE;
|
||||
portalCd.m_name = "Homecoming Portal";
|
||||
portalCd.m_tooltip = "The way home has not yet settled enough to open again.";
|
||||
portalCd.m_icon = GetItemIcon("Wood");
|
||||
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(portalCd, fixReference: false));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drives the HUD countdown for an ability, mirroring DvergarStatusEffects: the effect
|
||||
/// only has to exist with a m_ttl for the icon to tick down by itself.
|
||||
/// </summary>
|
||||
public static void ApplyCooldownIcon(string effectName, float seconds)
|
||||
{
|
||||
if (Player.m_localPlayer == null || seconds <= 0f) return;
|
||||
|
||||
int hash = effectName.GetStableHashCode();
|
||||
SEMan seman = Player.m_localPlayer.GetSEMan();
|
||||
seman.RemoveStatusEffect(hash, true);
|
||||
seman.AddStatusEffect(hash, true);
|
||||
|
||||
StatusEffect se = seman.GetStatusEffect(hash);
|
||||
if (se != null) se.m_ttl = seconds;
|
||||
}
|
||||
|
||||
private static Sprite GetItemIcon(string prefabName)
|
||||
{
|
||||
GameObject prefab = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName)?.gameObject;
|
||||
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
|
||||
if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0)
|
||||
{
|
||||
return drop.m_itemData.m_shared.m_icons[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
53
JotunnModStub/Trenta/TrentaVisuals.cs
Normal file
53
JotunnModStub/Trenta/TrentaVisuals.cs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// The Trenta's looks: body scale, skin tint, and whatever cosmetic parts the race wears.
|
||||
///
|
||||
/// Everything here runs for local and remote players alike, which is why it takes a Player
|
||||
/// rather than reading Player.m_localPlayer.
|
||||
/// </summary>
|
||||
public static class TrentaVisuals
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads the race off the ZDO so remote players render correctly, falling back to
|
||||
/// m_customData for the main-menu preview which has no ZNetView.
|
||||
/// </summary>
|
||||
public static string GetPlayerRace(Player player)
|
||||
{
|
||||
if (player == null) return "Human";
|
||||
|
||||
ZNetView nview = player.GetComponent<ZNetView>();
|
||||
if (nview != null && nview.IsValid())
|
||||
{
|
||||
string race = nview.GetZDO().GetString("RacesOfValheim_Race", "");
|
||||
if (!string.IsNullOrEmpty(race)) return race;
|
||||
}
|
||||
|
||||
if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string custom))
|
||||
{
|
||||
return custom;
|
||||
}
|
||||
|
||||
return "Human";
|
||||
}
|
||||
|
||||
public static bool IsTrentaPlayer(Player player)
|
||||
{
|
||||
return GetPlayerRace(player) == TrentaConfig.RaceId;
|
||||
}
|
||||
|
||||
// TODO: the rest of the cosmetic work. Skin and hair/beard tint are already handled by
|
||||
// Trenta_VisEquipment_UpdateColors_Patch in TrentaPatches.cs.
|
||||
//
|
||||
// Body scale goes on the player's "Visual" child, not the root transform - scaling the
|
||||
// root drags the collider and the camera pivot with it. RaceScale owns the list of races
|
||||
// that resize, so the Trenta has to be added there rather than fighting it per-frame.
|
||||
//
|
||||
// Extra meshes (bark, foliage) are hung off a bone of the player's rig and hidden by
|
||||
// collapsing every unwanted bone to zero scale - a creature prefab's mesh usually ships
|
||||
// with Read/Write disabled and cannot be carved at runtime. DvergarVisuals.ApplyHood is
|
||||
// the worked example.
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue