Made Networking and PlayerList static, changes to class hierarchy

This commit is contained in:
sausage
2022-05-23 16:59:49 +08:00
parent e6332ff9d2
commit 118725e949
17 changed files with 205 additions and 198 deletions

View File

@ -99,7 +99,7 @@ namespace RageCoop.Client
/// <param name="serverAddress">The server address to connect. Example: 127.0.0.1:4499</param> /// <param name="serverAddress">The server address to connect. Example: 127.0.0.1:4499</param>
public static void Connect(string serverAddress) public static void Connect(string serverAddress)
{ {
Main.MainNetworking.DisConnectFromServer(serverAddress); Networking.DisConnectFromServer(serverAddress);
} }
/// <summary> /// <summary>
@ -107,7 +107,7 @@ namespace RageCoop.Client
/// </summary> /// </summary>
public static void Disconnect() public static void Disconnect()
{ {
Main.MainNetworking.DisConnectFromServer(null); Networking.DisConnectFromServer(null);
} }
/// <summary> /// <summary>
@ -115,7 +115,7 @@ namespace RageCoop.Client
/// </summary> /// </summary>
public static bool IsOnServer() public static bool IsOnServer()
{ {
return Main.MainNetworking.IsOnServer(); return Networking.IsOnServer();
} }
/// <summary> /// <summary>
@ -124,7 +124,7 @@ namespace RageCoop.Client
/// <returns>PlayerID</returns> /// <returns>PlayerID</returns>
public static long GetPlayerID() public static long GetPlayerID()
{ {
return Main.MyPlayerID; return Main.LocalPlayerID;
} }
/* /*
@ -166,7 +166,7 @@ namespace RageCoop.Client
/// </summary> /// </summary>
public static bool IsPlayerListVisible() public static bool IsPlayerListVisible()
{ {
return Main.MainPlayerList != null && Util.GetTickCount64() - Main.MainPlayerList.Pressed < 5000; return Util.GetTickCount64() - PlayerList.Pressed < 5000;
} }
/// <summary> /// <summary>
@ -185,7 +185,7 @@ namespace RageCoop.Client
/// <param name="bytes">Your class, structure or whatever in bytes</param> /// <param name="bytes">Your class, structure or whatever in bytes</param>
public static void SendDataToServer(string modName, byte customID, byte[] bytes) public static void SendDataToServer(string modName, byte customID, byte[] bytes)
{ {
Main.MainNetworking.SendModData(-1, modName, customID, bytes); Networking.SendModData(-1, modName, customID, bytes);
} }
/// <summary> /// <summary>
@ -196,7 +196,7 @@ namespace RageCoop.Client
/// <param name="bytes">Your class, structure or whatever in bytes</param> /// <param name="bytes">Your class, structure or whatever in bytes</param>
public static void SendDataToAll(string modName, byte customID, byte[] bytes) public static void SendDataToAll(string modName, byte customID, byte[] bytes)
{ {
Main.MainNetworking.SendModData(0, modName, customID, bytes); Networking.SendModData(0, modName, customID, bytes);
} }
/// <summary> /// <summary>
@ -208,7 +208,7 @@ namespace RageCoop.Client
/// <param name="bytes">Your class, structure or whatever in bytes</param> /// <param name="bytes">Your class, structure or whatever in bytes</param>
public static void SendDataToPlayer(long netHandle, string modName, byte customID, byte[] bytes) public static void SendDataToPlayer(long netHandle, string modName, byte customID, byte[] bytes)
{ {
Main.MainNetworking.SendModData(netHandle, modName, customID, bytes); Networking.SendModData(netHandle, modName, customID, bytes);
} }
/// <summary> /// <summary>
@ -253,10 +253,7 @@ namespace RageCoop.Client
/// <param name="leftAlign">true to move the player list to the left</param> /// <param name="leftAlign">true to move the player list to the left</param>
public static void SetPlayerListLeftAlign(bool leftAlign) public static void SetPlayerListLeftAlign(bool leftAlign)
{ {
if (Main.MainPlayerList != null) PlayerList.LeftAlign = leftAlign;
{
Main.MainPlayerList.LeftAlign = leftAlign;
}
} }
#if DEBUG #if DEBUG

View File

@ -25,19 +25,17 @@ namespace RageCoop.Client
public static readonly string CurrentVersion = "V0_1"; public static readonly string CurrentVersion = "V0_1";
public static int MyPlayerID=0; public static int LocalPlayerID=0;
public static bool DisableTraffic = true; public static bool DisableTraffic = true;
public static bool NPCsAllowed = false; public static bool NPCsAllowed = false;
internal static RelationshipGroup SyncedPedsGroup; internal static RelationshipGroup SyncedPedsGroup;
public static new Settings Settings = null; public static new Settings Settings = null;
public static Networking MainNetworking = null;
#if !NON_INTERACTIVE #if !NON_INTERACTIVE
public static RageCoopMenu MainMenu = null; public static RageCoopMenu MainMenu = null;
#endif #endif
public static Chat MainChat = null; public static Chat MainChat = null;
public static PlayerList MainPlayerList = new PlayerList();
public static Stopwatch Counter = new Stopwatch(); public static Stopwatch Counter = new Stopwatch();
public static ulong Ticked = 0; public static ulong Ticked = 0;
@ -72,8 +70,7 @@ namespace RageCoop.Client
SyncedPedsGroup=World.AddRelationshipGroup("SYNCPED"); SyncedPedsGroup=World.AddRelationshipGroup("SYNCPED");
Game.Player.Character.RelationshipGroup.SetRelationshipBetweenGroups(SyncedPedsGroup, Relationship.Neutral, true); Game.Player.Character.RelationshipGroup.SetRelationshipBetweenGroups(SyncedPedsGroup, Relationship.Neutral, true);
Settings = Util.ReadSettings(); Settings = Util.ReadSettings();
MainNetworking = new Networking(); Networking.Start();
MainNetworking.Start();
#if !NON_INTERACTIVE #if !NON_INTERACTIVE
MainMenu = new RageCoopMenu(); MainMenu = new RageCoopMenu();
#endif #endif
@ -120,7 +117,7 @@ namespace RageCoop.Client
_isGoingToCar = false; _isGoingToCar = false;
} }
DoQueuedActions(); DoQueuedActions();
if (!MainNetworking.IsOnServer()) if (!Networking.IsOnServer())
{ {
return; return;
} }
@ -130,7 +127,7 @@ namespace RageCoop.Client
} }
try try
{ {
MainNetworking.Tick(); Networking.Tick();
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -145,20 +142,20 @@ namespace RageCoop.Client
MapLoader.LoadAll(); MapLoader.LoadAll();
#if DEBUG #if DEBUG
if (MainNetworking.ShowNetworkInfo) if (Networking.ShowNetworkInfo)
{ {
ulong time = Util.GetTickCount64(); ulong time = Util.GetTickCount64();
if (time - _lastDebugData > 1000) if (time - _lastDebugData > 1000)
{ {
_lastDebugData = time; _lastDebugData = time;
_debugBytesReceived = MainNetworking.BytesReceived; _debugBytesReceived = Networking.BytesReceived;
MainNetworking.BytesReceived = 0; Networking.BytesReceived = 0;
_debugBytesSend = MainNetworking.BytesSend; _debugBytesSend = Networking.BytesSend;
MainNetworking.BytesSend = 0; Networking.BytesSend = 0;
} }
new LemonUI.Elements.ScaledText(new PointF(Screen.PrimaryScreen.Bounds.Width / 2, 0), $"L: {MainNetworking.Latency * 1000:N0}ms", 0.5f) { Alignment = GTA.UI.Alignment.Center }.Draw(); new LemonUI.Elements.ScaledText(new PointF(Screen.PrimaryScreen.Bounds.Width / 2, 0), $"L: {Networking.Latency * 1000:N0}ms", 0.5f) { Alignment = GTA.UI.Alignment.Center }.Draw();
new LemonUI.Elements.ScaledText(new PointF(Screen.PrimaryScreen.Bounds.Width / 2, 30), $"R: {Lidgren.Network.NetUtility.ToHumanReadable(_debugBytesReceived)}/s", 0.5f) { Alignment = GTA.UI.Alignment.Center }.Draw(); new LemonUI.Elements.ScaledText(new PointF(Screen.PrimaryScreen.Bounds.Width / 2, 30), $"R: {Lidgren.Network.NetUtility.ToHumanReadable(_debugBytesReceived)}/s", 0.5f) { Alignment = GTA.UI.Alignment.Center }.Draw();
new LemonUI.Elements.ScaledText(new PointF(Screen.PrimaryScreen.Bounds.Width / 2, 60), $"S: {Lidgren.Network.NetUtility.ToHumanReadable(_debugBytesSend)}/s", 0.5f) { Alignment = GTA.UI.Alignment.Center }.Draw(); new LemonUI.Elements.ScaledText(new PointF(Screen.PrimaryScreen.Bounds.Width / 2, 60), $"S: {Lidgren.Network.NetUtility.ToHumanReadable(_debugBytesSend)}/s", 0.5f) { Alignment = GTA.UI.Alignment.Center }.Draw();
} }
@ -167,7 +164,7 @@ namespace RageCoop.Client
MainChat.Tick(); MainChat.Tick();
MainPlayerList.Tick(); PlayerList.Tick();
@ -175,7 +172,6 @@ namespace RageCoop.Client
Ticked++; Ticked++;
} }
#if !NON_INTERACTIVE
private void OnKeyDown(object sender, KeyEventArgs e) private void OnKeyDown(object sender, KeyEventArgs e)
{ {
if (MainChat.Focused) if (MainChat.Focused)
@ -202,15 +198,15 @@ namespace RageCoop.Client
} }
else if (Game.IsControlJustPressed(GTA.Control.MultiplayerInfo)) else if (Game.IsControlJustPressed(GTA.Control.MultiplayerInfo))
{ {
if (MainNetworking.IsOnServer()) if (Networking.IsOnServer())
{ {
ulong currentTimestamp = Util.GetTickCount64(); ulong currentTimestamp = Util.GetTickCount64();
MainPlayerList.Pressed = (currentTimestamp - MainPlayerList.Pressed) < 5000 ? (currentTimestamp - 6000) : currentTimestamp; PlayerList.Pressed = (currentTimestamp - PlayerList.Pressed) < 5000 ? (currentTimestamp - 6000) : currentTimestamp;
} }
} }
else if (Game.IsControlJustPressed(GTA.Control.MpTextChatAll)) else if (Game.IsControlJustPressed(GTA.Control.MpTextChatAll))
{ {
if (MainNetworking.IsOnServer()) if (Networking.IsOnServer())
{ {
MainChat.Focused = true; MainChat.Focused = true;
} }
@ -238,41 +234,12 @@ namespace RageCoop.Client
} }
} }
} }
#else
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (MainChat.Focused)
{
MainChat.OnKeyDown(e.KeyCode);
return;
}
if (Game.IsControlJustPressed(GTA.Control.MultiplayerInfo))
{
if (MainNetworking.IsOnServer())
{
ulong currentTimestamp = Util.GetTickCount64();
PlayerList.Pressed = (currentTimestamp - PlayerList.Pressed) < 5000 ? (currentTimestamp - 6000) : currentTimestamp;
}
}
else if (Game.IsControlJustPressed(GTA.Control.MpTextChatAll))
{
if (MainNetworking.IsOnServer())
{
MainChat.Focused = true;
}
}
}
#endif
public static void CleanUp() public static void CleanUp()
{ {
MainChat.Clear(); MainChat.Clear();
EntityPool.Cleanup(); EntityPool.Cleanup();
MainPlayerList=new PlayerList(); PlayerList.Cleanup();
Main.LocalPlayerID=default;
Main.MyPlayerID=default;
} }
@ -411,7 +378,7 @@ namespace RageCoop.Client
public static string DumpPlayers() public static string DumpPlayers()
{ {
string s = "Players:"; string s = "Players:";
foreach (PlayerData p in MainPlayerList.Players) foreach (PlayerData p in PlayerList.Players)
{ {
s+=$"\r\nID:{p.PedID} Username:{p.Username}"; s+=$"\r\nID:{p.PedID} Username:{p.Username}";

View File

@ -45,7 +45,7 @@ namespace RageCoop.Client.Menus
_usernameItem.Activated += UsernameActivated; _usernameItem.Activated += UsernameActivated;
ServerIpItem.Activated += ServerIpActivated; ServerIpItem.Activated += ServerIpActivated;
_serverConnectItem.Activated += (sender, item) => { Main.MainNetworking.DisConnectFromServer(Main.Settings.LastServerAddress); }; _serverConnectItem.Activated += (sender, item) => { Networking.DisConnectFromServer(Main.Settings.LastServerAddress); };
MainMenu.Add(_usernameItem); MainMenu.Add(_usernameItem);

View File

@ -19,7 +19,7 @@ namespace RageCoop.Client.Menus.Sub
private readonly NativeCheckboxItem _disableTrafficItem = new NativeCheckboxItem("Disable Traffic (NPCs/Vehicles)", "Local traffic only", Main.DisableTraffic); private readonly NativeCheckboxItem _disableTrafficItem = new NativeCheckboxItem("Disable Traffic (NPCs/Vehicles)", "Local traffic only", Main.DisableTraffic);
private readonly NativeCheckboxItem _flipMenuItem = new NativeCheckboxItem("Flip menu", Main.Settings.FlipMenu); private readonly NativeCheckboxItem _flipMenuItem = new NativeCheckboxItem("Flip menu", Main.Settings.FlipMenu);
private readonly NativeCheckboxItem _showNetworkInfoItem = new NativeCheckboxItem("Show Network Info", Main.MainNetworking.ShowNetworkInfo); private readonly NativeCheckboxItem _showNetworkInfoItem = new NativeCheckboxItem("Show Network Info", Networking.ShowNetworkInfo);
private static NativeItem _menuKey = new NativeItem("Menu Key","The key to open menu", Main.Settings.MenuKey.ToString()); private static NativeItem _menuKey = new NativeItem("Menu Key","The key to open menu", Main.Settings.MenuKey.ToString());
private static NativeItem _passengerKey = new NativeItem("Passenger Key", "The key to enter a vehicle as passenger", Main.Settings.PassengerKey.ToString()); private static NativeItem _passengerKey = new NativeItem("Passenger Key", "The key to enter a vehicle as passenger", Main.Settings.PassengerKey.ToString());
@ -88,12 +88,12 @@ namespace RageCoop.Client.Menus.Sub
public void ShowNetworkInfoCheckboxChanged(object a, System.EventArgs b) public void ShowNetworkInfoCheckboxChanged(object a, System.EventArgs b)
{ {
Main.MainNetworking.ShowNetworkInfo = _showNetworkInfoItem.Checked; Networking.ShowNetworkInfo = _showNetworkInfoItem.Checked;
if (!Main.MainNetworking.ShowNetworkInfo) if (!Networking.ShowNetworkInfo)
{ {
Main.MainNetworking.BytesReceived = 0; Networking.BytesReceived = 0;
Main.MainNetworking.BytesSend = 0; Networking.BytesSend = 0;
} }
} }
} }

View File

@ -137,7 +137,7 @@ namespace RageCoop.Client
if (!string.IsNullOrWhiteSpace(CurrentInput)) if (!string.IsNullOrWhiteSpace(CurrentInput))
{ {
Main.MainNetworking.SendChatMessage(CurrentInput); Networking.SendChatMessage(CurrentInput);
} }
Focused = false; Focused = false;

View File

@ -23,7 +23,7 @@ namespace RageCoop.Client
if (FileAlreadyExists(downloadFolder, name, length)) if (FileAlreadyExists(downloadFolder, name, length))
{ {
// Send the server we are already done // Send the server we are already done
Main.MainNetworking.SendDownloadFinish(id); Networking.SendDownloadFinish(id);
Cancel(id); Cancel(id);
return; return;

View File

@ -11,18 +11,16 @@ using GTA.Native;
namespace RageCoop.Client namespace RageCoop.Client
{ {
public partial class Networking public static partial class Networking
{ {
public NetClient Client; public static NetClient Client;
public float Latency = 0; public static float Latency = 0;
public static bool ShowNetworkInfo = false;
public static int BytesReceived = 0;
public static int BytesSend = 0;
private static Thread ReceiveThread;
public bool ShowNetworkInfo = false; public static void DisConnectFromServer(string address)
public int BytesReceived = 0;
public int BytesSend = 0;
private Thread ReceiveThread;
public void DisConnectFromServer(string address)
{ {
if (IsOnServer()) if (IsOnServer())
{ {
@ -61,7 +59,7 @@ namespace RageCoop.Client
NetOutgoingMessage outgoingMessage = Client.CreateMessage(); NetOutgoingMessage outgoingMessage = Client.CreateMessage();
new Packets.Handshake() new Packets.Handshake()
{ {
PedID = Main.MyPlayerID, PedID = Main.LocalPlayerID,
Username = Main.Settings.Username, Username = Main.Settings.Username,
ModVersion = Main.CurrentVersion, ModVersion = Main.CurrentVersion,
NPCsAllowed = false NPCsAllowed = false
@ -70,12 +68,11 @@ namespace RageCoop.Client
Client.Connect(ip[0], short.Parse(ip[1]), outgoingMessage); Client.Connect(ip[0], short.Parse(ip[1]), outgoingMessage);
} }
} }
public static bool IsOnServer()
public bool IsOnServer()
{ {
return Client?.ConnectionStatus == NetConnectionStatus.Connected; return Client?.ConnectionStatus == NetConnectionStatus.Connected;
} }
public void Start() public static void Start()
{ {
ReceiveThread=new Thread(() => ReceiveThread=new Thread(() =>
{ {
@ -95,10 +92,9 @@ namespace RageCoop.Client
ReceiveThread.Start(); ReceiveThread.Start();
} }
#region -- GET -- #region -- GET --
#region -- PLAYER -- #region -- PLAYER --
private void PlayerConnect(Packets.PlayerConnect packet) private static void PlayerConnect(Packets.PlayerConnect packet)
{ {
var p = new PlayerData var p = new PlayerData
{ {
@ -106,24 +102,23 @@ namespace RageCoop.Client
Username= packet.Username, Username= packet.Username,
}; };
GTA.UI.Notification.Show($"{p.Username} connected."); GTA.UI.Notification.Show($"{p.Username} connected.");
Main.MainPlayerList.SetPlayer(packet.PedID, packet.Username); PlayerList.SetPlayer(packet.PedID, packet.Username);
Main.Logger.Debug($"player connected:{p.Username}"); Main.Logger.Debug($"player connected:{p.Username}");
Main.DumpCharacters(); Main.DumpCharacters();
COOPAPI.Connected(packet.PedID); COOPAPI.Connected(packet.PedID);
} }
private static void PlayerDisconnect(Packets.PlayerDisconnect packet)
private void PlayerDisconnect(Packets.PlayerDisconnect packet)
{ {
var name=Main.MainPlayerList.GetPlayer(packet.PedID).Username; var name=PlayerList.GetPlayer(packet.PedID).Username;
GTA.UI.Notification.Show($"{name} left."); GTA.UI.Notification.Show($"{name} left.");
COOPAPI.Disconnected(packet.PedID); COOPAPI.Disconnected(packet.PedID);
Main.MainPlayerList.RemovePlayer(packet.PedID); PlayerList.RemovePlayer(packet.PedID);
EntityPool.RemoveAllFromPlayer(packet.PedID); EntityPool.RemoveAllFromPlayer(packet.PedID);
} }
private object DecodeNativeCall(ulong hash, List<object> args, bool returnValue, byte? returnType = null) private static object DecodeNativeCall(ulong hash, List<object> args, bool returnValue, byte? returnType = null)
{ {
List<InputArgument> arguments = new List<InputArgument>(); List<InputArgument> arguments = new List<InputArgument>();
@ -185,7 +180,7 @@ namespace RageCoop.Client
} }
} }
private void DecodeNativeResponse(Packets.NativeResponse packet) private static void DecodeNativeResponse(Packets.NativeResponse packet)
{ {
object result = DecodeNativeCall(packet.Hash, packet.Args, true, packet.ResultType); object result = DecodeNativeCall(packet.Hash, packet.Args, true, packet.ResultType);
@ -217,7 +212,7 @@ namespace RageCoop.Client
#endregion // -- PLAYER -- #endregion // -- PLAYER --
#endregion #endregion
public void Tick() public static void Tick()
{ {

View File

@ -10,9 +10,9 @@ using GTA.Native;
namespace RageCoop.Client namespace RageCoop.Client
{ {
public partial class Networking public static partial class Networking
{ {
public void ReceiveMessages() public static void ReceiveMessages()
{ {
if (Client == null) if (Client == null)
{ {
@ -65,7 +65,7 @@ namespace RageCoop.Client
Main.QueueAction(() => { Main.QueueAction(() => {
Main.MainMenu.ConnectedMenuSetting(); Main.MainMenu.ConnectedMenuSetting();
Main.MainChat.Init(); Main.MainChat.Init();
Main.MainPlayerList = new PlayerList(); PlayerList.Cleanup();
GTA.UI.Notification.Show("~g~Connected!"); GTA.UI.Notification.Show("~g~Connected!");
}); });
@ -87,7 +87,6 @@ namespace RageCoop.Client
Main.MainChat.Focused = false; Main.MainChat.Focused = false;
} }
Main.MainPlayerList = null;
Main.QueueAction(() => Main.CleanUp()); Main.QueueAction(() => Main.CleanUp());
#if !NON_INTERACTIVE #if !NON_INTERACTIVE
@ -290,7 +289,7 @@ namespace RageCoop.Client
Client.Recycle(message); Client.Recycle(message);
} }
} }
private void PedSync(Packets.PedSync packet) private static void PedSync(Packets.PedSync packet)
{ {
lock (EntityPool.PedsLock) lock (EntityPool.PedsLock)
{ {
@ -332,7 +331,7 @@ namespace RageCoop.Client
} }
} }
} }
private void PedStateSync(Packets.PedStateSync packet) private static void PedStateSync(Packets.PedStateSync packet)
{ {
lock (EntityPool.PedsLock) lock (EntityPool.PedsLock)
{ {
@ -351,7 +350,7 @@ namespace RageCoop.Client
c.LastSynced=c.LastStateSynced = Main.Ticked; c.LastSynced=c.LastStateSynced = Main.Ticked;
} }
} }
private void VehicleSync(Packets.VehicleSync packet) private static void VehicleSync(Packets.VehicleSync packet)
{ {
lock (EntityPool.VehiclesLock) lock (EntityPool.VehiclesLock)
{ {
@ -371,7 +370,7 @@ namespace RageCoop.Client
v.LastSynced=Main.Ticked; v.LastSynced=Main.Ticked;
} }
} }
private void VehicleStateSync(Packets.VehicleStateSync packet) private static void VehicleStateSync(Packets.VehicleStateSync packet)
{ {
lock (EntityPool.VehiclesLock) lock (EntityPool.VehiclesLock)
{ {

View File

@ -11,7 +11,7 @@ using GTA.Math;
namespace RageCoop.Client namespace RageCoop.Client
{ {
public partial class Networking public static partial class Networking
{ {
/// <summary> /// <summary>
@ -20,7 +20,7 @@ namespace RageCoop.Client
/// <param name="p"></param> /// <param name="p"></param>
/// <param name="channel"></param> /// <param name="channel"></param>
/// <param name="method"></param> /// <param name="method"></param>
public void Send(Packet p, ConnectionChannel channel = ConnectionChannel.Default,NetDeliveryMethod method=NetDeliveryMethod.UnreliableSequenced) public static void Send(Packet p, ConnectionChannel channel = ConnectionChannel.Default,NetDeliveryMethod method=NetDeliveryMethod.UnreliableSequenced)
{ {
NetOutgoingMessage outgoingMessage = Client.CreateMessage(); NetOutgoingMessage outgoingMessage = Client.CreateMessage();
p.Pack(outgoingMessage); p.Pack(outgoingMessage);
@ -28,7 +28,7 @@ namespace RageCoop.Client
} }
#region -- SEND -- #region -- SEND --
public void SendPed(SyncedPed c) public static void SendPed(SyncedPed c)
{ {
Ped p = c.MainPed; Ped p = c.MainPed;
var packet=new Packets.PedSync() var packet=new Packets.PedSync()
@ -53,7 +53,7 @@ namespace RageCoop.Client
} }
Send(packet, ConnectionChannel.CharacterSync); Send(packet, ConnectionChannel.CharacterSync);
} }
public void SendPedState(SyncedPed c) public static void SendPedState(SyncedPed c)
{ {
Ped p = c.MainPed; Ped p = c.MainPed;
@ -68,7 +68,7 @@ namespace RageCoop.Client
Send(packet, ConnectionChannel.CharacterSync); Send(packet, ConnectionChannel.CharacterSync);
} }
public void SendVehicle(SyncedVehicle v) public static void SendVehicle(SyncedVehicle v)
{ {
Vehicle veh = v.MainVehicle; Vehicle veh = v.MainVehicle;
var packet = new Packets.VehicleSync() var packet = new Packets.VehicleSync()
@ -84,7 +84,7 @@ namespace RageCoop.Client
}; };
Send(packet,ConnectionChannel.VehicleSync); Send(packet,ConnectionChannel.VehicleSync);
} }
public void SendVehicleState(SyncedVehicle v) public static void SendVehicleState(SyncedVehicle v)
{ {
Vehicle veh = v.MainVehicle; Vehicle veh = v.MainVehicle;
byte primaryColor = 0; byte primaryColor = 0;
@ -111,7 +111,7 @@ namespace RageCoop.Client
} }
#region SYNC EVENTS #region SYNC EVENTS
public void SendBulletShot(Vector3 start,Vector3 end,uint weapon,int ownerID) public static void SendBulletShot(Vector3 start,Vector3 end,uint weapon,int ownerID)
{ {
Send(new Packets.BulletShot() Send(new Packets.BulletShot()
{ {
@ -122,7 +122,7 @@ namespace RageCoop.Client
}, ConnectionChannel.SyncEvents); }, ConnectionChannel.SyncEvents);
} }
#endregion #endregion
public void SendChatMessage(string message) public static void SendChatMessage(string message)
{ {
NetOutgoingMessage outgoingMessage = Client.CreateMessage(); NetOutgoingMessage outgoingMessage = Client.CreateMessage();
@ -138,8 +138,7 @@ namespace RageCoop.Client
} }
#endif #endif
} }
public static void SendModData(long target, string modName, byte customID, byte[] bytes)
public void SendModData(long target, string modName, byte customID, byte[] bytes)
{ {
NetOutgoingMessage outgoingMessage = Client.CreateMessage(); NetOutgoingMessage outgoingMessage = Client.CreateMessage();
new Packets.Mod() new Packets.Mod()
@ -160,8 +159,7 @@ namespace RageCoop.Client
} }
#endif #endif
} }
public static void SendDownloadFinish(byte id)
public void SendDownloadFinish(byte id)
{ {
NetOutgoingMessage outgoingMessage = Client.CreateMessage(); NetOutgoingMessage outgoingMessage = Client.CreateMessage();
@ -177,8 +175,7 @@ namespace RageCoop.Client
} }
#endif #endif
} }
public static void SendTriggerEvent(string eventName, params object[] args)
public void SendTriggerEvent(string eventName, params object[] args)
{ {
NetOutgoingMessage outgoingMessage = Client.CreateMessage(); NetOutgoingMessage outgoingMessage = Client.CreateMessage();

View File

@ -6,19 +6,19 @@ using GTA.Native;
namespace RageCoop.Client namespace RageCoop.Client
{ {
public class PlayerList public static class PlayerList
{ {
private const float LEFT_POSITION = 0.122f; private const float LEFT_POSITION = 0.122f;
private const float RIGHT_POSITION = 0.9f; private const float RIGHT_POSITION = 0.9f;
private readonly Scaleform _mainScaleform = new Scaleform("mp_mm_card_freemode"); private static readonly Scaleform _mainScaleform = new Scaleform("mp_mm_card_freemode");
private ulong _lastUpdate = Util.GetTickCount64(); private static ulong _lastUpdate = Util.GetTickCount64();
public ulong Pressed { get; set; } public static ulong Pressed { get; set; }
public bool LeftAlign = true; public static bool LeftAlign = true;
public List<PlayerData> Players=new List<PlayerData> { }; public static List<PlayerData> Players=new List<PlayerData> { };
public void Tick() public static void Tick()
{ {
if (!Main.MainNetworking.IsOnServer()) if (!Networking.IsOnServer())
{ {
return; return;
} }
@ -41,12 +41,12 @@ namespace RageCoop.Client
} }
} }
private void Update( string localUsername) private static void Update( string localUsername)
{ {
_lastUpdate = Util.GetTickCount64(); _lastUpdate = Util.GetTickCount64();
_mainScaleform.CallFunction("SET_DATA_SLOT_EMPTY", 0); _mainScaleform.CallFunction("SET_DATA_SLOT_EMPTY", 0);
_mainScaleform.CallFunction("SET_DATA_SLOT", 0, $"{Main.MainNetworking.Latency * 1000:N0}ms", localUsername, 116, 0, 0, "", "", 2, "", "", ' '); _mainScaleform.CallFunction("SET_DATA_SLOT", 0, $"{Networking.Latency * 1000:N0}ms", localUsername, 116, 0, 0, "", "", 2, "", "", ' ');
int i = 1; int i = 1;
@ -58,7 +58,7 @@ namespace RageCoop.Client
_mainScaleform.CallFunction("SET_TITLE", "Player list", (Players.Count) + " players"); _mainScaleform.CallFunction("SET_TITLE", "Player list", (Players.Count) + " players");
_mainScaleform.CallFunction("DISPLAY_VIEW"); _mainScaleform.CallFunction("DISPLAY_VIEW");
} }
public void SetPlayer(int id, string username) public static void SetPlayer(int id, string username)
{ {
var toset = Players.Where(x => x.PedID==id); var toset = Players.Where(x => x.PedID==id);
@ -74,11 +74,11 @@ namespace RageCoop.Client
Players.Add(p); Players.Add(p);
} }
} }
public PlayerData GetPlayer(int id) public static PlayerData GetPlayer(int id)
{ {
return Players.Find(x => x.PedID==id); return Players.Find(x => x.PedID==id);
} }
public void RemovePlayer(int id) public static void RemovePlayer(int id)
{ {
var p = Players.Where(x => x.PedID==id); var p = Players.Where(x => x.PedID==id);
if (p.Any()) if (p.Any())
@ -86,6 +86,10 @@ namespace RageCoop.Client
Players.Remove(p.First()); Players.Remove(p.First());
} }
} }
public static void Cleanup()
{
Players=new List<PlayerData> { };
}
} }
} }

View File

@ -131,6 +131,7 @@
<Compile Include="Sync\Entities\SyncedPed.cs" /> <Compile Include="Sync\Entities\SyncedPed.cs" />
<None Include="app.config" /> <None Include="app.config" />
<None Include="packages.config" /> <None Include="packages.config" />
<Compile Include="Sync\Entities\SyncedProjectile.cs" />
<Compile Include="Sync\EntityPool.cs" /> <Compile Include="Sync\EntityPool.cs" />
<Compile Include="Sync\SyncEvents.cs" /> <Compile Include="Sync\SyncEvents.cs" />
<Compile Include="Sync\Entities\SyncedEntity.cs" /> <Compile Include="Sync\Entities\SyncedEntity.cs" />

View File

@ -8,7 +8,7 @@ using GTA.Math;
namespace RageCoop.Client namespace RageCoop.Client
{ {
public class SyncedEntity public abstract class SyncedEntity
{ {
/// <summary> /// <summary>
@ -18,7 +18,7 @@ namespace RageCoop.Client
{ {
get get
{ {
return OwnerID==Main.MyPlayerID; return OwnerID==Main.LocalPlayerID;
} }
} }
@ -31,6 +31,14 @@ namespace RageCoop.Client
return Main.Ticked-LastSynced>200; return Main.Ticked-LastSynced>200;
} }
} }
public bool IsReady
{
get {return !(LastSynced==0||LastStateSynced==0);}
}
public bool NeedUpdate
{
get { return LastSynced>LastUpdated; }
}
#region LAST STATE #region LAST STATE
/// <summary> /// <summary>
/// Last time a new sync message arrived. /// Last time a new sync message arrived.
@ -49,6 +57,7 @@ namespace RageCoop.Client
public Vector3 Position { get; set; } public Vector3 Position { get; set; }
public Vector3 Rotation { get; set; } public Vector3 Rotation { get; set; }
public Vector3 Velocity { get; set; } public Vector3 Velocity { get; set; }
public abstract void Update();
} }
} }

View File

@ -36,7 +36,7 @@ namespace RageCoop.Client
p.CanWrithe=false; p.CanWrithe=false;
p.IsOnlyDamagedByPlayer=false; p.IsOnlyDamagedByPlayer=false;
MainPed=p; MainPed=p;
OwnerID=Main.MyPlayerID; OwnerID=Main.LocalPlayerID;
} }
@ -87,60 +87,48 @@ namespace RageCoop.Client
public bool Update() public override void Update()
{ {
if (IsPlayer &&PedBlip!=null)
if (IsMine) {
// Main.Logger.Trace($"Skipping update for ped {ID}. Reason:WrongWay");
return false;
}
if (IsPlayer && (MainPed!=null))
{ {
if (Username=="N/A") if (Username=="N/A")
{ {
var p = Main.MainPlayerList.GetPlayer(ID); var p = PlayerList.GetPlayer(ID);
if (p!=null) if (p!=null)
{ {
Username=p.Username; Username=p.Username;
PedBlip.Name=Username; PedBlip.Name=Username;
Main.Logger.Debug($"Username updated:{Username}");
} }
} }
RenderNameTag(); RenderNameTag();
} }
// Check if all data avalible // Check if all data avalible
if ( LastSynced== 0) { if (!IsReady) { return; }
// Main.Logger.Trace($"Skipping update for ped {ID}. Reason:NotReady");
return false;
}
if(LastStateSynced==0) {
// Main.Logger.Trace($"Skipping update for ped {ID}. Reason:StateNotReady");
return false;
}
// Skip update if no new sync message has arrived. // Skip update if no new sync message has arrived.
if (LastUpdated>=LastSynced) { if (!NeedUpdate)
// Main.Logger.Trace($"Skipping update for ped {ID}. Reason:NoNewMessage"); {
return false; return;
} }
bool characterExist = MainPed != null && MainPed.Exists();
bool characterExist = (MainPed != null) && MainPed.Exists();
if (!characterExist) if (!characterExist)
{ {
CreateCharacter(); CreateCharacter();
return false; return;
} }
// Need to update state // Need to update state
if (LastStateSynced>=LastUpdated) if (LastStateSynced>=LastUpdated)
{ {
@ -148,7 +136,7 @@ namespace RageCoop.Client
if (MainPed!=null&& (ModelHash != MainPed.Model.Hash)) if (MainPed!=null&& (ModelHash != MainPed.Model.Hash))
{ {
CreateCharacter(); CreateCharacter();
return false; return;
} }
if (!Clothes.Compare(_lastClothes)) if (!Clothes.Compare(_lastClothes))
@ -183,7 +171,7 @@ namespace RageCoop.Client
MainPed.IsInvincible = false; MainPed.IsInvincible = false;
Main.Logger.Debug($"Killing ped {ID}. Reason:PedDied"); Main.Logger.Debug($"Killing ped {ID}. Reason:PedDied");
MainPed.Kill(); MainPed.Kill();
return false; return;
} }
} }
@ -196,8 +184,7 @@ namespace RageCoop.Client
DisplayOnFoot(); DisplayOnFoot();
} }
LastUpdated=Main.Ticked; LastUpdated=Main.Ticked;
// Main.Logger.Trace($"Character updated:{ID} LastUpdated:{LastUpdated}"); return;
return true;
} }
@ -715,7 +702,7 @@ namespace RageCoop.Client
{ {
MainPed.PositionNoOffset = Position; MainPed.PositionNoOffset = Position;
/* /*
float lerpValue = (int)((Latency * 1000 / 2) + (Main.MainNetworking.Latency * 1000 / 2)) * 2 / 50000f; float lerpValue = (int)((Latency * 1000 / 2) + (Networking.Latency * 1000 / 2)) * 2 / 50000f;
Vector2 biDimensionalPos = Vector2.Lerp(new Vector2(Character.Position.X, Character.Position.Y), new Vector2(Position.X + (Velocity.X / 5), Position.Y + (Velocity.Y / 5)), lerpValue); Vector2 biDimensionalPos = Vector2.Lerp(new Vector2(Character.Position.X, Character.Position.Y), new Vector2(Position.X + (Velocity.X / 5), Position.Y + (Velocity.Y / 5)), lerpValue);
float zPos = Util.Lerp(Character.Position.Z, Position.Z, 0.1f); float zPos = Util.Lerp(Character.Position.Z, Position.Z, 0.1f);

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GTA;
namespace RageCoop.Client.Sync.Entities
{
internal class SyncedProjectile:SyncedEntity
{
public bool Exploded { get; set; } = false;
public Projectile MainProjectile { get; set; }
public WeaponHash Hash { get; set; }
private WeaponAsset Asset;
public override void Update()
{
// Check if all data avalible
if (!IsReady) { return; }
// Skip update if no new sync message has arrived.
if (!NeedUpdate)
{
return;
}
if (Exploded)
{
if (Exploded)
{
if(MainProjectile != null && MainProjectile.Exists())
{
MainProjectile.Explode();
return;
}
}
}
else
{
if (MainProjectile != null && MainProjectile.Exists())
{
MainProjectile.Position=Position+Velocity*Networking.Latency;
MainProjectile.Velocity=Velocity;
}
else
{
CreateProjectile();
}
}
}
private void CreateProjectile()
{
throw new NotImplementedException();
}
}
}

View File

@ -33,7 +33,7 @@ namespace RageCoop.Client
} }
MainVehicle=v; MainVehicle=v;
MainVehicle.CanPretendOccupants=false; MainVehicle.CanPretendOccupants=false;
OwnerID=Main.MyPlayerID; OwnerID=Main.LocalPlayerID;
} }
@ -99,18 +99,16 @@ namespace RageCoop.Client
private long _lastPositionCalibrated { get; set; } private long _lastPositionCalibrated { get; set; }
#endregion #endregion
public void Update() public override void Update()
{ {
#region -- INITIAL CHECK -- #region -- INITIAL CHECK --
if (IsMine) { return; }
// Check if all data avalible // Check if all data avalible
if (LastStateSynced == 0) { return; } if(!IsReady) { return; }
if (LastSynced==0) { return; }
// Skip update if no new sync message has arrived. // Skip update if no new sync message has arrived.
if (LastUpdated>=LastSynced) { return; } if (!NeedUpdate) { return; }
#endregion #endregion
#region -- CHECK EXISTENCE -- #region -- CHECK EXISTENCE --
@ -124,10 +122,6 @@ namespace RageCoop.Client
#region -- SYNC CRITICAL -- #region -- SYNC CRITICAL --
if (SteeringAngle != MainVehicle.SteeringAngle) if (SteeringAngle != MainVehicle.SteeringAngle)
{ {
MainVehicle.CustomSteeringAngle((float)(Math.PI / 180) * SteeringAngle); MainVehicle.CustomSteeringAngle((float)(Math.PI / 180) * SteeringAngle);

View File

@ -30,8 +30,8 @@ namespace RageCoop.Client
{ {
foreach(int id in new List<int>(ID_Peds.Keys)) foreach(int id in new List<int>(ID_Peds.Keys))
{ {
if (keepPlayer&&(id==Main.MyPlayerID)) { continue; } if (keepPlayer&&(id==Main.LocalPlayerID)) { continue; }
if (keepMine&&(ID_Peds[id].OwnerID==Main.MyPlayerID)) { continue; } if (keepMine&&(ID_Peds[id].OwnerID==Main.LocalPlayerID)) { continue; }
RemovePed(id); RemovePed(id);
} }
ID_Peds.Clear(); ID_Peds.Clear();
@ -39,7 +39,7 @@ namespace RageCoop.Client
foreach (int id in new List<int>(ID_Vehicles.Keys)) foreach (int id in new List<int>(ID_Vehicles.Keys))
{ {
if (keepMine&&(ID_Vehicles[id].OwnerID==Main.MyPlayerID)) { continue; } if (keepMine&&(ID_Vehicles[id].OwnerID==Main.LocalPlayerID)) { continue; }
RemoveVehicle(id); RemoveVehicle(id);
} }
ID_Vehicles.Clear(); ID_Vehicles.Clear();
@ -60,7 +60,7 @@ namespace RageCoop.Client
public static bool AddPlayer() public static bool AddPlayer()
{ {
Ped p = Game.Player.Character; Ped p = Game.Player.Character;
SyncedPed player = GetPedByID(Main.MyPlayerID); SyncedPed player = GetPedByID(Main.LocalPlayerID);
if (player!=null) if (player!=null)
{ {
if (player.MainPed!=p) if (player.MainPed!=p)
@ -88,10 +88,10 @@ namespace RageCoop.Client
{ {
Main.Logger.Debug($"Creating SyncEntity for player, handle:{p.Handle}"); Main.Logger.Debug($"Creating SyncEntity for player, handle:{p.Handle}");
SyncedPed c = new SyncedPed(p); SyncedPed c = new SyncedPed(p);
Main.MyPlayerID=c.OwnerID=c.ID; Main.LocalPlayerID=c.OwnerID=c.ID;
Add(c); Add(c);
Main.Logger.Debug($"My player ID is:{c.ID}"); Main.Logger.Debug($"My player ID is:{c.ID}");
Main.MainPlayerList.SetPlayer(c.ID, Main.Settings.Username ); PlayerList.SetPlayer(c.ID, Main.Settings.Username );
return true; return true;
} }
return false; return false;
@ -243,11 +243,11 @@ namespace RageCoop.Client
if (Main.Ticked%20==0) if (Main.Ticked%20==0)
{ {
Main.MainNetworking.SendPedState(c); Networking.SendPedState(c);
} }
else else
{ {
Main.MainNetworking.SendPed(c); Networking.SendPed(c);
} }
} }
@ -300,12 +300,12 @@ namespace RageCoop.Client
{ {
if (Main.Ticked%20==0) if (Main.Ticked%20==0)
{ {
Main.MainNetworking.SendVehicleState(v); Networking.SendVehicleState(v);
} }
else else
{ {
Main.MainNetworking.SendVehicle(v); Networking.SendVehicle(v);
} }
} }

View File

@ -13,18 +13,14 @@ namespace RageCoop.Client {
internal static class SyncEvents internal static class SyncEvents
{ {
#region TRIGGER #region TRIGGER
/// <summary>
/// Informs other players that this ped has been killed.
/// </summary>
/// <param name="c"></param>
public static void TriggerPedKilled(SyncedPed victim) public static void TriggerPedKilled(SyncedPed victim)
{ {
Main.MainNetworking.Send(new Packets.PedKilled() { VictimID=victim.ID},ConnectionChannel.SyncEvents); Networking.Send(new Packets.PedKilled() { VictimID=victim.ID},ConnectionChannel.SyncEvents);
} }
public static void TriggerEnteringVehicle(SyncedPed c,SyncedVehicle veh, VehicleSeat seat) public static void TriggerEnteringVehicle(SyncedPed c,SyncedVehicle veh, VehicleSeat seat)
{ {
Main.MainNetworking. Networking.
Send(new Packets.EnteringVehicle() Send(new Packets.EnteringVehicle()
{ {
PedID=c.ID, PedID=c.ID,
@ -35,24 +31,24 @@ namespace RageCoop.Client {
public static void TriggerEnteredVehicle(SyncedPed c, SyncedVehicle veh, VehicleSeat seat) public static void TriggerEnteredVehicle(SyncedPed c, SyncedVehicle veh, VehicleSeat seat)
{ {
Main.MainNetworking.Send(new Packets.EnteredVehicle() if (seat==VehicleSeat.Driver)
{
TriggerChangeOwner(veh, c.ID);
veh.OwnerID=Main.LocalPlayerID;
veh.LastSynced=Main.Ticked;
}
Networking.Send(new Packets.EnteredVehicle()
{ {
VehicleSeat=(short)seat, VehicleSeat=(short)seat,
PedID=c.ID, PedID=c.ID,
VehicleID=veh.ID VehicleID=veh.ID
},ConnectionChannel.SyncEvents); },ConnectionChannel.SyncEvents);
if (seat==VehicleSeat.Driver)
{
TriggerChangeOwner(veh, c.ID);
veh.OwnerID=Main.MyPlayerID;
veh.LastSynced=Main.Ticked;
}
} }
public static void TriggerChangeOwner(SyncedVehicle c, int newOwnerID) public static void TriggerChangeOwner(SyncedVehicle c, int newOwnerID)
{ {
Main.MainNetworking.Send(new Packets.OwnerChanged() Networking.Send(new Packets.OwnerChanged()
{ {
ID= c.ID, ID= c.ID,
NewOwnerID= newOwnerID, NewOwnerID= newOwnerID,
@ -77,11 +73,11 @@ namespace RageCoop.Client {
// Reduce latency // Reduce latency
start=impactPosition-(impactPosition-start).Normalized*10; start=impactPosition-(impactPosition-start).Normalized*10;
} }
Main.MainNetworking.SendBulletShot(start, impactPosition, hash, owner.ID); Networking.SendBulletShot(start, impactPosition, hash, owner.ID);
} }
public static void TriggerLeaveVehicle(int id) public static void TriggerLeaveVehicle(int id)
{ {
Main.MainNetworking. Networking.
Send(new Packets.LeaveVehicle() Send(new Packets.LeaveVehicle()
{ {
ID=id ID=id
@ -101,7 +97,7 @@ namespace RageCoop.Client {
var start = p.Position; var start = p.Position;
var end = start+p.Velocity; var end = start+p.Velocity;
Main.MainNetworking.SendBulletShot(start, end, (uint)p.WeaponHash, pp.GetSyncEntity().ID); Networking.SendBulletShot(start, end, (uint)p.WeaponHash, pp.GetSyncEntity().ID);
} }
} }
#endregion #endregion
@ -136,7 +132,11 @@ namespace RageCoop.Client {
var v = EntityPool.GetVehicleByID(p.ID); var v = EntityPool.GetVehicleByID(p.ID);
if (v==null) { return; } if (v==null) { return; }
v.OwnerID=p.NewOwnerID; v.OwnerID=p.NewOwnerID;
v.ModelHash=v.MainVehicle.Model;
// So this vehicle doesn's get re-spawned
} }
private static ParticleEffectAsset CorePFXAsset = default; private static ParticleEffectAsset CorePFXAsset = default;
static WeaponAsset _weaponAsset = default; static WeaponAsset _weaponAsset = default;