diff --git a/Directory.Build.props b/Directory.Build.props
index 4ec01a6dd..534d72ae5 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -1,61 +1,61 @@
-
- $(MSBuildThisFileDirectory)DevEnv.targets
-
-
-
-
-
-
- C:\Program Files (x86)\Steam\steamapps\common\Dyson Sphere Program\
- $([MSBuild]::EnsureTrailingSlash('$(DSPGameDir)'))
- $(DSPGameDir)BepInEx\plugins\nebula-NebulaMultiplayerMod\
- $([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)'))
- $(PropSheetPath)dist\release\nebula-NebulaMultiplayerMod\
-
-
-
- false
- false
- true
-
- $(PluginOutputDirectory)
- net472
- latest
- true
- true
- $(DefaultItemExcludes);*.binlog
-
- portable
- true
- $(MSBuildThisFileDirectory)
-
-
-
- $(OutputPath)..\nebula-NebulaMultiplayerModApi
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+ $(MSBuildThisFileDirectory)DevEnv.targets
+
+
+
+
+
+
+ C:\Program Files (x86)\Steam\steamapps\common\Dyson Sphere Program\
+ $([MSBuild]::EnsureTrailingSlash('$(DSPGameDir)'))
+ $(DSPGameDir)BepInEx\plugins\nebula-NebulaMultiplayerMod\
+ $([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)'))
+ $(PropSheetPath)dist\release\nebula-NebulaMultiplayerMod\
+
+
+
+ false
+ false
+ true
+
+ $(PluginOutputDirectory)
+ net472
+ latest
+ true
+ true
+ $(DefaultItemExcludes);*.binlog
+
+ portable
+ true
+ $(MSBuildThisFileDirectory)
+
+
+
+ $(OutputPath)..\nebula-NebulaMultiplayerModApi
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Directory.Build.targets b/Directory.Build.targets
index 1c8bb4c28..048dc696a 100644
--- a/Directory.Build.targets
+++ b/Directory.Build.targets
@@ -1,4 +1,4 @@
-
+
\ No newline at end of file
diff --git a/NebulaAPI/CHANGELOG.md b/NebulaAPI/CHANGELOG.md
index c6fb49364..3da32250e 100644
--- a/NebulaAPI/CHANGELOG.md
+++ b/NebulaAPI/CHANGELOG.md
@@ -35,7 +35,8 @@
1.1.0:
-- Float3 IPlayerData.MechaColor has been changed to Float4[] IPlayerData.MechaColors in line with changes introduced in DSP version 0.8.21.8562.
+- Float3 IPlayerData.MechaColor has been changed to Float4[] IPlayerData.MechaColors in line with changes introduced in
+ DSP version 0.8.21.8562.
- Edited description.
1.0.0:
diff --git a/NebulaAPI/DataStructures/CollectionExtensions.cs b/NebulaAPI/DataStructures/CollectionExtensions.cs
index 43fefafdd..31573ed59 100644
--- a/NebulaAPI/DataStructures/CollectionExtensions.cs
+++ b/NebulaAPI/DataStructures/CollectionExtensions.cs
@@ -1,37 +1,40 @@
-using System;
+#region
+
+using System;
using System.Collections;
using System.Threading;
-namespace NebulaAPI
+#endregion
+
+namespace NebulaAPI;
+
+public static class CollectionExtensions
{
- public static class CollectionExtensions
+ public static Locker Lock(this ICollection collection)
{
- public static Locker Lock(this ICollection collection)
- {
- return new Locker(collection.SyncRoot);
- }
-
- public static Locker GetLocked(this T collection, out T result) where T : ICollection
- {
- result = collection;
- return new Locker(collection.SyncRoot);
- }
+ return new Locker(collection.SyncRoot);
}
- public readonly struct Locker : IDisposable
+ public static Locker GetLocked(this T collection, out T result) where T : ICollection
{
- private readonly object lockObject;
+ result = collection;
+ return new Locker(collection.SyncRoot);
+ }
+}
- public Locker(object lockObject)
- {
- this.lockObject = lockObject;
+public readonly struct Locker : IDisposable
+{
+ private readonly object lockObject;
- Monitor.Enter(lockObject);
- }
+ public Locker(object lockObject)
+ {
+ this.lockObject = lockObject;
- public void Dispose()
- {
- Monitor.Exit(lockObject);
- }
+ Monitor.Enter(lockObject);
+ }
+
+ public void Dispose()
+ {
+ Monitor.Exit(lockObject);
}
}
diff --git a/NebulaAPI/DataStructures/DataStructureExtenstions.cs b/NebulaAPI/DataStructures/DataStructureExtenstions.cs
index 9d8d5c7e1..6595b58e5 100644
--- a/NebulaAPI/DataStructures/DataStructureExtenstions.cs
+++ b/NebulaAPI/DataStructures/DataStructureExtenstions.cs
@@ -1,32 +1,35 @@
-using UnityEngine;
+#region
-namespace NebulaAPI
+using UnityEngine;
+
+#endregion
+
+namespace NebulaAPI;
+
+public static class DataStructureExtenstions
{
- public static class DataStructureExtenstions
+ public static Vector3 ToVector3(this Float3 value)
+ {
+ return new Vector3(value.x, value.y, value.z);
+ }
+
+ public static VectorLF3 ToVectorLF3(this Double3 value)
+ {
+ return new VectorLF3(value.x, value.y, value.z);
+ }
+
+ public static Float3 ToFloat3(this Vector3 value)
+ {
+ return new Float3(value.x, value.y, value.z);
+ }
+
+ public static Quaternion ToQuaternion(this Float4 value)
+ {
+ return new Quaternion(value.x, value.y, value.z, value.w);
+ }
+
+ public static Float4 ToFloat4(this Quaternion value)
{
- public static Vector3 ToVector3(this Float3 value)
- {
- return new Vector3(value.x, value.y, value.z);
- }
-
- public static VectorLF3 ToVectorLF3(this Double3 value)
- {
- return new VectorLF3(value.x, value.y, value.z);
- }
-
- public static Float3 ToFloat3(this Vector3 value)
- {
- return new Float3(value.x, value.y, value.z);
- }
-
- public static Quaternion ToQuaternion(this Float4 value)
- {
- return new Quaternion(value.x, value.y, value.z, value.w);
- }
-
- public static Float4 ToFloat4(this Quaternion value)
- {
- return new Float4(value.x, value.y, value.z, value.w);
- }
+ return new Float4(value.x, value.y, value.z, value.w);
}
-}
\ No newline at end of file
+}
diff --git a/NebulaAPI/DataStructures/Double3.cs b/NebulaAPI/DataStructures/Double3.cs
index 7706ece86..f7d3ad31c 100644
--- a/NebulaAPI/DataStructures/Double3.cs
+++ b/NebulaAPI/DataStructures/Double3.cs
@@ -1,38 +1,36 @@
-
-namespace NebulaAPI
+namespace NebulaAPI;
+
+[RegisterNestedType]
+public struct Double3 : INetSerializable
{
- [RegisterNestedType]
- public struct Double3 : INetSerializable
- {
- public double x;
- public double y;
- public double z;
+ public double x;
+ public double y;
+ public double z;
- public Double3(double x, double y, double z)
- {
- this.x = x;
- this.y = y;
- this.z = z;
- }
+ public Double3(double x, double y, double z)
+ {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ }
- public void Serialize(INetDataWriter writer)
- {
- writer.Put(x);
- writer.Put(y);
- writer.Put(z);
- }
+ public void Serialize(INetDataWriter writer)
+ {
+ writer.Put(x);
+ writer.Put(y);
+ writer.Put(z);
+ }
- public void Deserialize(INetDataReader reader)
- {
- x = reader.GetDouble();
- y = reader.GetDouble();
- z = reader.GetDouble();
- }
+ public void Deserialize(INetDataReader reader)
+ {
+ x = reader.GetDouble();
+ y = reader.GetDouble();
+ z = reader.GetDouble();
+ }
- public override string ToString()
- {
- return $"x: {x}, y: {y}, z: {z}";
- }
+ public override string ToString()
+ {
+ return $"x: {x}, y: {y}, z: {z}";
}
}
diff --git a/NebulaAPI/DataStructures/Float3.cs b/NebulaAPI/DataStructures/Float3.cs
index 6a3abb723..ec4bd2641 100644
--- a/NebulaAPI/DataStructures/Float3.cs
+++ b/NebulaAPI/DataStructures/Float3.cs
@@ -1,49 +1,53 @@
-using UnityEngine;
+#region
-namespace NebulaAPI
+using UnityEngine;
+
+#endregion
+
+namespace NebulaAPI;
+
+[RegisterNestedType]
+public struct Float3 : INetSerializable
{
- [RegisterNestedType]
- public struct Float3 : INetSerializable
+ public float x;
+ public float y;
+ public float z;
+
+ public Float3(float x, float y, float z)
+ {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ }
+
+ public Float3(Vector3 value)
+ {
+ x = value.x;
+ y = value.y;
+ z = value.z;
+ }
+
+ public Color ToColor()
+ {
+ return new Color(x, y, z);
+ }
+
+ public void Serialize(INetDataWriter writer)
+ {
+ writer.Put(x);
+ writer.Put(y);
+ writer.Put(z);
+ }
+
+ public void Deserialize(INetDataReader reader)
+ {
+ x = reader.GetFloat();
+ y = reader.GetFloat();
+ z = reader.GetFloat();
+ }
+
+ public override string ToString()
{
- public float x;
- public float y;
- public float z;
-
- public Float3(float x, float y, float z)
- {
- this.x = x;
- this.y = y;
- this.z = z;
- }
-
- public Float3(Vector3 value)
- {
- x = value.x;
- y = value.y;
- z = value.z;
- }
- public Color ToColor()
- {
- return new Color(x, y, z);
- }
-
- public void Serialize(INetDataWriter writer)
- {
- writer.Put(x);
- writer.Put(y);
- writer.Put(z);
- }
-
- public void Deserialize(INetDataReader reader)
- {
- x = reader.GetFloat();
- y = reader.GetFloat();
- z = reader.GetFloat();
- }
-
- public override string ToString()
- {
- return $"(x: {x}, y: {y}, z: {z})";
- }
+ return $"(x: {x}, y: {y}, z: {z})";
}
}
diff --git a/NebulaAPI/DataStructures/Float4.cs b/NebulaAPI/DataStructures/Float4.cs
index 8f9d865b2..cff43bc2b 100644
--- a/NebulaAPI/DataStructures/Float4.cs
+++ b/NebulaAPI/DataStructures/Float4.cs
@@ -1,85 +1,89 @@
-using UnityEngine;
+#region
-namespace NebulaAPI
+using UnityEngine;
+
+#endregion
+
+namespace NebulaAPI;
+
+[RegisterNestedType]
+public struct Float4 : INetSerializable
{
- [RegisterNestedType]
- public struct Float4 : INetSerializable
+ public float x;
+ public float y;
+ public float z;
+ public float w;
+
+ public Float4(float x, float y, float z, float w)
{
- public float x;
- public float y;
- public float z;
- public float w;
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ this.w = w;
+ }
- public Float4(float x, float y, float z, float w)
- {
- this.x = x;
- this.y = y;
- this.z = z;
- this.w = w;
- }
+ public Float4(Quaternion value)
+ {
+ x = value.x;
+ y = value.y;
+ z = value.z;
+ w = value.w;
+ }
- public Float4(Quaternion value)
- {
- x = value.x;
- y = value.y;
- z = value.z;
- w = value.w;
- }
+ public Color ToColor()
+ {
+ return new Color(x, y, z, w);
+ }
- public Color ToColor()
- {
- return new Color(x, y, z, w);
- }
+ public Color32 ToColor32()
+ {
+ return new Color32((byte)x, (byte)y, (byte)z, (byte)w);
+ }
- public Color32 ToColor32()
+ public static Color32[] ToColor32(Float4[] float4s)
+ {
+ var color32s = new Color32[float4s.Length];
+ for (var i = 0; i < float4s.Length; i++)
{
- return new Color32((byte)x, (byte)y, (byte)z, (byte)w);
+ color32s[i] = float4s[i].ToColor32();
}
+ return color32s;
+ }
- public static Color32[] ToColor32(Float4[] float4s)
- {
- Color32[] color32s = new Color32[float4s.Length];
- for (int i = 0; i < float4s.Length; i++)
- {
- color32s[i] = float4s[i].ToColor32();
- }
- return color32s;
- }
- public static Float4 ToFloat4(Color32 color32)
- {
- return new Float4(color32.r, color32.g, color32.b, color32.a);
- }
+ public static Float4 ToFloat4(Color32 color32)
+ {
+ return new Float4(color32.r, color32.g, color32.b, color32.a);
+ }
- public static Float4[] ToFloat4(Color32[] color32s)
+ public static Float4[] ToFloat4(Color32[] color32s)
+ {
+ var float4s = new Float4[color32s.Length];
+ for (var i = 0; i < color32s.Length; i++)
{
- Float4[] float4s = new Float4[color32s.Length];
- for (int i = 0; i < color32s.Length; i++)
- {
- float4s[i] = new Float4(color32s[i].r, color32s[i].g, color32s[i].b, color32s[i].a);
- }
- return float4s;
+ float4s[i] = new Float4(color32s[i].r, color32s[i].g, color32s[i].b, color32s[i].a);
}
+ return float4s;
+ }
- public void Serialize(INetDataWriter writer)
- {
- writer.Put(x);
- writer.Put(y);
- writer.Put(z);
- writer.Put(w);
- }
+ public void Serialize(INetDataWriter writer)
+ {
+ writer.Put(x);
+ writer.Put(y);
+ writer.Put(z);
+ writer.Put(w);
+ }
- public void Deserialize(INetDataReader reader)
- {
- x = reader.GetFloat();
- y = reader.GetFloat();
- z = reader.GetFloat();
- w = reader.GetFloat();
- }
+ public void Deserialize(INetDataReader reader)
+ {
+ x = reader.GetFloat();
+ y = reader.GetFloat();
+ z = reader.GetFloat();
+ w = reader.GetFloat();
+ }
- public override string ToString()
- {
- return $"x: {x}, y: {y}, z: {z}, w: {w}";
- }
+ public override string ToString()
+ {
+ return $"x: {x}, y: {y}, z: {z}, w: {w}";
}
}
diff --git a/NebulaAPI/DataStructures/IMechaData.cs b/NebulaAPI/DataStructures/IMechaData.cs
index aedf07cf1..09bfff0e2 100644
--- a/NebulaAPI/DataStructures/IMechaData.cs
+++ b/NebulaAPI/DataStructures/IMechaData.cs
@@ -1,16 +1,13 @@
-// unset
+namespace NebulaAPI;
-namespace NebulaAPI
+public interface IMechaData : INetSerializable
{
- public interface IMechaData : INetSerializable
- {
- int SandCount { get; set; }
- double CoreEnergy { get; set; }
- double ReactorEnergy { get; set; }
- StorageComponent Inventory { get; set; }
- DeliveryPackage DeliveryPackage { get; set; }
- StorageComponent ReactorStorage { get; set; }
- StorageComponent WarpStorage { get; set; }
- MechaForge Forge { get; set; }
- }
-}
\ No newline at end of file
+ int SandCount { get; set; }
+ double CoreEnergy { get; set; }
+ double ReactorEnergy { get; set; }
+ StorageComponent Inventory { get; set; }
+ DeliveryPackage DeliveryPackage { get; set; }
+ StorageComponent ReactorStorage { get; set; }
+ StorageComponent WarpStorage { get; set; }
+ MechaForge Forge { get; set; }
+}
diff --git a/NebulaAPI/DataStructures/IPlayerTechBonuses.cs b/NebulaAPI/DataStructures/IPlayerTechBonuses.cs
index 1fdae9053..591b66c20 100644
--- a/NebulaAPI/DataStructures/IPlayerTechBonuses.cs
+++ b/NebulaAPI/DataStructures/IPlayerTechBonuses.cs
@@ -1,37 +1,34 @@
-// unset
+namespace NebulaAPI;
-namespace NebulaAPI
+public interface IPlayerTechBonuses : INetSerializable
{
- public interface IPlayerTechBonuses : INetSerializable
- {
- double coreEnergyCap { get; }
- double corePowerGen { get; }
- double reactorPowerGen { get; }
- double walkPower { get; }
- double jumpEnergy { get; }
- double thrustPowerPerAcc { get; }
- double warpKeepingPowerPerSpeed { get; }
- double warpStartPowerPerSpeed { get; }
- double miningPower { get; }
- double replicatePower { get; }
- double researchPower { get; }
- double droneEjectEnergy { get; }
- double droneEnergyPerMeter { get; }
- int coreLevel { get; }
- int thrusterLevel { get; }
- float miningSpeed { get; }
- float replicateSpeed { get; }
- float walkSpeed { get; }
- float jumpSpeed { get; }
- float maxSailSpeed { get; }
- float maxWarpSpeed { get; }
- float buildArea { get; }
- int droneCount { get; }
- float droneSpeed { get; }
- int droneMovement { get; }
- int inventorySize { get; }
- bool deliveryPackageUnlocked { get; }
- int deliveryPackageColCount { get; set; }
- int deliveryPackageStackSizeMultiplier { get; }
- }
-}
\ No newline at end of file
+ double coreEnergyCap { get; }
+ double corePowerGen { get; }
+ double reactorPowerGen { get; }
+ double walkPower { get; }
+ double jumpEnergy { get; }
+ double thrustPowerPerAcc { get; }
+ double warpKeepingPowerPerSpeed { get; }
+ double warpStartPowerPerSpeed { get; }
+ double miningPower { get; }
+ double replicatePower { get; }
+ double researchPower { get; }
+ double droneEjectEnergy { get; }
+ double droneEnergyPerMeter { get; }
+ int coreLevel { get; }
+ int thrusterLevel { get; }
+ float miningSpeed { get; }
+ float replicateSpeed { get; }
+ float walkSpeed { get; }
+ float jumpSpeed { get; }
+ float maxSailSpeed { get; }
+ float maxWarpSpeed { get; }
+ float buildArea { get; }
+ int droneCount { get; }
+ float droneSpeed { get; }
+ int droneMovement { get; }
+ int inventorySize { get; }
+ bool deliveryPackageUnlocked { get; }
+ int deliveryPackageColCount { get; set; }
+ int deliveryPackageStackSizeMultiplier { get; }
+}
diff --git a/NebulaAPI/GameState/IFactoryManager.cs b/NebulaAPI/GameState/IFactoryManager.cs
index a977cf22b..dd529cd0f 100644
--- a/NebulaAPI/GameState/IFactoryManager.cs
+++ b/NebulaAPI/GameState/IFactoryManager.cs
@@ -1,47 +1,50 @@
-using System;
+#region
+
+using System;
using UnityEngine;
-namespace NebulaAPI
+#endregion
+
+namespace NebulaAPI;
+
+///
+/// Represents data about factory
+///
+public interface IFactoryManager : IDisposable
{
///
- /// Represents data about factory
+ /// Did we receive a packet?
///
- public interface IFactoryManager : IDisposable
- {
- ///
- /// Did we receive a packet?
- ///
- IToggle IsIncomingRequest { get; }
+ IToggle IsIncomingRequest { get; }
- int PacketAuthor { get; set; }
+ int PacketAuthor { get; set; }
- int TargetPlanet { get; set; }
+ int TargetPlanet { get; set; }
- PlanetFactory EventFactory { get; set; }
+ PlanetFactory EventFactory { get; set; }
- ///
- /// Request to load planet
- ///
- void AddPlanetTimer(int planetId);
+ ///
+ /// Request to load planet
+ ///
+ void AddPlanetTimer(int planetId);
- void LoadPlanetData(int planetId);
+ void LoadPlanetData(int planetId);
- void UnloadPlanetData(int planetId);
+ void UnloadPlanetData(int planetId);
- void InitializePrebuildRequests();
+ void InitializePrebuildRequests();
- void SetPrebuildRequest(int planetId, int prebuildId, ushort playerId);
+ void SetPrebuildRequest(int planetId, int prebuildId, ushort playerId);
- bool RemovePrebuildRequest(int planetId, int prebuildId);
+ bool RemovePrebuildRequest(int planetId, int prebuildId);
- bool ContainsPrebuildRequest(int planetId, int prebuildId);
+ bool ContainsPrebuildRequest(int planetId, int prebuildId);
- int GetNextPrebuildId(int planetId);
+ int GetNextPrebuildId(int planetId);
- int GetNextPrebuildId(PlanetFactory factory);
+ int GetNextPrebuildId(PlanetFactory factory);
- void OnNewSetInserterPickTarget(int objId, int otherObjId, int inserterId, int offset, Vector3 pointPos);
+ void OnNewSetInserterPickTarget(int objId, int otherObjId, int inserterId, int offset, Vector3 pointPos);
- void OnNewSetInserterInsertTarget(int objId, int otherObjId, int inserterId, int offset, Vector3 pointPos);
- }
-}
\ No newline at end of file
+ void OnNewSetInserterInsertTarget(int objId, int otherObjId, int inserterId, int offset, Vector3 pointPos);
+}
diff --git a/NebulaAPI/GameState/ILocalPlayer.cs b/NebulaAPI/GameState/ILocalPlayer.cs
index 008d98459..9d283740d 100644
--- a/NebulaAPI/GameState/ILocalPlayer.cs
+++ b/NebulaAPI/GameState/ILocalPlayer.cs
@@ -1,17 +1,20 @@
-using System;
+#region
-namespace NebulaAPI
+using System;
+
+#endregion
+
+namespace NebulaAPI;
+
+///
+/// Represents local player. Allows to send packets.
+///
+public interface ILocalPlayer : IDisposable
{
- ///
- /// Represents local player. Allows to send packets.
- ///
- public interface ILocalPlayer : IDisposable
- {
- bool IsInitialDataReceived { get; }
- bool IsHost { get; }
- bool IsClient { get; }
- bool IsNewPlayer { get; }
- ushort Id { get; }
- IPlayerData Data { get; }
- }
-}
\ No newline at end of file
+ bool IsInitialDataReceived { get; }
+ bool IsHost { get; }
+ bool IsClient { get; }
+ bool IsNewPlayer { get; }
+ ushort Id { get; }
+ IPlayerData Data { get; }
+}
diff --git a/NebulaAPI/GameState/IMultiplayerSession.cs b/NebulaAPI/GameState/IMultiplayerSession.cs
index b66a55784..99c7703be 100644
--- a/NebulaAPI/GameState/IMultiplayerSession.cs
+++ b/NebulaAPI/GameState/IMultiplayerSession.cs
@@ -1,11 +1,10 @@
-namespace NebulaAPI
+namespace NebulaAPI;
+
+public interface IMultiplayerSession
{
- public interface IMultiplayerSession
- {
- INetworkProvider Network { get; }
- ILocalPlayer LocalPlayer { get; }
- IFactoryManager Factories { get; }
+ INetworkProvider Network { get; }
+ ILocalPlayer LocalPlayer { get; }
+ IFactoryManager Factories { get; }
- bool IsGameLoaded { get; }
- }
-}
\ No newline at end of file
+ bool IsGameLoaded { get; }
+}
diff --git a/NebulaAPI/GameState/INebulaPlayer.cs b/NebulaAPI/GameState/INebulaPlayer.cs
index d7d89a25d..ac182c526 100644
--- a/NebulaAPI/GameState/INebulaPlayer.cs
+++ b/NebulaAPI/GameState/INebulaPlayer.cs
@@ -1,12 +1,12 @@
-namespace NebulaAPI
+namespace NebulaAPI;
+
+public interface INebulaPlayer
{
- public interface INebulaPlayer
- {
- INebulaConnection Connection { get; }
- IPlayerData Data { get; }
- ushort Id { get; }
+ INebulaConnection Connection { get; }
+ IPlayerData Data { get; }
+ ushort Id { get; }
+
+ void SendPacket(T packet) where T : class, new();
- void SendPacket(T packet) where T : class, new();
- void LoadUserData(IPlayerData data);
- }
-}
\ No newline at end of file
+ void LoadUserData(IPlayerData data);
+}
diff --git a/NebulaAPI/GameState/INetworkProvider.cs b/NebulaAPI/GameState/INetworkProvider.cs
index 8ef1071dc..f3ffff5f2 100644
--- a/NebulaAPI/GameState/INetworkProvider.cs
+++ b/NebulaAPI/GameState/INetworkProvider.cs
@@ -1,42 +1,49 @@
-using System;
+#region
-namespace NebulaAPI
+using System;
+
+#endregion
+
+namespace NebulaAPI;
+
+public interface INetworkProvider : IDisposable
{
- public interface INetworkProvider : IDisposable
- {
- ///
- /// Send packet to Host (If ran on Client) or all Clients (If ran on Host)
- ///
- void SendPacket(T packet) where T : class, new();
- ///
- /// Broadcast packet to all Players within current star system
- ///
- void SendPacketToLocalStar(T packet) where T : class, new();
- ///
- /// Broadcast packet to all Players within current planet
- ///
- void SendPacketToLocalPlanet(T packet) where T : class, new();
-
- ///
- /// Send packet to all Clients on a planet
- ///
- void SendPacketToPlanet(T packet, int planetId) where T : class, new();
- ///
- /// Send packet to all Clients within star system
- ///
- void SendPacketToStar(T packet, int starId) where T : class, new();
-
- ///
- /// Send packet to all Clients except the excluded client
- ///
- void SendPacketExclude(T packet, INebulaConnection exclude) where T : class, new();
- ///
- /// Send packet to all Clients within star system except the excluded client
- ///
- void SendPacketToStarExclude(T packet, int starId, INebulaConnection exclude) where T : class, new();
-
- IPlayerManager PlayerManager { get; }
-
- void Update();
- }
-}
\ No newline at end of file
+ IPlayerManager PlayerManager { get; }
+
+ ///
+ /// Send packet to Host (If ran on Client) or all Clients (If ran on Host)
+ ///
+ void SendPacket(T packet) where T : class, new();
+
+ ///
+ /// Broadcast packet to all Players within current star system
+ ///
+ void SendPacketToLocalStar(T packet) where T : class, new();
+
+ ///
+ /// Broadcast packet to all Players within current planet
+ ///
+ void SendPacketToLocalPlanet(T packet) where T : class, new();
+
+ ///
+ /// Send packet to all Clients on a planet
+ ///
+ void SendPacketToPlanet(T packet, int planetId) where T : class, new();
+
+ ///
+ /// Send packet to all Clients within star system
+ ///
+ void SendPacketToStar(T packet, int starId) where T : class, new();
+
+ ///
+ /// Send packet to all Clients except the excluded client
+ ///
+ void SendPacketExclude(T packet, INebulaConnection exclude) where T : class, new();
+
+ ///
+ /// Send packet to all Clients within star system except the excluded client
+ ///
+ void SendPacketToStarExclude(T packet, int starId, INebulaConnection exclude) where T : class, new();
+
+ void Update();
+}
diff --git a/NebulaAPI/GameState/IPlayerData.cs b/NebulaAPI/GameState/IPlayerData.cs
index 8b81b5186..61390e330 100644
--- a/NebulaAPI/GameState/IPlayerData.cs
+++ b/NebulaAPI/GameState/IPlayerData.cs
@@ -1,22 +1,21 @@
-namespace NebulaAPI
+namespace NebulaAPI;
+
+public interface IPlayerData : INetSerializable
{
- public interface IPlayerData : INetSerializable
- {
- string Username { get; set; }
- ushort PlayerId { get; set; }
- int LocalPlanetId { get; set; }
- Float3 LocalPlanetPosition { get; set; }
- Double3 UPosition { get; set; }
- Float3 Rotation { get; set; }
- Float3 BodyRotation { get; set; }
- int LocalStarId { get; set; }
+ string Username { get; set; }
+ ushort PlayerId { get; set; }
+ int LocalPlanetId { get; set; }
+ Float3 LocalPlanetPosition { get; set; }
+ Double3 UPosition { get; set; }
+ Float3 Rotation { get; set; }
+ Float3 BodyRotation { get; set; }
+ int LocalStarId { get; set; }
- IMechaData Mecha { get; set; }
- MechaAppearance Appearance { get; set; }
- MechaAppearance DIYAppearance { get; set; }
- int[] DIYItemId { get; set; }
- int[] DIYItemValue { get; set; }
+ IMechaData Mecha { get; set; }
+ MechaAppearance Appearance { get; set; }
+ MechaAppearance DIYAppearance { get; set; }
+ int[] DIYItemId { get; set; }
+ int[] DIYItemValue { get; set; }
- IPlayerData CreateCopyWithoutMechaData();
- }
-}
\ No newline at end of file
+ IPlayerData CreateCopyWithoutMechaData();
+}
diff --git a/NebulaAPI/GameState/IPlayerManager.cs b/NebulaAPI/GameState/IPlayerManager.cs
index 4f51f1f03..14ba089ed 100644
--- a/NebulaAPI/GameState/IPlayerManager.cs
+++ b/NebulaAPI/GameState/IPlayerManager.cs
@@ -1,55 +1,58 @@
-using System.Collections.Generic;
+#region
-namespace NebulaAPI
+using System.Collections.Generic;
+
+#endregion
+
+namespace NebulaAPI;
+
+public interface IPlayerManager
{
- public interface IPlayerManager
- {
- Locker GetPendingPlayers(out Dictionary pendingPlayers);
+ Locker GetPendingPlayers(out Dictionary pendingPlayers);
- Locker GetSyncingPlayers(out Dictionary syncingPlayers);
+ Locker GetSyncingPlayers(out Dictionary syncingPlayers);
- Locker GetConnectedPlayers(out Dictionary connectedPlayers);
+ Locker GetConnectedPlayers(out Dictionary connectedPlayers);
- Locker GetSavedPlayerData(out Dictionary savedPlayerData);
+ Locker GetSavedPlayerData(out Dictionary savedPlayerData);
- IPlayerData[] GetAllPlayerDataIncludingHost();
+ IPlayerData[] GetAllPlayerDataIncludingHost();
- INebulaPlayer GetPlayer(INebulaConnection conn);
+ INebulaPlayer GetPlayer(INebulaConnection conn);
- INebulaPlayer GetSyncingPlayer(INebulaConnection conn);
+ INebulaPlayer GetSyncingPlayer(INebulaConnection conn);
- INebulaPlayer GetPlayerById(ushort playerId);
+ INebulaPlayer GetPlayerById(ushort playerId);
- INebulaPlayer GetConnectedPlayerByUsername(string username);
+ INebulaPlayer GetConnectedPlayerByUsername(string username);
- void SendPacketToAllPlayers(T packet) where T : class, new();
+ void SendPacketToAllPlayers(T packet) where T : class, new();
- void SendPacketToLocalStar(T packet) where T : class, new();
+ void SendPacketToLocalStar(T packet) where T : class, new();
- void SendPacketToLocalPlanet(T packet) where T : class, new();
+ void SendPacketToLocalPlanet(T packet) where T : class, new();
- void SendPacketToPlanet(T packet, int planetId) where T : class, new();
+ void SendPacketToPlanet(T packet, int planetId) where T : class, new();
- void SendPacketToStar(T packet, int starId) where T : class, new();
+ void SendPacketToStar(T packet, int starId) where T : class, new();
- void SendPacketToStarExcept(T packet, int starId, INebulaConnection exclude) where T : class, new();
+ void SendPacketToStarExcept(T packet, int starId, INebulaConnection exclude) where T : class, new();
- void SendRawPacketToStar(byte[] rawPacket, int starId, INebulaConnection sender);
+ void SendRawPacketToStar(byte[] rawPacket, int starId, INebulaConnection sender);
- void SendRawPacketToPlanet(byte[] rawPacket, int planetId, INebulaConnection sender);
+ void SendRawPacketToPlanet(byte[] rawPacket, int planetId, INebulaConnection sender);
- void SendPacketToOtherPlayers(T packet, INebulaConnection exclude) where T : class, new();
+ void SendPacketToOtherPlayers(T packet, INebulaConnection exclude) where T : class, new();
- void SendPacketToOtherPlayers(T packet, INebulaPlayer sender) where T : class, new();
+ void SendPacketToOtherPlayers(T packet, INebulaPlayer sender) where T : class, new();
- INebulaPlayer PlayerConnected(INebulaConnection conn);
+ INebulaPlayer PlayerConnected(INebulaConnection conn);
- void PlayerDisconnected(INebulaConnection conn);
+ void PlayerDisconnected(INebulaConnection conn);
- ushort GetNextAvailablePlayerId();
+ ushort GetNextAvailablePlayerId();
- void UpdateMechaData(IMechaData mechaData, INebulaConnection conn);
+ void UpdateMechaData(IMechaData mechaData, INebulaConnection conn);
- void UpdateSyncedSandCount(int deltaSandCount);
- }
+ void UpdateSyncedSandCount(int deltaSandCount);
}
diff --git a/NebulaAPI/GlobalSuppressions.cs b/NebulaAPI/GlobalSuppressions.cs
index ef5300a0b..b754e58db 100644
--- a/NebulaAPI/GlobalSuppressions.cs
+++ b/NebulaAPI/GlobalSuppressions.cs
@@ -1,8 +1,9 @@
-// This file is used by Code Analysis to maintain SuppressMessage
-// attributes that are applied to this project.
-// Project-level suppressions either have no target or are given
-// a specific target and scoped to a namespace, type, member, etc.
+#region
using System.Diagnostics.CodeAnalysis;
-[assembly: SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Field Name", Scope = "namespaceanddescendants", Target = "NebulaAPI")]
+#endregion
+
+[assembly:
+ SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Original Field Name", Scope = "namespaceanddescendants",
+ Target = "NebulaAPI")]
diff --git a/NebulaAPI/Interfaces/BinaryInterfaces.cs b/NebulaAPI/Interfaces/BinaryInterfaces.cs
index 06c710ecb..d28a485a4 100644
--- a/NebulaAPI/Interfaces/BinaryInterfaces.cs
+++ b/NebulaAPI/Interfaces/BinaryInterfaces.cs
@@ -1,22 +1,26 @@
-using System;
+#region
+
+using System;
using System.IO;
-namespace NebulaAPI
+#endregion
+
+namespace NebulaAPI;
+
+///
+/// Provides access to BinaryWriter with LZ4 compression
+///
+public interface IWriterProvider : IDisposable
{
- ///
- /// Provides access to BinaryWriter with LZ4 compression
- ///
- public interface IWriterProvider : IDisposable
- {
- BinaryWriter BinaryWriter { get; }
- byte[] CloseAndGetBytes();
- }
+ BinaryWriter BinaryWriter { get; }
- ///
- /// Provides access to BinaryReader with LZ4 compression
- ///
- public interface IReaderProvider : IDisposable
- {
- BinaryReader BinaryReader { get; }
- }
-}
\ No newline at end of file
+ byte[] CloseAndGetBytes();
+}
+
+///
+/// Provides access to BinaryReader with LZ4 compression
+///
+public interface IReaderProvider : IDisposable
+{
+ BinaryReader BinaryReader { get; }
+}
diff --git a/NebulaAPI/Interfaces/IMultiplayerMod.cs b/NebulaAPI/Interfaces/IMultiplayerMod.cs
index bcaee5fc2..9f50715a9 100644
--- a/NebulaAPI/Interfaces/IMultiplayerMod.cs
+++ b/NebulaAPI/Interfaces/IMultiplayerMod.cs
@@ -1,22 +1,27 @@
-using System.IO;
+#region
-namespace NebulaAPI
+using System.IO;
+
+#endregion
+
+namespace NebulaAPI;
+
+///
+/// Implement this interface to make sure your mod will be the same version on the host
+///
+public interface IMultiplayerMod
+{
+ string Version { get; }
+
+ bool CheckVersion(string hostVersion, string clientVersion);
+}
+
+///
+/// Implement this interface if you have important settings that clients need to know
+///
+public interface IMultiplayerModWithSettings : IMultiplayerMod
{
- ///
- /// Implement this interface to make sure your mod will be the same version on the host
- ///
- public interface IMultiplayerMod
- {
- string Version { get; }
- bool CheckVersion(string hostVersion, string clientVersion);
- }
+ void Export(BinaryWriter w);
- ///
- /// Implement this interface if you have important settings that clients need to know
- ///
- public interface IMultiplayerModWithSettings : IMultiplayerMod
- {
- void Export(BinaryWriter w);
- void Import(BinaryReader r);
- }
+ void Import(BinaryReader r);
}
diff --git a/NebulaAPI/Interfaces/INetSerializable.cs b/NebulaAPI/Interfaces/INetSerializable.cs
index 7df6ca20c..99d9a7bf8 100644
--- a/NebulaAPI/Interfaces/INetSerializable.cs
+++ b/NebulaAPI/Interfaces/INetSerializable.cs
@@ -1,149 +1,153 @@
-using System;
+#region
+
+using System;
using System.Net;
-namespace NebulaAPI
+#endregion
+
+namespace NebulaAPI;
+
+public interface INetSerializable
{
- public interface INetSerializable
- {
- void Serialize(INetDataWriter writer);
- void Deserialize(INetDataReader reader);
- }
+ void Serialize(INetDataWriter writer);
+
+ void Deserialize(INetDataReader reader);
+}
- public interface INetDataWriter
- {
- void Put(float value);
+public interface INetDataWriter
+{
+ void Put(float value);
- void Put(double value);
+ void Put(double value);
- void Put(long value);
+ void Put(long value);
- void Put(ulong value);
+ void Put(ulong value);
- void Put(int value);
+ void Put(int value);
- void Put(uint value);
+ void Put(uint value);
- void Put(char value);
+ void Put(char value);
- void Put(ushort value);
+ void Put(ushort value);
- void Put(short value);
+ void Put(short value);
- void Put(sbyte value);
+ void Put(sbyte value);
- void Put(byte value);
+ void Put(byte value);
- void Put(byte[] data, int offset, int length);
+ void Put(byte[] data, int offset, int length);
- void Put(byte[] data);
+ void Put(byte[] data);
- void PutSBytesWithLength(sbyte[] data, int offset, int length);
+ void PutSBytesWithLength(sbyte[] data, int offset, int length);
- void PutSBytesWithLength(sbyte[] data);
+ void PutSBytesWithLength(sbyte[] data);
- void PutBytesWithLength(byte[] data, int offset, int length);
+ void PutBytesWithLength(byte[] data, int offset, int length);
- void PutBytesWithLength(byte[] data);
+ void PutBytesWithLength(byte[] data);
- void Put(bool value);
+ void Put(bool value);
- void PutArray(float[] value);
+ void PutArray(float[] value);
- void PutArray(double[] value);
+ void PutArray(double[] value);
- void PutArray(long[] value);
+ void PutArray(long[] value);
- void PutArray(ulong[] value);
+ void PutArray(ulong[] value);
- void PutArray(int[] value);
+ void PutArray(int[] value);
- void PutArray(uint[] value);
+ void PutArray(uint[] value);
- void PutArray(ushort[] value);
+ void PutArray(ushort[] value);
- void PutArray(short[] value);
+ void PutArray(short[] value);
- void PutArray(bool[] value);
+ void PutArray(bool[] value);
- void PutArray(string[] value);
+ void PutArray(string[] value);
- void PutArray(string[] value, int maxLength);
+ void PutArray(string[] value, int maxLength);
- void Put(IPEndPoint endPoint);
+ void Put(IPEndPoint endPoint);
- void Put(string value);
+ void Put(string value);
- void Put(string value, int maxLength);
+ void Put(string value, int maxLength);
- void Put(T obj) where T : INetSerializable;
- }
+ void Put(T obj) where T : INetSerializable;
+}
- public interface INetDataReader
- {
- IPEndPoint GetNetEndPoint();
+public interface INetDataReader
+{
+ IPEndPoint GetNetEndPoint();
- byte GetByte();
+ byte GetByte();
- sbyte GetSByte();
+ sbyte GetSByte();
- bool[] GetBoolArray();
+ bool[] GetBoolArray();
- ushort[] GetUShortArray();
+ ushort[] GetUShortArray();
- short[] GetShortArray();
+ short[] GetShortArray();
- long[] GetLongArray();
+ long[] GetLongArray();
- ulong[] GetULongArray();
+ ulong[] GetULongArray();
- int[] GetIntArray();
+ int[] GetIntArray();
- uint[] GetUIntArray();
+ uint[] GetUIntArray();
- float[] GetFloatArray();
+ float[] GetFloatArray();
- double[] GetDoubleArray();
+ double[] GetDoubleArray();
- string[] GetStringArray();
+ string[] GetStringArray();
- string[] GetStringArray(int maxStringLength);
+ string[] GetStringArray(int maxStringLength);
- bool GetBool();
+ bool GetBool();
- char GetChar();
+ char GetChar();
- ushort GetUShort();
+ ushort GetUShort();
- short GetShort();
+ short GetShort();
- long GetLong();
+ long GetLong();
- ulong GetULong();
+ ulong GetULong();
- int GetInt();
+ int GetInt();
- uint GetUInt();
+ uint GetUInt();
- float GetFloat();
+ float GetFloat();
- double GetDouble();
+ double GetDouble();
- string GetString(int maxLength);
+ string GetString(int maxLength);
- string GetString();
+ string GetString();
- ArraySegment GetRemainingBytesSegment();
+ ArraySegment GetRemainingBytesSegment();
- T Get() where T : INetSerializable, new();
+ T Get() where T : INetSerializable, new();
- byte[] GetRemainingBytes();
+ byte[] GetRemainingBytes();
- void GetBytes(byte[] destination, int start, int count);
+ void GetBytes(byte[] destination, int start, int count);
- void GetBytes(byte[] destination, int count);
+ void GetBytes(byte[] destination, int count);
- sbyte[] GetSBytesWithLength();
+ sbyte[] GetSBytesWithLength();
- byte[] GetBytesWithLength();
- }
+ byte[] GetBytesWithLength();
}
diff --git a/NebulaAPI/Interfaces/IToggle.cs b/NebulaAPI/Interfaces/IToggle.cs
index 35f757294..158c1c2a8 100644
--- a/NebulaAPI/Interfaces/IToggle.cs
+++ b/NebulaAPI/Interfaces/IToggle.cs
@@ -1,10 +1,14 @@
-using System;
+#region
-namespace NebulaAPI
+using System;
+
+#endregion
+
+namespace NebulaAPI;
+
+public interface IToggle
{
- public interface IToggle
- {
- bool Value { get; }
- IDisposable On();
- }
-}
\ No newline at end of file
+ bool Value { get; }
+
+ IDisposable On();
+}
diff --git a/NebulaAPI/NebulaAPI.csproj b/NebulaAPI/NebulaAPI.csproj
index e34922699..03d81a464 100644
--- a/NebulaAPI/NebulaAPI.csproj
+++ b/NebulaAPI/NebulaAPI.csproj
@@ -1,12 +1,12 @@
-
- DysonSphereProgram.Modding.NebulaMultiplayerModApi
- Nebula Mod Team
- API for other mods to work with the Nebula Multiplayer Mod for Dyson Sphere Program.
- https://github.com/hubastard/nebula
- $(MSBuildThisFileDirectory)
-
+
+ DysonSphereProgram.Modding.NebulaMultiplayerModApi
+ Nebula Mod Team
+ API for other mods to work with the Nebula Multiplayer Mod for Dyson Sphere Program.
+ https://github.com/hubastard/nebula
+ $(MSBuildThisFileDirectory)
+
\ No newline at end of file
diff --git a/NebulaAPI/NebulaModAPI.cs b/NebulaAPI/NebulaModAPI.cs
index aab774ac1..b97d11e55 100644
--- a/NebulaAPI/NebulaModAPI.cs
+++ b/NebulaAPI/NebulaModAPI.cs
@@ -1,178 +1,180 @@
-using BepInEx;
-using HarmonyLib;
+#region
+
using System;
using System.Collections.Generic;
using System.Reflection;
+using BepInEx;
+using BepInEx.Bootstrap;
+using HarmonyLib;
-namespace NebulaAPI
-{
- [BepInPlugin(API_GUID, API_NAME, ThisAssembly.AssemblyFileVersion)]
- [BepInDependency(NEBULA_MODID, BepInDependency.DependencyFlags.SoftDependency)]
- public class NebulaModAPI : BaseUnityPlugin
- {
- private static bool nebulaIsInstalled;
-
- private static Type multiplayer;
-
- private static Type binaryWriter;
- private static Type binaryReader;
-
- public static readonly List TargetAssemblies = new List();
-
- public const string NEBULA_MODID = "dsp.nebula-multiplayer";
-
- public const string API_GUID = "dsp.nebula-multiplayer-api";
- public const string API_NAME = "NebulaMultiplayerModApi";
+#endregion
- public static bool NebulaIsInstalled => nebulaIsInstalled;
+namespace NebulaAPI;
- ///
- /// Is this session in multiplayer
- ///
- public static bool IsMultiplayerActive
+[BepInPlugin(API_GUID, API_NAME, ThisAssembly.AssemblyFileVersion)]
+[BepInDependency(NEBULA_MODID, BepInDependency.DependencyFlags.SoftDependency)]
+public class NebulaModAPI : BaseUnityPlugin
+{
+ public const string NEBULA_MODID = "dsp.nebula-multiplayer";
+
+ public const string API_GUID = "dsp.nebula-multiplayer-api";
+ public const string API_NAME = "NebulaMultiplayerModApi";
+
+ public const int PLANET_NONE = -2;
+ public const int AUTHOR_NONE = -1;
+ public const int STAR_NONE = -1;
+
+ private static Type multiplayer;
+
+ private static Type binaryWriter;
+ private static Type binaryReader;
+
+ public static readonly List TargetAssemblies = new();
+
+ ///
+ /// Subscribe to receive event when new multiplayer game is started
+ /// (Host sets up a game, or Client establishes connection)
+ ///
+ public static Action OnMultiplayerGameStarted;
+
+ ///
+ /// Subscribe to receive event when multiplayer game end
+ /// (Host ends the game, or Client disconnects)
+ ///
+ public static Action OnMultiplayerGameEnded;
+
+ ///
+ /// Subscribe to receive event when a new star starts loading (client)
+ /// int starIndex - index of star to load
+ ///
+ public static Action OnStarLoadRequest;
+
+ ///
+ /// Subscribe to receive event when a DysonSphere finishs loading (client)
+ /// int starIndex - index of star of dyson sphere to load
+ ///
+ public static Action OnDysonSphereLoadFinished;
+
+ ///
+ /// Subscribe to receive event when a PlanetFactory starts loading (client)
+ /// int planetId - id of planet to load
+ ///
+ public static Action OnPlanetLoadRequest;
+
+ ///
+ /// Subscribe to receive event when a PlanetFactory is finished loading (client)
+ /// int planetId - id of planet to load
+ ///
+ public static Action OnPlanetLoadFinished;
+
+ ///
+ /// Subscribe to receive even when a player joins the game (Host)
+ /// The event fires after the player sync all the data
+ /// - joined player data
+ ///
+ public static Action OnPlayerJoinedGame;
+
+ ///
+ /// Subscribe to receive even when a player leaves the game (Host)
+ /// The event fires after the player disconnect
+ /// - left player data
+ ///
+ public static Action OnPlayerLeftGame;
+
+ public static bool NebulaIsInstalled { get; private set; }
+
+ ///
+ /// Is this session in multiplayer
+ ///
+ public static bool IsMultiplayerActive
+ {
+ get
{
- get
+ if (!NebulaIsInstalled)
{
- if (!NebulaIsInstalled)
- {
- return false;
- }
-
- return (bool)multiplayer.GetProperty("IsActive").GetValue(null);
+ return false;
}
+
+ return (bool)multiplayer.GetProperty("IsActive").GetValue(null);
}
+ }
- ///
- /// Provides access to MultiplayerSession class
- ///
- public static IMultiplayerSession MultiplayerSession
+ ///
+ /// Provides access to MultiplayerSession class
+ ///
+ public static IMultiplayerSession MultiplayerSession
+ {
+ get
{
- get
+ if (!NebulaIsInstalled)
{
- if (!NebulaIsInstalled)
- {
- return null;
- }
-
- return (IMultiplayerSession)multiplayer.GetProperty("Session").GetValue(null);
+ return null;
}
+
+ return (IMultiplayerSession)multiplayer.GetProperty("Session").GetValue(null);
}
+ }
- ///
- /// Subscribe to receive event when new multiplayer game is started
- /// (Host sets up a game, or Client establishes connection)
- ///
- public static Action OnMultiplayerGameStarted;
-
- ///
- /// Subscribe to receive event when multiplayer game end
- /// (Host ends the game, or Client disconnects)
- ///
- public static Action OnMultiplayerGameEnded;
-
- ///
- /// Subscribe to receive event when a new star starts loading (client)
- /// int starIndex - index of star to load
- ///
- public static Action OnStarLoadRequest;
-
- ///
- /// Subscribe to receive event when a DysonSphere finishs loading (client)
- /// int starIndex - index of star of dyson sphere to load
- ///
- public static Action OnDysonSphereLoadFinished;
-
- ///
- /// Subscribe to receive event when a PlanetFactory starts loading (client)
- /// int planetId - id of planet to load
- ///
- public static Action OnPlanetLoadRequest;
-
- ///
- /// Subscribe to receive event when a PlanetFactory is finished loading (client)
- /// int planetId - id of planet to load
- ///
- public static Action OnPlanetLoadFinished;
-
- ///
- /// Subscribe to receive even when a player joins the game (Host)
- /// The event fires after the player sync all the data
- /// - joined player data
- ///
- public static Action OnPlayerJoinedGame;
-
- ///
- /// Subscribe to receive even when a player leaves the game (Host)
- /// The event fires after the player disconnect
- /// - left player data
- ///
- public static Action OnPlayerLeftGame;
-
- private void Awake()
- {
- nebulaIsInstalled = false;
+ private void Awake()
+ {
+ NebulaIsInstalled = false;
- foreach (KeyValuePair pluginInfo in BepInEx.Bootstrap.Chainloader.PluginInfos)
+ foreach (var pluginInfo in Chainloader.PluginInfos)
+ {
+ if (pluginInfo.Value.Metadata.GUID == NEBULA_MODID)
{
- if (pluginInfo.Value.Metadata.GUID == NEBULA_MODID)
- {
- nebulaIsInstalled = true;
- break;
- }
+ NebulaIsInstalled = true;
+ break;
}
+ }
- if (!nebulaIsInstalled)
- {
- return;
- }
+ if (!NebulaIsInstalled)
+ {
+ return;
+ }
- multiplayer = AccessTools.TypeByName("NebulaWorld.Multiplayer");
+ multiplayer = AccessTools.TypeByName("NebulaWorld.Multiplayer");
- Type binaryUtils = AccessTools.TypeByName("NebulaModel.Networking.BinaryUtils");
+ var binaryUtils = AccessTools.TypeByName("NebulaModel.Networking.BinaryUtils");
- binaryWriter = binaryUtils.GetNestedType("Writer");
- binaryReader = binaryUtils.GetNestedType("Reader");
+ binaryWriter = binaryUtils.GetNestedType("Writer");
+ binaryReader = binaryUtils.GetNestedType("Reader");
- Logger.LogInfo("Nebula API is ready!");
- }
+ Logger.LogInfo("Nebula API is ready!");
+ }
- public const int PLANET_NONE = -2;
- public const int AUTHOR_NONE = -1;
- public const int STAR_NONE = -1;
+ ///
+ /// Register all packets within assembly
+ ///
+ /// Target assembly
+ public static void RegisterPackets(Assembly assembly)
+ {
+ TargetAssemblies.Add(assembly);
+ }
- ///
- /// Register all packets within assembly
- ///
- /// Target assembly
- public static void RegisterPackets(Assembly assembly)
+ ///
+ /// Provides access to BinaryWriter with LZ4 compression
+ ///
+ public static IWriterProvider GetBinaryWriter()
+ {
+ if (!NebulaIsInstalled)
{
- TargetAssemblies.Add(assembly);
+ return null;
}
- ///
- /// Provides access to BinaryWriter with LZ4 compression
- ///
- public static IWriterProvider GetBinaryWriter()
- {
- if (!NebulaIsInstalled)
- {
- return null;
- }
-
- return (IWriterProvider)binaryWriter.GetConstructor(new Type[0]).Invoke(new object[0]);
- }
+ return (IWriterProvider)binaryWriter.GetConstructor(new Type[0]).Invoke(new object[0]);
+ }
- ///
- /// Provides access to BinaryReader with LZ4 compression
- ///
- public static IReaderProvider GetBinaryReader(byte[] bytes)
+ ///
+ /// Provides access to BinaryReader with LZ4 compression
+ ///
+ public static IReaderProvider GetBinaryReader(byte[] bytes)
+ {
+ if (!NebulaIsInstalled)
{
- if (!NebulaIsInstalled)
- {
- return null;
- }
-
- return (IReaderProvider)binaryReader.GetConstructor(new[] { typeof(byte[]) }).Invoke(new object[] { bytes });
+ return null;
}
+
+ return (IReaderProvider)binaryReader.GetConstructor(new[] { typeof(byte[]) }).Invoke(new object[] { bytes });
}
-}
\ No newline at end of file
+}
diff --git a/NebulaAPI/Packets/BasePacketProcessor.cs b/NebulaAPI/Packets/BasePacketProcessor.cs
index 066232bcb..a5d64b13f 100644
--- a/NebulaAPI/Packets/BasePacketProcessor.cs
+++ b/NebulaAPI/Packets/BasePacketProcessor.cs
@@ -1,30 +1,30 @@
-namespace NebulaAPI
+namespace NebulaAPI;
+
+///
+/// Describes how to process received packets of type T
+///
+/// Packet class
+public abstract class BasePacketProcessor
{
///
- /// Describes how to process received packets of type T
+ /// Is code running on Host
///
- /// Packet class
- public abstract class BasePacketProcessor
- {
- ///
- /// Is code running on Host
- ///
- protected bool IsHost;
- ///
- /// Is code running on Client
- ///
- protected bool IsClient => !IsHost;
+ protected bool IsHost;
- internal void Initialize(bool isHost)
- {
- IsHost = isHost;
- }
+ ///
+ /// Is code running on Client
+ ///
+ protected bool IsClient => !IsHost;
- ///
- /// Process packets here
- ///
- /// Received packet
- /// Connection that sent the packet
- public abstract void ProcessPacket(T packet, INebulaConnection conn);
+ internal void Initialize(bool isHost)
+ {
+ IsHost = isHost;
}
-}
\ No newline at end of file
+
+ ///
+ /// Process packets here
+ ///
+ /// Received packet
+ /// Connection that sent the packet
+ public abstract void ProcessPacket(T packet, INebulaConnection conn);
+}
diff --git a/NebulaAPI/Packets/HidePacketInDebugLogsAttribute.cs b/NebulaAPI/Packets/HidePacketInDebugLogsAttribute.cs
index b3a3a3415..59ad8d381 100644
--- a/NebulaAPI/Packets/HidePacketInDebugLogsAttribute.cs
+++ b/NebulaAPI/Packets/HidePacketInDebugLogsAttribute.cs
@@ -1,7 +1,12 @@
-using System;
+#region
-namespace NebulaAPI
+using System;
+
+#endregion
+
+namespace NebulaAPI;
+
+[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
+public class HidePacketInDebugLogsAttribute : Attribute
{
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)]
- public class HidePacketInDebugLogsAttribute : Attribute { }
}
diff --git a/NebulaAPI/Packets/INebulaConnection.cs b/NebulaAPI/Packets/INebulaConnection.cs
index b97187962..d85d89494 100644
--- a/NebulaAPI/Packets/INebulaConnection.cs
+++ b/NebulaAPI/Packets/INebulaConnection.cs
@@ -1,11 +1,15 @@
-using System;
+#region
-namespace NebulaAPI
+using System;
+
+#endregion
+
+namespace NebulaAPI;
+
+// Use Equals() to check value equality
+public interface INebulaConnection : IEquatable
{
- // Use Equals() to check value equality
- public interface INebulaConnection : IEquatable
- {
- void SendPacket(T packet) where T : class, new();
- void SendRawPacket(byte[] rawData);
- }
+ void SendPacket(T packet) where T : class, new();
+
+ void SendRawPacket(byte[] rawData);
}
diff --git a/NebulaAPI/Packets/RegisterNestedTypeAttribute.cs b/NebulaAPI/Packets/RegisterNestedTypeAttribute.cs
index ed1cf53f8..30a1d3aad 100644
--- a/NebulaAPI/Packets/RegisterNestedTypeAttribute.cs
+++ b/NebulaAPI/Packets/RegisterNestedTypeAttribute.cs
@@ -1,10 +1,15 @@
-using System;
+#region
-namespace NebulaAPI
+using System;
+
+#endregion
+
+namespace NebulaAPI;
+
+///
+/// Registers custom data structure serializer. Make sure to register your assembly using NebulaModAPI.RegisterPackets
+///
+[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
+public class RegisterNestedTypeAttribute : Attribute
{
- ///
- /// Registers custom data structure serializer. Make sure to register your assembly using NebulaModAPI.RegisterPackets
- ///
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)]
- public class RegisterNestedTypeAttribute : Attribute { }
}
diff --git a/NebulaAPI/Packets/RegisterPacketProcessorAttribute.cs b/NebulaAPI/Packets/RegisterPacketProcessorAttribute.cs
index c229a7f12..c408e066d 100644
--- a/NebulaAPI/Packets/RegisterPacketProcessorAttribute.cs
+++ b/NebulaAPI/Packets/RegisterPacketProcessorAttribute.cs
@@ -1,10 +1,15 @@
-using System;
+#region
-namespace NebulaAPI
+using System;
+
+#endregion
+
+namespace NebulaAPI;
+
+///
+/// Registers packet processors. Make sure to register your assembly using NebulaModAPI.RegisterPackets
+///
+[AttributeUsage(AttributeTargets.Class)]
+public class RegisterPacketProcessorAttribute : Attribute
{
- ///
- /// Registers packet processors. Make sure to register your assembly using NebulaModAPI.RegisterPackets
- ///
- [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
- public class RegisterPacketProcessorAttribute : Attribute { }
}
diff --git a/NebulaAPI/README.md b/NebulaAPI/README.md
index 928e4c700..e92ea9517 100644
--- a/NebulaAPI/README.md
+++ b/NebulaAPI/README.md
@@ -1,17 +1,23 @@
# Nebula Multiplayer API
-API for [Nebula multiplayer mod](https://dsp.thunderstore.io/package/nebula/NebulaMultiplayerMod/). This API allows mod developers to support Nebula. You can find setting up guide, examples and documentation [here](https://github.com/hubastard/nebula/wiki)
+API for [Nebula multiplayer mod](https://dsp.thunderstore.io/package/nebula/NebulaMultiplayerMod/). This API allows mod
+developers to support Nebula. You can find setting up guide, examples and
+documentation [here](https://github.com/hubastard/nebula/wiki)
# FAQ
## Where can I get help using the API?
-Please join our [Discord Server](https://discord.gg/UHeB2QvgDa) and ask your question in the `General` channel. We have a really nice community that will be able to answer your questions.
+Please join our [Discord Server](https://discord.gg/UHeB2QvgDa) and ask your question in the `General` channel. We have
+a really nice community that will be able to answer your questions.
## How can I contribute?
-Please join our [Discord Server](https://discord.gg/UHeB2QvgDa) to ask if someone is already working on the task that you want to do. Once, you are done with your modification, simply submit a pull request. Contribution documentation can be found here: [Wiki](https://github.com/hubastard/nebula/wiki/Setting-up-a-development-environment).
+Please join our [Discord Server](https://discord.gg/UHeB2QvgDa) to ask if someone is already working on the task that
+you want to do. Once, you are done with your modification, simply submit a pull request. Contribution documentation can
+be found here: [Wiki](https://github.com/hubastard/nebula/wiki/Setting-up-a-development-environment).
## How can I support the team?
-If you like what we do and would like to support us, you can donate through our [Patreon](https://www.patreon.com/nebula_mod_team). Thanks for the support <3
\ No newline at end of file
+If you like what we do and would like to support us, you can donate through
+our [Patreon](https://www.patreon.com/nebula_mod_team). Thanks for the support <3
\ No newline at end of file
diff --git a/NebulaModel/Attributes/UICharacterLimitAttribute.cs b/NebulaModel/Attributes/UICharacterLimitAttribute.cs
index d325541d4..4dc13e928 100644
--- a/NebulaModel/Attributes/UICharacterLimitAttribute.cs
+++ b/NebulaModel/Attributes/UICharacterLimitAttribute.cs
@@ -1,15 +1,18 @@
-using System;
+#region
-namespace NebulaModel.Attributes
+using System;
+
+#endregion
+
+namespace NebulaModel.Attributes;
+
+[AttributeUsage(AttributeTargets.Property)]
+public class UICharacterLimitAttribute : Attribute
{
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
- public class UICharacterLimitAttribute : Attribute
- {
- public readonly int Max;
+ public readonly int Max;
- public UICharacterLimitAttribute(int max)
- {
- Max = max;
- }
+ public UICharacterLimitAttribute(int max)
+ {
+ Max = max;
}
}
diff --git a/NebulaModel/Attributes/UIContentTypeAttribute.cs b/NebulaModel/Attributes/UIContentTypeAttribute.cs
index 5ecfbc193..67d72e607 100644
--- a/NebulaModel/Attributes/UIContentTypeAttribute.cs
+++ b/NebulaModel/Attributes/UIContentTypeAttribute.cs
@@ -1,16 +1,19 @@
-using System;
+#region
+
+using System;
using UnityEngine.UI;
-namespace NebulaModel.Attributes
+#endregion
+
+namespace NebulaModel.Attributes;
+
+[AttributeUsage(AttributeTargets.Property)]
+public class UIContentTypeAttribute : Attribute
{
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
- public class UIContentTypeAttribute : Attribute
- {
- public readonly InputField.ContentType ContentType;
+ public readonly InputField.ContentType ContentType;
- public UIContentTypeAttribute(InputField.ContentType contentType)
- {
- ContentType = contentType;
- }
+ public UIContentTypeAttribute(InputField.ContentType contentType)
+ {
+ ContentType = contentType;
}
}
diff --git a/NebulaModel/Attributes/UIRangeAttribute.cs b/NebulaModel/Attributes/UIRangeAttribute.cs
index 995245bd5..a32e5f7c0 100644
--- a/NebulaModel/Attributes/UIRangeAttribute.cs
+++ b/NebulaModel/Attributes/UIRangeAttribute.cs
@@ -1,19 +1,22 @@
-using System;
+#region
-namespace NebulaModel.Attributes
+using System;
+
+#endregion
+
+namespace NebulaModel.Attributes;
+
+[AttributeUsage(AttributeTargets.Property)]
+public class UIRangeAttribute : Attribute
{
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
- public class UIRangeAttribute : Attribute
- {
- public readonly float Min;
- public readonly float Max;
- public readonly bool Slider;
+ public readonly float Max;
+ public readonly float Min;
+ public readonly bool Slider;
- public UIRangeAttribute(float min, float max, bool slider = false)
- {
- Min = min;
- Max = max;
- Slider = slider;
- }
+ public UIRangeAttribute(float min, float max, bool slider = false)
+ {
+ Min = min;
+ Max = max;
+ Slider = slider;
}
-}
\ No newline at end of file
+}
diff --git a/NebulaModel/Config.cs b/NebulaModel/Config.cs
index de5963644..4a6646575 100644
--- a/NebulaModel/Config.cs
+++ b/NebulaModel/Config.cs
@@ -1,80 +1,81 @@
-using BepInEx;
-using BepInEx.Configuration;
-using HarmonyLib;
-using NebulaModel.Logger;
+#region
+
using System;
-using System.Collections.Generic;
using System.IO;
using System.Linq;
-using System.Reflection;
+using BepInEx;
+using BepInEx.Configuration;
+using HarmonyLib;
+using NebulaModel.Logger;
+
+#endregion
-namespace NebulaModel
+namespace NebulaModel;
+
+public static class Config
{
- public static class Config
- {
- private const string OPTION_SAVE_FILE = "nebula.cfg";
- private const string SECTION_NAME = "Nebula - Settings";
+ private const string OPTION_SAVE_FILE = "nebula.cfg";
+ private const string SECTION_NAME = "Nebula - Settings";
+
+ public static Action OnConfigApplied;
+
+ private static ConfigFile configFile;
- public static PluginInfo ModInfo { get; set; }
- public static string ModVersion => ThisAssembly.AssemblyInformationalVersion;
- public static MultiplayerOptions Options { get; set; }
+ public static PluginInfo ModInfo { get; set; }
+ public static string ModVersion => ThisAssembly.AssemblyInformationalVersion;
+ public static MultiplayerOptions Options { get; set; }
- public static Action OnConfigApplied;
-
- private static ConfigFile configFile;
-
- public static bool LoadOptions()
+ public static bool LoadOptions()
+ {
+ Options = new MultiplayerOptions();
+
+ try
{
- Options = new MultiplayerOptions();
+ configFile = new ConfigFile(Path.Combine(Paths.ConfigPath, OPTION_SAVE_FILE), true);
- try
- {
- configFile = new ConfigFile(Path.Combine(Paths.ConfigPath, OPTION_SAVE_FILE), true);
-
- List properties = AccessTools.GetDeclaredProperties(typeof(MultiplayerOptions));
- MethodInfo configBindMethod = typeof(ConfigFile)
- .GetMethods()
- .Where(m => m.Name == nameof(ConfigFile.Bind))
- .First(m => m.IsGenericMethod && m.GetParameters().Length == 4);
-
- foreach (PropertyInfo prop in properties)
- {
- object entry = configBindMethod.MakeGenericMethod(prop.PropertyType).Invoke(configFile,
- new object[] { SECTION_NAME, prop.Name, prop.GetValue(Options), null });
-
- Type entryType = typeof(ConfigEntry<>).MakeGenericType(prop.PropertyType);
- prop.SetValue(Options, AccessTools.Property(entryType, "Value").GetValue(entry));
- }
- }
- catch (Exception e)
+ var properties = AccessTools.GetDeclaredProperties(typeof(MultiplayerOptions));
+ var configBindMethod = typeof(ConfigFile)
+ .GetMethods()
+ .Where(m => m.Name == nameof(ConfigFile.Bind))
+ .First(m => m.IsGenericMethod && m.GetParameters().Length == 4);
+
+ foreach (var prop in properties)
{
- Log.Error($"Could not load {OPTION_SAVE_FILE}", e);
- return false;
- }
+ var entry = configBindMethod.MakeGenericMethod(prop.PropertyType).Invoke(configFile,
+ new[] { SECTION_NAME, prop.Name, prop.GetValue(Options), null });
- return true;
+ var entryType = typeof(ConfigEntry<>).MakeGenericType(prop.PropertyType);
+ prop.SetValue(Options, AccessTools.Property(entryType, "Value").GetValue(entry));
+ }
}
+ catch (Exception e)
+ {
+ Log.Error($"Could not load {OPTION_SAVE_FILE}", e);
+ return false;
+ }
+
+ return true;
+ }
- public static bool SaveOptions()
+ public static bool SaveOptions()
+ {
+ try
{
- try
- {
- List properties = AccessTools.GetDeclaredProperties(typeof(MultiplayerOptions));
- foreach (PropertyInfo prop in properties)
- {
- ConfigDefinition key = new ConfigDefinition(SECTION_NAME, prop.Name);
- configFile[key].BoxedValue = prop.GetValue(Options);
- }
- configFile.Save();
- }
- catch (Exception e)
+ var properties = AccessTools.GetDeclaredProperties(typeof(MultiplayerOptions));
+ foreach (var prop in properties)
{
- Log.Error($"Could not load {OPTION_SAVE_FILE}", e);
- return false;
+ var key = new ConfigDefinition(SECTION_NAME, prop.Name);
+ configFile[key].BoxedValue = prop.GetValue(Options);
}
-
- return true;
+ configFile.Save();
}
+ catch (Exception e)
+ {
+ Log.Error($"Could not load {OPTION_SAVE_FILE}", e);
+ return false;
+ }
+
+ return true;
}
}
diff --git a/NebulaModel/DataStructures/Chat/ChatMessage.cs b/NebulaModel/DataStructures/Chat/ChatMessage.cs
index edfb6f932..dadc629dd 100644
--- a/NebulaModel/DataStructures/Chat/ChatMessage.cs
+++ b/NebulaModel/DataStructures/Chat/ChatMessage.cs
@@ -1,69 +1,71 @@
-using NebulaModel.Utils;
+#region
+
using System;
+using NebulaModel.Utils;
using TMPro;
using UnityEngine;
using Object = UnityEngine.Object;
+#endregion
+
#pragma warning disable IDE1006
-namespace NebulaModel.DataStructures
+namespace NebulaModel.DataStructures;
+
+///
+/// This is what is rendered in the chat area (already sent chat messages)
+///
+[Serializable]
+public class ChatMessage
{
- ///
- /// This is what is rendered in the chat area (already sent chat messages)
- ///
- [Serializable]
- public class ChatMessage
- {
- private string text;
- private ChatMessageType messageType;
+ public TMP_Text textObject;
+ public TMP_Text notificationText;
+ private ChatMessageType messageType;
+ private string text;
- public TMP_Text textObject;
- public TMP_Text notificationText;
+ public ChatMessage(GameObject textObj, string message, ChatMessageType messageType)
+ {
+ textObject = textObj.GetComponent();
+ Text = message;
+ MessageType = messageType;
+ }
- public string Text
+ public string Text
+ {
+ get => text;
+ set
{
- get => text;
- set
+ textObject.text = value;
+ if (notificationText != null)
{
- textObject.text = value;
- if (notificationText != null)
- {
- notificationText.text = value;
- }
-
- text = value;
+ notificationText.text = value;
}
+
+ text = value;
}
+ }
- public ChatMessageType MessageType
+ public ChatMessageType MessageType
+ {
+ get => messageType;
+ set
{
- get => messageType;
- set
+ textObject.color = ChatUtils.GetMessageColor(value);
+ if (notificationText != null)
{
- textObject.color = ChatUtils.GetMessageColor(value);
- if (notificationText != null)
- {
- notificationText.color = textObject.color;
- }
-
- messageType = value;
+ notificationText.color = textObject.color;
}
- }
- public ChatMessage(GameObject textObj, string message, ChatMessageType messageType)
- {
- textObject = textObj.GetComponent();
- Text = message;
- MessageType = messageType;
+ messageType = value;
}
+ }
- public void DestroyMessage()
+ public void DestroyMessage()
+ {
+ Object.Destroy(textObject.gameObject);
+ if (notificationText != null)
{
- Object.Destroy(textObject.gameObject);
- if (notificationText != null)
- {
- Object.Destroy(notificationText.gameObject);
- }
+ Object.Destroy(notificationText.gameObject);
}
}
}
diff --git a/NebulaModel/DataStructures/Chat/ChatMessageType.cs b/NebulaModel/DataStructures/Chat/ChatMessageType.cs
index 3e2af68ed..827acc50d 100644
--- a/NebulaModel/DataStructures/Chat/ChatMessageType.cs
+++ b/NebulaModel/DataStructures/Chat/ChatMessageType.cs
@@ -1,13 +1,12 @@
-namespace NebulaModel.DataStructures
+namespace NebulaModel.DataStructures;
+
+public enum ChatMessageType
{
- public enum ChatMessageType
- {
- PlayerMessage = 0,
- SystemInfoMessage = 1,
- SystemWarnMessage = 2,
- CommandUsageMessage = 3,
- CommandOutputMessage = 4,
- CommandErrorMessage = 5,
- PlayerMessagePrivate = 6
- }
-}
\ No newline at end of file
+ PlayerMessage = 0,
+ SystemInfoMessage = 1,
+ SystemWarnMessage = 2,
+ CommandUsageMessage = 3,
+ CommandOutputMessage = 4,
+ CommandErrorMessage = 5,
+ PlayerMessagePrivate = 6
+}
diff --git a/NebulaModel/DataStructures/Chat/ChatPosition.cs b/NebulaModel/DataStructures/Chat/ChatPosition.cs
index d24195538..547345d99 100644
--- a/NebulaModel/DataStructures/Chat/ChatPosition.cs
+++ b/NebulaModel/DataStructures/Chat/ChatPosition.cs
@@ -1,17 +1,16 @@
-namespace NebulaModel.DataStructures
+namespace NebulaModel.DataStructures;
+
+public enum ChatPosition
{
- public enum ChatPosition
- {
- LeftMiddle = 0,
- RightMiddle = 1,
- LeftTop = 2,
- RightTop = 3
- }
+ LeftMiddle = 0,
+ RightMiddle = 1,
+ LeftTop = 2,
+ RightTop = 3
+}
- public enum ChatSize
- {
- Small = 0,
- Medium = 1,
- Big = 2
- }
-}
\ No newline at end of file
+public enum ChatSize
+{
+ Small = 0,
+ Medium = 1,
+ Big = 2
+}
diff --git a/NebulaModel/DataStructures/DysonLaunchData.cs b/NebulaModel/DataStructures/DysonLaunchData.cs
index 38edbd5a4..90c57a7ed 100644
--- a/NebulaModel/DataStructures/DysonLaunchData.cs
+++ b/NebulaModel/DataStructures/DysonLaunchData.cs
@@ -1,90 +1,93 @@
-using NebulaAPI;
+#region
+
using System.Collections.Generic;
+using NebulaAPI;
using UnityEngine;
-namespace NebulaModel.DataStructures
+#endregion
+
+namespace NebulaModel.DataStructures;
+
+[RegisterNestedType]
+public class DysonLaunchData : INetSerializable
{
- [RegisterNestedType]
- public class DysonLaunchData : INetSerializable
+ public DysonLaunchData(int starIndex)
{
- public struct Projectile
- {
- public int PlanetId;
- public byte Interval;
- public ushort TargetId;
- public Vector3 LocalPos;
- }
+ StarIndex = starIndex;
+ BulletList = new List();
+ RocketList = new List();
+ }
- public int StarIndex { get; set; }
- public List BulletList { get; set; }
- public List RocketList { get; set; }
- public int BulletCursor { get; set; }
- public int RocketCursor { get; set; }
- public byte BulletTick { get; set; }
- public byte RocketTick { get; set; }
+ public DysonLaunchData() : this(0) { }
- public DysonLaunchData(int starIndex)
+ public int StarIndex { get; set; }
+ public List BulletList { get; set; }
+ public List RocketList { get; set; }
+ public int BulletCursor { get; set; }
+ public int RocketCursor { get; set; }
+ public byte BulletTick { get; set; }
+ public byte RocketTick { get; set; }
+
+ public void Serialize(INetDataWriter writer)
+ {
+ writer.Put(StarIndex);
+ writer.Put((ushort)BulletList.Count);
+ for (ushort i = 0; i < (ushort)BulletList.Count; i++)
{
- StarIndex = starIndex;
- BulletList = new List();
- RocketList = new List();
+ var data = BulletList[i];
+ writer.Put((byte)(data.PlanetId % 100));
+ writer.Put(data.Interval);
+ writer.Put(data.TargetId);
+ writer.Put(data.LocalPos.ToFloat3());
}
-
- public DysonLaunchData() : this(0) { }
-
- public void Serialize(INetDataWriter writer)
+ writer.Put((ushort)RocketList.Count);
+ for (ushort i = 0; i < (ushort)RocketList.Count; i++)
{
- writer.Put(StarIndex);
- writer.Put((ushort)BulletList.Count);
- for (ushort i = 0; i < (ushort)BulletList.Count; i++)
- {
- Projectile data = BulletList[i];
- writer.Put((byte)(data.PlanetId % 100));
- writer.Put(data.Interval);
- writer.Put(data.TargetId);
- writer.Put(data.LocalPos.ToFloat3());
- }
- writer.Put((ushort)RocketList.Count);
- for (ushort i = 0; i < (ushort)RocketList.Count; i++)
- {
- Projectile data = RocketList[i];
- writer.Put((byte)(data.PlanetId % 100));
- writer.Put(data.Interval);
- writer.Put(data.TargetId);
- writer.Put(data.LocalPos.ToFloat3());
- }
+ var data = RocketList[i];
+ writer.Put((byte)(data.PlanetId % 100));
+ writer.Put(data.Interval);
+ writer.Put(data.TargetId);
+ writer.Put(data.LocalPos.ToFloat3());
}
+ }
- public void Deserialize(INetDataReader reader)
+ public void Deserialize(INetDataReader reader)
+ {
+ StarIndex = reader.GetInt();
+ var starId = (StarIndex + 1) * 100;
+ int count = reader.GetUShort();
+ BulletList = new List(count);
+ for (var i = 0; i < count; i++)
{
- StarIndex = reader.GetInt();
- int starId = (StarIndex + 1) * 100;
- int count = reader.GetUShort();
- BulletList = new List(count);
- for (int i = 0; i < count; i++)
+ var data = new Projectile
{
- Projectile data = new Projectile
- {
- PlanetId = reader.GetByte() + starId,
- Interval = reader.GetByte(),
- TargetId = reader.GetUShort(),
- LocalPos = reader.GetFloat3().ToVector3()
- };
- BulletList.Add(data);
- }
- count = reader.GetUShort();
- RocketList = new List(count);
- for (ushort i = 0; i < count; i++)
+ PlanetId = reader.GetByte() + starId,
+ Interval = reader.GetByte(),
+ TargetId = reader.GetUShort(),
+ LocalPos = reader.GetFloat3().ToVector3()
+ };
+ BulletList.Add(data);
+ }
+ count = reader.GetUShort();
+ RocketList = new List(count);
+ for (ushort i = 0; i < count; i++)
+ {
+ var data = new Projectile
{
- Projectile data = new Projectile
- {
- PlanetId = reader.GetByte() + starId,
- Interval = reader.GetByte(),
- TargetId = reader.GetUShort(),
- LocalPos = reader.GetFloat3().ToVector3()
- };
- RocketList.Add(data);
- }
+ PlanetId = reader.GetByte() + starId,
+ Interval = reader.GetByte(),
+ TargetId = reader.GetUShort(),
+ LocalPos = reader.GetFloat3().ToVector3()
+ };
+ RocketList.Add(data);
}
}
+
+ public struct Projectile
+ {
+ public int PlanetId;
+ public byte Interval;
+ public ushort TargetId;
+ public Vector3 LocalPos;
+ }
}
diff --git a/NebulaModel/DataStructures/GameState.cs b/NebulaModel/DataStructures/GameState.cs
index b6c5df8e6..f8c5d767a 100644
--- a/NebulaModel/DataStructures/GameState.cs
+++ b/NebulaModel/DataStructures/GameState.cs
@@ -1,29 +1,32 @@
-using NebulaAPI;
+#region
-namespace NebulaModel.DataStructures
+using NebulaAPI;
+
+#endregion
+
+namespace NebulaModel.DataStructures;
+
+[RegisterNestedType]
+public struct GameState : INetSerializable
{
- [RegisterNestedType]
- public struct GameState : INetSerializable
- {
- public long timestamp;
- public long gameTick;
+ public long timestamp;
+ public long gameTick;
- public GameState(long timestamp, long gameTick)
- {
- this.timestamp = timestamp;
- this.gameTick = gameTick;
- }
+ public GameState(long timestamp, long gameTick)
+ {
+ this.timestamp = timestamp;
+ this.gameTick = gameTick;
+ }
- public void Serialize(INetDataWriter writer)
- {
- writer.Put(timestamp);
- writer.Put(gameTick);
- }
+ public void Serialize(INetDataWriter writer)
+ {
+ writer.Put(timestamp);
+ writer.Put(gameTick);
+ }
- public void Deserialize(INetDataReader reader)
- {
- timestamp = reader.GetLong();
- gameTick = reader.GetLong();
- }
+ public void Deserialize(INetDataReader reader)
+ {
+ timestamp = reader.GetLong();
+ gameTick = reader.GetLong();
}
}
diff --git a/NebulaModel/DataStructures/MechaData.cs b/NebulaModel/DataStructures/MechaData.cs
index 8582545a4..eac912571 100644
--- a/NebulaModel/DataStructures/MechaData.cs
+++ b/NebulaModel/DataStructures/MechaData.cs
@@ -1,140 +1,133 @@
-using NebulaAPI;
-using NebulaModel.Packets.Players;
+#region
+
using System.Collections.Generic;
using System.IO;
+using NebulaAPI;
+using NebulaModel.Packets.Players;
+
+#endregion
-namespace NebulaModel.DataStructures
+namespace NebulaModel.DataStructures;
+
+[RegisterNestedType]
+public class MechaData : IMechaData
{
- [RegisterNestedType]
- public class MechaData : IMechaData
+ public MechaData()
{
- public int SandCount { get; set; }
- public double CoreEnergy { get; set; }
- public double ReactorEnergy { get; set; }
- public StorageComponent Inventory { get; set; }
- public DeliveryPackage DeliveryPackage { get; set; }
- public StorageComponent ReactorStorage { get; set; }
- public StorageComponent WarpStorage { get; set; }
- public MechaForge Forge { get; set; }
- public PlayerTechBonuses TechBonuses { get; set; }
+ //This is needed for the serialization and deserialization
+ Forge = new MechaForge { tasks = new List() };
+ TechBonuses = new PlayerTechBonuses();
+ }
- public MechaData()
- {
- //This is needed for the serialization and deserialization
- Forge = new MechaForge
- {
- tasks = new List()
- };
- TechBonuses = new PlayerTechBonuses();
- }
+ public MechaData(int sandCount, double coreEnergy, double reactorEnergy, StorageComponent inventory,
+ DeliveryPackage deliveryPackage, StorageComponent reactorStorage, StorageComponent warpStorage, MechaForge forge)
+ {
+ SandCount = sandCount;
+ CoreEnergy = coreEnergy;
+ ReactorEnergy = reactorEnergy;
+ ReactorStorage = reactorStorage;
+ WarpStorage = warpStorage;
+ Forge = forge;
+ Inventory = inventory;
+ DeliveryPackage = deliveryPackage;
+ TechBonuses = new PlayerTechBonuses();
+ }
- public MechaData(int sandCount, double coreEnergy, double reactorEnergy, StorageComponent inventory, DeliveryPackage deliveryPackage, StorageComponent reactorStorage, StorageComponent warpStorage, MechaForge forge)
- {
- SandCount = sandCount;
- CoreEnergy = coreEnergy;
- ReactorEnergy = reactorEnergy;
- ReactorStorage = reactorStorage;
- WarpStorage = warpStorage;
- Forge = forge;
- Inventory = inventory;
- DeliveryPackage = deliveryPackage;
- TechBonuses = new PlayerTechBonuses();
- }
+ public PlayerTechBonuses TechBonuses { get; set; }
+ public int SandCount { get; set; }
+ public double CoreEnergy { get; set; }
+ public double ReactorEnergy { get; set; }
+ public StorageComponent Inventory { get; set; }
+ public DeliveryPackage DeliveryPackage { get; set; }
+ public StorageComponent ReactorStorage { get; set; }
+ public StorageComponent WarpStorage { get; set; }
+ public MechaForge Forge { get; set; }
- public void Serialize(INetDataWriter writer)
+ public void Serialize(INetDataWriter writer)
+ {
+ TechBonuses.Serialize(writer);
+ writer.Put(SandCount);
+ writer.Put(CoreEnergy);
+ writer.Put(ReactorEnergy);
+ writer.Put(ReactorStorage != null);
+ if (ReactorStorage != null)
{
- TechBonuses.Serialize(writer);
- writer.Put(SandCount);
- writer.Put(CoreEnergy);
- writer.Put(ReactorEnergy);
- writer.Put(ReactorStorage != null);
- if (ReactorStorage != null)
+ using var ms = new MemoryStream();
+ using (var wr = new BinaryWriter(ms))
{
- using MemoryStream ms = new MemoryStream();
- using (BinaryWriter wr = new BinaryWriter(ms))
- {
- Inventory.Export(wr);
- DeliveryPackage.Export(wr);
- ReactorStorage.Export(wr);
- WarpStorage.Export(wr);
- Forge.Export(wr);
- }
- byte[] export = ms.ToArray();
- writer.Put(export.Length);
- writer.Put(export);
+ Inventory.Export(wr);
+ DeliveryPackage.Export(wr);
+ ReactorStorage.Export(wr);
+ WarpStorage.Export(wr);
+ Forge.Export(wr);
}
+ var export = ms.ToArray();
+ writer.Put(export.Length);
+ writer.Put(export);
}
+ }
- public void Deserialize(INetDataReader reader)
+ public void Deserialize(INetDataReader reader)
+ {
+ TechBonuses = new PlayerTechBonuses();
+ Inventory = new StorageComponent(4);
+ DeliveryPackage = new DeliveryPackage();
+ DeliveryPackage.Init();
+ ReactorStorage = new StorageComponent(4);
+ WarpStorage = new StorageComponent(1);
+ Forge = new MechaForge { tasks = new List(), extraItems = new ItemBundle() };
+ TechBonuses.Deserialize(reader);
+ SandCount = reader.GetInt();
+ CoreEnergy = reader.GetDouble();
+ ReactorEnergy = reader.GetDouble();
+ var isPayloadPresent = reader.GetBool();
+ if (isPayloadPresent)
{
- TechBonuses = new PlayerTechBonuses();
- Inventory = new StorageComponent(4);
- DeliveryPackage = new DeliveryPackage();
- DeliveryPackage.Init();
- ReactorStorage = new StorageComponent(4);
- WarpStorage = new StorageComponent(1);
- Forge = new MechaForge
- {
- tasks = new List(),
- extraItems = new ItemBundle()
- };
- TechBonuses.Deserialize(reader);
- SandCount = reader.GetInt();
- CoreEnergy = reader.GetDouble();
- ReactorEnergy = reader.GetDouble();
- bool isPayloadPresent = reader.GetBool();
- if (isPayloadPresent)
+ var mechaLength = reader.GetInt();
+ var mechaBytes = new byte[mechaLength];
+ reader.GetBytes(mechaBytes, mechaLength);
+ using (var ms = new MemoryStream(mechaBytes))
+ using (var br = new BinaryReader(ms))
{
- int mechaLength = reader.GetInt();
- byte[] mechaBytes = new byte[mechaLength];
- reader.GetBytes(mechaBytes, mechaLength);
- using (MemoryStream ms = new MemoryStream(mechaBytes))
- using (BinaryReader br = new BinaryReader(ms))
- {
- Inventory.Import(br);
- DeliveryPackage.Import(br);
- ReactorStorage.Import(br);
- WarpStorage.Import(br);
- Forge.Import(br);
- }
+ Inventory.Import(br);
+ DeliveryPackage.Import(br);
+ ReactorStorage.Import(br);
+ WarpStorage.Import(br);
+ Forge.Import(br);
}
}
+ }
- public void Import(INetDataReader reader, int revision)
+ public void Import(INetDataReader reader, int revision)
+ {
+ TechBonuses = new PlayerTechBonuses();
+ Inventory = new StorageComponent(4);
+ DeliveryPackage = new DeliveryPackage();
+ DeliveryPackage.Init();
+ ReactorStorage = new StorageComponent(4);
+ WarpStorage = new StorageComponent(1);
+ Forge = new MechaForge { tasks = new List(), extraItems = new ItemBundle() };
+ TechBonuses.Import(reader, revision);
+ SandCount = reader.GetInt();
+ CoreEnergy = reader.GetDouble();
+ ReactorEnergy = reader.GetDouble();
+ var isPayloadPresent = reader.GetBool();
+ if (isPayloadPresent)
{
- TechBonuses = new PlayerTechBonuses();
- Inventory = new StorageComponent(4);
- DeliveryPackage = new DeliveryPackage();
- DeliveryPackage.Init();
- ReactorStorage = new StorageComponent(4);
- WarpStorage = new StorageComponent(1);
- Forge = new MechaForge
- {
- tasks = new List(),
- extraItems = new ItemBundle()
- };
- TechBonuses.Import(reader, revision);
- SandCount = reader.GetInt();
- CoreEnergy = reader.GetDouble();
- ReactorEnergy = reader.GetDouble();
- bool isPayloadPresent = reader.GetBool();
- if (isPayloadPresent)
+ var mechaLength = reader.GetInt();
+ var mechaBytes = new byte[mechaLength];
+ reader.GetBytes(mechaBytes, mechaLength);
+ using (var ms = new MemoryStream(mechaBytes))
+ using (var br = new BinaryReader(ms))
{
- int mechaLength = reader.GetInt();
- byte[] mechaBytes = new byte[mechaLength];
- reader.GetBytes(mechaBytes, mechaLength);
- using (MemoryStream ms = new MemoryStream(mechaBytes))
- using (BinaryReader br = new BinaryReader(ms))
+ Inventory.Import(br);
+ if (revision >= 7)
{
- Inventory.Import(br);
- if (revision >= 7)
- {
- DeliveryPackage.Import(br);
- }
- ReactorStorage.Import(br);
- WarpStorage.Import(br);
- Forge.Import(br);
+ DeliveryPackage.Import(br);
}
+ ReactorStorage.Import(br);
+ WarpStorage.Import(br);
+ Forge.Import(br);
}
}
}
diff --git a/NebulaModel/DataStructures/NetDataReaderExtensions.cs b/NebulaModel/DataStructures/NetDataReaderExtensions.cs
index d800add81..50b4d3e3a 100644
--- a/NebulaModel/DataStructures/NetDataReaderExtensions.cs
+++ b/NebulaModel/DataStructures/NetDataReaderExtensions.cs
@@ -1,28 +1,31 @@
-using NebulaAPI;
+#region
-namespace NebulaModel.DataStructures
+using NebulaAPI;
+
+#endregion
+
+namespace NebulaModel.DataStructures;
+
+public static class NetDataReaderExtensions
{
- public static class NetDataReaderExtensions
+ public static Float3 GetFloat3(this INetDataReader reader)
{
- public static Float3 GetFloat3(this INetDataReader reader)
- {
- Float3 value = new Float3();
- value.Deserialize(reader);
- return value;
- }
+ var value = new Float3();
+ value.Deserialize(reader);
+ return value;
+ }
- public static Float4 GetFloat4(this INetDataReader reader)
- {
- Float4 value = new Float4();
- value.Deserialize(reader);
- return value;
- }
+ public static Float4 GetFloat4(this INetDataReader reader)
+ {
+ var value = new Float4();
+ value.Deserialize(reader);
+ return value;
+ }
- public static Double3 GetDouble3(this INetDataReader reader)
- {
- Double3 value = new Double3();
- value.Deserialize(reader);
- return value;
- }
+ public static Double3 GetDouble3(this INetDataReader reader)
+ {
+ var value = new Double3();
+ value.Deserialize(reader);
+ return value;
}
}
diff --git a/NebulaModel/DataStructures/PlayerData.cs b/NebulaModel/DataStructures/PlayerData.cs
index db5b4bfa8..2688a765a 100644
--- a/NebulaModel/DataStructures/PlayerData.cs
+++ b/NebulaModel/DataStructures/PlayerData.cs
@@ -1,212 +1,218 @@
-using NebulaAPI;
+#region
+
+using System;
using System.IO;
+using NebulaAPI;
+
+#endregion
-namespace NebulaModel.DataStructures
+namespace NebulaModel.DataStructures;
+
+[RegisterNestedType]
+public class PlayerData : IPlayerData
{
- [RegisterNestedType]
- public class PlayerData : IPlayerData
+ public PlayerData()
{
- public string Username { get; set; }
- public ushort PlayerId { get; set; }
- public int LocalPlanetId { get; set; }
- public Float3 LocalPlanetPosition { get; set; }
- public Double3 UPosition { get; set; }
- public Float3 Rotation { get; set; }
- public Float3 BodyRotation { get; set; }
- public IMechaData Mecha { get; set; }
- public int LocalStarId { get; set; }
- public MechaAppearance Appearance { get; set; }
- public MechaAppearance DIYAppearance { get; set; }
- public int[] DIYItemId { get; set; }
- public int[] DIYItemValue { get; set; }
+ Appearance = null;
+ DIYAppearance = null;
+ DIYItemId = Array.Empty();
+ DIYItemValue = Array.Empty();
+ }
- public PlayerData()
- {
- Appearance = null;
- DIYAppearance = null;
- DIYItemId = System.Array.Empty();
- DIYItemValue = System.Array.Empty();
- }
- public PlayerData(ushort playerId, int localPlanetId, string username = null, Float3 localPlanetPosition = new Float3(), Double3 position = new Double3(), Float3 rotation = new Float3(), Float3 bodyRotation = new Float3())
- {
- PlayerId = playerId;
- LocalPlanetId = localPlanetId;
- Username = !string.IsNullOrWhiteSpace(username) ? username : $"Player {playerId}";
- LocalPlanetPosition = localPlanetPosition;
- UPosition = position;
- Rotation = rotation;
- BodyRotation = bodyRotation;
- Mecha = new MechaData();
- Appearance = null;
- DIYAppearance = null;
- DIYItemId = System.Array.Empty();
- DIYItemValue = System.Array.Empty();
- }
+ public PlayerData(ushort playerId, int localPlanetId, string username = null, Float3 localPlanetPosition = new(),
+ Double3 position = new(), Float3 rotation = new(), Float3 bodyRotation = new())
+ {
+ PlayerId = playerId;
+ LocalPlanetId = localPlanetId;
+ Username = !string.IsNullOrWhiteSpace(username) ? username : $"Player {playerId}";
+ LocalPlanetPosition = localPlanetPosition;
+ UPosition = position;
+ Rotation = rotation;
+ BodyRotation = bodyRotation;
+ Mecha = new MechaData();
+ Appearance = null;
+ DIYAppearance = null;
+ DIYItemId = Array.Empty();
+ DIYItemValue = Array.Empty();
+ }
- public void Serialize(INetDataWriter writer)
+ public string Username { get; set; }
+ public ushort PlayerId { get; set; }
+ public int LocalPlanetId { get; set; }
+ public Float3 LocalPlanetPosition { get; set; }
+ public Double3 UPosition { get; set; }
+ public Float3 Rotation { get; set; }
+ public Float3 BodyRotation { get; set; }
+ public IMechaData Mecha { get; set; }
+ public int LocalStarId { get; set; }
+ public MechaAppearance Appearance { get; set; }
+ public MechaAppearance DIYAppearance { get; set; }
+ public int[] DIYItemId { get; set; }
+ public int[] DIYItemValue { get; set; }
+
+ public void Serialize(INetDataWriter writer)
+ {
+ writer.Put(Username);
+ writer.Put(PlayerId);
+ writer.Put(LocalPlanetId);
+ LocalPlanetPosition.Serialize(writer);
+ UPosition.Serialize(writer);
+ Rotation.Serialize(writer);
+ BodyRotation.Serialize(writer);
+ Mecha.Serialize(writer);
+ writer.Put(Appearance != null);
+ if (Appearance != null)
{
- writer.Put(Username);
- writer.Put(PlayerId);
- writer.Put(LocalPlanetId);
- LocalPlanetPosition.Serialize(writer);
- UPosition.Serialize(writer);
- Rotation.Serialize(writer);
- BodyRotation.Serialize(writer);
- Mecha.Serialize(writer);
- writer.Put(Appearance != null);
- if(Appearance != null)
+ using (var ms = new MemoryStream())
{
- using (MemoryStream ms = new MemoryStream())
+ using (var wr = new BinaryWriter(ms))
{
- using (BinaryWriter wr = new BinaryWriter(ms))
- {
- Appearance.Export(wr);
- }
- byte[] export = ms.ToArray();
- writer.Put(export.Length);
- writer.Put(export);
+ Appearance.Export(wr);
}
+ var export = ms.ToArray();
+ writer.Put(export.Length);
+ writer.Put(export);
}
- writer.Put(DIYAppearance != null);
- if (DIYAppearance != null)
+ }
+ writer.Put(DIYAppearance != null);
+ if (DIYAppearance != null)
+ {
+ using (var ms = new MemoryStream())
{
- using (MemoryStream ms = new MemoryStream())
+ using (var wr = new BinaryWriter(ms))
{
- using (BinaryWriter wr = new BinaryWriter(ms))
- {
- DIYAppearance.Export(wr);
- }
- byte[] export = ms.ToArray();
- writer.Put(export.Length);
- writer.Put(export);
+ DIYAppearance.Export(wr);
}
+ var export = ms.ToArray();
+ writer.Put(export.Length);
+ writer.Put(export);
}
- writer.Put(DIYItemId.Length);
- for(int i = 0; i < DIYItemId.Length; i++)
+ }
+ writer.Put(DIYItemId.Length);
+ for (var i = 0; i < DIYItemId.Length; i++)
+ {
+ writer.Put(DIYItemId[i]);
+ writer.Put(DIYItemValue[i]);
+ }
+ }
+
+ public void Deserialize(INetDataReader reader)
+ {
+ Username = reader.GetString();
+ PlayerId = reader.GetUShort();
+ LocalPlanetId = reader.GetInt();
+ LocalPlanetPosition = reader.GetFloat3();
+ UPosition = reader.GetDouble3();
+ Rotation = reader.GetFloat3();
+ BodyRotation = reader.GetFloat3();
+ Mecha = new MechaData();
+ Mecha.Deserialize(reader);
+ var isAppearancePresent = reader.GetBool();
+ if (isAppearancePresent)
+ {
+ var len = reader.GetInt();
+ var data = new byte[len];
+ reader.GetBytes(data, len);
+ using (var ms = new MemoryStream(data))
+ using (var br = new BinaryReader(ms))
+ {
+ Appearance = new MechaAppearance();
+ Appearance.Init();
+ Appearance.Import(br);
+ }
+ }
+ var isDIYAppearancePresent = reader.GetBool();
+ if (isDIYAppearancePresent)
+ {
+ var len = reader.GetInt();
+ var data = new byte[len];
+ reader.GetBytes(data, len);
+ using (var ms = new MemoryStream(data))
+ using (var br = new BinaryReader(ms))
{
- writer.Put(DIYItemId[i]);
- writer.Put(DIYItemValue[i]);
+ DIYAppearance = new MechaAppearance();
+ DIYAppearance.Init();
+ DIYAppearance.Import(br);
}
}
+ var DIYItemLen = reader.GetInt();
+ DIYItemId = new int[DIYItemLen];
+ DIYItemValue = new int[DIYItemLen];
+ for (var i = 0; i < DIYItemLen; i++)
+ {
+ DIYItemId[i] = reader.GetInt();
+ DIYItemValue[i] = reader.GetInt();
+ }
+ }
+
+ public IPlayerData CreateCopyWithoutMechaData()
+ {
+ return new PlayerData(PlayerId, LocalPlanetId, Username, LocalPlanetPosition, UPosition, Rotation, BodyRotation);
+ }
- public void Deserialize(INetDataReader reader)
+ // Backward compatiblity for older versions
+ public void Import(INetDataReader reader, int revision)
+ {
+ Username = reader.GetString();
+ PlayerId = reader.GetUShort();
+ LocalPlanetId = reader.GetInt();
+ if (revision < 7)
+ {
+ // MechaColors is obsoleted by MechaAppearance
+ var mechaColors = new Float4[reader.GetInt()];
+ for (var i = 0; i < mechaColors.Length; i++)
+ {
+ mechaColors[i] = reader.GetFloat4();
+ }
+ }
+ LocalPlanetPosition = reader.GetFloat3();
+ UPosition = reader.GetDouble3();
+ Rotation = reader.GetFloat3();
+ BodyRotation = reader.GetFloat3();
+ MechaData mechaData = new();
+ mechaData.Import(reader, revision);
+ Mecha = mechaData;
+ if (revision >= 5)
{
- Username = reader.GetString();
- PlayerId = reader.GetUShort();
- LocalPlanetId = reader.GetInt();
- LocalPlanetPosition = reader.GetFloat3();
- UPosition = reader.GetDouble3();
- Rotation = reader.GetFloat3();
- BodyRotation = reader.GetFloat3();
- Mecha = new MechaData();
- Mecha.Deserialize(reader);
- bool isAppearancePresent = reader.GetBool();
+ var isAppearancePresent = reader.GetBool();
if (isAppearancePresent)
{
- int len = reader.GetInt();
- byte[] data = new byte[len];
+ var len = reader.GetInt();
+ var data = new byte[len];
reader.GetBytes(data, len);
- using (MemoryStream ms = new MemoryStream(data))
- using (BinaryReader br = new BinaryReader(ms))
+ using (var ms = new MemoryStream(data))
+ using (var br = new BinaryReader(ms))
{
Appearance = new MechaAppearance();
Appearance.Init();
Appearance.Import(br);
}
}
- bool isDIYAppearancePresent = reader.GetBool();
+ }
+ if (revision >= 6)
+ {
+ var isDIYAppearancePresent = reader.GetBool();
if (isDIYAppearancePresent)
{
- int len = reader.GetInt();
- byte[] data = new byte[len];
+ var len = reader.GetInt();
+ var data = new byte[len];
reader.GetBytes(data, len);
- using (MemoryStream ms = new MemoryStream(data))
- using (BinaryReader br = new BinaryReader(ms))
+ using (var ms = new MemoryStream(data))
+ using (var br = new BinaryReader(ms))
{
DIYAppearance = new MechaAppearance();
DIYAppearance.Init();
DIYAppearance.Import(br);
}
}
- int DIYItemLen = reader.GetInt();
+ var DIYItemLen = reader.GetInt();
DIYItemId = new int[DIYItemLen];
DIYItemValue = new int[DIYItemLen];
- for(int i = 0; i < DIYItemLen; i++)
+ for (var i = 0; i < DIYItemLen; i++)
{
DIYItemId[i] = reader.GetInt();
DIYItemValue[i] = reader.GetInt();
}
}
-
- // Backward compatiblity for older versions
- public void Import(INetDataReader reader, int revision)
- {
- Username = reader.GetString();
- PlayerId = reader.GetUShort();
- LocalPlanetId = reader.GetInt();
- if (revision < 7)
- {
- // MechaColors is obsoleted by MechaAppearance
- Float4[] mechaColors = new Float4[reader.GetInt()];
- for (int i = 0; i < mechaColors.Length; i++)
- {
- mechaColors[i] = reader.GetFloat4();
- }
- }
- LocalPlanetPosition = reader.GetFloat3();
- UPosition = reader.GetDouble3();
- Rotation = reader.GetFloat3();
- BodyRotation = reader.GetFloat3();
- MechaData mechaData = new();
- mechaData.Import(reader, revision);
- Mecha = mechaData;
- if (revision >= 5)
- {
- bool isAppearancePresent = reader.GetBool();
- if (isAppearancePresent)
- {
- int len = reader.GetInt();
- byte[] data = new byte[len];
- reader.GetBytes(data, len);
- using (MemoryStream ms = new MemoryStream(data))
- using (BinaryReader br = new BinaryReader(ms))
- {
- Appearance = new MechaAppearance();
- Appearance.Init();
- Appearance.Import(br);
- }
- }
- }
- if (revision >= 6)
- {
- bool isDIYAppearancePresent = reader.GetBool();
- if (isDIYAppearancePresent)
- {
- int len = reader.GetInt();
- byte[] data = new byte[len];
- reader.GetBytes(data, len);
- using (MemoryStream ms = new MemoryStream(data))
- using (BinaryReader br = new BinaryReader(ms))
- {
- DIYAppearance = new MechaAppearance();
- DIYAppearance.Init();
- DIYAppearance.Import(br);
- }
- }
- int DIYItemLen = reader.GetInt();
- DIYItemId = new int[DIYItemLen];
- DIYItemValue = new int[DIYItemLen];
- for (int i = 0; i < DIYItemLen; i++)
- {
- DIYItemId[i] = reader.GetInt();
- DIYItemValue[i] = reader.GetInt();
- }
- }
- }
-
- public IPlayerData CreateCopyWithoutMechaData()
- {
- return new PlayerData(PlayerId, LocalPlanetId, Username, LocalPlanetPosition, UPosition, Rotation, BodyRotation);
- }
}
}
diff --git a/NebulaModel/DataStructures/StatisticalSnapshot.cs b/NebulaModel/DataStructures/StatisticalSnapshot.cs
index 9e748af5c..72204cb90 100644
--- a/NebulaModel/DataStructures/StatisticalSnapshot.cs
+++ b/NebulaModel/DataStructures/StatisticalSnapshot.cs
@@ -1,116 +1,121 @@
-using System.Collections.Generic;
+#region
+
+using System.Collections.Generic;
using System.IO;
-namespace NebulaModel.DataStructures
+#endregion
+
+namespace NebulaModel.DataStructures;
+
+public class StatisticalSnapShot
{
- public class StatisticalSnapShot
+ public long CapturedGameTick;
+ public long[] EnergyStored;
+ public long[] HashRegister;
+ public long[] PowerChargingRegister;
+ public long[] PowerConsumptionRegister;
+ public long[] PowerDischargingRegister;
+
+ public long[] PowerGenerationRegister;
+
+ //List of statistical changes for each planet that happend in one gameTick
+ public List[] ProductionChangesPerFactory;
+
+ public StatisticalSnapShot(long gameTick, int numOfActiveFactories)
{
- //List of statistical changes for each planet that happend in one gameTick
- public List[] ProductionChangesPerFactory;
- public long[] PowerGenerationRegister;
- public long[] PowerConsumptionRegister;
- public long[] PowerChargingRegister;
- public long[] PowerDischargingRegister;
- public long[] HashRegister;
- public long CapturedGameTick;
- public long[] EnergyStored;
-
- public StatisticalSnapShot(long gameTick, int numOfActiveFactories)
+ ProductionChangesPerFactory = new List[numOfActiveFactories];
+ for (var i = 0; i < numOfActiveFactories; i++)
{
- ProductionChangesPerFactory = new List[numOfActiveFactories];
- for (int i = 0; i < numOfActiveFactories; i++)
- {
- ProductionChangesPerFactory[i] = new List();
- }
- PowerGenerationRegister = new long[numOfActiveFactories];
- PowerConsumptionRegister = new long[numOfActiveFactories];
- PowerChargingRegister = new long[numOfActiveFactories];
- PowerDischargingRegister = new long[numOfActiveFactories];
- HashRegister = new long[numOfActiveFactories];
- EnergyStored = new long[numOfActiveFactories];
- CapturedGameTick = gameTick;
+ ProductionChangesPerFactory[i] = new List();
}
+ PowerGenerationRegister = new long[numOfActiveFactories];
+ PowerConsumptionRegister = new long[numOfActiveFactories];
+ PowerChargingRegister = new long[numOfActiveFactories];
+ PowerDischargingRegister = new long[numOfActiveFactories];
+ HashRegister = new long[numOfActiveFactories];
+ EnergyStored = new long[numOfActiveFactories];
+ CapturedGameTick = gameTick;
+ }
+
+ public StatisticalSnapShot(BinaryReader br)
+ {
+ CapturedGameTick = br.ReadInt64();
+ var factoryCount = br.ReadInt32();
+
+ ProductionChangesPerFactory = new List[factoryCount];
+ PowerGenerationRegister = new long[factoryCount];
+ PowerConsumptionRegister = new long[factoryCount];
+ PowerChargingRegister = new long[factoryCount];
+ PowerDischargingRegister = new long[factoryCount];
+ EnergyStored = new long[factoryCount];
+ HashRegister = new long[factoryCount];
- public StatisticalSnapShot(BinaryReader br)
+ for (var factoryId = 0; factoryId < factoryCount; factoryId++)
{
- CapturedGameTick = br.ReadInt64();
- int factoryCount = br.ReadInt32();
-
- ProductionChangesPerFactory = new List[factoryCount];
- PowerGenerationRegister = new long[factoryCount];
- PowerConsumptionRegister = new long[factoryCount];
- PowerChargingRegister = new long[factoryCount];
- PowerDischargingRegister = new long[factoryCount];
- EnergyStored = new long[factoryCount];
- HashRegister = new long[factoryCount];
-
- for (int factoryId = 0; factoryId < factoryCount; factoryId++)
+ ProductionChangesPerFactory[factoryId] = new List();
+ var changesCount = br.ReadInt32();
+ for (var changeId = 0; changeId < changesCount; changeId++)
{
- ProductionChangesPerFactory[factoryId] = new List();
- int changesCount = br.ReadInt32();
- for (int changeId = 0; changeId < changesCount; changeId++)
- {
- ProductionChangesPerFactory[factoryId].Add(new ProductionChangeStruct(br));
- }
- PowerGenerationRegister[factoryId] = br.ReadInt64();
- PowerConsumptionRegister[factoryId] = br.ReadInt64();
- PowerChargingRegister[factoryId] = br.ReadInt64();
- PowerDischargingRegister[factoryId] = br.ReadInt64();
- EnergyStored[factoryId] = br.ReadInt64();
- HashRegister[factoryId] = br.ReadInt64();
+ ProductionChangesPerFactory[factoryId].Add(new ProductionChangeStruct(br));
}
+ PowerGenerationRegister[factoryId] = br.ReadInt64();
+ PowerConsumptionRegister[factoryId] = br.ReadInt64();
+ PowerChargingRegister[factoryId] = br.ReadInt64();
+ PowerDischargingRegister[factoryId] = br.ReadInt64();
+ EnergyStored[factoryId] = br.ReadInt64();
+ HashRegister[factoryId] = br.ReadInt64();
}
+ }
- public void Export(BinaryWriter bw)
- {
- bw.Write(CapturedGameTick);
+ public void Export(BinaryWriter bw)
+ {
+ bw.Write(CapturedGameTick);
- //Collect production/consumption statistics from factories
- bw.Write(ProductionChangesPerFactory.Length);
- for (int factoryId = 0; factoryId < ProductionChangesPerFactory.Length; factoryId++)
+ //Collect production/consumption statistics from factories
+ bw.Write(ProductionChangesPerFactory.Length);
+ for (var factoryId = 0; factoryId < ProductionChangesPerFactory.Length; factoryId++)
+ {
+ bw.Write(ProductionChangesPerFactory[factoryId].Count);
+ for (var changeId = 0; changeId < ProductionChangesPerFactory[factoryId].Count; changeId++)
{
- bw.Write(ProductionChangesPerFactory[factoryId].Count);
- for (int changeId = 0; changeId < ProductionChangesPerFactory[factoryId].Count; changeId++)
- {
- ProductionChangesPerFactory[factoryId][changeId].Export(bw);
- }
-
- //Collect info about power system of the factory
- bw.Write(PowerGenerationRegister[factoryId]);
- bw.Write(PowerConsumptionRegister[factoryId]);
- bw.Write(PowerChargingRegister[factoryId]);
- bw.Write(PowerDischargingRegister[factoryId]);
- bw.Write(EnergyStored[factoryId]);
- bw.Write(HashRegister[factoryId]);
+ ProductionChangesPerFactory[factoryId][changeId].Export(bw);
}
+
+ //Collect info about power system of the factory
+ bw.Write(PowerGenerationRegister[factoryId]);
+ bw.Write(PowerConsumptionRegister[factoryId]);
+ bw.Write(PowerChargingRegister[factoryId]);
+ bw.Write(PowerDischargingRegister[factoryId]);
+ bw.Write(EnergyStored[factoryId]);
+ bw.Write(HashRegister[factoryId]);
}
+ }
- public struct ProductionChangeStruct //12 bytes total
- {
- public bool IsProduction; //1-byte
- public ushort ProductId; //2-byte
- public int Amount; //4-byte
+ public struct ProductionChangeStruct //12 bytes total
+ {
+ public bool IsProduction; //1-byte
+ public ushort ProductId; //2-byte
+ public int Amount; //4-byte
- public ProductionChangeStruct(bool isProduction, ushort productId, int amount)
- {
- IsProduction = isProduction;
- ProductId = productId;
- Amount = amount;
- }
+ public ProductionChangeStruct(bool isProduction, ushort productId, int amount)
+ {
+ IsProduction = isProduction;
+ ProductId = productId;
+ Amount = amount;
+ }
- public ProductionChangeStruct(BinaryReader r)
- {
- IsProduction = r.ReadBoolean();
- ProductId = r.ReadUInt16();
- Amount = r.ReadInt32();
- }
+ public ProductionChangeStruct(BinaryReader r)
+ {
+ IsProduction = r.ReadBoolean();
+ ProductId = r.ReadUInt16();
+ Amount = r.ReadInt32();
+ }
- public void Export(BinaryWriter w)
- {
- w.Write(IsProduction);
- w.Write(ProductId);
- w.Write(Amount);
- }
+ public void Export(BinaryWriter w)
+ {
+ w.Write(IsProduction);
+ w.Write(ProductId);
+ w.Write(Amount);
}
}
}
diff --git a/NebulaModel/DataStructures/ToggleSwitch.cs b/NebulaModel/DataStructures/ToggleSwitch.cs
index eb2b78f92..cedc875fd 100644
--- a/NebulaModel/DataStructures/ToggleSwitch.cs
+++ b/NebulaModel/DataStructures/ToggleSwitch.cs
@@ -1,47 +1,50 @@
-using NebulaAPI;
+#region
+
using System;
using System.Threading;
+using NebulaAPI;
+
+#endregion
+
+namespace NebulaModel.DataStructures;
-namespace NebulaModel.DataStructures
+public sealed class ToggleSwitch : IToggle
{
- public sealed class ToggleSwitch : IToggle
+ private int onCount;
+
+ public bool Value => onCount > 0;
+
+ public IDisposable On()
{
- private int onCount;
+ return new Toggle(this, 1);
+ }
- public bool Value => onCount > 0;
+ public static implicit operator bool(ToggleSwitch toggle)
+ {
+ return toggle.Value;
+ }
- public static implicit operator bool(ToggleSwitch toggle)
- {
- return toggle.Value;
- }
+ public Toggle On(bool conditional)
+ {
+ return new Toggle(this, conditional ? 1 : 0);
+ }
- public Toggle On(bool conditional)
- {
- return new Toggle(this, conditional ? 1 : 0);
- }
+ public readonly struct Toggle : IDisposable
+ {
+ private readonly ToggleSwitch value;
+ private readonly int count;
- public IDisposable On()
+ public Toggle(ToggleSwitch value, int count)
{
- return new Toggle(this, 1);
+ this.value = value;
+ this.count = count;
+
+ Interlocked.Add(ref value.onCount, count);
}
- public readonly struct Toggle : IDisposable
+ public void Dispose()
{
- private readonly ToggleSwitch value;
- private readonly int count;
-
- public Toggle(ToggleSwitch value, int count)
- {
- this.value = value;
- this.count = count;
-
- Interlocked.Add(ref value.onCount, count);
- }
-
- public void Dispose()
- {
- Interlocked.Add(ref value.onCount, -count);
- }
+ Interlocked.Add(ref value.onCount, -count);
}
}
}
diff --git a/NebulaModel/Logger/ILogger.cs b/NebulaModel/Logger/ILogger.cs
index 2caea6b15..d013e9f94 100644
--- a/NebulaModel/Logger/ILogger.cs
+++ b/NebulaModel/Logger/ILogger.cs
@@ -1,13 +1,12 @@
-namespace NebulaModel.Logger
+namespace NebulaModel.Logger;
+
+public interface ILogger
{
- public interface ILogger
- {
- void LogDebug(object data);
+ void LogDebug(object data);
- void LogInfo(object data);
+ void LogInfo(object data);
- void LogWarning(object data);
+ void LogWarning(object data);
- void LogError(object data);
- }
+ void LogError(object data);
}
diff --git a/NebulaModel/Logger/Log.cs b/NebulaModel/Logger/Log.cs
index 116e0d95f..db6fb9075 100644
--- a/NebulaModel/Logger/Log.cs
+++ b/NebulaModel/Logger/Log.cs
@@ -1,99 +1,101 @@
-using System;
+#region
+
+using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
using WebSocketSharp;
-namespace NebulaModel.Logger
+#endregion
+
+namespace NebulaModel.Logger;
+
+public static class Log
{
- public static class Log
+ private static ILogger logger;
+ public static string LastInfoMsg { get; set; }
+ public static string LastWarnMsg { get; set; }
+ public static string LastErrorMsg { get; set; }
+
+ public static void Init(ILogger logger)
{
- public static string LastInfoMsg { get; set; }
- public static string LastWarnMsg { get; set; }
- public static string LastErrorMsg { get; set; }
+ Log.logger = logger;
+ }
- private static ILogger logger;
+ [Conditional("DEBUG")]
+ public static void Debug(string message)
+ {
+ logger.LogDebug(message);
+ }
- public static void Init(ILogger logger)
- {
- Log.logger = logger;
- }
+ [Conditional("DEBUG")]
+ public static void Debug(object message)
+ {
+ Debug(message?.ToString());
+ }
- [Conditional("DEBUG")]
- public static void Debug(string message)
- {
- logger.LogDebug(message);
- }
+ public static void Info(string message)
+ {
+ logger.LogInfo(message);
+ LastInfoMsg = message;
+ }
- [Conditional("DEBUG")]
- public static void Debug(object message)
- {
- Debug(message?.ToString());
- }
+ public static void Info(object message)
+ {
+ Info(message?.ToString());
+ }
- public static void Info(string message)
- {
- logger.LogInfo(message);
- LastInfoMsg = message;
- }
+ public static void Warn(string message)
+ {
+ logger.LogWarning(message);
+ }
- public static void Info(object message)
- {
- Info(message?.ToString());
- }
+ public static void Warn(object message)
+ {
+ Warn(message?.ToString());
+ }
- public static void Warn(string message)
- {
- logger.LogWarning(message);
- }
+ public static void WarnInform(string message)
+ {
+ Warn(message);
+ LastWarnMsg = message;
+ }
- public static void Warn(object message)
+ public static void Error(string message)
+ {
+ logger.LogError(message);
+ LastErrorMsg = message;
+ if (UIFatalErrorTip.instance != null)
{
- Warn(message?.ToString());
+ UIFatalErrorTip.instance.ShowError("[Nebula Error] " + message, "");
}
+ }
- public static void WarnInform(string message)
- {
- Warn(message);
- LastWarnMsg = message;
- }
+ public static void Error(Exception ex)
+ {
+ Error(ex?.ToString());
+ }
- public static void Error(string message)
- {
- logger.LogError(message);
- LastErrorMsg = message;
- if (UIFatalErrorTip.instance != null)
- {
- UIFatalErrorTip.instance.ShowError("[Nebula Error] " + message, "");
- }
- }
+ public static void Error(string message, Exception ex)
+ {
+ Error(message);
+ Error(ex);
+ }
- public static void Error(Exception ex)
- {
- Error(ex?.ToString());
- }
+ public static void SocketOutput(LogData data, string _)
+ {
+ var log = data.ToString();
+ var ipv4Regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
+ var ipv6Regex = "([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}";
+ log = Regex.Replace(log, ipv4Regex, "(IPv4 Address)");
+ log = Regex.Replace(log, ipv6Regex, "(IPv6 Address)");
- public static void Error(string message, Exception ex)
+ if (data.Level >= LogLevel.Warn)
{
- Error(message);
- Error(ex);
+ Warn(log);
}
-
- public static void SocketOutput(LogData data, string _)
+ else
{
- string log = data.ToString();
- string ipv4Regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
- string ipv6Regex = "([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}";
- log = Regex.Replace(log, ipv4Regex, "(IPv4 Address)");
- log = Regex.Replace(log, ipv6Regex, "(IPv6 Address)");
-
- if (data.Level >= LogLevel.Warn)
- {
- Warn(log);
- }
- else
- {
- Info(log);
- }
+ Info(log);
}
}
}
diff --git a/NebulaModel/MultiplayerOptions.cs b/NebulaModel/MultiplayerOptions.cs
index 5a26ecb8b..da8d7398b 100644
--- a/NebulaModel/MultiplayerOptions.cs
+++ b/NebulaModel/MultiplayerOptions.cs
@@ -1,173 +1,186 @@
-using BepInEx.Configuration;
-using NebulaAPI;
+#region
+
+using System;
+using System.ComponentModel;
+using BepInEx.Configuration;
using NebulaModel.Attributes;
using NebulaModel.DataStructures;
using NebulaModel.Utils;
-using System;
-using System.ComponentModel;
using UnityEngine;
using UnityEngine.UI;
-namespace NebulaModel
+#endregion
+
+namespace NebulaModel;
+
+[Serializable]
+public class MultiplayerOptions : ICloneable
{
- [System.Serializable]
- public class MultiplayerOptions : ICloneable
- {
- [DisplayName("Nickname")]
- public string Nickname { get; set; } = string.Empty;
+ private const string _ngrokAuthtokenDisplayname = "Ngrok Authtoken";
- [DisplayName("Server Password"), Category("Network")]
- [Description("If provided, this will set a password for your hosted server.")]
- [UIContentType(InputField.ContentType.Password)]
- public string ServerPassword { get; set; } = string.Empty;
+ private bool _streamerMode;
- public string LastClientPassword { get; set; } = string.Empty;
+ [DisplayName("Nickname")] public string Nickname { get; set; } = string.Empty;
- [DisplayName("Host Port"), Category("Network")]
- [UIRange(1, ushort.MaxValue)]
- public ushort HostPort { get; set; } = 8469;
+ [DisplayName("Server Password")]
+ [Category("Network")]
+ [Description("If provided, this will set a password for your hosted server.")]
+ [UIContentType(InputField.ContentType.Password)]
+ public string ServerPassword { get; set; } = string.Empty;
- [DisplayName("Enable UPnp/Pmp Support"), Category("Network")]
- [Description("If enabled, attempt to automatically create a port mapping using UPnp/Pmp (only works if your router has this feature and it is enabled)")]
- public bool EnableUPnpOrPmpSupport { get; set; } = false;
+ public string LastClientPassword { get; set; } = string.Empty;
- [DisplayName("Enable Experimental Ngrok support"), Category("Network")]
- [Description("If enabled, when hosting a server this will automatically download and install the Ngrok client and set up an Ngrok tunnel that provides an address at which the server can be joined")]
- public bool EnableNgrok { get; set; } = false;
+ [DisplayName("Host Port")] [Category("Network")] [UIRange(1, ushort.MaxValue)]
+ public ushort HostPort { get; set; } = 8469;
- private const string _ngrokAuthtokenDisplayname = "Ngrok Authtoken";
- [DisplayName(_ngrokAuthtokenDisplayname), Category("Network")]
- [Description("This is required for Ngrok support and can be obtained by creating a free account at https://ngrok.com/")]
- [UICharacterLimit(49)]
- public string NgrokAuthtoken { get; set; } = string.Empty;
+ [DisplayName("Enable UPnp/Pmp Support")]
+ [Category("Network")]
+ [Description(
+ "If enabled, attempt to automatically create a port mapping using UPnp/Pmp (only works if your router has this feature and it is enabled)")]
+ public bool EnableUPnpOrPmpSupport { get; set; } = false;
- [DisplayName("Ngrok Region"), Category("Network")]
- [Description("Available Regions: us, eu, au, ap, sa, jp, in")]
- public string NgrokRegion { get; set; } = string.Empty;
+ [DisplayName("Enable Experimental Ngrok support")]
+ [Category("Network")]
+ [Description(
+ "If enabled, when hosting a server this will automatically download and install the Ngrok client and set up an Ngrok tunnel that provides an address at which the server can be joined")]
+ public bool EnableNgrok { get; set; } = false;
- [DisplayName("Remember Last IP"), Category("Network")]
- public bool RememberLastIP { get; set; } = true;
+ [DisplayName(_ngrokAuthtokenDisplayname)]
+ [Category("Network")]
+ [Description("This is required for Ngrok support and can be obtained by creating a free account at https://ngrok.com/")]
+ [UICharacterLimit(49)]
+ public string NgrokAuthtoken { get; set; } = string.Empty;
- [DisplayName("Remember Last Client Password"), Category("Network")]
- public bool RememberLastClientPassword { get; set; } = true;
+ [DisplayName("Ngrok Region")] [Category("Network")] [Description("Available Regions: us, eu, au, ap, sa, jp, in")]
+ public string NgrokRegion { get; set; } = string.Empty;
- [DisplayName("Enable Discord RPC (requires restart)"), Category("Network")]
- public bool EnableDiscordRPC { get; set; } = true;
+ [DisplayName("Remember Last IP")] [Category("Network")]
+ public bool RememberLastIP { get; set; } = true;
- [DisplayName("Auto accept Discord join requests"), Category("Network")]
- public bool AutoAcceptDiscordJoinRequests { get; set; } = false;
+ [DisplayName("Remember Last Client Password")] [Category("Network")]
+ public bool RememberLastClientPassword { get; set; } = true;
- [DisplayName("IP Configuration"), Category("Network")]
- [Description("Configure which type of IP should be used by Discord RPC")]
- public IPUtils.IPConfiguration IPConfiguration { get; set; }
+ [DisplayName("Enable Discord RPC (requires restart)")] [Category("Network")]
+ public bool EnableDiscordRPC { get; set; } = true;
- [DisplayName("Cleanup inactive sessions"), Category("Network")]
- [Description("If disabled the underlying networking library will not cleanup inactive connections. This might solve issues with clients randomly disconnecting and hosts having a 'System.ObjectDisposedException'.")]
- public bool CleanupInactiveSessions { get; set; } = false;
+ [DisplayName("Auto accept Discord join requests")] [Category("Network")]
+ public bool AutoAcceptDiscordJoinRequests { get; set; } = false;
- [DisplayName("Show Lobby Hints")]
- public bool ShowLobbyHints { get; set; } = true;
+ [DisplayName("IP Configuration")]
+ [Category("Network")]
+ [Description("Configure which type of IP should be used by Discord RPC")]
+ public IPUtils.IPConfiguration IPConfiguration { get; set; }
- public string LastIP { get; set; } = string.Empty;
+ [DisplayName("Cleanup inactive sessions")]
+ [Category("Network")]
+ [Description(
+ "If disabled the underlying networking library will not cleanup inactive connections. This might solve issues with clients randomly disconnecting and hosts having a 'System.ObjectDisposedException'.")]
+ public bool CleanupInactiveSessions { get; set; } = false;
- [DisplayName("Sync Ups")]
- [Description("If enabled the UPS of each player is synced. This ensures a similar amount of GameTick() calls.")]
- public bool SyncUps { get; set; } = true;
+ [DisplayName("Show Lobby Hints")] public bool ShowLobbyHints { get; set; } = true;
- [DisplayName("Sync Soil")]
- [Description("If enabled the soil count of each players is added together and used as one big pool for everyone. Note that this is a server side setting applied to all clients.")]
- public bool SyncSoil { get; set; } = false;
+ public string LastIP { get; set; } = string.Empty;
- private bool _streamerMode = false;
- [DisplayName("Streamer mode")]
- [Description("If enabled specific personal information like your IP address is hidden from the ingame chat and input fields.")]
- public bool StreamerMode {
- get => _streamerMode;
- set {
- _streamerMode = value;
+ [DisplayName("Sync Ups")]
+ [Description("If enabled the UPS of each player is synced. This ensures a similar amount of GameTick() calls.")]
+ public bool SyncUps { get; set; } = true;
- InputField ngrokAuthTokenInput = GameObject.Find("list/scroll-view/viewport/content/Network/NgrokAuthtoken")?.GetComponentInChildren();
- UpdateInputFieldContentType(ref ngrokAuthTokenInput);
+ [DisplayName("Sync Soil")]
+ [Description(
+ "If enabled the soil count of each players is added together and used as one big pool for everyone. Note that this is a server side setting applied to all clients.")]
+ public bool SyncSoil { get; set; } = false;
- InputField hostIpInput = GameObject.Find("UI Root/Overlay Canvas/Nebula - Multiplayer Menu/Host IP Address/InputField")?.GetComponentInChildren();
- UpdateInputFieldContentType(ref hostIpInput);
- }
+ [DisplayName("Streamer mode")]
+ [Description(
+ "If enabled specific personal information like your IP address is hidden from the ingame chat and input fields.")]
+ public bool StreamerMode
+ {
+ get => _streamerMode;
+ set
+ {
+ _streamerMode = value;
+
+ var ngrokAuthTokenInput = GameObject.Find("list/scroll-view/viewport/content/Network/NgrokAuthtoken")
+ ?.GetComponentInChildren();
+ UpdateInputFieldContentType(ref ngrokAuthTokenInput);
+
+ var hostIpInput = GameObject.Find("UI Root/Overlay Canvas/Nebula - Multiplayer Menu/Host IP Address/InputField")
+ ?.GetComponentInChildren();
+ UpdateInputFieldContentType(ref hostIpInput);
}
+ }
- [DisplayName("Chat Hotkey"), Category("Chat")]
- [Description("Keyboard shortcut to toggle the chat window")]
- public KeyboardShortcut ChatHotkey { get; set; } = new KeyboardShortcut(KeyCode.BackQuote, KeyCode.LeftAlt);
+ [DisplayName("Chat Hotkey")] [Category("Chat")] [Description("Keyboard shortcut to toggle the chat window")]
+ public KeyboardShortcut ChatHotkey { get; set; } = new(KeyCode.BackQuote, KeyCode.LeftAlt);
- [DisplayName("Auto Open Chat"), Category("Chat")]
- [Description("Auto open chat window when receiving message from other players")]
- public bool AutoOpenChat { get; set; } = true;
+ [DisplayName("Auto Open Chat")]
+ [Category("Chat")]
+ [Description("Auto open chat window when receiving message from other players")]
+ public bool AutoOpenChat { get; set; } = true;
- [DisplayName("Show system warn message"), Category("Chat")]
- public bool EnableWarnMessage { get; set; } = true;
+ [DisplayName("Show system warn message")] [Category("Chat")]
+ public bool EnableWarnMessage { get; set; } = true;
- [DisplayName("Show system info message"), Category("Chat")]
- public bool EnableInfoMessage { get; set; } = true;
+ [DisplayName("Show system info message")] [Category("Chat")]
+ public bool EnableInfoMessage { get; set; } = true;
- [DisplayName("Default chat position"), Category("Chat")]
- public ChatPosition DefaultChatPosition { get; set; } = ChatPosition.LeftMiddle;
-
- [DisplayName("Default chat size"), Category("Chat")]
- public ChatSize DefaultChatSize { get; set; } = ChatSize.Medium;
+ [DisplayName("Default chat position")] [Category("Chat")]
+ public ChatPosition DefaultChatPosition { get; set; } = ChatPosition.LeftMiddle;
- [DisplayName("Notification duration"), Category("Chat")]
- [Description("How long should the active message stay on the screen in seconds")]
- public int NotificationDuration { get; set; } = 15;
+ [DisplayName("Default chat size")] [Category("Chat")]
+ public ChatSize DefaultChatSize { get; set; } = ChatSize.Medium;
- [DisplayName("Chat Window Opacity"), Category("Chat")]
- [UIRange(0f, 1.0f, true)]
- public float ChatWindowOpacity { get; set; } = 0.8f;
+ [DisplayName("Notification duration")]
+ [Category("Chat")]
+ [Description("How long should the active message stay on the screen in seconds")]
+ public int NotificationDuration { get; set; } = 15;
- // Detail function group buttons
- public bool PowerGridEnabled { get; set; } = false;
- public bool VeinDistributionEnabled { get; set; } = false;
- public bool SpaceNavigationEnabled { get; set; } = true;
- public bool BuildingWarningEnabled { get; set; } = true;
- public bool BuildingIconEnabled { get; set; } = true;
- public bool GuidingLightEnabled { get; set; } = true;
+ [DisplayName("Chat Window Opacity")] [Category("Chat")] [UIRange(0f, 1.0f, true)]
+ public float ChatWindowOpacity { get; set; } = 0.8f;
- public bool RemoteAccessEnabled { get; set; } = false;
- public string RemoteAccessPassword { get; set; } = "";
- public bool AutoPauseEnabled { get; set; } = true;
+ // Detail function group buttons
+ public bool PowerGridEnabled { get; set; } = false;
+ public bool VeinDistributionEnabled { get; set; } = false;
+ public bool SpaceNavigationEnabled { get; set; } = true;
+ public bool BuildingWarningEnabled { get; set; } = true;
+ public bool BuildingIconEnabled { get; set; } = true;
+ public bool GuidingLightEnabled { get; set; } = true;
+ public bool RemoteAccessEnabled { get; set; } = false;
+ public string RemoteAccessPassword { get; set; } = "";
+ public bool AutoPauseEnabled { get; set; } = true;
- public object Clone()
- {
- return MemberwiseClone();
- }
- private void UpdateInputFieldContentType(ref InputField inputField)
+ public object Clone()
+ {
+ return MemberwiseClone();
+ }
+
+ private void UpdateInputFieldContentType(ref InputField inputField)
+ {
+ if (inputField != null)
{
- if (inputField != null)
+ if (StreamerMode)
{
- if (StreamerMode)
- {
- inputField.contentType = InputField.ContentType.Password;
- }
- else
- {
- inputField.contentType = InputField.ContentType.Standard;
- }
- inputField.UpdateLabel();
+ inputField.contentType = InputField.ContentType.Password;
}
- }
-
- public void ModifyInputFieldAtCreation(string displayName, ref InputField inputField)
- {
- switch (displayName)
+ else
{
- case _ngrokAuthtokenDisplayname:
- {
- UpdateInputFieldContentType(ref inputField);
- break;
- }
+ inputField.contentType = InputField.ContentType.Standard;
}
-
+ inputField.UpdateLabel();
}
+ }
+ public void ModifyInputFieldAtCreation(string displayName, ref InputField inputField)
+ {
+ switch (displayName)
+ {
+ case _ngrokAuthtokenDisplayname:
+ {
+ UpdateInputFieldContentType(ref inputField);
+ break;
+ }
+ }
}
}
diff --git a/NebulaModel/NebulaModel.csproj b/NebulaModel/NebulaModel.csproj
index 336c618cd..9a118cda4 100644
--- a/NebulaModel/NebulaModel.csproj
+++ b/NebulaModel/NebulaModel.csproj
@@ -1,20 +1,20 @@
-
-
-
-
+
+
+
+
-
-
- PreserveNewest
-
-
- PreserveNewest
-
-
+
+
+ PreserveNewest
+
+
+ PreserveNewest
+
+
-
-
-
+
+
+
\ No newline at end of file
diff --git a/NebulaModel/NetworkProvider.cs b/NebulaModel/NetworkProvider.cs
index c517461a7..e14e1da8d 100644
--- a/NebulaModel/NetworkProvider.cs
+++ b/NebulaModel/NetworkProvider.cs
@@ -1,43 +1,46 @@
-using NebulaAPI;
-using NebulaModel.Networking.Serialization;
+#region
+
using System;
+using NebulaAPI;
+using NebulaModel.Networking.Serialization;
+
+#endregion
-namespace NebulaModel
+namespace NebulaModel;
+
+public abstract class NetworkProvider : IDisposable, INetworkProvider
{
- public abstract class NetworkProvider : IDisposable, INetworkProvider
+ protected NetworkProvider(IPlayerManager playerManager)
{
- public NetPacketProcessor PacketProcessor { get; protected set; }
+ PacketProcessor = new NetPacketProcessor();
+ PlayerManager = playerManager;
+ }
- public IPlayerManager PlayerManager { get; }
+ public NetPacketProcessor PacketProcessor { get; protected set; }
- protected NetworkProvider(IPlayerManager playerManager)
- {
- PacketProcessor = new NetPacketProcessor();
- PlayerManager = playerManager;
- }
+ public abstract void Dispose();
- public abstract void Start();
+ public IPlayerManager PlayerManager { get; }
- public abstract void Stop();
+ public abstract void SendPacket(T packet) where T : class, new();
- public abstract void Dispose();
+ public abstract void SendPacketToLocalStar(T packet) where T : class, new();
- public abstract void SendPacket(T packet) where T : class, new();
+ public abstract void SendPacketToLocalPlanet(T packet) where T : class, new();
- public abstract void SendPacketToLocalStar(T packet) where T : class, new();
+ public abstract void SendPacketToPlanet(T packet, int planetId) where T : class, new();
- public abstract void SendPacketToLocalPlanet(T packet) where T : class, new();
+ public abstract void SendPacketToStar(T packet, int starId) where T : class, new();
- public abstract void SendPacketToPlanet(T packet, int planetId) where T : class, new();
+ public abstract void SendPacketExclude(T packet, INebulaConnection exclude)
+ where T : class, new();
- public abstract void SendPacketToStar(T packet, int starId) where T : class, new();
+ public abstract void SendPacketToStarExclude(T packet, int starId, INebulaConnection exclude)
+ where T : class, new();
- public abstract void SendPacketExclude(T packet, INebulaConnection exclude)
- where T : class, new();
+ public abstract void Update();
- public abstract void SendPacketToStarExclude(T packet, int starId, INebulaConnection exclude)
- where T : class, new();
+ public abstract void Start();
- public abstract void Update();
- }
+ public abstract void Stop();
}
diff --git a/NebulaModel/Networking/BinaryUtils.cs b/NebulaModel/Networking/BinaryUtils.cs
index d765cac0a..d72ac3036 100644
--- a/NebulaModel/Networking/BinaryUtils.cs
+++ b/NebulaModel/Networking/BinaryUtils.cs
@@ -1,73 +1,74 @@
-using K4os.Compression.LZ4.Streams;
-using NebulaAPI;
+#region
+
using System;
using System.IO;
+using K4os.Compression.LZ4.Streams;
+using NebulaAPI;
+
+#endregion
-namespace NebulaModel.Networking
+namespace NebulaModel.Networking;
+
+public static class BinaryUtils
{
- public static class BinaryUtils
+ private const int BUFFER_SIZE = 8192;
+
+ public class Writer : IWriterProvider
{
- private const int BUFFER_SIZE = 8192;
+ private readonly BufferedStream bs;
+ private readonly LZ4EncoderStream ls;
+ private readonly MemoryStream ms;
- public class Writer : IWriterProvider
+ public Writer()
{
- private readonly MemoryStream ms;
- private readonly LZ4EncoderStream ls;
- private readonly BufferedStream bs;
- private readonly BinaryWriter bw;
-
- public BinaryWriter BinaryWriter => bw;
+ ms = new MemoryStream();
+ ls = LZ4Stream.Encode(ms);
+ bs = new BufferedStream(ls, BUFFER_SIZE);
+ BinaryWriter = new BinaryWriter(bs);
+ }
- public Writer()
- {
- ms = new MemoryStream();
- ls = LZ4Stream.Encode(ms);
- bs = new BufferedStream(ls, BUFFER_SIZE);
- bw = new BinaryWriter(bs);
- }
+ public BinaryWriter BinaryWriter { get; }
- public void Dispose()
- {
- bw?.Close();
- bs?.Dispose();
- ls?.Dispose();
- ms?.Dispose();
- GC.SuppressFinalize(this);
- }
+ public void Dispose()
+ {
+ BinaryWriter?.Close();
+ bs?.Dispose();
+ ls?.Dispose();
+ ms?.Dispose();
+ GC.SuppressFinalize(this);
+ }
- public byte[] CloseAndGetBytes()
- {
- bw?.Close();
- return ms?.ToArray() ?? Array.Empty();
- }
+ public byte[] CloseAndGetBytes()
+ {
+ BinaryWriter?.Close();
+ return ms?.ToArray() ?? Array.Empty();
}
+ }
- public class Reader : IReaderProvider
+ public class Reader : IReaderProvider
+ {
+ private readonly BufferedStream bs;
+ private readonly LZ4DecoderStream ls;
+
+ public Reader(byte[] bytes)
{
- private readonly MemoryStream ms;
- private readonly LZ4DecoderStream ls;
- private readonly BufferedStream bs;
- private readonly BinaryReader br;
+ MemoryStream = new MemoryStream(bytes);
+ ls = LZ4Stream.Decode(MemoryStream);
+ bs = new BufferedStream(ls, BUFFER_SIZE);
+ BinaryReader = new BinaryReader(bs);
+ }
- public MemoryStream MemoryStream => ms;
- public BinaryReader BinaryReader => br;
+ public MemoryStream MemoryStream { get; }
- public Reader(byte[] bytes)
- {
- ms = new MemoryStream(bytes);
- ls = LZ4Stream.Decode(ms);
- bs = new BufferedStream(ls, BUFFER_SIZE);
- br = new BinaryReader(bs);
- }
+ public BinaryReader BinaryReader { get; }
- public void Dispose()
- {
- br?.Close();
- bs?.Dispose();
- ls?.Dispose();
- ms?.Dispose();
- GC.SuppressFinalize(this);
- }
+ public void Dispose()
+ {
+ BinaryReader?.Close();
+ bs?.Dispose();
+ ls?.Dispose();
+ MemoryStream?.Dispose();
+ GC.SuppressFinalize(this);
}
}
}
diff --git a/NebulaModel/Networking/DelayedPacket.cs b/NebulaModel/Networking/DelayedPacket.cs
index 16e91d812..ea3e214c7 100644
--- a/NebulaModel/Networking/DelayedPacket.cs
+++ b/NebulaModel/Networking/DelayedPacket.cs
@@ -1,16 +1,19 @@
-using System;
+#region
-namespace NebulaModel.Networking
+using System;
+
+#endregion
+
+namespace NebulaModel.Networking;
+
+public struct DelayedPacket
{
- public struct DelayedPacket
- {
- public PendingPacket Packet { get; }
- public DateTime DueTime { get; }
+ public PendingPacket Packet { get; }
+ public DateTime DueTime { get; }
- public DelayedPacket(PendingPacket packet, DateTime dueTime)
- {
- Packet = packet;
- DueTime = dueTime;
- }
+ public DelayedPacket(PendingPacket packet, DateTime dueTime)
+ {
+ Packet = packet;
+ DueTime = dueTime;
}
}
diff --git a/NebulaModel/Networking/DisconnectionReason.cs b/NebulaModel/Networking/DisconnectionReason.cs
index c75e7046d..2b1626de4 100644
--- a/NebulaModel/Networking/DisconnectionReason.cs
+++ b/NebulaModel/Networking/DisconnectionReason.cs
@@ -1,21 +1,20 @@
-namespace NebulaModel.Networking
+namespace NebulaModel.Networking;
+
+public enum DisconnectionReason
{
- public enum DisconnectionReason
- {
- // Websocket Error Codes
- Normal = 1000,
- ProtocolError = 1002,
- InvalidData = 1007,
+ // Websocket Error Codes
+ Normal = 1000,
+ ProtocolError = 1002,
+ InvalidData = 1007,
- // Nebula Specific Error Codes
- HostStillLoading = 2000,
- ClientRequestedDisconnect = 2001,
- ModVersionMismatch = 2002,
- GameVersionMismatch = 2003,
+ // Nebula Specific Error Codes
+ HostStillLoading = 2000,
+ ClientRequestedDisconnect = 2001,
+ ModVersionMismatch = 2002,
+ GameVersionMismatch = 2003,
- // Mod Specific Error Codes
- ModIsMissing = 2500,
- ModIsMissingOnServer = 2501
- }
+ // Mod Specific Error Codes
+ ModIsMissing = 2500,
+ ModIsMissingOnServer = 2501
}
diff --git a/NebulaModel/Networking/IClient.cs b/NebulaModel/Networking/IClient.cs
index fd0cdad1c..0ee488939 100644
--- a/NebulaModel/Networking/IClient.cs
+++ b/NebulaModel/Networking/IClient.cs
@@ -1,9 +1,12 @@
-using System.Net;
+#region
-namespace NebulaModel.Networking
+using System.Net;
+
+#endregion
+
+namespace NebulaModel.Networking;
+
+public interface IClient
{
- public interface IClient
- {
- IPEndPoint ServerEndpoint { get; }
- }
-}
\ No newline at end of file
+ IPEndPoint ServerEndpoint { get; }
+}
diff --git a/NebulaModel/Networking/IServer.cs b/NebulaModel/Networking/IServer.cs
index ed9e68945..d49f21557 100644
--- a/NebulaModel/Networking/IServer.cs
+++ b/NebulaModel/Networking/IServer.cs
@@ -1,11 +1,10 @@
-namespace NebulaModel.Networking
+namespace NebulaModel.Networking;
+
+public interface IServer
{
- public interface IServer
- {
- ushort Port { get; }
- string NgrokAddress { get; }
- bool NgrokActive { get; }
- bool NgrokEnabled { get; }
- string NgrokLastErrorCode { get; }
- }
-}
\ No newline at end of file
+ ushort Port { get; }
+ string NgrokAddress { get; }
+ bool NgrokActive { get; }
+ bool NgrokEnabled { get; }
+ string NgrokLastErrorCode { get; }
+}
diff --git a/NebulaModel/Networking/NebulaConnection.cs b/NebulaModel/Networking/NebulaConnection.cs
index 021e04524..78a89f7f4 100644
--- a/NebulaModel/Networking/NebulaConnection.cs
+++ b/NebulaModel/Networking/NebulaConnection.cs
@@ -1,129 +1,133 @@
-using NebulaAPI;
-using NebulaModel.Logger;
-using NebulaModel.Networking.Serialization;
+#region
+
using System;
using System.Collections.Generic;
using System.Net;
+using System.Text;
+using NebulaAPI;
+using NebulaModel.Logger;
+using NebulaModel.Networking.Serialization;
using WebSocketSharp;
-namespace NebulaModel.Networking
+#endregion
+
+namespace NebulaModel.Networking;
+
+public class NebulaConnection : INebulaConnection
{
- public class NebulaConnection : INebulaConnection
+ private readonly NetPacketProcessor packetProcessor;
+ private readonly EndPoint peerEndpoint;
+ private readonly WebSocket peerSocket;
+ private readonly Queue pendingPackets = new();
+ private bool enable = true;
+
+ public NebulaConnection(WebSocket peerSocket, EndPoint peerEndpoint, NetPacketProcessor packetProcessor)
{
- private readonly EndPoint peerEndpoint;
- private readonly WebSocket peerSocket;
- private readonly NetPacketProcessor packetProcessor;
- private readonly Queue pendingPackets = new Queue();
- private bool enable = true;
+ this.peerEndpoint = peerEndpoint;
+ this.peerSocket = peerSocket;
+ this.packetProcessor = packetProcessor;
+ }
- public bool IsAlive => peerSocket?.IsAlive ?? false;
+ public bool IsAlive => peerSocket?.IsAlive ?? false;
- public NebulaConnection(WebSocket peerSocket, EndPoint peerEndpoint, NetPacketProcessor packetProcessor)
+ public void SendPacket(T packet) where T : class, new()
+ {
+ lock (pendingPackets)
{
- this.peerEndpoint = peerEndpoint;
- this.peerSocket = peerSocket;
- this.packetProcessor = packetProcessor;
+ var rawData = packetProcessor.Write(packet);
+ pendingPackets.Enqueue(rawData);
+ ProcessPacketQueue();
}
+ }
- public void SendPacket(T packet) where T : class, new()
+ public void SendRawPacket(byte[] rawData)
+ {
+ lock (pendingPackets)
{
- lock (pendingPackets)
- {
- byte[] rawData = packetProcessor.Write(packet);
- pendingPackets.Enqueue(rawData);
- ProcessPacketQueue();
- }
+ pendingPackets.Enqueue(rawData);
+ ProcessPacketQueue();
}
+ }
- public void SendRawPacket(byte[] rawData)
- {
- lock (pendingPackets)
- {
- pendingPackets.Enqueue(rawData);
- ProcessPacketQueue();
- }
- }
+ public bool Equals(INebulaConnection connection)
+ {
+ return connection != null && (connection as NebulaConnection).peerEndpoint.Equals(peerEndpoint);
+ }
- private void ProcessPacketQueue()
+ private void ProcessPacketQueue()
+ {
+ if (enable && pendingPackets.Count > 0)
{
- if (enable && pendingPackets.Count > 0)
+ var packet = pendingPackets.Dequeue();
+ if (peerSocket.ReadyState == WebSocketState.Open)
{
- byte[] packet = pendingPackets.Dequeue();
- if (peerSocket.ReadyState == WebSocketState.Open)
- {
- peerSocket.SendAsync(packet, OnSendCompleted);
- enable = false;
- }
- else
- {
- Log.Warn($"Cannot send packet to a {peerSocket.ReadyState} connection {peerEndpoint.GetHashCode()}");
- }
+ peerSocket.SendAsync(packet, OnSendCompleted);
+ enable = false;
+ }
+ else
+ {
+ Log.Warn($"Cannot send packet to a {peerSocket.ReadyState} connection {peerEndpoint.GetHashCode()}");
}
}
+ }
- private void OnSendCompleted(bool result)
+ private void OnSendCompleted(bool result)
+ {
+ lock (pendingPackets)
{
- lock (pendingPackets)
- {
- enable = true;
- ProcessPacketQueue();
- }
+ enable = true;
+ ProcessPacketQueue();
}
+ }
- public void Disconnect(DisconnectionReason reason = DisconnectionReason.Normal, string reasonString = null)
+ public void Disconnect(DisconnectionReason reason = DisconnectionReason.Normal, string reasonString = null)
+ {
+ if (string.IsNullOrEmpty(reasonString))
{
- if (string.IsNullOrEmpty(reasonString))
+ peerSocket.Close((ushort)reason);
+ }
+ else
+ {
+ if (Encoding.UTF8.GetBytes(reasonString).Length <= 123)
{
- peerSocket.Close((ushort)reason);
+ peerSocket.Close((ushort)reason, reasonString);
}
else
{
- if (System.Text.Encoding.UTF8.GetBytes(reasonString).Length <= 123)
- {
- peerSocket.Close((ushort)reason, reasonString);
- }
- else
- {
- throw new ArgumentException("Reason string cannot take up more than 123 bytes");
- }
+ throw new ArgumentException("Reason string cannot take up more than 123 bytes");
}
}
+ }
- public static bool operator ==(NebulaConnection left, NebulaConnection right)
- {
- return Equals(left, right);
- }
+ public static bool operator ==(NebulaConnection left, NebulaConnection right)
+ {
+ return Equals(left, right);
+ }
- public static bool operator !=(NebulaConnection left, NebulaConnection right)
- {
- return !Equals(left, right);
- }
+ public static bool operator !=(NebulaConnection left, NebulaConnection right)
+ {
+ return !Equals(left, right);
+ }
- public bool Equals(INebulaConnection connection)
+ public override bool Equals(object obj)
+ {
+ if (obj is null)
{
- return connection != null && (connection as NebulaConnection).peerEndpoint.Equals(peerEndpoint);
+ return false;
}
-
- public override bool Equals(object obj)
+ if (ReferenceEquals(this, obj))
{
- if (obj is null)
- {
- return false;
- }
- if (ReferenceEquals(this, obj))
- {
- return true;
- }
- if (obj.GetType() != GetType())
- {
- return false;
- }
- return (obj as NebulaConnection).peerEndpoint.Equals(peerEndpoint);
+ return true;
}
-
- public override int GetHashCode()
+ if (obj.GetType() != GetType())
{
- return peerEndpoint?.GetHashCode() ?? 0;
+ return false;
}
+ return (obj as NebulaConnection).peerEndpoint.Equals(peerEndpoint);
+ }
+
+ public override int GetHashCode()
+ {
+ return peerEndpoint?.GetHashCode() ?? 0;
}
}
diff --git a/NebulaModel/Networking/PacketUtils.cs b/NebulaModel/Networking/PacketUtils.cs
index 8e1b0d1be..526d6a82b 100644
--- a/NebulaModel/Networking/PacketUtils.cs
+++ b/NebulaModel/Networking/PacketUtils.cs
@@ -1,117 +1,126 @@
+#region
+
+using System;
+using System.Linq;
+using System.Reflection;
using NebulaAPI;
using NebulaModel.Logger;
using NebulaModel.Networking.Serialization;
using NebulaModel.Utils;
-using System;
-using System.Linq;
-using System.Reflection;
-namespace NebulaModel.Networking
+#endregion
+
+namespace NebulaModel.Networking;
+
+public static class PacketUtils
{
- public static class PacketUtils
+ public static void RegisterAllPacketNestedTypesInAssembly(Assembly assembly, NetPacketProcessor packetProcessor)
{
-
- public static void RegisterAllPacketNestedTypesInAssembly(Assembly assembly, NetPacketProcessor packetProcessor)
+ var nestedTypes = AssembliesUtils.GetTypesWithAttributeInAssembly(assembly);
+ var isAPIAssemblies = NebulaModAPI.TargetAssemblies.Contains(assembly);
+ foreach (var type in nestedTypes)
{
- System.Collections.Generic.IEnumerable nestedTypes = AssembliesUtils.GetTypesWithAttributeInAssembly(assembly);
- bool isAPIAssemblies = NebulaModAPI.TargetAssemblies.Contains(assembly);
- foreach (Type type in nestedTypes)
+ if (isAPIAssemblies)
{
- if (isAPIAssemblies)
- {
- Log.Info($"Registering Nested Type: {type.Name}");
- }
- else
- {
- Log.Debug($"Registering Nested Type: {type.Name}");
- }
- if (type.IsClass)
- {
- MethodInfo registerMethod = packetProcessor.GetType().GetMethods()
- .Where(m => m.Name == nameof(NetPacketProcessor.RegisterNestedType))
- .FirstOrDefault(m => m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType.Name.Equals(typeof(Func<>).Name))
- .MakeGenericMethod(type);
+ Log.Info($"Registering Nested Type: {type.Name}");
+ }
+ else
+ {
+ Log.Debug($"Registering Nested Type: {type.Name}");
+ }
+ if (type.IsClass)
+ {
+ var registerMethod = packetProcessor.GetType().GetMethods()
+ .Where(m => m.Name == nameof(NetPacketProcessor.RegisterNestedType))
+ .FirstOrDefault(m =>
+ m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType.Name.Equals(typeof(Func<>).Name))
+ .MakeGenericMethod(type);
- MethodInfo delegateMethod = packetProcessor.GetType().GetMethod(nameof(NetPacketProcessor.CreateNestedClassInstance)).MakeGenericMethod(type);
- Type funcType = typeof(Func<>).MakeGenericType(type);
- Delegate callback = Delegate.CreateDelegate(funcType, packetProcessor, delegateMethod);
- registerMethod.Invoke(packetProcessor, new object[] { callback });
- }
- else if (type.IsValueType)
- {
- MethodInfo method = typeof(NetPacketProcessor).GetMethod(nameof(NetPacketProcessor.RegisterNestedType), Type.EmptyTypes);
- MethodInfo generic = method.MakeGenericMethod(type);
- generic.Invoke(packetProcessor, null);
- }
- else
- {
- Log.Error($"Could not register nested type: {type.Name}. Must be a class or struct.");
- }
+ var delegateMethod = packetProcessor.GetType().GetMethod(nameof(NetPacketProcessor.CreateNestedClassInstance))
+ .MakeGenericMethod(type);
+ var funcType = typeof(Func<>).MakeGenericType(type);
+ var callback = Delegate.CreateDelegate(funcType, packetProcessor, delegateMethod);
+ registerMethod.Invoke(packetProcessor, new object[] { callback });
+ }
+ else if (type.IsValueType)
+ {
+ var method = typeof(NetPacketProcessor).GetMethod(nameof(NetPacketProcessor.RegisterNestedType),
+ Type.EmptyTypes);
+ var generic = method.MakeGenericMethod(type);
+ generic.Invoke(packetProcessor, null);
+ }
+ else
+ {
+ Log.Error($"Could not register nested type: {type.Name}. Must be a class or struct.");
}
}
+ }
- private static bool IsSubclassOfRawGeneric(Type generic, Type toCheck)
+ private static bool IsSubclassOfRawGeneric(Type generic, Type toCheck)
+ {
+ while (toCheck != null && toCheck != typeof(object))
{
- while (toCheck != null && toCheck != typeof(object))
+ var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
+ if (generic == cur)
{
- Type cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
- if (generic == cur)
- {
- return true;
- }
- toCheck = toCheck.BaseType;
+ return true;
}
- return false;
+ toCheck = toCheck.BaseType;
}
+ return false;
+ }
- public static void RegisterAllPacketProcessorsInAssembly(Assembly assembly, NetPacketProcessor packetProcessor, bool isMasterClient)
- {
- System.Collections.Generic.IEnumerable processors = assembly.GetTypes()
- .Where(t => t.GetCustomAttributes(typeof(RegisterPacketProcessorAttribute), true).Length > 0);
+ public static void RegisterAllPacketProcessorsInAssembly(Assembly assembly, NetPacketProcessor packetProcessor,
+ bool isMasterClient)
+ {
+ var processors = assembly.GetTypes()
+ .Where(t => t.GetCustomAttributes(typeof(RegisterPacketProcessorAttribute), true).Length > 0);
- MethodInfo method = packetProcessor.GetType().GetMethods()
- .Where(m => m.Name == nameof(NetPacketProcessor.SubscribeReusable))
- .Where(m => m.IsGenericMethod && m.GetGenericArguments().Length == 2)
- .FirstOrDefault();
+ var method = packetProcessor.GetType().GetMethods()
+ .Where(m => m.Name == nameof(NetPacketProcessor.SubscribeReusable))
+ .Where(m => m.IsGenericMethod && m.GetGenericArguments().Length == 2)
+ .FirstOrDefault();
- bool isAPIAssemblies = NebulaModAPI.TargetAssemblies.Contains(assembly);
- foreach (Type type in processors)
+ var isAPIAssemblies = NebulaModAPI.TargetAssemblies.Contains(assembly);
+ foreach (var type in processors)
+ {
+ if (IsSubclassOfRawGeneric(typeof(BasePacketProcessor<>), type))
{
- if (IsSubclassOfRawGeneric(typeof(BasePacketProcessor<>), type))
+ var packetType = type.BaseType.GetGenericArguments().FirstOrDefault();
+ if (isAPIAssemblies)
{
- Type packetType = type.BaseType.GetGenericArguments().FirstOrDefault();
- if (isAPIAssemblies)
- {
- Log.Info($"Registering {type.Name} to process packet of type: {packetType.Name}");
- }
- else
- {
- Log.Debug($"Registering {type.Name} to process packet of type: {packetType.Name}");
- }
-
- // Create instance of the processor
- Type delegateType = typeof(Action<,>).MakeGenericType(packetType, typeof(INebulaConnection));
- object processor = Activator.CreateInstance(type);
- Delegate callback = Delegate.CreateDelegate(delegateType, processor, type.GetMethod(nameof(BasePacketProcessor