Modding Monster Train – Patch to Allow for Adding Custom Units with Custom Syntheses

July 28, 2021

Modding with Harmony

Monster Train


Title:
My Monster Train Custom Unit Synthesis Patch

By:
Steven lilley (Me)


Github – Link

Description:
Link to my github page leading to my patch for adding custom units and syntheses to Monster Train.


Overview

Monster Train modding suffered from a lot of issues when the latest large DLC was made, the Last Divinity. Trainworks, a modding API created to help with modding Monster Train, was created before this DLC, and its addition broke many of its features.

One of the large additions from the DLC itself was unit synthesis, which let you break a character down into a unique upgrade for another character. This however was impossible to implement with Trainworks since it encountered new bugs because of unforeseen interactions with the new content. Originally, it would not even run if using new content, but a few updates to Trainworks at least made using them possible. However, unit syntheses continued to be an issue that did not work.

The existing custom units did not have any essences as they were created before the DLC. Trying to synthesize them into another unit would then create a softlock in the game. Being such a crucial aspect of the game, I investigated the error in an effort to remove it either on my own or through additional information to improve future iterations of Trainworks.

Issue and Monster Train’s UnitSynthesisMapping Class

CollectMappingData Method

The new DLC added a class within Monster Train’s base code named UnitSynthesisMapping which is responsible for creating the list of unit syntheses and holding that data for use in game. It has a method named CollectMappingData, which searches through the AllGameData for a list of all the CharacterData and all the CardUpgradeData in the game. It creates an initial list from every CharacterData in the game (to make sure every character has one, and only one upgrade).

While this appeared to be a perfect point to approach this issue, it was a bit indirect. This class was contained within a Unity Scriptable object, and most of the properties and methods contained within were private and very encapsulated. My best guess is that this Scriptable Object exists for the Monster Train team within the Unity Inspector and they actually call the CollectMappingData method with a button in the Inspector. This is because that method specifically has a Unity attribute called Context Menu which lets it be called from within the Inspector, outside of running the game. This threw me off for a while since I was trying to track when this method was called, and it turns out it never gets called naturally during the running of the game.

CollectMappingData Code from Monster Train

[ContextMenu("Collect Mapping Data")]
	private void CollectMappingData()
	{
		this.editorMappings.Clear();
		foreach (CardData cardData in this.allGameData.GetAllCardData())
		{
			if (!cardData.IsArchived && cardData.IsSpawnerCard() && !cardData.GetSpawnCharacterData().IsChampion())
			{
				this.editorMappings.Add(new UnitSynthesisMapping.MappingEntry(cardData.GetSpawnCharacterData(), null));
			}
		}
		this.editorMappings.Sort((UnitSynthesisMapping.MappingEntry a, UnitSynthesisMapping.MappingEntry b) => a.character.name.CompareTo(b.character.name));
		foreach (CardUpgradeData cardUpgradeData in this.allGameData.GetAllCardUpgradeData())
		{
			if (cardUpgradeData.IsUnitSynthesisUpgrade())
			{
				foreach (UnitSynthesisMapping.MappingEntry mappingEntry in this.editorMappings)
				{
					if (mappingEntry.character == cardUpgradeData.GetSourceSynthesisUnit())
					{
						mappingEntry.cardUpgrade = cardUpgradeData;
					}
				}
				cardUpgradeData.InternalSetLinkedPactDuplicateRarity(CollectableRarity.Rare);
			}
		}
	}

Calling Private Methods with Harmony and Reverse Patch

I covered this in a previous blog post, but it did turn out that this method worked well for accessing a calling a private method from within the base game’s code when I wanted to. Since I just wanted to forcibly call that private method, CollectMappingData, I did not need any other extra logic to run at the time. This makes the code for it very tight as follows:

[HarmonyPatch(typeof(UnitSynthesisMapping), "CollectMappingData", new Type[] { })]
    public class RecallingCollectMappingData
    {
        [HarmonyReversePatch]
        public static void MyTest(object instance)
        {
            // It's a stub so it has no initial content
        }
    }

The hardest part of implementing this was that it would work easiest with the single existing instance of the UnitSynthesisMapping class during the runtime of the game. We could instantiate our own instance to supply to this method, but without the other data it did not work at all. I was finally able to find a route to getting a reference to the actual existing instance through Trainworks actually.

Trainworks has a way to access the AllGameData class instance in the game, which gave me an entry point into a lot of data in the game. Through this, I was able to access the BalanceData class, which then gave me direct access to the existing UnitSynthesisMapping instance. This could then be passed into my Reverse Patch to call the method just as if it had been called from within that specific instance, which has all the access to the game’s data and existing lists if needed. This example path is shown below:

public static void FindUnitSynthesisMappingInstanceToStub()
        {
            // Gets a reference to AllGameData with Trainworks
            AllGameData testData = ProviderManager.SaveManager.GetAllGameData();
            CustomUnitSynthesisPatcher.Log("Got reference to AllGameData: " + testData.name);

            // Use AllGameData to get access to BalanceData
            BalanceData balanceData = testData.GetBalanceData();
            CustomUnitSynthesisPatcher.Log("Got reference to BalanceData: " + balanceData.name);

            // Use BalanceData to get access to the current instance of the UnitSynthesisMapping
            UnitSynthesisMapping mappingInstance = balanceData.SynthesisMapping;
            if (mappingInstance == null)
            {
                CustomUnitSynthesisPatcher.Log("Failed to find a mapping instance.");
            }
            else
            {
                CustomUnitSynthesisPatcher.Log("Able to find mapping instance: " + mappingInstance.GetID()); // Test to see if this is a different instance
            }

            // Calls CollectMappingData method
            RecallingCollectMappingData.MyTest(mappingInstance);
            CustomUnitSynthesisPatcher.Log("Called CollectMappingData.");
        }

Key String Tests for this Approach: CardEffectData and CardUpgradeData

Renaming the EffectStateName of the CardEffectData to Override Trainworks Default

It turns out two of the main hiccups I ran into with this approach were simply because of string checks not finding exactly what they wanted (or accidentally finding too many strings that were exactly the same). The first issue was in the CollectMappingData method’s first foreach loop, which includes in its if statement that cardData.IsSpawnerCard(). Somewhere along the lines it checks that the card has a CardEffectData specifically named “CardEffectSpawnMonster”. This was not being picked up initially however because Trainworks sets that property of your card to a very long string that also included “CardEffectSpawnMonster”, but all that information kept that part of the check from returning true. So simply making sure to rename that specific CardEffectData object’s EffectStateName to “CardEffectSpawnMonster” after setting EffectStateType (since this includes methods for creating its own EffectStateName) gets through this issue.

Setting the UpgradeTitleKey of your Synthesis CardUpgradeData to Override Trainworks Default

It just so happens that Trainworks default string options for some of these do not match the exact needs of this new Monster Train class (as they were made before these existed), and this was another case of that (although it made more sense). In the synthesis you build, if an UpgradeTitleKey is not set, a fairly empty default one is made for your CardUpgradeData. If you do not set this for several CardUpgradeData objects you make, then they will all have this SAME default UpgradeTitleKey. As a duplication check however, when adding a new CardUpgradeData to the overall list in the game, Trainworks checks by UpgradeTitleKey whether that name already exists or not, and if it does, it removes it from the list and adds the new one. As one would expect, if you have a bunch of objects with the same UpgradeTitleKey then, they all continually get replaced until only the last one remains (as it never gets replaced).

This is easy enough to solve by simply making sure to set a unique UpgradeTitleKey for each of your unit synthesis CardUpgardeDataBuilder objects. This is all that is required to make sure they do not keep deleting themselves in the current iteration of Trainworks (and is just a good practice in general).

via Blogger http://stevelilleyschool.blogspot.com/2021/07/modding-monster-train-patch-to-allow.html

Modding Monster Train – Harmony Reverse Patches

July 14, 2021

Modding with Harmony

Monster Train


Title:
Harmony ParDeike – Reverse Patch

By:
Harmony


Harmony – Documentation

Description:
Harmony documentation on patching with the Reverse Patch.


Overview

I was investigating ways to use Harmony to access private methods and fields from classes within the Unity target game itself, Monster Train in this case. One of the first direct options I came across was using reverse patches.

Basics of the Reverse Patch

“A reverse patch is a stub method in your own code that ‘becomes’ the original or part of the original method so you can use that yourself.”

    Typical use cases:

  • easily call private methods
  • no reflection, no delegate, native performance
  • you can cherry-pick part of the original method by using a transpiler
  • can give you the unmodified original
  • will freeze the implementation to the time you reverse patch

Implementation

After seeing its first use case being calling private methods, I thought this would be a perfect tool to use. As far as I have found, it appears to need a reference to an instance of the object that the private method belongs to. This has proved rather troublesome. While the setting up of the reverse patch has appeared to work and run, it is running into other issues that require further research.

The class I am trying to access is a Unity Scriptable Object, and has no easy way to directly access the existing instance (that I have found so far). I tried circumventing this by creating my own instance to work from, but that has its own issues. The new instance, if it is even being generated properly, is not intialized in any way and is missing integral references, such as to the AllGameData, which are also difficult to inject into the instance. This is again because it is a Unity Scriptable Object, so most fields are private but serialized, so they are very protected and only exposed in the Unity Inspector to make the necessary references I am missing in a newly generated instance.

via Blogger http://stevelilleyschool.blogspot.com/2021/07/modding-monster-train-harmony-reverse.html

Modding Monster Train – Basics and Introduction

June 21, 2021

Modding

Monster Train


Title:
Monster Train – Shiny Mark mades mods

By:
Good Shepherd Entertainment


Youtube – Tutorial #1

Description:
Extremely basic introduction to setting up a C# project for modding Monster Train (slightly outdated).


Title:
Monster Train Modding Card Creation Tutorial Mod

By:
Good Shepherd Entertainment


Youtube – Tutorial #2

Description:
Introduction to using the Trainworks API, a modding tool for Monster Train geared towards adding new content.


Title:
Getting Started with Trainworks Modding Tools

By:
KittenAqua


Github – Wiki

Description:
More detailed and indepth documentation on properly setting up a C# project for modding Monster Train as well as examples for modding various content.


Overview

Monster Train is a game I have played a lot and really enjoyed, and it recently put out some modding support in the last year. Being a Unity-based game, I figured I could use some of my Unity and C# knowledge to take a crack at modding in some content of my own to play around with and possibly add to the community.

It is not the most straight forward process, and there was recently a large DLC added to the game that makes parts of the old modding tutorials different or completely obsolete, but I still think there enough to sift through to make a base for starting a mod going. I think there is also a decently strong community that would appreciate some mod content since it is rather lacking, so it could also just be a nice place to implement some game design practices and create some new stuff for others to play with.

via Blogger http://stevelilleyschool.blogspot.com/2021/06/modding-monster-train-basics-and.html