using QSB.Messaging; using QSB.TransformSync; using QSB.Utility; namespace QSB.Events { /// /// Abstract class that handles all event code. /// /// The message type to use. public abstract class QSBEvent where T : PlayerMessage, new() { public abstract MessageType Type { get; } public uint LocalPlayerId => PlayerRegistry.LocalPlayer.NetId; private readonly MessageHandler _eventHandler; protected bool IsInUniverse { get; private set; } protected QSBEvent() { _eventHandler = new MessageHandler(Type); _eventHandler.OnClientReceiveMessage += OnClientReceive; _eventHandler.OnServerReceiveMessage += OnServerReceive; SetupListener(); LoadManager.OnCompleteSceneLoad += OnCompleteSceneLoad; } private void OnCompleteSceneLoad(OWScene oldScene, OWScene newScene) { IsInUniverse = newScene == OWScene.SolarSystem || newScene == OWScene.EyeOfTheUniverse; } /// /// Called to set up the activators for the event. /// public abstract void SetupListener(); /// /// Called on every client that didn't send the event. /// /// public virtual void OnReceiveRemote(T message) { } /// /// Called on the client that sent the event. /// /// public virtual void OnReceiveLocal(T message) { } /// /// Called on the server. /// /// public virtual void OnServerReceive(T message) { _eventHandler.SendToAll(message); } public void SendEvent(T message) { UnityHelper.Instance.RunWhen(() => PlayerTransformSync.LocalInstance != null, () => Send(message)); } private void Send(T message) { _eventHandler.SendToServer(message); } private void OnClientReceive(T message) { if (message.SenderId == PlayerTransformSync.LocalInstance?.netId.Value) { OnReceiveLocal(message); return; } OnReceiveRemote(message); } } }