From ce87e987c9d5e2eb00eea64b54e23d4c45dd7e55 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Thu, 6 Aug 2026 10:13:57 +0200 Subject: [PATCH] factionsmerchants --- .../Factions/FactionHostilityPatch.cs | 88 ++++++ JotunnModStub/Factions/FactionMerchant.cs | 12 + .../Factions/FactionMerchantCatalog.cs | 268 ++++++++++++++++++ .../Factions/FactionMerchantJokes.cs | 131 +++++++++ .../Factions/FactionMerchantPatches.cs | 161 +++++++++++ .../Factions/FactionMerchantRuntime.cs | 56 ++++ .../Factions/FactionMerchantSellPanel.cs | 193 +++++++++++++ .../Factions/FactionMerchantSetup.cs | 71 +++++ 8 files changed, 980 insertions(+) create mode 100644 JotunnModStub/Factions/FactionHostilityPatch.cs create mode 100644 JotunnModStub/Factions/FactionMerchant.cs create mode 100644 JotunnModStub/Factions/FactionMerchantCatalog.cs create mode 100644 JotunnModStub/Factions/FactionMerchantJokes.cs create mode 100644 JotunnModStub/Factions/FactionMerchantPatches.cs create mode 100644 JotunnModStub/Factions/FactionMerchantRuntime.cs create mode 100644 JotunnModStub/Factions/FactionMerchantSellPanel.cs create mode 100644 JotunnModStub/Factions/FactionMerchantSetup.cs diff --git a/JotunnModStub/Factions/FactionHostilityPatch.cs b/JotunnModStub/Factions/FactionHostilityPatch.cs new file mode 100644 index 0000000..7a20956 --- /dev/null +++ b/JotunnModStub/Factions/FactionHostilityPatch.cs @@ -0,0 +1,88 @@ +using System.Collections.Generic; +using HarmonyLib; + +namespace RacesOfValheim +{ + // "Mobs of a faction don't attack players of the same faction" - the core Factions + // rule from the brainstorm. RaceHostilityManager.cs already grants some of this + // (Fenrir/Aswid/Draugh/Trenta), but several races have no coverage at all (Trol, + // Furling, Skadi, Dvergar, Skeleton), and none of it lines up race-for-race with the + // three Factions groupings. Both patches postfix the same vanilla method, so this one + // simply layers the full, faction-consistent ruleset on top without touching the + // older file - a player already exempted there stays exempted, this only adds pairs. + // + // Without this, a matching-faction mob keeps fighting the player, which is why the + // Trader's "E to use" prompt never has a chance to come up: BaseAI.UpdateAI() is + // still busy chasing/attacking every frame. + [HarmonyPatch(typeof(BaseAI), nameof(BaseAI.IsEnemy), new System.Type[] { typeof(Character), typeof(Character) })] + public static class FactionHostilityPatch + { + private static readonly HashSet NeraForestaMobs = new HashSet + { + "Greydwarf", "Greydwarf_Elite", "Greydwarf_Shaman", + "Fuling", "GoblinBrute", "GoblinShaman", + "Troll", + }; + + private static readonly HashSet MontagnaMobs = new HashSet + { + "Hatchling", // Drake + "Wolf", "Ulv", "Fenring", "Fenring_Cultist", + "Dverger", "DvergerMageFire", "DvergerMageIce", "DvergerMageSupport", "DvergerAshlands", + }; + + private static readonly HashSet PaludeMobs = new HashSet + { + "Ghost", "Skeleton", "Skeleton_Poison", // Skeleton, Rancid remains + "Draugr", "Draugr_Elite", + "Wraith", "Leech", "Abomination", + "Blob", "BlobElite", "BlobTar", // Blob, Oozer, Growth + }; + + // Every race id ever assigned to m_customData["Race"] for the nine playable races, + // grouped by which faction's mobs they get along with (see RacesOfValheim.cs for + // where each string is set, and DvergarRace.cs's LegacyRaceId for the old save value). + private static readonly Dictionary> RaceFactionMobs = new Dictionary> + { + { TrentaConfig.RaceId, NeraForestaMobs }, + { "Trol", NeraForestaMobs }, + { "Furling", NeraForestaMobs }, + + { "Skadi", MontagnaMobs }, + { "Fenrir", MontagnaMobs }, + { DvergarConfig.RaceId, MontagnaMobs }, + { DvergarRace.LegacyRaceId, MontagnaMobs }, + + { "Aswid", PaludeMobs }, + { "Draugh", PaludeMobs }, + { SkeletonVisuals.RaceId, PaludeMobs }, + }; + + // Shared with FactionMerchantHoverPatch: a player should only get the "E - Talk" + // hover prompt for a mob whose faction actually matches their own race. + public static bool IsSameFaction(Player player, Character monster) + { + if (player == null || monster == null) return false; + if (!player.m_customData.TryGetValue("Race", out string race)) return false; + if (!RaceFactionMobs.TryGetValue(race, out HashSet mobs)) return false; + + string prefabName = monster.gameObject.name.Replace("(Clone)", "").Trim(); + return mobs.Contains(prefabName); + } + + public static void Postfix(Character a, Character b, ref bool __result) + { + if (!__result) return; // already not enemies, nothing to add + if (a == null || b == null) return; + + Character playerCharacter = a.IsPlayer() ? a : (b.IsPlayer() ? b : null); + Character monster = a.IsPlayer() ? b : (b.IsPlayer() ? a : null); + if (!(playerCharacter is Player p) || monster == null) return; + + if (IsSameFaction(p, monster)) + { + __result = false; + } + } + } +} diff --git a/JotunnModStub/Factions/FactionMerchant.cs b/JotunnModStub/Factions/FactionMerchant.cs new file mode 100644 index 0000000..3ee6bbd --- /dev/null +++ b/JotunnModStub/Factions/FactionMerchant.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + // Marker component added to a spawned mob instance that FactionMerchantSetup has + // turned into a trader. Everything else in the Factions module reads this to know + // "this Character belongs to our system" and which catalogue/jokes it uses. + public class FactionMerchant : MonoBehaviour + { + public FactionMerchantCatalog.ShopDefinition Shop; + } +} diff --git a/JotunnModStub/Factions/FactionMerchantCatalog.cs b/JotunnModStub/Factions/FactionMerchantCatalog.cs new file mode 100644 index 0000000..126cee9 --- /dev/null +++ b/JotunnModStub/Factions/FactionMerchantCatalog.cs @@ -0,0 +1,268 @@ +using System.Collections.Generic; + +namespace RacesOfValheim +{ + // Data-only: the full buy/sell catalogue designed in the Factions brainstorm + // (see Pacchetto_Rame/Factions_Brainstorm.txt for the source-of-truth tables). + // Prices are symmetric: a merchant buys and sells every listed item at the + // same price, coins are never a tradeable item. + public static class FactionMerchantCatalog + { + public class CatalogEntry + { + public string PrefabName; + public int Price; + + public CatalogEntry(string prefabName, int price) + { + PrefabName = prefabName; + Price = price; + } + } + + public class ShopDefinition + { + public string DisplayName; + public string JokeCategory; + public List Items; + } + + // Joke category keys, matched against FactionMerchantJokes. + public const string JokeLegnoFalegname = "LegnoFalegname"; + public const string JokeGoblin = "Goblin"; + public const string JokeTroll = "Troll"; + public const string JokeLupoLicantropo = "LupoLicantropo"; + public const string JokeNano = "Nano"; + public const string JokeStrega = "Strega"; + public const string JokeScheletro = "Scheletro"; + public const string JokeNonMortoZombie = "NonMortoZombie"; + public const string JokeFantasma = "Fantasma"; + + private static readonly ShopDefinition GreydwarfShop = new ShopDefinition + { + DisplayName = "Greydwarf", + JokeCategory = JokeLegnoFalegname, + Items = new List + { + new CatalogEntry("Wood", 1), + new CatalogEntry("Stone", 2), + new CatalogEntry("Resin", 5), + new CatalogEntry("GreydwarfEye", 5), + new CatalogEntry("Dandelion", 5), + new CatalogEntry("Bukeperries", 5), + new CatalogEntry("Mushroom", 5), + new CatalogEntry("Blueberries", 5), + new CatalogEntry("Thistle", 5), + new CatalogEntry("Carrot", 5), + new CatalogEntry("CarrotSeeds", 20), + new CatalogEntry("AncientSeed", 20), + new CatalogEntry("TrophyGreydwarf", 20), + new CatalogEntry("TrophyGreydwarfBrute", 350), + new CatalogEntry("TrophyGreydwarfShaman", 350), + } + }; + + private static readonly ShopDefinition TrollShop = new ShopDefinition + { + DisplayName = "Troll", + JokeCategory = JokeTroll, + Items = new List + { + new CatalogEntry("TrollHide", 1), + new CatalogEntry("DeerHide", 2), + new CatalogEntry("DeerMeat", 2), + new CatalogEntry("LeatherScraps", 5), + new CatalogEntry("BoarMeat", 5), + new CatalogEntry("NeckTail", 5), + new CatalogEntry("TrophyNeck", 20), + new CatalogEntry("TrophyDeer", 20), + new CatalogEntry("TrophyBoar", 50), + new CatalogEntry("TrophyForestTroll", 1500), + } + }; + + private static readonly ShopDefinition FulingShop = new ShopDefinition + { + DisplayName = "Fuling", + JokeCategory = JokeGoblin, + Items = new List + { + new CatalogEntry("BlackMetalScrap", 1), + new CatalogEntry("LoxMeat", 1), + new CatalogEntry("SerpentMeat", 1), + new CatalogEntry("SerpentScale", 1), + new CatalogEntry("LoxPelt", 2), + new CatalogEntry("Flax", 5), + new CatalogEntry("Barley", 5), + new CatalogEntry("Cloudberries", 5), + new CatalogEntry("Tar", 5), // Growth, folded in here: Growth lives in Plains, same biome as Lox/Ocean + new CatalogEntry("Tuna", 50), + new CatalogEntry("CoralCod", 70), + new CatalogEntry("FulingTotem", 350), + new CatalogEntry("TrophyGoblin", 350), + new CatalogEntry("TrophyGoblinShaman", 350), + new CatalogEntry("TrophyLox", 350), + new CatalogEntry("Pufferfish", 350), + new CatalogEntry("TrophyGrowth", 800), // Growth + new CatalogEntry("TrophyGoblinBrute", 1500), + new CatalogEntry("TrophySerpent", 1500), + } + }; + + private static readonly ShopDefinition WolfShop = new ShopDefinition + { + DisplayName = "Wolf", + JokeCategory = JokeLupoLicantropo, + Items = new List + { + new CatalogEntry("WolfFang", 5), + new CatalogEntry("WolfMeat", 5), + new CatalogEntry("WolfPelt", 5), + new CatalogEntry("Onion", 5), + new CatalogEntry("FreezeGland", 5), // Drake, folded in here: no talk-capable rig + new CatalogEntry("OnionSeeds", 20), + new CatalogEntry("TrophyWolf", 350), + new CatalogEntry("TrophyHatchling", 350), // Drake (internal id "Hatchling") + } + }; + + private static readonly ShopDefinition UlvShop = new ShopDefinition + { + DisplayName = "Ulv", + JokeCategory = JokeLupoLicantropo, + Items = new List + { + new CatalogEntry("WolfFang", 5), + new CatalogEntry("TrophyUlv", 350), + } + }; + + private static readonly ShopDefinition FenringShop = new ShopDefinition + { + DisplayName = "Fenring", + JokeCategory = JokeLupoLicantropo, + Items = new List + { + new CatalogEntry("WolfFang", 5), + new CatalogEntry("TrophyFenring", 350), + } + }; + + private static readonly ShopDefinition CultistShop = new ShopDefinition + { + DisplayName = "Cultist", + JokeCategory = JokeStrega, + Items = new List + { + new CatalogEntry("JuteRed", 2), + new CatalogEntry("TrophyCultist", 1500), + } + }; + + private static readonly ShopDefinition DvergShop = new ShopDefinition + { + DisplayName = "Dverg", + JokeCategory = JokeNano, + Items = new List + { + new CatalogEntry("BlackMarble", 20), + new CatalogEntry("SoftTissue", 250), + new CatalogEntry("Sap", 250), // extracted from Yggdrasil roots with Dvergr extractors + new CatalogEntry("TrophyDvergr", 1500), + } + }; + + private static readonly ShopDefinition DraugrShop = new ShopDefinition + { + DisplayName = "Draugr", + JokeCategory = JokeNonMortoZombie, + Items = new List + { + new CatalogEntry("Entrails", 2), + new CatalogEntry("Mushroom", 5), + new CatalogEntry("Thistle", 5), + new CatalogEntry("Turnip", 5), + new CatalogEntry("Bloodbag", 5), // Leech, folded in here: no talk-capable rig + new CatalogEntry("Guck", 1), // Abomination, folded in here: cannot speak at all + new CatalogEntry("Root", 1), // Abomination + new CatalogEntry("TurnipSeeds", 20), + new CatalogEntry("TrophyDraugr", 350), + new CatalogEntry("TrophyLeech", 350), // Leech + new CatalogEntry("TrophyDraugrElite", 800), + new CatalogEntry("TrophyAbomination", 1500), // Abomination + } + }; + + private static readonly ShopDefinition SkeletonShop = new ShopDefinition + { + DisplayName = "Skeleton", + JokeCategory = JokeScheletro, + Items = new List + { + new CatalogEntry("BoneFragments", 1), + new CatalogEntry("Ooze", 2), // Blob/Oozer, folded in here: no talk-capable rig + new CatalogEntry("ScrapIron", 20), // Oozer + new CatalogEntry("TrophySkeleton", 350), + new CatalogEntry("TrophyBlob", 350), // Blob + new CatalogEntry("TrophySkeletonPoison", 800), + } + }; + + private static readonly ShopDefinition GhostShop = new ShopDefinition + { + DisplayName = "Ghost", + JokeCategory = JokeFantasma, + Items = new List + { + new CatalogEntry("Ectoplasm", 2), + new CatalogEntry("TrophyGhost", 350), + } + }; + + private static readonly ShopDefinition WraithShop = new ShopDefinition + { + DisplayName = "Wraith", + JokeCategory = JokeFantasma, + Items = new List + { + new CatalogEntry("Chain", 5), + new CatalogEntry("TrophyWraith", 1500), + } + }; + + // Key = vanilla creature prefab name (internal id, not the wiki display name). + // Several creature families share one ShopDefinition instance on purpose. + public static readonly Dictionary Shops = new Dictionary + { + { "Greydwarf", GreydwarfShop }, + { "Greydwarf_Elite", GreydwarfShop }, + { "Greydwarf_Shaman", GreydwarfShop }, + + { "Troll", TrollShop }, + + { "Fuling", FulingShop }, + { "GoblinBrute", FulingShop }, + { "GoblinShaman", FulingShop }, + + { "Wolf", WolfShop }, + { "Ulv", UlvShop }, + { "Fenring", FenringShop }, + { "Fenring_Cultist", CultistShop }, + + { "Dverger", DvergShop }, + { "DvergerMageFire", DvergShop }, + { "DvergerMageIce", DvergShop }, + { "DvergerMageSupport", DvergShop }, + { "DvergerAshlands", DvergShop }, + + { "Draugr", DraugrShop }, + { "Draugr_Elite", DraugrShop }, + + { "Skeleton", SkeletonShop }, + { "Skeleton_Poison", SkeletonShop }, + + { "Ghost", GhostShop }, + { "Wraith", WraithShop }, + }; + } +} diff --git a/JotunnModStub/Factions/FactionMerchantJokes.cs b/JotunnModStub/Factions/FactionMerchantJokes.cs new file mode 100644 index 0000000..ca811e9 --- /dev/null +++ b/JotunnModStub/Factions/FactionMerchantJokes.cs @@ -0,0 +1,131 @@ +using System.Collections.Generic; + +namespace RacesOfValheim +{ + // Source: Pacchetto_Rame/Factions_Battute_Mercanti.txt (English originals column). + // One random line from the matching category is shown for 6 seconds when the + // merchant window closes (see FactionMerchantPatches). All player-facing text. + public static class FactionMerchantJokes + { + public static readonly Dictionary Lines = new Dictionary + { + [FactionMerchantCatalog.JokeScheletro] = new[] + { + "What do you call a skeleton who never does his chores? Lazy bones.", + "Why did the skeleton quit his job? His heart wasn't in it.", + "What skeleton was the first emperor of France? Napoleon Bone-aparte.", + "Who is the world's most famous skeleton detective? Sherlock Bones.", + "What did the French skeletons say before eating their dinner? Bone appetit!", + "What do skeletons always order when they go to a restaurant? Spare ribs.", + "How do skeletons call each other? On their tele-bone.", + "What's a skeleton's favorite fruit? Bone-ana!", + "Why are skeletons bad at lying? You can see right through them!", + "Why don't skeletons fight each other? They don't have the guts.", + }, + [FactionMerchantCatalog.JokeNonMortoZombie] = new[] + { + "When do zombies go to sleep? When they are dead tired.", + "What streets do zombies live on? Dead ends.", + "Where do zombies go sailing? Lake Eerie.", + "What do you call a zombie in pajamas? The sleepwalking dead.", + "How are zombies like computers? They use mega-bites!", + "Why did the zombie lose his lawsuit? He had no leg to stand on!", + "Why did the zombie eat a light bulb? Because he wanted a light snack.", + "Why don't zombies eat clowns? Because they taste funny!", + "Why did the zombie go to school? To improve his brainpower.", + "Zombies are hopeless romantics, seeking their ghoul-mate.", + }, + [FactionMerchantCatalog.JokeFantasma] = new[] + { + "Why was the ghost lonely? It had no-body.", + "What's the most useless room in a house for a ghost? A living room.", + "What's a ghost's favourite cheese? Ghoul-da cheese.", + "What's a ghost's favourite food? Boo-rritos.", + "What's a ghost's favourite dessert? I-scream.", + "What's a ghost's favourite game? Hide and Shriek.", + "What do you call a ghost with a broken leg? A hoblin goblin.", + "What happens when a ghost gets lost in the fog? He is mist.", + "Ghosts love elevators because it lifts their spirits.", + "Why did the ghost cross the road? Because it was a poultry-geist.", + }, + [FactionMerchantCatalog.JokeTroll] = new[] + { + "Why do trolls love bridges? They're always crossing into new territory.", + "Why did the troll get a bad grade? He was always under the bridge of understanding.", + "Trolls don't watch TV - they stream mischief.", + "Trolls love parties - they bring the bridge snacks.", + "Trolls hate Mondays - they bridge the gap to Friday.", + "Where do trolls keep their money? Under the bridge, of course.", + "What's a troll's favorite candy? Bridge bars.", + "Why did the troll go to school? To bridge the knowledge gap.", + "What's a troll's favorite movie? The Bridge Runner.", + "What makes a troll laugh? Someone taking it seriously.", + }, + [FactionMerchantCatalog.JokeNano] = new[] + { + "A dwarf who loved gardening had a real green thumbelina.", + "Dwarves make excellent bakers; their scone courses are always the shortest.", + "Why do dwarfs make great secret agents? They can really keep things low-key.", + "A dwarf walks into a bar and hits his head - the bar was set too low.", + "Why are dwarfs so good at math? Because it's the little things that count.", + "I saw a dwarf climbing down a prison wall - it was a little condescending.", + "What do dwarfs use to fight trolls? Short swords.", + "What's a dwarf warrior's motto? Small but deadly.", + "A dwarf opened a bakery because he kneaded dough at his level.", + "What do you call a dwarf who can be invisible? A short circuit!", + }, + [FactionMerchantCatalog.JokeLupoLicantropo] = new[] + { + "Why did the werewolf laugh while chewing on the skeleton? He got to the funny bone.", + "Why did the werewolf need to talk with the skeleton? He had a bone to pick with him.", + "A what-to-wear-wolf.", + "My werewolf skills are claw-some.", + "'Howl'-oween, hands down - a werewolf's favorite holiday.", + "Why don't werewolves use cell phones? Because they prefer to roam.", + "Why did the werewolf sit in the corner? He didn't want to be spotted.", + "Why don't werewolves gossip? They can't keep a straight paw.", + "You're fur-ociously awesome.", + "Howl you doin' tonight?", + }, + [FactionMerchantCatalog.JokeStrega] = new[] + { + "Resting witch face.", + "Hag a nice day.", + "What do you call a mage in the desert? A sand-witch.", + "What happens to witches who break the rules at school? They get ex-spelled.", + "What do witches put in their hair? Scare spray.", + "Why did three witches call in the plumber? Hubble, bubble, toilet trouble.", + "Why couldn't the little witch read her spellbook? It was written in curse-ive.", + "Why did the witch become a lawyer? She wanted to practice witchcraft.", + "Witches don't fart. They cast smells.", + "A witch tells the time by looking at her witch watch.", + }, + [FactionMerchantCatalog.JokeLegnoFalegname] = new[] + { + "Carpenters nail it every time: that's their true calling.", + "I told my saw a joke: it couldn't handle the cut.", + "I dated a carpenter once: it was a solid relationship.", + "Carpenters have great timing: they always measure up.", + "My friend builds furniture: he really wood make you laugh.", + "A good carpenter never quits: he just saws what he started.", + "I asked the wood if it was okay: it said, 'I'm board.'", + "I made a joke about a piece of wood, but it was too plane.", + "How do trees access the internet? They just log on!", + "Why did the plank cross the road? To get to the other siding!", + }, + [FactionMerchantCatalog.JokeGoblin] = new[] + { + "Those goblin fingers are dexter-gnome-us.", + "Why did the goblin break the vase? He wanted to smash expectations.", + "That goblin really gnome-napped my sandwich.", + "Just goblin around.", + "They love orc-strating trouble.", + "If a goblin smiles at you, check your pockets.", + "Why don't goblins shower? They prefer natural grime.", + "What's a goblin's favorite sport? Lootball.", + "How do goblins shop? Five-finger discount only.", + "What's a goblin's password? 'MineMineMine!'", + }, + }; + } +} diff --git a/JotunnModStub/Factions/FactionMerchantPatches.cs b/JotunnModStub/Factions/FactionMerchantPatches.cs new file mode 100644 index 0000000..c308da0 --- /dev/null +++ b/JotunnModStub/Factions/FactionMerchantPatches.cs @@ -0,0 +1,161 @@ +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + // Trader.Update() was written for Haldor/Hildir, who have no AI of their own and are + // permanently idle: it unconditionally plays a "Stand" animator bool and a greet/goodbye + // speech bubble the instant any player enters m_standRange (15m by default), with no + // check for whether a trade is actually happening. Grafted onto a mob that has its own + // MonsterAI, that reads as the creature freezing and mumbling "..." the moment it merely + // notices the player - not what a "press E to talk" merchant should do. Skipping Update() + // entirely leaves Interactable.Interact() (E opens StoreGui) and Hoverable.GetHoverText() + // (the "E - Talk" prompt) untouched, since neither of those depends on Update() running. + [HarmonyPatch(typeof(Trader), "Update")] + public static class FactionMerchantSuppressAmbientPatch + { + public static bool Prefix(Trader __instance) + { + if (((Component)__instance).GetComponent() != null) + { + return false; + } + return true; + } + } + + // Player.FindHoverObject() always figures out m_hoveringCreature correctly (it only + // needs a Character component on the hit collider, no Hoverable/Interactable + // involved) but separately sets m_hovering - the field the "E - Talk" prompt and the + // E-key handler actually use - by checking Hoverable/attachedRigidbody on the exact + // collider the raycast hit. On a full creature rig that hit is very often a limb or + // hitbox collider with no Rigidbody of its own, so m_hovering ends up pointing at + // nothing useful and the Trader added in FactionMerchantSetup is never found, even + // though the game already correctly knows which creature is being looked at. Fixing + // that one field is enough to get the vanilla prompt and E-to-open-store working. + [HarmonyPatch(typeof(Player), "UpdateHover")] + public static class FactionMerchantHoverPatch + { + // Matches vanilla Player.m_maxInteractDistance's default (5m) - FindHoverObject's + // own hoverCreature detection has no range cap of its own (only m_hovering does, + // which is exactly the field this patch is replacing), so this keeps the prompt + // from showing across the whole 50m raycast. + private const float MaxTalkDistance = 5f; + + public static void Postfix(Player __instance) + { + // Both fields are private in the assembly this project compiles against. + var traverse = Traverse.Create(__instance); + Character hovering = traverse.Field("m_hoveringCreature").GetValue(); + if (hovering == null) return; + + GameObject go = ((Component)hovering).gameObject; + if (go.GetComponent() == null) return; + if (!FactionHostilityPatch.IsSameFaction(__instance, hovering)) return; + if (Vector3.Distance(((Component)__instance).transform.position, go.transform.position) > MaxTalkDistance) return; + + traverse.Field("m_hovering").SetValue(go); + } + } + + // Player.Interact(GameObject, bool, bool) normally resolves the target itself via + // go.GetComponentInParent(), picking whichever Interactable-implementing + // component happens to sit first in the GameObject's component list. AswidPatches.cs's + // own Character.Awake postfix (Aswid_Awake_Patch) adds AswidThrall - also Interactable - + // to essentially every non-boss mob with a MonsterAI, unrelated to Factions entirely, + // and it wins that race on every creature FactionMerchantSetup also touches. The result: + // pressing E called AswidThrall.Interact() instead of Trader.Interact(), silently, with + // no error - confirmed by logging componentInParent's actual runtime type against a live + // game. Handling FactionMerchant targets here, before vanilla's own lookup ever runs, + // sidesteps the ambiguity completely instead of depending on component add order. + [HarmonyPatch(typeof(Player), "Interact")] + public static class FactionMerchantInteractPatch + { + public static bool Prefix(Player __instance, GameObject go, bool hold, bool alt) + { + if (go == null) return true; + FactionMerchant merchant = go.GetComponentInParent(); + if (merchant == null) return true; // not ours - let vanilla's own resolution run + + if (hold) return false; // Trader-style interactions have no "hold" behaviour + + Trader trader = ((Component)merchant).GetComponent(); + if (trader == null || StoreGui.instance == null) return false; + + StoreGui.instance.Show(trader); + // Say(List, string) is private in this build's assembly reference. + Traverse.Create(trader).Method("Say", trader.m_randomStartTrade, "Talk").GetValue(); + return false; + } + } + + // Keeps a faction-merchant mob standing still while (and briefly after) trading - + // MonsterAI drives the vanilla wander/attack behaviour on these creatures, and + // Trader alone (built for the always-static Haldor/Hildir) does nothing to stop it. + [HarmonyPatch(typeof(MonsterAI), "UpdateAI")] + public static class FactionMerchantFreezeAIPatch + { + public static bool Prefix(MonsterAI __instance, ref bool __result) + { + // BaseAI.m_character is private in the assembly this project compiles against. + Character character = Traverse.Create(__instance).Field("m_character").GetValue(); + if (FactionMerchantRuntime.IsProtected(character)) + { + __result = false; + return false; + } + return true; + } + } + + // Blocks player damage against a merchant mob while trading and for a few seconds + // after closing, so an accidental click right as the window shuts does not open a + // fight with someone the player was just buying wood from. + [HarmonyPatch(typeof(Character), "ApplyDamage")] + public static class FactionMerchantBlockAttackPatch + { + public static bool Prefix(Character __instance, HitData hit) + { + if (hit != null && hit.GetAttacker() == Player.m_localPlayer && FactionMerchantRuntime.IsProtected(__instance)) + { + return false; + } + return true; + } + } + + // On close: say a random joke for the mob's race (visible m_hideDialogDelay seconds, + // set to 6 in FactionMerchantSetup) and start the post-close protection window that + // the two patches above key off of. + [HarmonyPatch(typeof(StoreGui), "Hide")] + public static class FactionMerchantCloseDialoguePatch + { + private static Trader _closingTrader; + + public static void Prefix(StoreGui __instance) + { + _closingTrader = FactionMerchantRuntime.GetActiveTrader(__instance); + } + + public static void Postfix(StoreGui __instance) + { + Trader trader = _closingTrader; + _closingTrader = null; + if (trader == null) return; + + GameObject go = ((Component)trader).gameObject; + FactionMerchant merchant = go.GetComponent(); + if (merchant == null) return; + + string line = FactionMerchantRuntime.PickJokeLine(merchant.Shop); + if (!string.IsNullOrEmpty(line)) + { + // Trader.Say(string, string) is private in this build's assembly reference. + Traverse.Create(trader).Method("Say", line, "Talk").GetValue(); + } + + Character character = go.GetComponent(); + FactionMerchantRuntime.BeginProtection(character, trader.m_hideDialogDelay); + } + } +} diff --git a/JotunnModStub/Factions/FactionMerchantRuntime.cs b/JotunnModStub/Factions/FactionMerchantRuntime.cs new file mode 100644 index 0000000..b4d2ff6 --- /dev/null +++ b/JotunnModStub/Factions/FactionMerchantRuntime.cs @@ -0,0 +1,56 @@ +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + // Tracks the "just traded with this mob" window used by two independent patches: + // the MonsterAI freeze (keeps the merchant from wandering off mid-chat) and the + // player attack block (keeps an accidental click from starting a fight the instant + // the trade window closes). Both share one timer so the mob is protected for + // exactly as long as its closing joke line stays on screen. + public static class FactionMerchantRuntime + { + private static Character _lastTraded; + private static float _protectUntil; + + // StoreGui.m_trader is private in the assembly this project actually compiles + // against (see RacesOfValheim.csproj - it references the plain, non-publicized + // game DLL), so every read goes through Traverse like the rest of the codebase. + public static Trader GetActiveTrader(StoreGui gui) + { + return gui == null ? null : Traverse.Create(gui).Field("m_trader").GetValue(); + } + + public static void BeginProtection(Character trader, float seconds) + { + _lastTraded = trader; + _protectUntil = Time.time + seconds; + } + + public static bool IsProtected(Character character) + { + if (character == null) return false; + + // Actively trading right now: StoreGui itself is the source of truth. + Trader activeTraderComponent = GetActiveTrader(StoreGui.instance); + if (StoreGui.IsVisible() && activeTraderComponent != null) + { + Character activeTrader = ((Component)activeTraderComponent).GetComponent(); + if (activeTrader == character) return true; + } + + // Just closed: covered by the post-close timer. + return character == _lastTraded && Time.time < _protectUntil; + } + + public static string PickJokeLine(FactionMerchantCatalog.ShopDefinition shop) + { + if (shop == null) return null; + if (!FactionMerchantJokes.Lines.TryGetValue(shop.JokeCategory, out string[] lines) || lines.Length == 0) + { + return null; + } + return lines[Random.Range(0, lines.Length)]; + } + } +} diff --git a/JotunnModStub/Factions/FactionMerchantSellPanel.cs b/JotunnModStub/Factions/FactionMerchantSellPanel.cs new file mode 100644 index 0000000..ad97708 --- /dev/null +++ b/JotunnModStub/Factions/FactionMerchantSellPanel.cs @@ -0,0 +1,193 @@ +using System.Collections.Generic; +using HarmonyLib; +using TMPro; +using UnityEngine; +using UnityEngine.UI; + +namespace RacesOfValheim +{ + // Builds the second column the brainstorm asked for: every item in the current + // trader's catalogue that the player is currently carrying, priced the same as the + // buy column (buy price == sell price, per the Factions design rules). Left click + // sells one unit, ctrl+click sells the whole stack. + // + // Vanilla StoreGui has no such list - its own "Sell" button only ever sells a single + // arbitrary valuable item (GetSellableItem(), first m_value > 0 item found) - so this + // is a genuinely new panel, cloned at runtime from the existing buy-list column. + [HarmonyPatch(typeof(StoreGui), "Awake")] + public static class FactionMerchantSellPanelSetupPatch + { + public static void Postfix(StoreGui __instance) + { + FactionMerchantSellPanel.CreateSellColumn(__instance); + } + } + + [HarmonyPatch(typeof(StoreGui), "FillList")] + public static class FactionMerchantSellPanelFillPatch + { + public static void Postfix(StoreGui __instance) + { + FactionMerchantSellPanel.RefreshSellColumn(__instance); + } + } + + [HarmonyPatch(typeof(StoreGui), "Hide")] + public static class FactionMerchantSellPanelHidePatch + { + public static void Postfix(StoreGui __instance) + { + FactionMerchantSellPanel.ClearSellColumn(); + } + } + + public static class FactionMerchantSellPanel + { + // Column spacing is a best guess (list width isn't visible from outside the Unity + // editor) - nudge this if the two columns overlap or sit too far apart in-game. + private const float ColumnOffsetX = 260f; + + private static RectTransform _sellListRoot; + private static readonly List _sellRows = new List(); + + public static void CreateSellColumn(StoreGui gui) + { + if (_sellListRoot != null || gui.m_listRoot == null) return; + + GameObject clone = Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent); + clone.name = "FactionSellList"; + RectTransform rt = clone.GetComponent(); + rt.anchoredPosition = gui.m_listRoot.anchoredPosition + new Vector2(ColumnOffsetX, 0f); + _sellListRoot = rt; + } + + public static void ClearSellColumn() + { + foreach (GameObject row in _sellRows) + { + if (row != null) Object.Destroy(row); + } + _sellRows.Clear(); + } + + public static void RefreshSellColumn(StoreGui gui) + { + ClearSellColumn(); + Trader trader = FactionMerchantRuntime.GetActiveTrader(gui); + if (_sellListRoot == null || trader == null) return; + + FactionMerchant merchant = ((Component)trader).GetComponent(); + if (merchant == null) return; + + Player player = Player.m_localPlayer; + if (player == null) return; + + List owned = player.GetInventory().GetAllItems(); + int rowIndex = 0; + + foreach (FactionMerchantCatalog.CatalogEntry entry in merchant.Shop.Items) + { + List stacks = owned.FindAll(i => i.m_dropPrefab != null && i.m_dropPrefab.name == entry.PrefabName); + if (stacks.Count == 0) continue; + + int totalCount = 0; + foreach (ItemDrop.ItemData stack in stacks) totalCount += stack.m_stack; + + BuildRow(gui, entry, stacks[0], totalCount, rowIndex); + rowIndex++; + } + + float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue(); + float height = Mathf.Max(baseSize, rowIndex * gui.m_itemSpacing); + _sellListRoot.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height); + } + + private static void BuildRow(StoreGui gui, FactionMerchantCatalog.CatalogEntry entry, ItemDrop.ItemData sample, int totalCount, int rowIndex) + { + GameObject element = Object.Instantiate(gui.m_listElement, _sellListRoot); + element.SetActive(true); + + RectTransform rt = (RectTransform)element.transform; + float listWidth = _sellListRoot.rect.width; + float elementWidth = rt.rect.width; + float xCenterOffset = (listWidth - elementWidth) / 2f; + rt.anchoredPosition = new Vector2(xCenterOffset, rowIndex * -gui.m_itemSpacing - xCenterOffset); + + Image icon = element.transform.Find("icon").GetComponent(); + icon.sprite = sample.m_shared.m_icons[0]; + + string label = Localization.instance.Localize(sample.m_shared.m_name); + if (totalCount > 1) label = label + " x" + totalCount; + TMP_Text nameLabel = element.transform.Find("name").GetComponent(); + nameLabel.text = label; + + TMP_Text priceLabel = FindDescendant(element.transform, "price"); + if (priceLabel != null) priceLabel.text = entry.Price.ToString(); + + UITooltip tooltip = element.GetComponent(); + if (tooltip != null) + { + tooltip.Set(sample.m_shared.m_name, sample.GetTooltip(totalCount), gui.m_tooltipAnchor, default(Vector2)); + } + + Button button = element.GetComponent