### NPM Commands - Install, Develop, Build (Bash)
Source: https://context7.com/bannerlord-modding/documentation/llms.txt
Provides essential NPM commands for managing the documentation project. 'npm install' fetches dependencies, 'npm run dev' starts a local development server with hot-reloading, and 'npm run build' generates the static site in the 'docs/.vuepress/dist' directory for deployment.
```bash
# Install dependencies
npm install
# Run development server with hot reload at localhost:8080
npm run dev
# Build static site to docs/.vuepress/dist
npm run build
# The built site can be deployed to any static hosting service
# Output directory: docs/.vuepress/dist/
```
--------------------------------
### CampaignGameStarter Example Use
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/zh/_csharp-api/campaignsystem/campaigngamestarter.md
Example demonstrating how CampaignGameStarter is used within the MBSubModuleBase class.
```APIDOC
## CampaignGameStarter Example Use
This is used within our [MBSubModuleBase]() class:
```csharp
protected override void OnGameStart(Game game, IGameStarter gameStarter)
{
if(game.GameType is Campaign)
{
//Current game is a campaign, so IGameStarter object must be CampaignGameStarter
CampaignGameStarter campaignStarter = (CampaignGameStarter) gameStarter;
//Can now use CampaignGameStarter
}
}
```
```
--------------------------------
### Example Settlement XML Entries (Town and Villages)
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/zh/_tutorials/new_settlements.md
This example demonstrates how to add new settlement entries to your settlements.xml file, including a town and two villages. It highlights key attributes like 'trade_bound', 'bound', and 'village_type'.
```xml
```
--------------------------------
### Check if Campaign Starts with Tutorial
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/zh/_csharp-api/campaignsystem/campaigngamestarter.md
Retrieves a boolean value indicating whether the campaign is initialized with a tutorial sequence. This attribute is read-only.
```csharp
public readonly bool IsTutorial
```
--------------------------------
### XML Example: Adding Town and Villages to settlements.xml
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_tutorials/new_settlements.md
Example demonstrating how to add a new town and two villages to the settlements.xml file. It shows custom parameters like trade bounds and village types, crucial for defining new settlements.
```xml
```
--------------------------------
### Example Usage
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/campaignsystem/TournamentGame.md
Demonstrates how to iterate through settlements and access tournament information.
```APIDOC
## Example Usage
```csharp
foreach (var settlement in Settlement.All) {
if (settlement.HasTournament) {
var tournament = Campaign.Current.TournamentManager.GetTournamentGame(settlement.Town);
showMessage("Tournament at : " + settlement.Town.StringId + " with up to " + tournament.MaxTeamNumberPerMatch + " teams per match.");
}
}
```
```
--------------------------------
### NPM Scripts - Build and Development (JSON)
Source: https://context7.com/bannerlord-modding/documentation/llms.txt
Defines the NPM scripts for the documentation project. Includes dependencies required for VuePress and Markdown processing. The 'dev' script starts a development server, and 'build' creates a static site for deployment.
```json
{
"name": "bannerlord-documentation-website",
"version": "0.0.1",
"description": "",
"main": "index.js",
"repository": "/bannerlord-documentation-website",
"scripts": {
"dev": "vuepress dev docs",
"build": "vuepress build docs"
},
"license": "MIT",
"dependencies": {
"markdown-it": "^12.3.2",
"markdown-it-meta": "^0.0.1",
"vue-click-outside": "^1.1.0",
"vuepress": "^1.8.2"
}
}
```
--------------------------------
### VuePress Configuration - Documentation Site Setup (JavaScript)
Source: https://context7.com/bannerlord-modding/documentation/llms.txt
Configures the VuePress documentation site, including multi-language support, SEO metadata, theme settings (Yuu theme with dark mode), GitHub integration for contributions, and navigation/sidebar structure. It also specifies VuePress plugins like back-to-top and medium-zoom.
```javascript
// docs/.vuepress/config.js
const apiGen = require('./apiPathGenerator')
module.exports = {
// Multi-language support
locales: {
'/': {
lang: 'en-US',
title: 'Bannerlord Documentation',
description: 'Community Documentation for Mount & Blade II: Bannerlord'
},
'/zh/': {
lang: 'zh-CN',
title: '骑马与砍杀2 领主 Mod 制作文档',
}
},
// SEO and metadata
head: [
['meta', { property: 'description', content: 'Community Documentation for Mount & Blade II: Bannerlord' }],
['meta', { property: 'og:type', content: 'website' }],
['meta', { property: 'og:url', content: 'https://docs.bannerlordmodding.com' }],
['meta', { property: 'og:image', content: '/images/bannerlord-icon.png' }],
['link', { rel: 'icon', type: 'image/png', sizes: '352x352', href: '/images/bannerlord-icon.png' }],
['meta', { name: 'theme-color', content: '#3eaf7c' }],
],
themeConfig: {
// Yuu theme with dark mode enabled by default
yuu: {
defaultDarkTheme: true,
},
// GitHub integration
repo: 'Bannerlord-Modding/Documentation',
repoLabel: 'Contribute',
editLinks: true,
docsRepo: 'Bannerlord-Modding/Documentation',
editLinkText: 'Click to edit this page!',
locales: {
'/': {
selectText: 'Languages',
label: 'English',
// Navigation bar
nav: [
{ text: 'Home', link: '/' },
{ text: 'Guide', link: '/_intro/getting-started' }
],
// Sidebar structure - dynamically generated from folder structure
sidebar: [
{
title: 'Introduction',
sidebarDepth: 1,
children: [
'/_intro/getting-started',
'/_intro/folder-structure',
'/_intro/advanced'
]
},
{
title: 'Tutorials',
sidebarDepth: 1,
children: apiGen.getAPITree('docs', '_tutorials')
},
{
title: 'C# API',
sidebarDepth: 1,
children: apiGen.getAPITree('docs', '_csharp-api')
},
{
title: 'Gauntlet',
sidebarDepth: 1,
children: apiGen.getAPITree('docs', '_gauntlet')
},
{
title: 'XML Docs',
sidebarDepth: 1,
children: apiGen.getAPITree('docs', '_xmldocs', false)
}
]
}
}
},
// Plugins for additional functionality
plugins: [
'@vuepress/plugin-back-to-top',
'@vuepress/plugin-medium-zoom',
'@vuepress/google-analytics',
{
ga: 'UA-164248376-1'
}
]
}
```
--------------------------------
### C# - Implement OnSubModuleLoad for Initial State Options
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_tutorials/basic-csharp-mod.md
This code snippet demonstrates how to override the OnSubModuleLoad method to add a custom initial state option. This option, when selected, will display a 'Hello World!' message in the game. It requires the 'Module' and 'InformationManager' classes from the Bannerlord API.
```csharp
Module.CurrentModule.AddInitialStateOption(new InitialStateOption("Message",
new TextObject("Message", null),
9990,
() => { InformationManager.DisplayMessage(new InformationMessage("Hello World!")); },
() => { return (false, null); }));
```
--------------------------------
### Example Scene Entity for New Settlement
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/zh/_tutorials/new_settlements.md
This XML snippet shows a 'game_entity' definition for a settlement within your Main_map/scene.xscene file. Each settlement defined in settlements.xml requires a corresponding game_entity.
```xml
```
--------------------------------
### Registering a Custom Campaign Behavior in C#
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/campaignsystem/campaignbehaviorbase.md
This C# example shows how to register a custom campaign behavior within the OnGameStart method of an MBSubModuleBase class. It checks if the current game is a campaign and then adds an instance of a custom behavior (ExampleBehavior) to the campaign starter. This is the standard way to integrate custom campaign logic into the game.
```csharp
protected override void OnGameStart(Game game, IGameStarter gameStarter)
{
if(game.GameType is Campaign)
{
//The current game is a campaign
CampaignGameStarter campaignStarter = (CampaignGameStarter) gameStarter;
campaignStarter.AddBehavior(new ExampleBehavior());
//ExampleBehavoir is our custom class which extends CampaignBehaviorBase
}
}
```
--------------------------------
### C# Custom Title Screen Implementation using MBInitialScreenBase
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/mountandblade/mbinitialscreenbase.md
This C# code snippet shows how to create a custom title screen by inheriting from MBInitialScreenBase. It initializes a Gauntlet layer, loads a specific movie, sets input restrictions, and adds the layer to the game. The example requires the `MBInitialScreenBase` class and related Bannerlord game classes.
```csharp
[GameStateScreen(typeof(InitialState))]
public class MyInitialScreen : MBInitialScreenBase
{
private GauntletLayer _gauntletLayer;
private InitialMenuVM _dataSource;
public MBInitialScreen(InitialState initialState) : base(initialState) { }
protected override void OnInitialize()
{
base.OnInitialize();
this._dataSource = new InitialMenuVM();
this._gauntletLayer = new GauntletLayer(1, "GauntletLayer");
this._gauntletLayer.LoadMovie("InitialScreen", this._dataSource);
this._gauntletLayer.InputRestrictions.SetInputRestrictions(true, InputUsageMask.Mouse);
base.AddLayer(this._gauntletLayer);
GameNotificationManager.Current?.LoadMovie(false);
ChatLog.Current?.LoadMovie(false);
InformationManager.ClearAllMessages();
}
}
```
--------------------------------
### Accessing the Player Agent
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/mountandblade/agent.md
Provides a code example for accessing the main player agent using the `Agent.Main` property. This is a common requirement for player-specific actions.
```csharp
Agent playerAgent = Agent.Main; // Get the player agent (if alive)
```
--------------------------------
### Registering Generic List for Saving with SaveableTypeDefiner C#
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/savesystem/README.md
Provides an example of registering a generic List of a custom struct (ExampleStruct) for saving using the SaveableTypeDefiner. This is necessary for the game to correctly serialize and deserialize lists of custom types.
```csharp
protected override void DefineContainerDefinitions() {
ConstructContainerDefinition(typeof(List));
}
```
--------------------------------
### Agent Usage and Interaction Events
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/zh/_csharp-api/mountandblade/missionbehaviour/README.md
Callbacks related to agent interactions with objects and other agents. These events allow for custom logic when an agent starts or stops using an object, or when agents interact with each other.
```C#
void OnObjectStoppedBeingUsed(Agent agent, UsableMissionObject usableMissionObject)
{
// Logic when an agent stops using an object
}
bool IsThereAgentAction(Agent agent1, Agent agent2)
{
// Logic to determine if agent1 is interactable by agent2
return true;
}
void OnAgentInteraction(Agent interactor, Agent target)
{
// Logic when an agent interacts with another agent
}
```
--------------------------------
### Get Key State as Vector2
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/inputsystem/input.md
Retrieves the current state of a specified key as a `Vector2`. The `GetKeyState` method is documented as potentially useful but its specific application is unclear. It requires the `System.Numerics` namespace.
```C#
using System.Numerics; // Requires manual installation of System.Numerics.Vectors.dll
using TaleWorlds.InputSystem;
// ... inside a method ...
Vector2 keyState = new Vector2(Input.GetKeyState(InputKey.A));
Vector2 compareVector = new Vector2(10, 10);
if (Equals(keyState, compareVector))
{
InformationManager.DisplayMessage(new InformationMessage("Key state matches comparison."));
}
```
--------------------------------
### Persisting Data with SyncData in C#
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/campaignsystem/campaignbehaviorbase.md
This C# code illustrates the use of the SyncData method for saving and loading game data. It shows the general syntax for syncing a variable and provides an example of persisting a counter for raided villages. This method is crucial for ensuring modded data survives game saves and loads.
```csharp
public override void SyncData(IDataStore dataStore)
{
dataStore.SyncData("_numVillagesRaided", ref _numVillagesRaided);
}
```
--------------------------------
### Synchronize Shared Custom Data with CampaignBehaviorBase.SyncData (C#)
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/zh/_csharp-api/savesystem/README.md
This example shows how to manage 'shared data' that can be used across one or multiple CampaignBehaviorBase instances. It demonstrates using the SyncData method to save and load custom container data, such as Lists, Dictionaries, Arrays, and Queues, by referencing a unique key.
```csharp
public class CustomBehavior : CampaignBehaviorBase
{
private List _customDataMap = new List();
public override void SyncData(IDataStore dataStore)
{
dataStore.SyncData("customDataMap", ref _customDataMap);
}
}
```
--------------------------------
### C# MBSubModuleBase: Mod Entry Point
Source: https://context7.com/bannerlord-modding/documentation/llms.txt
The MBSubModuleBase class serves as the entry point for C# mods in Bannerlord. Inherit from this class to hook into game lifecycle events like loading, game start, and application ticks. It allows custom code registration, behavior implementation, and game system modification.
```csharp
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.MountAndBlade;
using TaleWorlds.Core;
namespace ExampleMod
{
public class MySubModule : MBSubModuleBase
{
protected override void OnSubModuleLoad()
{
// Called during initial game loading - register initial setup here
base.OnSubModuleLoad();
// Add a custom button to the main menu
Module.CurrentModule.AddInitialStateOption(new InitialStateOption("Message",
new TextObject("Message", null),
9990,
() => {
InformationManager.DisplayMessage(
new InformationMessage("Hello World!")
);
},
() => { return (false, null); }
));
}
protected override void OnGameStart(Game game, IGameStarter gameStarter)
{
base.OnGameStart(game, gameStarter);
// Called when entering a game mode - register campaign behaviors here
if(game.GameType is Campaign)
{
CampaignGameStarter campaignStarter = (CampaignGameStarter) gameStarter;
campaignStarter.AddBehavior(new ExampleBehavior());
}
}
protected override void OnApplicationTick(float dt)
{
base.OnApplicationTick(dt);
// Called every frame - avoid expensive operations here
// dt = time in milliseconds for frame completion
}
}
}
```
--------------------------------
### Basic Lumberjack ScriptComponentBehaviour in C#
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/engine/scriptcomponentbehaviour.md
This C# example demonstrates a basic ScriptComponentBehaviour for a 'Lumberjack'. It initializes a skeleton, sets an animation, and adds a mesh to a specific bone. It overrides OnTick for initialization, though OnInit might be preferable in some cases.
```csharp
public class Lumberjack : ScriptComponentBehaviour
{
private bool _initialized;
protected internal override void OnTick(float dt)
{
base.OnTick(dt);
if (!this._initialized)
{
this._initialized = true;
base.GameEntity.CreateSimpleSkeleton("human_skeleton");
base.GameEntity.CopyComponentsToSkeleton();
base.GameEntity.Skeleton.SetAnimationAtChannel("lumberjack", 0, 1f, -1f, 0f);
MetaMesh copy = MetaMesh.GetCopy("peasent_hatchet", true, false);
base.GameEntity.AddMultiMeshToSkeletonBone(copy, 27);
}
}
}
```
--------------------------------
### Complex Text Variables and Conditional Formatting in C#
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/zh/_csharp-api/localization/TextObject.md
Illustrates advanced usage of TextObjects, including nested TextObjects, properties of variables, and conditional text based on a bit flag. This example demonstrates how to build complex, dynamic, and localized strings for in-game display.
```csharp
private const string MAIN_STRING =
"{=stringIDMain}I spent {NESTED_TEXT_OBJECT} this example! " +
"By the way, using of number {VARIABLE_TAG} requires {VARIABLE_TAG.NESTED_PROPERTY} after it! " +
"{BIT_FLAG}Conditional text example for when value of bitFlag = 1{\\?}Another conditional text example for when value of bitFlag = 0{\\?}.";
private const string NESTED_STRING = "{=stringIDNested}{MINUTES} minutes to come up with and write";
private const string NESTED_PROPERTY_SINGULAR = "{=ie0XDdqR}singular noun";
private const string NESTED_PROPERTY_PLURAL = "{=oRPbCfYq}plural noun";
public static TextObject GetMainTextObject(int variable, bool flag)
{
TextObject mainTextObject = new TextObject(MAIN_STRING);
TextObject nestedTextObject = new TextObject(NESTED_STRING,
new Dictionary() { ["MINUTES"] = new TextObject(variable) });
mainTextObject.SetTextVariable("NESTED_TEXT_OBJECT", nestedTextObject);
TextObject variableTextObject = new TextObject(variable);
variableTextObject.SetTextVariable("NESTED_PROPERTY", variable == 1 ? NESTED_PROPERTY_SINGULAR : NESTED_PROPERTY_PLURAL);
mainTextObject.SetTextVariable("VARIABLE_TAG", variableTextObject);
mainTextObject.SetTextVariable("BIT_FLAG", flag ? 1 : 0);
return mainTextObject;
}
```
--------------------------------
### Implement ScreenBase for New Screens (C#)
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_gauntlet/screenbase.md
This C# code demonstrates how to implement the ScreenBase class to create a new screen. It covers initializing view models, loading Gauntlet movies, managing focus, and cleaning up resources. This is a foundational pattern for creating UI screens in Bannerlord mods.
```csharp
public class MyExampleScreen : ScreenBase
{
private MyExampleVM _dataSource;
private GauntletLayer _gauntletLayer;
private GauntletMovie _movie;
protected override void OnInitialize()
{
base.OnInitialize();
_dataSource = new MyExampleVM();
_gauntletLayer = new GauntletLayer(100)
{
IsFocusLayer = true
};
AddLayer(_gauntletLayer);
_gauntletLayer.InputRestrictions.SetInputRestrictions();
_movie = _gauntletLayer.LoadMovie("MyExampleMovie", _dataSource);
}
protected override void OnActivate()
{
base.OnActivate();
ScreenManager.TrySetFocus(_gauntletLayer);
}
protected override void OnDeactivate()
{
base.OnDeactivate();
_gauntletLayer.IsFocusLayer = false;
ScreenManager.TryLoseFocus(_gauntletLayer);
}
protected override void OnFinalize()
{
base.OnFinalize();
RemoveLayer(_gauntletLayer);
_dataSource = null;
_gauntletLayer = null;
}
}
```
--------------------------------
### Agent Creation and Building Callbacks
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/mountandblade/missionbehaviour/README.md
Callbacks related to the creation and preparation of agents for gameplay. `OnAgentCreated` is recommended for adding components, while `OnAgentBuild` is for setting up spawned agents before they are used.
```csharp
public void OnAgentCreated(Agent agent)
{
// Called after an agent is created on the engine side.
}
public void OnAgentBuild(Agent agent, Banner banner)
{
// Called after an agent is built and ready to be used.
}
```
--------------------------------
### XML Example: Scene Game Entity for Settlement
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_tutorials/new_settlements.md
An example of a 'game_entity' definition within a scene.xscene file, corresponding to a settlement entry in settlements.xml. Each settlement must have a unique game_entity defined to represent its visual presence on the map.
```xml
```
--------------------------------
### BodyPropertiesMax Attributes
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_xmldocs/NPCCharacters/NPCCharacter/face/BodyPropertiesMax/README.md
Details the attributes available for the BodyPropertiesMax node, including their types, examples, and descriptions.
```APIDOC
## BodyPropertiesMax Attributes
This section details the attributes associated with the BodyPropertiesMax node.
### Attributes
- **age** (float) - The age of the face. Example: `24.31`
- **build** (float) - TODO: Figure out what this does. Example: `0.7077`
- **key** (key) - Face key. Example: `0033F00E400005D3710005000004000050060800000000077718F00000000060000447A404000000000000000000000000000000000000000000000000505000`
- **version** (int) - TODO: Figure out what this is for. Example: `4`
- **weight** (float) - TODO: Figure out what this is for. Example: `0.4502`
### Example Usage
While there are no specific endpoints documented for direct interaction with BodyPropertiesMax, its attributes are typically accessed and modified within the context of other related nodes or systems, such as when defining or manipulating character faces in the game engine. The `key` attribute is particularly important for uniquely identifying a specific face configuration.
```
--------------------------------
### Bannerlord Mod Localization - Translated String File (Russian Example)
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/localization/README.md
Example of a translated `std_module_strings_xml.xml` file for a specific language, in this case, Russian. To translate, create a copy of the English XML file, change the `language` tag to the desired language ID (e.g., 'Русский'), and translate all text content while preserving original IDs and variables.
```xml
```
--------------------------------
### Implement Custom Campaign Logic with CampaignBehaviorBase
Source: https://context7.com/bannerlord-modding/documentation/llms.txt
Demonstrates how to extend CampaignBehaviorBase to add custom logic, respond to campaign events, and persist data across saves. It includes registering event listeners and syncing data using IDataStore.
```csharp
using TaleWorlds.CampaignSystem;
using TaleWorlds.Library;
using TaleWorlds.SaveSystem;
using System;
namespace ExampleMod
{
public class ExampleBehavior : CampaignBehaviorBase
{
// Private variables that need to persist across saves
private int _numVillagesRaided;
private int _totalGoldEarned;
public override void RegisterEvents()
{
// Register event listeners for campaign events
CampaignEvents.OnClanDestroyedEvent.AddNonSerializedListener(
this,
new Action(clan => {
String clanName = clan.Name.ToString();
InformationManager.DisplayMessage(
new InformationMessage("The " + clanName + " was destroyed!")
);
})
);
// Listen for village raiding events
CampaignEvents.VillageBeingRaided.AddNonSerializedListener(
this,
new Action(village => {
_numVillagesRaided++;
// Reward player after raiding 10 villages
if (_numVillagesRaided >= 10) {
Hero.MainHero.ChangeHeroGold(1000);
_totalGoldEarned += 1000;
InformationManager.DisplayMessage(
new InformationMessage("Raider bonus: 1000 gold!")
);
}
})
);
}
public override void SyncData(IDataStore dataStore)
{
// Persist behavior data between saves
// First parameter: unique string identifier within this behavior
// Second parameter: reference to the variable to save/load
dataStore.SyncData("_numVillagesRaided", ref _numVillagesRaided);
dataStore.SyncData("_totalGoldEarned", ref _totalGoldEarned);
}
}
}
```
--------------------------------
### GetParticipantCharacters Method
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/zh/_csharp-api/campaignsystem/TournamentGame.md
Defines the participants of a tournament when it starts. This method is called when a player joins or a tournament is simulated.
```APIDOC
## GetParticipantCharacters
### Description
This method defines, when a tournament starts, the participants. Called when a player joins a tournament or a tournament is simulated.
### Method
`public static List GetParticipantCharacters( Settlement settlement, int maxParticipantCount, bool includePlayer = true, bool includeHeroes = true )`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **List** - A list of characters participating in the tournament.
#### Response Example
None
```
--------------------------------
### Push Screen onto Screen Stack (C#)
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_gauntlet/screenbase.md
This C# code snippet shows how to push a newly created screen onto the game's screen stack using ScreenManager. It utilizes ViewCreatorManager to instantiate the screen and ensures it becomes active. This is essential for navigating between different UI screens.
```csharp
ScreenManager.PushScreen(ViewCreatorManager.CreateScreenView());
```
--------------------------------
### Add a Game Menu
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/zh/_csharp-api/campaignsystem/campaigngamestarter.md
Adds a new game menu to the campaign. This method allows defining a menu with specific text, initialization logic, overlay type, and flags. Refer to the GameMenu documentation for detailed usage.
Inputs:
- menuId: Unique identifier for the menu.
- menuText: Text displayed for the menu.
- initDelegate: Delegate to execute when the menu is initialized.
- overlay: Type of overlay for the menu (defaults to None).
- menuFlags: Flags to control menu behavior (defaults to none).
- relatedObject: An optional related object.
```csharp
public void AddGameMenu(string menuId, string menuText, OnInitDelegate initDelegate, GameOverlays.MenuOverlayType overlay = GameOverlays.MenuOverlayType.None, GameMenu.MenuFlags menuFlags = GameMenu.MenuFlags.none, object relatedObject = null)
```
--------------------------------
### Apply Settlement Ownership Change by Default
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/zh/_csharp-api/campaignsystem/actions/ChangeOwnerOfSettlementAction.md
Sets or changes the owner of a settlement. This function is typically called at the start of a campaign or when a player cheats to gain ownership.
```csharp
public static void ApplyByDefault(Hero hero, Settlement settlement)
{
// Implementation details for default ownership change
}
```
--------------------------------
### Agent Movement and Interaction Callbacks
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/mountandblade/missionbehaviour/README.md
Callbacks related to agent movement and interaction with the environment and objects. This includes mounting/dismounting, item pickup, and focusing on or using objects.
```csharp
public void OnAgentMount(Agent agent)
{
// Called when an agent mounts a mount.
}
public void OnAgentDismount(Agent agent)
{
// Called when an agent dismounts a mount.
}
public void OnAgentControllerChanged(Agent agent)
{
// Called when the controller of an agent is changed.
}
public void OnItemPickup(Agent agent, SpawnedItemEntity item)
{
// Called whenever an agent picks an item up.
}
public void OnFocusGained(Agent agent, IFocusable focusableObject, bool isInteractable)
{
// Called when an object gains the focus of an agent.
}
public void OnFocusLost(Agent agent, IFocusable focusableObject)
{
// Called when an object loses its focus.
}
public void OnObjectUsed(Agent agent, UsableMissionObject usableObject)
{
// Called when an agent uses an object.
}
```
--------------------------------
### Get BasicCharacterObject using MBObjectManager
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/core/mbobjectmanager.md
Demonstrates how to retrieve a BasicCharacterObject from the game using its ID. This function requires the MBObjectManager to be initialized and the object ID to be valid. It returns a BasicCharacterObject or null if not found.
```csharp
MBObjectManager.Instance.GetObject("example_troop_id");
```
--------------------------------
### Setting Agent AI State Flags (C#)
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/zh/_csharp-api/mountandblade/agent.md
This example shows how to set the AI state flags for an agent. The 'AIStateFlags' property accepts values from the Agent.AIStateFlag enum, such as 'Alarmed' or 'Guard'.
```csharp
unit.AIStateFlags = Agent.AIStateFlag.Alarmed;
unit.AIStateFlags = Agent.AIStateFlag.Guard;
```
--------------------------------
### MBSubModuleBase - Module Entry Point
Source: https://context7.com/bannerlord-modding/documentation/llms.txt
The MBSubModuleBase class serves as the entry point for all C# mods in Bannerlord. By inheriting from this class, mods can hook into the game's lifecycle events, register behaviors, and modify game systems.
```APIDOC
## MBSubModuleBase - Module Entry Point
### Description
The `MBSubModuleBase` class is the entry point for all C# mods in Bannerlord. By inheriting from this base class and referencing it in SubModule.xml, you can hook into the game's lifecycle events to load custom code, register behaviors, and modify game systems.
### Method
Inheritance and Overriding
### Endpoint
N/A (Code-based entry point)
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
```csharp
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.MountAndBlade;
using TaleWorlds.Core;
namespace ExampleMod
{
public class MySubModule : MBSubModuleBase
{
protected override void OnSubModuleLoad()
{
// Called during initial game loading - register initial setup here
base.OnSubModuleLoad();
// Add a custom button to the main menu
Module.CurrentModule.AddInitialStateOption(new InitialStateOption("Message",
new TextObject("Message", null),
9990,
() => {
InformationManager.DisplayMessage(
new InformationMessage("Hello World!")
);
},
() => { return (false, null); }
));
}
protected override void OnGameStart(Game game, IGameStarter gameStarter)
{
base.OnGameStart(game, gameStarter);
// Called when entering a game mode - register campaign behaviors here
if(game.GameType is Campaign)
{
CampaignGameStarter campaignStarter = (CampaignGameStarter) gameStarter;
campaignStarter.AddBehavior(new ExampleBehavior());
}
}
protected override void OnApplicationTick(float dt)
{
base.OnApplicationTick(dt);
// Called every frame - avoid expensive operations here
// dt = time in milliseconds for frame completion
}
}
}
```
### Response
#### Success Response (N/A - Code Execution)
N/A
#### Response Example
N/A
```
--------------------------------
### Agent Mount and Dismount Callbacks
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/zh/_csharp-api/mountandblade/missionbehaviour/README.md
Callbacks that are invoked when an agent mounts or dismounts a mount. These are useful for tracking changes in agent mobility and state.
```C#
public void OnAgentMount(Agent agent)
{
// Called when an agent mounts a mount.
}
public void OnAgentDismount(Agent agent)
{
// Called when an agent dismounts a mount.
}
```
--------------------------------
### Add a Wait Game Menu
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/zh/_csharp-api/campaignsystem/campaigngamestarter.md
Adds a special type of game menu designed for waiting periods within the campaign. It includes parameters for conditions, consequences, and ticking logic, allowing for dynamic wait menu behavior. Currently marked as work in progress.
Inputs:
- idString: Unique identifier for the wait menu.
- text: Text displayed for the wait menu.
- initDelegate: Delegate to execute when the menu is initialized.
- condition: Delegate defining the condition for the wait menu.
- consequence: Delegate defining the consequence when the wait condition is met.
- tick: Delegate to execute on each game tick while the menu is active.
- type: The type of menu and option for the wait menu.
- overlay: Type of overlay for the menu (defaults to None).
- targetWaitHours: The target duration to wait in hours (defaults to 0).
- flags: Flags to control menu behavior (defaults to none).
- relatedObject: An optional related object.
```csharp
public void AddWaitGameMenu(string idString, string text, OnInitDelegate initDelegate, OnConditionDelegate condition, OnConsequenceDelegate consequence, OnTickDelegate tick, GameMenu.MenuAndOptionType type, GameOverlays.MenuOverlayType overlay = GameOverlays.MenuOverlayType.None, float targetWaitHours = 0f, GameMenu.MenuFlags flags = GameMenu.MenuFlags.none, object relatedObject = null)
```
--------------------------------
### Agent Properties: Age, Scale, Crouch Mode
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/mountandblade/agent.md
Demonstrates how to get or set the age and scale of an agent, and check if an agent is crouched. These are fundamental properties for understanding an agent's state.
```csharp
float age = unit.Age; // Get the age of the agent
unit.Age = 25.5f; // Set the age of the agent
float scale = unit.Scale; // Get the scaling factor of the agent
bool crouch = unit.CrouchMode; // Check if the agent is crouched
```
--------------------------------
### Get Keyboard Text
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/inputsystem/input.md
Retrieves the current text content from the user's clipboard. The `GetKeyboardText` method returns this content as a string, which can be useful for pasting functionality or reading user input from the clipboard.
```C#
using TaleWorlds.InputSystem;
// ... inside a method ...
string clipboardText = Input.GetKeyboardText();
// Use clipboardText as needed
```
--------------------------------
### Agent Properties: AI State and Attack Direction
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/mountandblade/agent.md
Shows how to get or set the AI state flags and retrieve the attack direction of an agent. Useful for controlling NPC behavior and combat analysis.
```csharp
unit.AIStateFlags = Agent.AIStateFlag.Alarmed; // Set the AI state to Alarmed
Agent.AIStateFlag currentState = unit.AIStateFlags; // Get the current AI state
AttackDirection direction = unit.AttackDirection; // Get the direction the Agent is attacking towards
```
--------------------------------
### Agent Properties: Role, Controller, and Character Link
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/mountandblade/agent.md
Illustrates how to get or set the agent's role and controller, and how to access the basic character object. These properties are crucial for managing agent identity and interaction.
```csharp
// Assuming AgentRole and Contorller are defined enums or types
unit.AgentRole = Agent.AgentRole.Guard; // Set the agent's role
unit.Controller = Agent.Contorller.AI; // Set the agent's controller to AI
BasicCharacterObject character = unit.Character; // Get the basic character object linked to the agent
```
--------------------------------
### C# - Add Using Directives for Bannerlord Modding
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_tutorials/basic-csharp-mod.md
These using directives are essential for accessing core Bannerlord functionalities related to library, localization, and module base classes. They are required at the beginning of your C# module class.
```csharp
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.MountAndBlade;
```
--------------------------------
### CampaignGameStarter Methods
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/campaignsystem/campaigngamestarter.md
This section details the methods available for interacting with the CampaignGameStarter, allowing the addition of behaviors, models, and game texts.
```APIDOC
## CampaignGameStarter API Endpoints
### CampaignGameStarter Class
This class is used to introduce behaviors, dialog, menus, and models for campaigns. It implements the `IGameStarter` interface and is useful in the `OnGameStart` method in `MBSubModuleBase`.
### Methods
#### `public void ClearEmptyObjects()`
**Description**: (Work in progress) Clears empty objects within the campaign starter.
**Method**: POST
**Endpoint**: `/CampaignGameStarter/ClearEmptyObjects`
#### `public void AddBehavior(CampaignBehaviorBase campaignBehavior)`
**Description**: Adds a `CampaignBehaviorBase` to the current campaign.
**Method**: POST
**Endpoint**: `/CampaignGameStarter/AddBehavior`
**Parameters**:
**Request Body**:
- **campaignBehavior** (CampaignBehaviorBase) - Required - The campaign behavior to add.
#### `public void AddModel(GameModel model)`
**Description**: Adds a `GameModel` to the current campaign.
**Method**: POST
**Endpoint**: `/CampaignGameStarter/AddModel`
**Parameters**:
**Request Body**:
- **model** (GameModel) - Required - The game model to add.
#### `public void LoadGameTexts(string xmlPath)`
**Description**: (Work in progress) Loads game texts from an XML file at the specified path.
**Method**: POST
**Endpoint**: `/CampaignGameStarter/LoadGameTexts`
**Parameters**:
**Request Body**:
- **xmlPath** (string) - Required - The path to the XML file containing game texts.
#### `public void LoadGameMenus(Type typeOfGameMenusCallbacks, string xmlPath)`
**Description**: (Work in progress) Loads game menus from an XML file at the specified path, using the provided callback type.
**Method**: POST
**Endpoint**: `/CampaignGameStarter/LoadGameMenus`
**Parameters**:
**Request Body**:
- **typeOfGameMenusCallbacks** (Type) - Required - The type of callbacks for game menus.
- **xmlPath** (string) - Required - The path to the XML file containing game menus.
#### `public void AddGameMenu(string menuId, string menuText, OnInitDelegate initDelegate, GameOverlays.MenuOverlayType overlay = GameOverlays.MenuOverlayType.None, GameMenu.MenuFlags menuFlags = GameMenu.MenuFlags.none, object relatedObject = null)`
**Description**: Adds a game menu to the campaign. Refer to `GameMenu` for usage details.
**Method**: POST
**Endpoint**: `/CampaignGameStarter/AddGameMenu`
**Parameters**:
**Request Body**:
- **menuId** (string) - Required - The unique identifier for the menu.
- **menuText** (string) - Required - The text displayed for the menu.
- **initDelegate** (OnInitDelegate) - Required - The delegate to initialize the menu.
- **overlay** (GameOverlays.MenuOverlayType) - Optional - The type of overlay for the menu (default: `GameOverlays.MenuOverlayType.None`).
- **menuFlags** (GameMenu.MenuFlags) - Optional - Flags for the menu (default: `GameMenu.MenuFlags.none`).
- **relatedObject** (object) - Optional - An object related to the menu.
#### `public void AddWaitGameMenu(string idString, string text, OnInitDelegate initDelegate, OnConditionDelegate condition, OnConsequenceDelegate consequence, OnTickDelegate tick, GameMenu.MenuAndOptionType type, GameOverlays.MenuOverlayType overlay = GameOverlays.MenuOverlayType.None, float targetWaitHours = 0f, GameMenu.MenuFlags flags = GameMenu.MenuFlags.none, object relatedObject = null)`
**Description**: (Work in progress) Adds a wait game menu with specified configurations.
**Method**: POST
**Endpoint**: `/CampaignGameStarter/AddWaitGameMenu`
**Parameters**:
**Request Body**:
- **idString** (string) - Required - The unique identifier for the wait menu.
- **text** (string) - Required - The text displayed for the wait menu.
- **initDelegate** (OnInitDelegate) - Required - The delegate to initialize the wait menu.
- **condition** (OnConditionDelegate) - Required - The condition delegate for the wait menu.
- **consequence** (OnConsequenceDelegate) - Required - The consequence delegate for the wait menu.
- **tick** (OnTickDelegate) - Required - The tick delegate for the wait menu.
- **type** (GameMenu.MenuAndOptionType) - Required - The type of the wait menu option.
- **overlay** (GameOverlays.MenuOverlayType) - Optional - The type of overlay for the menu (default: `GameOverlays.MenuOverlayType.None`).
- **targetWaitHours** (float) - Optional - The target wait hours (default: 0f).
- **flags** (GameMenu.MenuFlags) - Optional - Flags for the menu (default: `GameMenu.MenuFlags.none`).
- **relatedObject** (object) - Optional - An object related to the menu.
#### `public void AddGameMenuOption(string menuId, string optionId, string optionText, GameMenuOption.OnConditionDelegate condition, GameMenuOption.OnConsequenceDelegate consequence, bool isLeave = false, int index = -1, bool isRepeatable = false)`
**Description**: Adds an option to an existing game menu. Refer to `GameMenu` for usage details.
**Method**: POST
**Endpoint**: `/CampaignGameStarter/AddGameMenuOption`
**Parameters**:
**Request Body**:
- **menuId** (string) - Required - The ID of the menu to which the option is added.
- **optionId** (string) - Required - The unique identifier for the menu option.
- **optionText** (string) - Required - The text displayed for the menu option.
- **condition** (GameMenuOption.OnConditionDelegate) - Required - The condition delegate for the menu option.
- **consequence** (GameMenuOption.OnConsequenceDelegate) - Required - The consequence delegate for the menu option.
- **isLeave** (bool) - Optional - Whether this option leaves the menu (default: false).
- **index** (int) - Optional - The index for the option (default: -1).
- **isRepeatable** (bool) - Optional - Whether the option is repeatable (default: false).
### Attributes
**NOTE**: *All attributes are get/read only.*
#### `public readonly bool IsTutorial`
**Description**: Returns `true` if the campaign starts with a tutorial, otherwise `false`.
**Method**: GET
**Endpoint**: `/CampaignGameStarter/IsTutorial`
#### `public ICollection CampaignBehaviors`
**Description**: A collection of all registered `CampaignBehaviourBase` instances.
**Method**: GET
**Endpoint**: `/CampaignGameStarter/CampaignBehaviors`
#### `public IEnumerable Models`
**Description**: An enumerable set of all registered `GameModel` instances.
**Method**: GET
**Endpoint**: `/CampaignGameStarter/Models`
### Example Use in MBSubModuleBase
```csharp
protected override void OnGameStart(Game game, IGameStarter gameStarter)
{
if(game.GameType is Campaign)
{
//Current game is a campaign, so IGameStarter object must be CampaignGameStarter
CampaignGameStarter campaignStarter = (CampaignGameStarter) gameStarter;
//Can now use CampaignGameStarter
}
}
```
```
--------------------------------
### Load Game Menus from XML
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/zh/_csharp-api/campaignsystem/campaigngamestarter.md
Loads custom game menus from an XML file specified by the given path. This allows for the creation of new menu interfaces within the game. Currently marked as work in progress.
Inputs:
- typeOfGameMenusCallbacks: The type that contains the callbacks for game menus.
- xmlPath: The path to the XML file containing game menu definitions.
```csharp
public void LoadGameMenus(Type typeOfGameMenusCallbacks, string xmlPath)
```
--------------------------------
### Get Loaded Module Information (C#)
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/library/moduleinfo.md
Retrieves a list of all loaded modules in Bannerlord and populates them with detailed ModuleInfo. This is useful for checking module existence and managing optional dependencies. It relies on the Utilities.GetModulesNames() function from the Talewords.Engine namespace.
```csharp
var loadedMods = new List();
foreach(var moduleName in Utilities.GetModulesNames())
{
var moduleInfo = new ModuleInfo();
moduleInfo.Load(moduleName);
loadedMods.Add(moduleInfo);
}
```
--------------------------------
### PrepareForTournamentGame Method
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/zh/_csharp-api/campaignsystem/TournamentGame.md
Prepares the game state for a tournament, regardless of whether the player is participating.
```APIDOC
## PrepareForTournamentGame
### Description
This method is called when starting a tournament, wether simulated or with player participation.
### Method
`public void PrepareForTournamentGame( bool isPlayerParticipating )`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
None
#### Success Response (200)
None
#### Response Example
None
```
--------------------------------
### Get Current Scene in C#
Source: https://github.com/bannerlord-modding/documentation/blob/master/docs/_csharp-api/engine/scene.md
This snippet demonstrates how to retrieve the currently loaded scene object in Bannerlord using the Mission.Current property. It assumes that a mission is currently active and the scene has been loaded. This is useful for accessing scene-specific properties and methods.
```csharp
if (Mission.Current != null && Mission.Current.Scene != null)
{
var currentScene = Mission.Current.Scene;
// Use currentScene object
}
```