Skip to content

About

Lobby, rules sync and mod compatibility for Dice Kingdoms BepInEx mods

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

ModCore

Shared game and networking logic for Dice Kingdoms mods (BepInEx 6 IL2CPP).

ModCore has no interface at all. It answers the questions every multiplayer mod ends up asking, once, and lets all mods share the answers:

  • Is the player in a Steam lobby? Who is in it? Who is the host? Did the lobby just turn into a match?
  • How do I add a setting that the host chooses in the lobby and everybody follows, frozen when the match starts?
  • Does everybody in the lobby have my mod? If not, warn before the game desyncs.
  • How do I add a new civilization without the game throwing?

Windows, buttons and settings screens are the job of UiKit. ModCore and UiKit do not know each other. ModBridge is the small plugin that shows ModCore's data on UiKit's screens (lobby rules in the lobby settings box, civilizations in the Rules drop-down).

Desync protection, not anticheat. The game has no anticheat or ban system: it uses Steam to connect the players and its own synchronisation for the match. A mod that changes the simulation on one machine only makes that machine disagree with the others. ModCore's compatibility check tells the players about this before the match; it cannot and does not stop anybody from playing.

You want Use
Know whether the player is in a Steam lobby, who is in it and who hosts it ModCore.Lobby.InLobby / IsHost / Members / Changed
React when the match starts, a phase begins or ends, somebody wins, the match screen closes ModCore.Match.Started / PhaseEntered / PhaseSynced / GameOver / Ended
Know the current phase and turn ModCore.Match.Phase / Turn / Running
Read the lobby's match settings (timer, multi meteor, teams, wonder victory), solo or tutorial ModCore.Match.Settings, Match.IsSolo, Match.IsTraining
List the players (humans and AI): name, AI difficulty, civilization, colour, team, island, defeated ModCore.Players.All / Local / Host / Find(id)
Give a mod civilization its own building models and pictures civ.Skins.BuildingModel(type, mesh, flag, yaw, icons), Tools.Meshes, Tools.Sprites
A setting the host chooses in the lobby and everybody follows ModCore.Lobby.Rules.Toggle / Number
Find out who in the lobby lacks a mod (desync warning) ModCore.Lobby.Compatibility.Warnings
Add a civilization the game accepts (tech tree, skins) ModCore.Civilizations.Add(...)
Patch game methods by name with OK/FAIL logging, find game types, call private members DiceModders.ModCore.Tools: Patcher, GameTypes, Reflect, Mem

Install (players)

Copy DiceModders.ModCore.dll into Dice-Kingdoms\BepInEx\plugins. Nothing else is needed. Mods that use it list it as a dependency, so a mod manager installs it for you. Install ModBridge as well if you want the screens (otherwise rules still work, they just have no rows to edit them).

Use it in your mod (developers)

1. Project setup

Add to your .csproj (a full file is in docs/EXAMPLE_MOD.md):

<ItemGroup>
  <Reference Include="interop/*.dll"><Private>false</Private></Reference>                       <!-- the game's interop assemblies -->
  <Reference Include="DiceModders.ModCore"><HintPath>path\to\DiceModders.ModCore.dll</HintPath><Private>false</Private></Reference>
</ItemGroup>

Private=false matters: never copy ModCore into your own package. Two copies would both patch the game.

2. Depend on it

[BepInPlugin("com.example.mymod", "My Mod", "1.0.0")]
[BepInDependency("DiceModders.ModCore")]      // ModCore loads first
public class MyModPlugin : BasePlugin { ... }

3. The name clash

The namespace DiceModders.ModCore contains a class ModCore. Inside any namespace that starts with DiceModders. the compiler reads ModCore as the namespace, so add an alias:

using Core = DiceModders.ModCore.ModCore;     // then: Core.Lobby..., Core.Civilizations...
using DiceModders.ModCore;                    // for LobbyMember, ModCivilization, ILobbyRule

Outside DiceModders.* (for example namespace MyName.MyMod) a plain using DiceModders.ModCore; is enough.

4. Call it

Everything is safe to call from Load(). ModCore installs its patches the first time you touch it (or call ModCore.Init()).


Lobby

if (Core.Lobby.InLobby && Core.Lobby.IsHost) { /* ... */ }
foreach (LobbyMember m in Core.Lobby.Members)
    Log($"{m.Name} id={m.SteamId} host={m.IsHost} me={m.IsLocal}");

Core.Lobby.Changed += () => Refresh();   // joined/left, member joined/left/kicked, owner changed (rule values: use rule.Changed)
Member Meaning
InLobby The local player is in a Steam lobby.
IsHost The local player owns the lobby.
Members IReadOnlyList<LobbyMember>: SteamId, Name, IsHost, IsLocal, IsConnected.
LocalSteamId The local Steam id (0 without Steam).
Current The raw Steamworks.Data.Lobby? for anything ModCore does not wrap.
Changed Event, raised on the main thread.

When the lobby turns into a match and back, see Match.

Limits worth knowing: a lobby entered before ModCore loaded is not seen (ModCore loads at game start, so this only matters for hot-reloading). ModCore has no update loop: Steam's lobby events are subscribed right after the game starts Steam, leaving is seen through the game's own Lobby.Leave, and a host change arrives with Steam's lobby data update.

Lobby rules

A rule is a setting the host edits before the match. The value lives in the Steam lobby data, so every client sees the same value, and it is frozen when the match starts so nobody can change it mid-game.

var meteors = Core.Lobby.Rules.Toggle("mymod.meteors", "Meteors", defaultValue: true, description: "Disasters hit the islands.");
var speed   = Core.Lobby.Rules.Number("mymod.speed", "Speed", defaultValue: 1, min: 1, max: 5, step: 1, visible: () => cheatsUnlocked);

meteors.Changed += v => Log($"meteors is now {v}");
if (meteors.Value) SpawnMeteor();                  // use .Value everywhere in gameplay code
Member of LobbyRule<T> Meaning
Value What the game should use: the host's value in a lobby, Default outside one, a frozen copy during a match.
Live The current lobby value, ignoring the freeze (what a settings screen shows).
Default, Key, Title, Description As registered. Min, Max, Step for numbers.
Editable The local player may change it now (host, before the match).
Visible Your visible callback; screens hide invisible rules.
IsNonDefault The host changed it from the default (this is what triggers compatibility warnings).
TrySet(value) Host-only; returns false when not allowed. Screens call this.
Changed Fires on every client when Value changes.
AffectsSimulation Set affectsSimulation: false for purely visual rules so they never cause a warning.

Rules to follow:

  1. Prefix the key with your mod (mymod.meteors). Registering a key twice returns the same rule.
  2. Read Value, never cache it. It changes when the lobby changes.
  3. Only rules that change what the simulation does need to be rules. A local graphics option is a normal config entry.
  4. ModCore.Lobby.Rules.All lists every rule (ILobbyRule, with ModId, ModName, ModVersion taken from the registering plugin's [BepInPlugin]); Registered fires when a new one appears.

Compatibility check

Every client publishes its rule keys and mod versions in its Steam member data (modcore.mods). When the host has set a rule away from its default and some member does not have the mod, Core.Lobby.Compatibility.Warnings contains a line such as "Alice does not have Meteors, this rule will be off for everyone in the match.". Core.Lobby.Compatibility.IsCompatible is Warnings.Count == 0. Screens (ModBridge) show these lines; your mod can also block a start button or log them.

Every client also publishes a fingerprint of each mod DLL that changes the simulation (modcore.builds: a mod with a simulation rule, a civilization, AI build orders, balance or unit-stat changes). Same version but a different file gives a warning such as "Alice has a different build of Lobby Rules 1.0.0: if the match desyncs, use the same files." The match still uses the mod. To keep the fingerprint the same for everybody who builds the same code, build reproducibly (the DiceModders mods do):

<PropertyGroup>
  <Deterministic>true</Deterministic>
  <PathMap>$(MSBuildProjectDirectory)\=/_/</PathMap>
  <IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
  <EnableSourceLink>false</EnableSourceLink>
  <EmbedUntrackedSources>false</EmbedUntrackedSources>
</PropertyGroup>

A Debug build differs from a Release build of the same code (other code is compiled), so it is reported too.

The host decides the match's rule values

When the rules are fixed for a match (the islands start to spawn), the host writes the values it uses into the lobby data (modcore.decision), and clears them when the match ends. A client that fixes its rules later takes the host's values instead of deciding by itself, so a player whose lobby data or member list was late, or who rejoins after a member without the mod left, plays with the same values as the host. Without the host's values (they have not arrived yet) every computer decides by itself from the lobby data, as before.

Match

Everything about the running match. The events come from the game's own GameState events, so they are raised on every machine (host and clients), on the main thread.

Core.Match.Started      += () => Log("match started");            // lobby rules are frozen before this
Core.Match.PhaseEntered += phase => Log($"turn {Core.Match.Turn}: {phase}");
Core.Match.PhaseSynced  += phase => Log($"{phase} ends, actions are applied now");
Core.Match.GameOver     += () => Log("somebody won");             // the match screen is still open
Core.Match.Ended        += () => Log("back in the lobby or menu"); // lobby rules follow the lobby again
Member Meaning
Running Between Started and Ended. Lobby rules are frozen while it is true.
Phase MatchPhase: None, Start (placing the first buildings, once), then every turn Harvest, Disasters, Build, Combat, Win (skipped when nobody is about to win).
Turn Turn number from 1; goes up when Win wraps back to Harvest. 0 outside a match.
IslandsSpawned Every player has loaded the islands; the match is about to start.
Started The match started.
PhaseEntered(phase) A phase began; Phase is already the new one.
PhaseSynced(phase) The phase's time ran out or everybody was ready: the planned actions are applied now. AI players make their moves at this moment.
GameOver Somebody won. Players can stay and watch.
Rejoined This machine reconnected to a running match.
Reset The game reset its match state.
Ended The match screen closed.
Settings The game's own match settings, read live: TimerSpeed (Fast, Slow, Unlimited), MultiMeteor, Teams, WonderVictory. With fewer than two humans the game itself switches the timer to Unlimited when the match starts.
IsSolo, IsTraining Fewer than two humans (no phase timer, developer commands work); the tutorial match.

Players

The players of the lobby screen and the match, humans and AI, from the game's own list (Lobby.Members is the Steam lobby: humans only).

foreach (MatchPlayer p in Core.Players.All)
    Log($"{p.Name} ai={p.IsAI} {p.Difficulty} {p.CivilizationName} {p.ColorName} team={p.Team} defeated={p.IsDefeated}");
MatchPlayer me = Core.Players.Local, host = Core.Players.Host;
MatchPlayer Meaning
Id Stable id: the Steam id for humans, a made-up id counting down from ulong.MaxValue for AI. The game recognises a reconnecting player by it.
Name, IsAI, IsLocal, IsHost Display name (AI: "Red Peasant"), and who it is.
Difficulty, Strategy AI only (AiDifficulty Passive..Sorcerer, AiStrategy Military/Wonder); null for humans. The strategy is picked when the Start phase ends.
Civilization, CivilizationName 0..4 built in, 5..127 mod civilizations (their own name).
ColorIndex, ColorName, Color, Team Player colour (0 Red .. 11 Purple) and team (colours in groups of three; meaningful with Settings.Teams).
Island, IsDefeated, IsConnected The island once spawned, defeat, connection (AI always false).
Game, IsValid The game's own Player for anything not wrapped; false once the game removed the player.

Values are read live, so keep the MatchPlayer and read it when you need it. Difficulty/Strategy are read from the game's field directly (the interop copy of that struct is broken); if a game update moves it they report null rather than a wrong value.

Civilizations

var civ = Core.Civilizations.Add("authorname.mycivilization", "My civilization", () => myTechTree, skinsLike: 2);
// civ.Id is the civilization number: the same key gives the same id on every machine, 5..127
// (the game sends the civilization as one signed byte; the built-in ones are 0..4)
Parameter Meaning
key Unique, prefixed with your name. It is hashed into the id, so multiplayer and saves agree.
name Display name.
techTree Function returning the game's DiceKingdoms.Game.TechTree for it. May be null (or return null): the tree of the skinsLike civilization is used then, so nothing throws.
skinsLike Built-in civilization whose biome and visuals are used: 0 Europe, 1 Middle East, 2 Viking, 3 Ancient, 4 Maya.

The game uses the civilization number in several places and throws (or freezes) for an unknown one. ModCore patches each of them:

Game code ModCore
Technologies.TechTree, and the copies the compiler inlined into Statistics.TechTree / IsTechnologyLearnable Your tree (or the skinsLike tree); the learnable rule is reproduced for your civilization
PlayerSkins constructor / setter (biome switch over 0..4) Built for skinsLike, the real number stored afterwards
PlayerSkins.Clone() (the Rules screen clones the lobby's skins) Cloned through skinsLike, the real number stored afterwards
The network readers of PlayerSkinsSerialization (the number travels as one byte) Build the skins from the number; an unknown number becomes the first civilization instead of throwing
PlayerSkins.Get*Prefab (skin registry lookups by civilization) Your civ.Skins model if you set one, otherwise the look of skinsLike
AIPlay.InitBuildOrders / SampleBuildOrder Every block is checked before the game parses it (one bad name would stop every AI); your civilization gets your orders, or the skinsLike ones rearranged to its tree
The castle click (Player.NextCivilization) Your civilization is added after the unlocked ones, only when every lobby member has it (published as modcore.civs); the host moves a player off one somebody lacks
The text key civilization.<id>.name name is added to the text table of the current language

Your mod provides what is its own: civ.Skins (building, unit, nature and ship prefabs; leave out what you do not replace), the tech tree (ModCore.Civilizations.CloneTree(from) copies a built-in one to edit), the name and optionally AI build orders. See the wiki page Making a civilization for the step by step guide, every asset a civilization can have and what cannot be changed (biome, 5..127). Civilizations.All, Added, Removed and civ.Remove() exist for tools. To make the civilization selectable on the Rules screen, players install ModBridge.

AI build orders

Core.Civilizations.AddBuildOrders(civ.Id, @"
civilization=ANY weight=2 strategy=MILITARY name=rush [
    technologies [ UNLOCK_STORAGE UNLOCK_ARCHERY_RANGE UNLOCK_GUARD_TOWER ]
    buildings [ house cot house farm racks racks archery storage guard ]
]");

The game's own format; civilization= is replaced with yours. Broken blocks are left out with a log line, technologies are arranged to fit the civilization's tree, and a strategy without an order uses the skinsLike orders rearranged the same way. The game's own orders (and custom-build-orders.txt) are checked too, so a broken file from another mod no longer stops the AI.

Own building models

Mesh castle = Tools.Meshes.LoadDkmesh(path, out var flag, out float yaw);          // or Tools.Meshes.Create(name, vertices, uvs, triangles)
// a model built into your DLL: the version keys ModCore's disk cache, so let it change with the model
Mesh tower = Tools.Meshes.LoadDkmesh("my-tower", () => assembly.GetManifestResourceStream("models/my-tower.dkmesh"), MyPlugin.Version + "+" + modelHash, out _, out _);
Sprite[] icons = Tools.Sprites.LoadPlayerColorSet(iconFolder);                      // 00.png .. 11.png, one per player colour
civ.Skins.BuildingModel(BuildingTypeName.CASTLE, castle, flag, yaw, icons);

On the first lookup ModCore copies the skinsLike civilization's building prefab once, puts the mesh into the normal and damaged look (one LOD group, the others blanked so nothing overlaps), moves the big flag, gives the copy the 12 pictures and returns it for your civilization. The game then uses it everywhere: in the match, pooled copies, the burnt state, and (through the pictures) the lobby card, player summary, scoreboard, end screen, build menu, Rules screen and texts. The game's materials stay, so player colours, tints and the burnt look keep working: give the mesh UVs on the game's 8x8 colour palette, in the prefab's own space. Footprint, rules and effects stay those of the original building. Pictures must be exactly one per player colour in the game's order (0 Red, 1 Pink, 2 Orange, 3 Green, 4 Carribean, 5 Cyan, 6 Yellow, 7 Ivory, 8 Brown, 9 Blue, 10 Grey, 11 Purple), 237x235 px like the game's own; otherwise they are ignored with a warning. A Skins.Building(type, prefab) for the same type wins over a model.

A whole civilization from the game's own prefabs

var civ = Core.Civilizations.Add("author.civ", "My Civ", () => myTree, skinsLike: 2);
civ.Skins.GroundColour(4, 3, grass).GroundColour(4, 4, grass2).NatureColour(2, 2, grass);   // island ground / mountains / trees
Core.Civilizations.WhenGameDataLoaded(() => {
    var look = new PlayerSkins((Civilization)2, Resources.FindObjectsOfTypeAll<SkinRegistry>()[0]);
    foreach (var type in Resources.FindObjectsOfTypeAll<BuildingTypes>()[0].Types) {
        var copy = Tools.Prefabs.Copy(look.GetBuildingVisualPrefab(type));   // change meshes, icons, ragdoll references on the copy
        civ.Skins.Building(type.name, copy);
    }
    Tools.TextSprites.AddLike("My Civ Text", entries);   // pictures inside game texts, named like your icon sprites
});
  • Civilizations.GameDataLoaded / WhenGameDataLoaded(action): once, when the game's data has loaded (SkinRegistry.Awake, main menu). Every prefab, tech tree and text sprite sheet exists from then on; build the civilization's copies here.
  • Tools.Prefabs.Copy(prefab): an inactive, persistent copy (same name) that you can change and hand to civ.Skins; the original stays untouched. The game instantiates the copy like its own prefab (pools, ragdolls, lobby card). Point ReplaceWithRagdoll.ragdollPrefab in units and inhabitants to your ragdoll copies.
  • civ.Skins.GroundColour(x, y, colour) / NatureColour(...): recolour 8x8 palette cells (x from the left, y from the bottom) on that civilization's islands only (ground; mountains, trees and flowers). Applied when the islands spawn and when the game adds a mountain or nature visual.
  • Tools.TextSprites.AddLike(assetName, entries): pictures inside game texts. The game writes <sprite name="..."> with the name of the icon sprite it shows; each entry (your sprite name, the game sprite to copy size from, a readable texture from Tools.Sprites.LoadTexture(path, true)) is fitted into a new sprite asset that is added to the fallbacks of the default one ("Icons Text"). Give your icon sprites unique names (e.g. building-icon-castle-mycivname-red).

The name the game shows comes from the name given to Add; ModCore.Civilizations.Rename(id, name, byLanguage) sets it per language ({"de": "...", "zh-CN": "..."}), and also renames a built-in civilization (0..4). ModCore answers when the game draws the name, so it follows a language change at once; it is local (other players see their own names).

Unit, building and technology names per civilization

Core.Civilizations.RenameUnit(civ.Id, Unit.Type.SOLDIER, "Footman", new Dictionary<string, string> { ["de"] = "Fußsoldat" });
Core.Civilizations.RenameBuilding(civ.Id, "WINDMILL", "Mill");
Core.Civilizations.SetText(civ.Id, "technology.TEMPLARS.description", "Replaces footmen with knights.");   // any game text key

A text is replaced while the civilization being looked at is that one: the one picked in an open Rules window, otherwise the local player's (lobby, match). Works for built-in and mod civilizations. Visual and local. The keys are the game's localization keys (unit.SOLDIER.name, unit.SOLDIER.lore, building.WINDMILL.name, technology.TEMPLARS.name / .description, ...).

Reskinning a built-in civilization

var viking = Core.Civilizations.Reskin(2);                       // same CivilizationSkins as a mod civilization
viking.Unit(6, mySoldierPrefab).GroundColour(4, 3, grass);         // anything left out stays the game's original
Core.Civilizations.ReplaceTree(2, () => myTree, "author.viking-tree", "My Viking tech tree");
  • Reskin(0..4): looks only (models, icons, island colours). Visual and local: players with and without the mod can play together.
  • ReplaceTree(0..4, tree, ruleKey, title): gameplay, so it is guarded. ModCore registers a lobby rule (on by default) and uses your tree only with no Steam lobby, or when the host's rule is on and every member has the mod; otherwise everybody plays the original tree. Frozen at match start.

Fast loading: cached textures

var atlas = Tools.IconAtlas.Build("My Civ icons", pngPaths, 256, 256);   // first launch: decode + pack + DXT5; later: one file read
Sprite s = atlas.Sprite(index, pivot, "building-icon-castle-mycivname-red");
Tools.TextSprites.AddLike("My Civ Text", entries, atlas.Key);             // the text sheet is cached too; pictures load only when it is rebuilt

Tools.TextureCache keeps built textures GPU-compressed in BepInEx\cache\ModCore, keyed by the source files' paths, sizes and change times: change a PNG and it is rebuilt on the next launch. Deleting the folder is always safe. Use TextSprites.Entry(name, likeName, () => load()) so pictures are only decoded when the sheet has to be redrawn.

Texts and translations

ModCore.Texts gives a mod its texts in the game's languages: one system for mod screens, civilization texts and texts the game itself left untranslated. Nothing is polled and nothing is added to the game's tables.

1. Write the texts in one JSON file, every key once with one entry per language:

{
  "settings.title": { "en": "My mod", "ru": "Мой мод" },
  "settings.found": { "en": "{0} {0:island|islands} found", "ru": "{0:Найден|Найдено|Найдено} {0} {0:остров|острова|островов}" }
}

2. Build the file into the DLL (.csproj):

<ItemGroup>
  <EmbeddedResource Include="texts.json" LogicalName="texts.json" />
</ItemGroup>

3. Use it:

static readonly TextSet T = Core.Texts.Load();          // once, e.g. in Load()
label.text = T.Get("settings.title");                    // the game's current language
label.text = T.Get("settings.found", count);             // values as in string.Format
Core.Texts.LanguageChanged += Redraw;                    // the game's own language-change event
  • Languages: any number. The codes are the game's: en, de, fr, ru, uk, zh-CN.
  • Fallback: the exact language (zh-CN), then its base (zh), then English, then the key itself, so a missing text is visible instead of blank. English is needed for every key; Load logs keys without it.
  • Loose file: a file named <DllName>.texts.json next to the DLL (for example MyMod.texts.json) wins over the built-in texts line by line. Players can fix a text or add a language without rebuilding; the mod passes no path.
  • Number words: {0:tile|tiles} picks the word by value 0: one | many in English, German and French; {0:клетка|клетки|клеток} (1 | 2-4 | 5+) in Russian and Ukrainian.

Civilization texts

Core.Civilizations.SetTexts(civ.Id, texts) gives a civilization its texts from the same kind of set: the key civilization.name is its name, every other key is a game text key (unit.SOLDIER.name, technology.TEMPLARS.description, ...), shown while the viewer's civilization is that one. Load("civ.json", "texts") reads the texts from the object texts inside a bigger built-in file.

The game's own untranslated texts

Two key prefixes translate texts of the game itself, for every player and civilization, in the languages the file has (other languages keep the game's text):

{
  "game:{0} tiles": { "ru": "{0} {0:клетка|клетки|клеток}" },
  "gamekey:unit.rules.range": { "uk": "Дальність: {a.0}" }
}
  • game:<text> is a text written in the game's code (the key is the English text as the game writes it, with its {0} slots). Such a text is translated when the game builds it, so one built before a language change keeps its language until its screen is opened again.
  • gamekey:<key> is one of the game's localization keys.

ModCore's own texts.json already translates the unit and building range ("3 tiles").

Mod on/off switch

var sw = Core.Mods.Switch(Config, affectsSimulation: true);   // [General] Enabled in your .cfg; in-game config editors show it as a toggle
sw.WhenOn(() => Enable(), () => Disable());                    // runs now and on every change
  • Editable in game with an in-game config editor (DiceModders ConfigMenu); the mod reacts to the change at once (no polling).
  • affectsSimulation: true: a change made during a match waits until the match ends. restartNeeded: true: read at start only.
  • While a mod is off, its lobby rules are not announced (the other players see it as missing), and its unit stats / tech trees are not used, so everybody plays the game's own values.

Unit stats

var stats = Core.Units.Register("author.balance", "My balance changes", priority: 10);   // also the host's lobby switch
stats.Set(Unit.Type.ARCHER, new UnitStatChange { AttackPeriod = 7 });                     // every civilization
stats.Set(civ.Id, Unit.Type.ARCHER, new UnitStatChange { Range = 8 });                    // one civilization
Core.Units.SetCivilizationDefaults(civ, Unit.Type.SOLDIER, new UnitStatChange { Parry = new Chance(3, 4) });   // a mod civilization's own values
  • Values: attack period / delay (ticks), aggro distance, range (both in the game's units: the Rules screen shows half), parry, arrow block, miss chance.
  • Order, lowest first: the game's values, a mod civilization's own defaults, all-civilization changes, per-civilization changes; a higher priority wins, equal priorities go by key. Fields left null keep the value below. A civilization without own defaults uses the game's values.
  • Synced safely: a mod's changes apply only with no Steam lobby, or when the host's switch is on and every member has the mod (and it is on); otherwise everybody plays the game's values. Frozen at match start.
  • Units.Mods, Units.Default(type), Units.Effective(civ, type), Units.CivilizationDefaults(civ, type): everything a lobby screen needs to list.

Building and technology values

var balance = Core.Balance.Register("author.economy", "Cheaper farms");
balance.Set(BuildingTypeName.FARM, new BuildingChange { Cost = new ResourceChange { Wood = 2 }, Health = 4 });
balance.SetCost(TechnologyName.UNLOCK_MARKET, new ResourceChange { Gold = 3 });

Building cost, storage, pillage / remains rewards, health, tower range and period; technology cost. Shared by every civilization. Same safety rules as unit stats; the game's values are restored whenever the set of active mods changes. Balance.Building(type) / DefaultBuilding(type) / TechnologyCost(tech) for screens.

Build actions

// once, in your plugin's Load: code 0..63, picked once for your mod
Core.BuildActions.Register(7, "author.mymod (bet)", (data, buildingId) => {
    var storage = data.Island.statistics.Storage;          // read only the game state: every computer runs this
    if (storage.stored.gold < 3) return false;              // false: the game drops the action, as it drops any failed action
    // ... take the gold, remember the bet for this island ...
    return true;
});

// on the player's click, during the build phase (BuildInterface.Data is the local player's build data)
bool ok = Core.BuildActions.Plan(buildInterface.Data, 7, buildingId);

A choice that changes the simulation and must happen at once, in the same order on every computer, works like the game's market purchase: the click is one of the game's own planned build actions, the player's screen applies it right away, the game sends it to everybody with its own messages and every computer applies it when the build phase ends. The game only knows its own action kinds, so a mod action travels as a repair action on a building id with a marker (bit 30, the code in bits 24..29); building ids never use those bits. Every player needs the mod that registered the code: plan actions only while your lobby rule is on (rules are used only when everybody has the mod). Codes in use: 0 Upkeep (Cathedral offering), 1 Casino (spin); a second registration of a code is refused and logged.

Building limits

// in your plugin's Load: your new building should be one per island by default, while its lobby rule is on
Core.Buildings.SuggestLimit(MyBuilding.Name, 1, myBuildingRule);

A mod that adds a building can suggest how many of it one island may have; ModCore then keeps every island to it. The check is part of the game's own check when a building is placed (BuildData.CanBuildType, the same step on every computer); a building at its limit is greyed out in the build bar with "On this island: n of m" in its tooltip, and a group of walls that would go over is refused. Computer players' buildings are refused by the same check. An upgraded building (the upgraded Guard Tower) counts with its base building. Without a suggestion a building has no limit (0). Call it in Load, for a building your mod adds (a player without your mod would not keep to a limit on one of the game's buildings). With the rule, the suggestion is used only while that rule is on for everybody.

// a mod that lets the host change the limits (the Building limits mod): its numbers instead of the suggested ones
Core.Buildings.SetLimits("My limits", type => rule.Value);   // null = the suggested limit; must be the same on every computer
int limit = Core.Buildings.LimitOf(BuildingTypeName.FARM);    // the limit in force, 0 = none
int count = Core.Buildings.CountOn(island, BuildingTypeName.FARM);

Buildings.SuggestedLimit(type) reads a suggestion (the Building limits mod uses it as the default of its rule), Buildings.BaseOf(type) gives the base building of an upgraded one.

Rule groups

rule.InGroup(Core.Lobby.Groups.ForCivilization(civ.Id));          // a heading per civilization
rule.InGroup(Core.Lobby.Groups.Get("author.events", "Events"));    // or your own

Core.Lobby.Groups.All (sorted) and Changed let a lobby screen show headings instead of one long list (ModBridge shows a heading's first on/off rule as a tick and its other rules in their own window).

Game fixes

ModCore fixes two places where the game itself fails on big islands. Both are always on and give exactly the game's results, so they are safe with players who do not have ModCore:

What Game code Fix
Island generation closes the game on grids above 119 tiles (stack overflow, nothing in the log) IslandGeneration.GenerateJob's sea-level fill Allow calls itself once per sea tile, on a job thread with a 1 MB stack Combat/SeaLevelFill.cs: the Burst copies of the function (AVX2 and SSE2) jump to an iterative version. Found by byte signature; if a game update changes the code, ModCore logs a warning and leaves it alone.
Combat on a very big island can close the game the same way CombatPhase.ComputeConnectedComponents' Visit calls itself once per walkable tile Combat/WalkableRegions.cs: the same labels without recursion

Documentation

Every feature with examples: the Modding Libraries section of the DiceModders wiki.

Tools

Small helpers almost every mod needs, in the namespace DiceModders.ModCore.Tools. They work without ModCore.Init().

Type What it does
Patcher new Patcher("my.mod", Log), then Patch("GameState", "ChangeTurnPhase", typeof(MyPatches), postfix: "AfterPhase") (private methods too; or pass a Type). Logs [patch] OK / [patch] FAIL with a hint when a type or method was renamed in a game update, and never throws. Summary() logs the count; Harmony gives the instance for anything else. Switch(...) prepares a patch that is applied only while its PatchSwitch.On is true: for methods the game calls every frame or every tile, switched on events, so the game method runs untouched while it is off.
GameTypes Find("IslandGrid") finds a game type by simple or full name in BepInEx\interop; Suggest / SuggestMethods list similar names.
Reflect Call(obj, "Method", args), TryGetMember, TrySetMember, CallStatic, Wrap(type, pointer): name-based access to interop objects, private members included. A plain int is accepted for enum parameters.
Mem Raw reads/writes at a field offset (ReadInt, WriteInt, ReadPtr, Str, ArrayLength, ArrayElem). Offsets change with every game build; use only for members the interop does not expose, never for encrypted values (resource storage).
using DiceModders.ModCore.Tools;

var patcher = new Patcher("com.example.mymod", Log);
patcher.Patch("GameState", "ChangeTurnPhase", typeof(MyPatches), postfix: nameof(MyPatches.AfterPhase));
patcher.Summary();

ModCore also switches off QuickEdit on the BepInEx console window at start (config [General] DisableConsoleQuickEdit, on by default). With QuickEdit on, one click inside the console pauses the game until Enter is pressed.


Build from source

Requirements: .NET SDK 6 or newer, the game installed.

$game = "<your Dice-Kingdoms folder>"   # the folder that contains BepInEx, e.g. ...\steamapps\common\Dice-Kingdoms (Steam: Properties > Installed Files > Browse)
git clone https://github.com/DiceModders/DiceKingdoms-ModCore
cd DiceKingdoms-ModCore
.\scripts\link-interop.ps1 $game   # makes .\interop point at BepInEx\interop (git-ignored)
dotnet build -c Release --no-incremental
Copy-Item bin\Release\net6.0\DiceModders.ModCore.dll "$game\BepInEx\plugins" -Force

The interop folder exists after the first game start with BepInEx 6 installed (it is generated into BepInEx\interop).

Project layout

Path What is in it
Plugin.cs The BepInEx entry point; calls Core.Ensure().
ModCore.cs, Core.cs Public ModCore.Init(); one-time installation of the hooks (no update loop).
Lobby/LobbyApi.cs The public lobby, rules and compatibility API (ModCore.Lobby).
Lobby/LobbyState.cs Steam subscription, members, owner, match start/end, freezing.
Lobby/LobbyHooks.cs Harmony patches on GameState.StartGame / FullReset (match start and end), SteamClient.Init (subscribe) and Lobby.Leave (left).
Lobby/LobbyRuleRegistry.cs, LobbyMods.cs Rule registry, the modcore.mods format, which plugin registered a rule.
Civilizations/CivilizationsApi.cs Public API (Add, Rename, CloneTree, registry).
Civilizations/CivilizationHooks.cs The patches that make unknown civilization numbers safe (tree, skins, network readers, castle click, AI, Statistics, guard).
Civilizations/CivilizationSkins.cs civ.Skins (own models) and the skin lookup patches.
Civilizations/CivilizationText.cs Answers the civilization name when the game draws it (ITextElement.Localized.Render), per language.
Civilizations/GameData.cs GameDataLoaded (postfix on SkinRegistry.Awake).
Civilizations/IslandColours.cs Per-civilization island ground / nature colours (MaterialPropertyBlock palette copies, island events).
Match/MatchApi.cs, MatchState.cs, MatchSettings.cs The public match API (ModCore.Match, MatchPhase, MatchSettings) and the listeners on the game's GameState events.
Players/PlayersApi.cs ModCore.Players and MatchPlayer.
Combat/WalkableRegions.cs, Combat/SeaLevelFill.cs The game fixes for big islands (see "Game fixes").
Tools/ Public helpers Patcher, GameTypes, Reflect, Mem, Meshes, Sprites, Prefabs, TextSprites, and the console ConsoleGuard.
docs/NOTES.md How it works inside and why (read before changing the hooks).
docs/EXAMPLE_MOD.md A complete minimal mod.

Contributing

  • Keep ModCore UI free and UiKit free. If a feature needs a screen, it belongs in ModBridge; if it is about drawing, it belongs in UiKit.
  • Public overloads instead of optional parameters on existing methods (optional parameters change the signature and break compiled mods).
  • Patch narrowly, wrap Harmony patch bodies in try/catch and log through CoreLog.Once(key, message) so a failure logs once and never every frame.
  • Test with two game instances (or a friend): lobby code only shows its bugs with a second member.

Troubleshooting

Symptom Cause / fix
CS0234 / name ModCore is a namespace Use the alias from "The name clash".
Rules never change in the lobby You are not the host, or the match already started (Editable is false).
Value is the default in a lobby The host has not changed it, or Steam is not initialised yet (ModCore.Lobby.InLobby false).
No rows in the lobby settings Install ModBridge (and UiKit); ModCore itself has no screens.
Game throws with a mod civilization Send Player.log (the game's own log, ...\LocalLow\Fivemid\Dice-Kingdoms) with the log: it has the full stack trace, which names the game code that still reads the number. See docs/NOTES.md.
A friend's game freezes when you pick the civilization The friend lacks the mod; ModCore only offers civilizations everybody has, so check both have the same ModCore version.

Logs are in BepInEx\LogOutput.log; ModCore lines are prefixed [ModCore]. Report issues with the log attached.

License

SPDX-License-Identifier: LGPL-2.1-or-later. See LICENSE.

About

Lobby, rules sync and mod compatibility for Dice Kingdoms BepInEx mods

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages