RacesOfValheim/JotunnModStub/Alfar/AlfarProbe.cs
Ferdinando 3f8cf1ee27 feat(alfar): v1.6.0 - the Alfar, an eleventh race
Grey, tall and thin, with black eyes. Eitr is armour and fuel (shield,
diet, soft fall, levitation), Heimkall sends a lethal blow home at one
health every 20 minutes. Caster powers from Skrid to the archon
Sameining, with on-screen cooldowns. Automated base around the
Ljoskjarne: drones, three constructs, crystals, Ljosgard, Prismavard.
Compendium page in EN/IT/RU.

README: New in block, race section, progression, station line, changelog.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 17:38:28 +01:00

434 lines
20 KiB
C#

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