quantum-space-buddies/QSB/ShipSync/Events/FlyShipEvent.cs
2021-05-10 14:32:47 +01:00

103 lines
2.9 KiB
C#

using OWML.Utils;
using QSB.Events;
using QSB.Messaging;
using QSB.Player;
using QSB.ShipSync.TransformSync;
using QSB.Utility;
using QSB.WorldSync;
using QuantumUNET;
using System.Linq;
using UnityEngine;
namespace QSB.ShipSync.Events
{
class FlyShipEvent : QSBEvent<BoolMessage>
{
public override QSB.Events.EventType Type => QSB.Events.EventType.FlyShip;
public override void SetupListener()
{
GlobalMessenger<OWRigidbody>.AddListener(EventNames.EnterFlightConsole, (OWRigidbody rigidbody) => Handler(true));
GlobalMessenger.AddListener(EventNames.ExitFlightConsole, () => Handler(false));
}
public override void CloseListener()
{
GlobalMessenger<OWRigidbody>.RemoveListener(EventNames.EnterFlightConsole, (OWRigidbody rigidbody) => Handler(true));
GlobalMessenger.RemoveListener(EventNames.ExitFlightConsole, () => Handler(false));
}
private void Handler(bool flying) => SendEvent(CreateMessage(flying));
private BoolMessage CreateMessage(bool flying) => new BoolMessage
{
AboutId = LocalPlayerId,
Value = flying
};
public override void OnReceiveLocal(bool server, BoolMessage message)
{
SetCurrentFlyer(message.Value, message.AboutId);
}
public override void OnReceiveRemote(bool server, BoolMessage message)
{
SetCurrentFlyer(message.Value, message.AboutId);
var shipCockpitController = GameObject.Find("ShipCockpitController").GetComponent<ShipCockpitController>();
var interactVolume = shipCockpitController.GetValue<SingleInteractionVolume>("_interactVolume");
if (message.Value)
{
interactVolume.DisableInteraction();
}
else
{
interactVolume.EnableInteraction();
}
}
private void SetCurrentFlyer(bool isFlying, uint id)
{
ShipManager.Instance.CurrentFlyer = isFlying
? id
: uint.MaxValue;
if (id == uint.MaxValue)
{
DebugLog.DebugWrite($"ShipDetector setactive {QSBCore.IsServer}");
Locator.GetShipDetector().SetActive(QSBCore.IsServer);
}
else if (id == LocalPlayerId)
{
DebugLog.DebugWrite($"Enable ship detector");
Locator.GetShipDetector().SetActive(true);
}
else
{
DebugLog.DebugWrite($"Disable ship detector");
Locator.GetShipDetector().SetActive(false);
}
if (QSBCore.IsServer)
{
DebugLog.DebugWrite($"Change ship auth to {id}");
var fromPlayer = ShipManager.Instance.CurrentFlyer == uint.MaxValue
? QNetworkServer.connections.First(x => x.GetPlayerId() == QSBPlayerManager.LocalPlayerId)
: QNetworkServer.connections.First(x => x.GetPlayerId() == id);
var ship = ShipTransformSync.LocalInstance;
var networkIdentity = ship.NetIdentity;
if (networkIdentity.ClientAuthorityOwner == fromPlayer)
{
return;
}
if (networkIdentity.ClientAuthorityOwner != null && networkIdentity.ClientAuthorityOwner != fromPlayer)
{
networkIdentity.RemoveClientAuthority(networkIdentity.ClientAuthorityOwner);
}
networkIdentity.AssignClientAuthority(fromPlayer);
}
}
}
}