85 lines
2.5 KiB
C#
85 lines
2.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using Unity.Netcode;
|
|
using OdinSerializer;
|
|
using System.IO;
|
|
using HarmonyLib;
|
|
using BepInEx.Configuration;
|
|
using BepInEx.Logging;
|
|
using UnityEngine;
|
|
|
|
namespace ScarletMansion {
|
|
|
|
[Serializable]
|
|
public class SyncedInstance<T> {
|
|
internal static CustomMessagingManager MessageManager => NetworkManager.Singleton.CustomMessagingManager;
|
|
internal static bool IsClient => NetworkManager.Singleton.IsClient;
|
|
internal static bool IsHost => NetworkManager.Singleton.IsHost;
|
|
internal static ManualLogSource logger => Plugin.logger;
|
|
|
|
[NonSerialized]
|
|
protected static int IntSize = 4;
|
|
|
|
public static T Default { get; private set; }
|
|
public static T Instance { get; private set; }
|
|
|
|
public static bool Synced { get; internal set; }
|
|
|
|
public bool SyncedLocal => Synced;
|
|
|
|
protected void InitInstance(T instance) {
|
|
Default = instance;
|
|
Instance = instance;
|
|
|
|
// Makes sure the size of an integer is correct for the current system.
|
|
// We use 4 by default as that's the size of an int on 32 and 64 bit systems.
|
|
IntSize = sizeof(int);
|
|
}
|
|
|
|
internal static void SyncInstance(byte[] data) {
|
|
Instance = DeserializeFromBytes(data);
|
|
Synced = true;
|
|
}
|
|
|
|
internal static void RevertSync() {
|
|
Instance = Default;
|
|
Synced = false;
|
|
}
|
|
|
|
public static byte[] SerializeToBytes(T val) {
|
|
try {
|
|
return SerializationUtility.SerializeValue(val, DataFormat.Binary);
|
|
}
|
|
catch (Exception e) {
|
|
logger.LogError($"Error serializing instance: {e}");
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public static T DeserializeFromBytes(byte[] data) {
|
|
try {
|
|
return SerializationUtility.DeserializeValue<T>(data, DataFormat.Binary);
|
|
} catch (Exception e) {
|
|
logger.LogError($"Error deserializing instance: {e}");
|
|
return default;
|
|
}
|
|
|
|
}
|
|
|
|
public static void SendMessage(FastBufferWriter stream, string title, ulong clientId = 0uL){
|
|
var pastCapacity = stream.Capacity > 1300;
|
|
var flag = pastCapacity ? NetworkDelivery.ReliableFragmentedSequenced : NetworkDelivery.Reliable;
|
|
if (pastCapacity){
|
|
logger.LogDebug("Stream is past capacity. Sending fragmented message");
|
|
}
|
|
|
|
MessageManager.SendNamedMessage(title, clientId, stream, flag);
|
|
Plugin.logger.LogDebug($"Send message to client {clientId} with title {title} and flag {flag}");
|
|
}
|
|
|
|
}
|
|
|
|
}
|