API - Parexy/Multiplayer GitHub Wiki
You can check other examples from the Multiplayer Compatibility Project.
In this section, we're going to focus on the basics of the api. Specifically, we're going to enable a mod for Multiplayer.
By the time RimWorld reaches your mod the API is ready to use, you can call it wherever you see fit. See basic C# mod tutorials. The easiest place is [StaticConstructorOnStartup]
The following is the most basic boilerplate code.
using Multiplayer.API;
using Verse;
namespace MyExampleMod
{
[StaticConstructorOnStartup]
public static class MyExampleModCompat
{
static MyExampleModCompat()
{
if (!MP.enabled) return;
// This is where the magic happens and your attributes
// auto register, similar to Harmony's PatchAll.
MP.RegisterAll();
// You can choose to not auto register and do it manually
// with the MP.Register* methods.
// Use MP.IsInMultiplayer to act upon it in other places
// user can have it enabled and not be in session
}
}
}
Say you want a method call to trigger, for example a GUI click or a drag. You possibly already have it somewhere, so it's a matter of registering it as SyncMethod with the API. The simple way is to add the [SyncMethod] attribute to your method. There is alternatives in MP.Register* if you don't feel comfortable with adding code to your other files.
...
[HarmonyPatch(typeof(RimWorldWindowClass), nameof(DoWindowContents))]
static class RimWorldWindowClass_DoWindowContents_Patch
{
// Draw a 16x16 square with your texture and make it clickable in RimWorldWindowClass
static void Postfix(Rect inRect)
{
Rect buttonRect = new Rect(inRect.x, inRect.y, 16f, 16f);
if (Widgets.ButtonImage(buttonRect, ResourceBank.Textures.MyButtonTexture))
{
Click();
}
}
[SyncMethod]
static void Click() {
Log.Message("This will happen in all clients");
}
}
...
That's all! You are done.
Well... sometimes you aren't that lucky. Sometimes you want to change a specific Field. For those scenarios there is the MP.Watch* methods. Basically, at the beginning of the operation you take a snapshot of the Field value and then compare it later. MPAPI checks them if they need to broadcast it and then spreads the change accordingly.
...
[HarmonyPatch(typeof(RimWorldWindowClass), nameof(DoWindowContents))]
static class RimWorldWindowClass_DoWindowContents_Patch
{
// Draw a 160x16 slider in RimWorldWindowClass
static void Postfix(Rect inRect)
{
if (MP.IsInMultiplayer) {
MP.WatchBegin(); // Let's being watching
// This is here to set the variable if it changed on other clients
// It will update the variable and the logic will stay the same.
MP.Watch(instance, nameof(instance.weight));
}
Rect sliderRect = new Rect(inRect.x, inRect.y, 160f, 16f);
instance.weight = GUI.HorizontalSlider(sliderRect, instance.weight, -10f, 10f);
if (MP.IsInMultiplayer) {
MP.WatchEnd(); // We are done watching!
}
}
static MyObject instance = new MyObject();
class MyObject {
[SyncField]
public float weight;
}
}
...
That's all! So easy! Is it...?
Oh dear! Oh deity no no--- NO- Pray you aren't dealing with them with Reflection. See the Examples for dark magic. But if it's your own code, just move the Action delegate to a method anywhere and tag it with [SyncMethod].
Sometimes, when you use [SyncMethod], you will encounter...
Error writing type: MyType, ... Multiplayer.Client.SerializationException: No writer for type MyType
MPAPI needs to know how to reference your type to send it to the other clients. Basically if you have...
[SyncMethod]
static MyReturnType MyMethod(MyArgumentType arg1, MyArgumentType2 arg2, int arg3, float arg4) { ... }
You need to teach MPApi to handle your types, so they can send them over the wire to the other players. For our example, we will need to write a SyncWorker for MyReturnType, MyArgumentType and MyArgumentType2, most of RimWorld types are already handled so don't be afraid to use them.
Assuming MyReturnType is made of aString, anInt and aFloat, here is how you write a SyncWorker for it:
[SyncWorker(shouldConstruct = true)]
static void SyncMyReturnType(SyncWorker sync, ref MyReturnType type) {
sync.Bind(type.aString);
sync.Bind(type.anInt);
sync.Bind(type.aFloat);
}
Bind does the writing and reading for you, shouldConstruct makes it so type is constructed before being passed to the SyncWorker (not needed for structs). But if you need more complex situations, you can use Write and Read.
Assuming MyArgumentType requires an argument Pawn to construct, you'd write it this way:
[SyncWorker]
static void SyncMyArgumentType(SyncWorker sync, ref MyArgumentType type) {
if (sync.isWriting) {
sync.Write(type.Pawn);
} else {
Pawn pawn = sync.Read<Pawn>();
type = new MyArgumentType(pawn);
}
}
The following is more detailed documentation.
MP | ISyncCall |
SyncMethodAttribute | SyncFieldAttribute |
SyncWorkerAttribute | SyncWorkerDelegate |
ISyncField | ISynchronizable |
ISyncMethod | ISyncDelegate |
SyncWorker | SyncContext |
The primary static class that contains methods used to interface with the multiplayer mod.
Contains the API version
Returns if API is initialized.
Returns if currently running on a host.
Returns if currently running in a multiplayer session (both on client and host).
Returns local player's name.
Registers the syncDelegate. Handles anonymous nested types, you will have to figure out the name of your target by decompiling.
The sync delegate.
Name | Description |
---|---|
inType |
System.Type In type. |
nestedType |
System.String Nested type. |
methodName |
System.String Method name. |
fields |
System.String[] Fields. |
args |
System.Type[] Arguments. |
Registers the syncDelegate. Handles anonymous nested types, you will have to figure out the name of your target by decompiling.
The sync delegate.
Name | Description |
---|---|
type |
System.Type Type. |
nestedType |
System.String Nested type. |
method |
System.String Method. |
Registers a field for syncing and returns it's ISyncField.
It's recommended to use SyncFieldAttribute instead, unless you have to otherwise.
They must be Watched between MP.WatchBegin and MP.WatchEnd with the MP.Watch* methods
Name | Description |
---|---|
field |
System.Reflection.FieldInfo FieldInfo of a field to register |
A new registered ISyncField
Registers a field for syncing and returns it's ISyncField.
It's recommended to use SyncFieldAttribute instead, unless you have to otherwise.
They must be Watched between MP.WatchBegin and MP.WatchEnd with the MP.Watch* methods
Name | Description |
---|---|
targetType |
System.Type |
Type of the target class that contains the specified member |
if null, memberPath will point at field from the global namespace in the "Type/fieldName" format.
|
| memberPath | System.String
Path to a member. If the member is to be indexed, it has to end with /[] eg. "myArray/[]"
|
A new registered ISyncField
Registers a method for syncing and returns its ISyncMethod.
Name | Description |
---|---|
method |
System.Reflection.MethodInfo MethodInfo of a method to register |
argTypes |
Multiplayer.API.SyncType[] Method's parameter types |
It's recommended to use SyncMethodAttribute instead, unless you have to otherwise.
A new registered ISyncMethod
Register a method for syncing using reflection and set it to debug only.
RegisterSyncMethod(typeof(MyType).GetMethod(nameof(MyType.MyMethod))).SetDebugOnly();
Registers a method for syncing and returns its ISyncMethod.
It's recommended to use SyncMethodAttribute instead, unless you have to otherwise.
Name | Description |
---|---|
type |
System.Type Type that contains the method |
methodOrPropertyName |
System.String Name of the method |
argTypes |
Multiplayer.API.SyncType[] Method's parameter types |
A new registered ISyncMethod
Registers the SyncWorker based on SyncWorkerDelegate.
It's recommended to use SyncWorkerAttribute instead, unless you have to otherwise.
Name | Description |
---|---|
syncWorkerDelegate |
Multiplayer.API.SyncWorkerDelegate{``0} Sync worker delegate. |
targetType |
System.Type Type to handle. |
isImplicit |
System.Boolean If set to true the SyncWorker will handle the type and all the derivate Types. |
shouldConstruct |
System.Boolean If set to true the SyncWorker will be provided with an instance created with no arguments. |
- T - Type to handle.
Helper method for ISyncField.Watch(System.Object,System.Object) given an instance.
Name | Description |
---|---|
target |
System.Object An object of type set in the ISyncField to watch |
fieldName |
System.String ISyncField name of the field to watch for changes |
index |
System.Object Index in the field path set in ISyncField |
Helper method for ISyncField.Watch(System.Object,System.Object) given an instance.
Name | Description |
---|---|
memberPath |
System.String ISyncField the memberPath of the ISyncField |
target |
System.Object An object of type set in the ISyncField to watch, null for static |
index |
System.Object Index in the field path set in ISyncField |
Helper method for ISyncField.Watch(System.Object,System.Object) given a type.
Name | Description |
---|---|
type |
System.Type An object of type set in the ISyncField to watch, for static types |
fieldName |
System.String ISyncField name of the field to watch for changes |
index |
System.Object Index in the field path set in ISyncField |
Starts a new synchronization stack.
Has to be called before invoking Watch methods.
See also ISyncField.Watch(System.Object,System.Object).
Ends the current synchronization stack and executes it.
Has to be called after invoking Watch methods.
See also ISyncField.Watch(System.Object,System.Object).
Context flags which are sent along with a command
Send current map context
Send mouse cell context (emulates mouse position)
Send map selected context (object selected on the map)
Default value. (no context)
Send order queue context (emulates pressing KeyBindingDefOf.QueueOrder)
Send world selected context (object selected on the world map)
An attribute that is used to mark fields for syncing. It will be Watched for changes by the MPApi when instructed.
An example showing how to mark a field for syncing.
public class MyClass
{
[SyncField]
bool myField;
...
}
Name | Description |
---|---|
context |
Multiplayer.API.SyncContext Context |
Instructs SyncField to use a buffer instead of syncing instantly (when MP.WatchEnd is called).
Instructs SyncField to cancel synchronization if the value of the member it's pointing at is null.
Instructs SyncField to synchronize only in debug mode.
Instructs SyncField to synchronize only if it's invoked by the host.
Instructs SyncField to sync in game loop.
An attribute that is used to mark methods for syncing. The call will be replicated by the MPApi on all clients automatically.
An example showing how to mark a method for syncing.
[SyncMethod]
public void MyMethod(...)
{
...
}
Name | Description |
---|---|
context |
Multiplayer.API.SyncContext Context |
Instructs SyncMethod to cancel synchronization if any arg is null (see ISyncMethod.CancelIfAnyArgNull).
Instructs SyncMethod to cancel synchronization if no map objects were selected during the call (see ISyncMethod.CancelIfNoSelectedMapObjects).
Instructs SyncMethod to cancel synchronization if no world objects were selected during call replication(see ISyncMethod.CancelIfNoSelectedWorldObjects).
Instructs SyncMethod to synchronize only in debug mode (see ISyncMethod.SetDebugOnly).
A list of types to expose (see ISyncMethod.ExposeParameter(System.Int32))
An abstract class that can be both a reader and a writer depending on implementation.
See ISynchronizable and SyncWorkerAttribute for usage examples.
Reads or writes an object inheriting ISynchronizable interface.
Does not create a new object.
Name | Description |
---|---|
obj |
Multiplayer.API.ISynchronizable@ object to bind |
Reads or writes an object referenced by obj.
Name | Description |
---|---|
obj |
System.Boolean@ object to bind |
Reads or writes an object referenced by obj.
Name | Description |
---|---|
obj |
System.Byte@ object to bind |
Reads or writes an object referenced by obj.
Name | Description |
---|---|
obj |
System.Double@ object to bind |
Reads or writes an object referenced by obj.
Name | Description |
---|---|
obj |
System.Int16@ object to bind |
Reads or writes an object referenced by obj.
Name | Description |
---|---|
obj |
System.Int32@ object to bind |
Reads or writes an object referenced by obj.
Name | Description |
---|---|
obj |
System.Int64@ object to bind |
Uses reflection to bind a field or property
Name | Description |
---|---|
obj |
System.Object |
object where the field or property can be found |
if null, name will point at field from the global namespace
|
| name | System.String
path to the field or property |
Reads or writes an object referenced by obj.
Name | Description |
---|---|
obj |
System.SByte@ object to bind |
Reads or writes an object referenced by obj.
Name | Description |
---|---|
obj |
System.Single@ object to bind |
Reads or writes an object referenced by obj.
Name | Description |
---|---|
obj |
System.String@ object to bind |
Reads or writes an object referenced by obj.
Name | Description |
---|---|
obj |
System.UInt16@ object to bind |
Reads or writes an object referenced by obj.
Name | Description |
---|---|
obj |
System.UInt32@ object to bind |
Reads or writes an object referenced by obj.
Name | Description |
---|---|
obj |
System.UInt64@ object to bind |
Reads or writes an object referenced by obj
Can read/write types using user defined syncers, ISynchronizables and readers/writers implemented by the multiplayer mod.
- T - type of the object to bind
Name | Description |
---|---|
obj |
``0@ object to bind |
Reads or writes a System.Type referenced by type.
- T - Base type that type derives from.
Name | Description |
---|---|
type |
System.Type@ type to bind |
if is currently writing.
Read the specified Type from the memory stream, only active during reading.
The requested Type object. Null if writing.
- T - The Type to read.
Write the specified obj, only active during writing.
Name | Description |
---|---|
obj |
``0 Object to write. |
- T - Type to write.
An attribute that marks a method as a SyncWorker for a type specified in its second parameter.
Method with this attribute has to be static.
An implementation that manually constructs an object.
[SyncWorkerAttribute]
public static void MySyncWorker(SyncWorker sync, ref MyClass inst)
{
if(!sync.isWriting)
inst = new MyClass("hello");
sync.bind(ref inst.myField);
}
An implementation that instead of creating a new object, references its existing one which resides in MyThingComp that inherits ThingComp class.
Subclasses of ThingComp are sent as a reference by the multiplayer mod itself.
[SyncWorkerAttribute]
public static void MySyncWorker(SyncWorker sync, ref MyClass inst)
{
if(!sync.isWriting)
MyThingComp parent = null;
sync.Bind(ref parent); // Receive its parent
inst = new MyClass(parent);
else
sync.Bind(ref inst.parent); // Send its parent
sync.bind(ref inst.myField);
}
Decides if the type specified in the second parameter should also be used as a syncer for all of its subclasses.
Decides if the method should get an already constructed object in case of reading data.
SyncWorker signature for adding new Types.
Name | Description |
---|---|
obj |
``0 Target Type |
SyncWorkerAttribute for usage examples.
An exception that is thrown if you try to use the API without avaiable host.
ISyncCall interface.
Used internally
Manually calls the synced method.
Name | Description |
---|---|
target |
System.Object Object currently bound to that method. Null if the method is static. |
args |
System.Object[] Parameters to call the method with. |
if the original call should be canceled.
Sync delegate.
See MP.RegisterSyncDelegate(System.Type,System.String,System.String) and MP.RegisterSyncDelegate(System.Type,System.String,System.String,System.String[],System.Type[]) to see how to use it.
Cancels if no selected objects.
self
Removes the nulls from lists.
self
Name | Description |
---|---|
listFields |
System.String[] List fields. |
Sets the context.
self
Name | Description |
---|---|
context |
Multiplayer.API.SyncContext Context. |
Sets the debug only.
self
SyncField interface.
Creates and registers a SyncField that points to myField
in object of type MyType
and enables its change buffer.
MPApi.SyncField(typeof(MyType), "myField").SetBufferChanges();
Creates and registers a SyncField that points to myField
which resides in MyStaticClass
.
MPApi.SyncField(null, "MyAssemblyNamespace.MyStaticClass.myField");
Creates and registers a SyncField that points to myField
that resides in an object stored by myEnumberable defined in an object of type MyType
.
To watch this one you have to supply an index in ISyncField.Watch(System.Object,System.Object).
MPApi.SyncField(typeof(MyType), "myEnumerable/[]/myField");
Instructs SyncField to cancel synchronization if the value of the member it's pointing at is null.
self
Manually syncs a field.
Name | Description |
---|---|
target |
System.Object An object of type set in the ISyncField. Set to null if you're watching a static field. |
value |
System.Object Value to apply to the synced field. |
index |
System.Object Index in the field path set in ISyncField |
if the change should be canceled.
Instructs SyncField to sync in game loop.
self
Adds an Action that runs after a field is synchronized.
Name | Description |
---|---|
action |
System.Action{System.Object,System.Object} An action ran after a field is synchronized. Called with target and value. |
self
Adds an Action that runs before a field is synchronized.
Name | Description |
---|---|
action |
System.Action{System.Object,System.Object} An action ran before a field is synchronized. Called with target and value. |
self
Instructs SyncField to use a buffer instead of syncing instantly (when MP.WatchEnd is called).
self
Instructs SyncField to synchronize only in debug mode.
self
Instructs SyncField to synchronize only if it's invoked by the host.
self
self
Name | Description |
---|---|
target |
System.Object An object of type set in the ISyncField. Set to null if you're watching a static field. |
index |
System.Object Index in the field path set in ISyncField. |
self
An interface that allows syncing objects that inherit it.
An entry point that is used when object is to be read/written.
Requires a default constructor that takes no parameters.
Check SyncWorkerAttribute to see how to make a syncer that allows for a manual object construction.
Name | Description |
---|---|
sync |
Multiplayer.API.SyncWorker A SyncWorker that will read/write data bound with Bind methods. |
A simple implementation that binds object's fields x, y, z for reading/writing.
public void Sync(SyncWorker sync)
{
sync.Bind(ref this.x);
sync.Bind(ref this.y);
sync.Bind(ref this.z);
}
An implementation that sends field a, but saves it back into field b when it's received.
public void Sync(SyncWorker sync)
{
if(sync.isWriting)
sync.Bind(ref this.a);
else
sync.Bind(ref this.b);
}
SyncMethod interface.
See SyncMethodAttribute, MP.RegisterSyncMethod(System.Reflection.MethodInfo,Multiplayer.API.SyncType[]) and MP.RegisterSyncMethod(System.Type,System.String,Multiplayer.API.SyncType[]) to see how to use it.
Instructs SyncMethod to cancel synchronization if any arg is null.
self
Instructs SyncMethod to cancel synchronization if no map objects were selected during call replication.
self
Instructs SyncMethod to cancel synchronization if no world objects were selected during call replication.
self
Use parameter's type's IExposable interface to transfer its data to other clients.
IExposable is the interface used for saving data to the save which means it utilizes IExposable.ExposeData() method.
Name | Description |
---|---|
index |
System.Int32 Index at which parameter is to be marked to expose |
self
Currently unused in the Multiplayer mod.
Name | Description |
---|---|
time |
System.Int32 Milliseconds between resends |
self
Instructs method to send context along with the call.
Context is restored after method is called.
Name | Description |
---|---|
context |
Multiplayer.API.SyncContext One or more context flags |
self
Instructs SyncMethod to synchronize only in debug mode.
self
Adds an Action that runs after a call is replicated on client.
Name | Description |
---|---|
action |
System.Action{System.Object,System.Object[]} An action ran after a call is replicated on client. Called with target and value. |
self
Adds an Action that runs before a call is replicated on client.
Name | Description |
---|---|
action |
System.Action{System.Object,System.Object[]} An action ran before a call is replicated on client. Called with target and value. |
self
Name | Description |
---|---|
version |
System.Int32 Handler version |
self