Compare commits
No commits in common. "main" and "feat/litenetlib" have entirely different histories.
main
...
feat/liten
2
.vscode/launch.json
vendored
2
.vscode/launch.json
vendored
@ -6,7 +6,7 @@
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build-client",
|
||||
"program": "${workspaceFolder}/Platforms/Desktop/bin/Debug/net9.0/Pong.dll",
|
||||
"program": "${workspaceFolder}/Platforms/Desktop/bin/Debug/net9.0/Desktop.dll",
|
||||
"args": [],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"stopAtEntry": false,
|
||||
|
2
Engine
2
Engine
@ -1 +1 @@
|
||||
Subproject commit 65dcb0c5647484b02767ac9fbcdb397a820d59f6
|
||||
Subproject commit 83b155fc5e8fd1892278876cb90e10dcb64e2154
|
@ -41,7 +41,7 @@
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../Shared/Shared.csproj" />
|
||||
<ProjectReference Include="..\..\Engine\Engine.Integration\Engine.Integration.Yaml\Engine.Integration.Yaml.csproj" />
|
||||
<ProjectReference Include="..\..\Engine\Engine.Serializers\Engine.Serializers.Yaml\Engine.Serializers.Yaml.csproj" />
|
||||
</ItemGroup>
|
||||
<Target Name="RestoreDotnetTools" BeforeTargets="Restore">
|
||||
<Message Text="Restoring dotnet tools" Importance="High" />
|
||||
|
@ -3,11 +3,11 @@ using System.IO;
|
||||
|
||||
using Microsoft.Xna.Framework.Graphics;
|
||||
|
||||
using Engine.Core;
|
||||
using Engine.Core.Debug;
|
||||
using Engine.Core.Serialization;
|
||||
using Engine.Integration.MonoGame;
|
||||
using Engine.Serializers.Yaml;
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Core.Debug;
|
||||
using Syntriax.Engine.Core.Serialization;
|
||||
using Syntriax.Engine.Integration.MonoGame;
|
||||
using Syntriax.Engine.Serializers.Yaml;
|
||||
|
||||
Universe universe = new();
|
||||
|
||||
@ -19,10 +19,22 @@ ILogger logger = new FileLogger($"Logs/{DateTime.UtcNow:yyyy-MM-dd_HH-mm-ss-ffff
|
||||
logger = new LoggerWrapper(logger, new ConsoleLogger());
|
||||
#endif
|
||||
|
||||
universe.InstantiateUniverseObject().SetUniverseObject("Logger").BehaviourController.AddBehaviour<LoggerContainer>().Logger = ILogger.Shared = logger;
|
||||
universe.InstantiateUniverseObject().SetUniverseObject("Logger").BehaviourController.AddBehaviour<LoggerContainer>().Logger = logger;
|
||||
|
||||
string settingsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "settings.yaml");
|
||||
ClientConfiguration clientConfiguration = GetOrCreateConfiguration(serializer, logger, settingsPath);
|
||||
ClientConfiguration clientConfiguration;
|
||||
try
|
||||
{
|
||||
clientConfiguration = serializer.Deserialize<ClientConfiguration>(File.ReadAllText(settingsPath));
|
||||
logger.Log(clientConfiguration, $"{settingsPath} read");
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
clientConfiguration = new();
|
||||
logger.LogError(serializer, $"Error loading {settingsPath}. Creating new settings file");
|
||||
logger.LogException(serializer, exception);
|
||||
File.WriteAllText(settingsPath, serializer.Serialize(clientConfiguration));
|
||||
}
|
||||
|
||||
if (clientConfiguration.Host)
|
||||
Pong.PongUniverse.ApplyPongServer(universe, clientConfiguration.HostPort);
|
||||
@ -39,36 +51,9 @@ monoGameWindow.Graphics.PreferredBackBufferWidth = clientConfiguration.windowWid
|
||||
monoGameWindow.Graphics.PreferredBackBufferHeight = clientConfiguration.windowHeight;
|
||||
monoGameWindow.Graphics.GraphicsProfile = GraphicsProfile.HiDef;
|
||||
|
||||
universe.FindBehaviour<Engine.Systems.Network.INetworkCommunicatorClient>()?
|
||||
universe.FindBehaviour<Syntriax.Engine.Network.INetworkCommunicatorClient>()?
|
||||
.OnConnectionEstablished.AddOneTimeListener(
|
||||
(sender, connection) => monoGameWindow.Window.Title = $"Client {connection.Id}"
|
||||
);
|
||||
|
||||
monoGameWindow.Run();
|
||||
|
||||
static ClientConfiguration GetOrCreateConfiguration(ISerializer serializer, ILogger logger, string settingsPath)
|
||||
{
|
||||
ClientConfiguration clientConfiguration;
|
||||
|
||||
try
|
||||
{
|
||||
clientConfiguration = serializer.Deserialize<ClientConfiguration>(File.ReadAllText(settingsPath));
|
||||
logger.Log(clientConfiguration, $"Configuration is successfully read");
|
||||
}
|
||||
catch (FileNotFoundException)
|
||||
{
|
||||
clientConfiguration = new();
|
||||
logger.Log(clientConfiguration, $"Configuration does not exist");
|
||||
File.WriteAllText(settingsPath, serializer.Serialize(clientConfiguration));
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
clientConfiguration = new();
|
||||
logger.LogError(clientConfiguration, $"Error loading configuration");
|
||||
logger.LogException(clientConfiguration, exception);
|
||||
File.WriteAllText(settingsPath, serializer.Serialize(clientConfiguration));
|
||||
}
|
||||
|
||||
logger.Log(clientConfiguration, $"Creating new configuration file at {settingsPath}");
|
||||
return clientConfiguration;
|
||||
}
|
||||
|
@ -5,8 +5,8 @@ using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
using Engine.Core;
|
||||
using Engine.Systems.Network;
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Network;
|
||||
|
||||
namespace Server;
|
||||
|
||||
|
@ -1,14 +1,14 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
using Engine.Core;
|
||||
using Engine.Core.Debug;
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Core.Debug;
|
||||
|
||||
Universe universe = new();
|
||||
|
||||
FileLogger fileLogger = new($"Logs/{DateTime.UtcNow:yyyy-MM-dd_HH-mm-ss-ffffff}.log");
|
||||
universe.InstantiateUniverseObject().SetUniverseObject("Logger").BehaviourController
|
||||
.AddBehaviour<LoggerContainer>().Logger = ILogger.Shared = new LoggerWrapper(fileLogger, new ConsoleLogger());
|
||||
.AddBehaviour<LoggerContainer>().Logger = new LoggerWrapper(fileLogger, new ConsoleLogger());
|
||||
|
||||
Pong.PongUniverse.ApplyPongServer(universe, int.Parse(Environment.GetEnvironmentVariable("PORT") ?? "8888"));
|
||||
Pong.PongUniverse.ApplyPongUniverse(universe);
|
||||
|
@ -5,8 +5,6 @@
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>Pong.Platforms.Server</RootNamespace>
|
||||
<AssemblyName>Server</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
19
Pong.sln
19
Pong.sln
@ -25,9 +25,9 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Engine.Integration.MonoGame
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Server", "Platforms\Server\Server.csproj", "{A15263DB-DF65-4A07-8CA1-33A2919501A0}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Engine.Integration.Yaml", "Engine\Engine.Integration\Engine.Integration.Yaml\Engine.Integration.Yaml.csproj", "{79F870AB-249E-4CA0-9DF0-F265514581DF}"
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Engine.Serializers", "Engine.Serializers", "{F1257AE1-A8BC-DE44-CB86-406F1335A1D0}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Engine.Integration.LiteNetLib", "Engine\Engine.Integration\Engine.Integration.LiteNetLib\Engine.Integration.LiteNetLib.csproj", "{7AA22306-772F-45F4-8F30-97EBD1FC124D}"
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Engine.Serializers.Yaml", "Engine\Engine.Serializers\Engine.Serializers.Yaml\Engine.Serializers.Yaml.csproj", "{79F870AB-249E-4CA0-9DF0-F265514581DF}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
@ -147,18 +147,6 @@ Global
|
||||
{79F870AB-249E-4CA0-9DF0-F265514581DF}.Release|x64.Build.0 = Release|Any CPU
|
||||
{79F870AB-249E-4CA0-9DF0-F265514581DF}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{79F870AB-249E-4CA0-9DF0-F265514581DF}.Release|x86.Build.0 = Release|Any CPU
|
||||
{7AA22306-772F-45F4-8F30-97EBD1FC124D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{7AA22306-772F-45F4-8F30-97EBD1FC124D}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{7AA22306-772F-45F4-8F30-97EBD1FC124D}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{7AA22306-772F-45F4-8F30-97EBD1FC124D}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{7AA22306-772F-45F4-8F30-97EBD1FC124D}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{7AA22306-772F-45F4-8F30-97EBD1FC124D}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{7AA22306-772F-45F4-8F30-97EBD1FC124D}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{7AA22306-772F-45F4-8F30-97EBD1FC124D}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{7AA22306-772F-45F4-8F30-97EBD1FC124D}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{7AA22306-772F-45F4-8F30-97EBD1FC124D}.Release|x64.Build.0 = Release|Any CPU
|
||||
{7AA22306-772F-45F4-8F30-97EBD1FC124D}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{7AA22306-772F-45F4-8F30-97EBD1FC124D}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@ -172,6 +160,7 @@ Global
|
||||
{9059393F-4073-9273-0EEC-2B1BA61B620B} = {F7F62670-237A-4C93-A30E-CE661C6FC401}
|
||||
{7CC31BC4-38EE-40F4-BBBA-9FC2F4CF6283} = {9059393F-4073-9273-0EEC-2B1BA61B620B}
|
||||
{A15263DB-DF65-4A07-8CA1-33A2919501A0} = {FECFFD54-338F-4060-9161-1E5770D1DC33}
|
||||
{7AA22306-772F-45F4-8F30-97EBD1FC124D} = {9059393F-4073-9273-0EEC-2B1BA61B620B}
|
||||
{F1257AE1-A8BC-DE44-CB86-406F1335A1D0} = {F7F62670-237A-4C93-A30E-CE661C6FC401}
|
||||
{79F870AB-249E-4CA0-9DF0-F265514581DF} = {F1257AE1-A8BC-DE44-CB86-406F1335A1D0}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
@ -1,15 +1,11 @@
|
||||
using Microsoft.Xna.Framework.Audio;
|
||||
using Microsoft.Xna.Framework.Content;
|
||||
|
||||
using Engine.Core;
|
||||
using Engine.Integration.MonoGame;
|
||||
using Engine.Systems.Network;
|
||||
using Engine.Physics2D;
|
||||
using Engine.Systems.Tween;
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Network;
|
||||
using Syntriax.Engine.Physics2D;
|
||||
using Syntriax.Engine.Systems.Tween;
|
||||
|
||||
namespace Pong.Behaviours;
|
||||
|
||||
public class Ball : Behaviour2D, IFirstFrameUpdate, ILoadContent, IPhysicsUpdate, INetworkEntity,
|
||||
public class Ball : Behaviour2D, IFirstFrameUpdate, IPhysicsUpdate, INetworkEntity,
|
||||
IPacketListenerClient<Ball.BallUpdatePacket>,
|
||||
IPacketListenerClient<Ball.BallResetPacket>
|
||||
{
|
||||
@ -23,8 +19,6 @@ public class Ball : Behaviour2D, IFirstFrameUpdate, ILoadContent, IPhysicsUpdate
|
||||
private INetworkCommunicatorServer? networkServer = null;
|
||||
private ITween? networkTween = null;
|
||||
|
||||
private SoundEffect? bounceSoundEffect = null;
|
||||
|
||||
public void FirstActiveFrame()
|
||||
{
|
||||
BehaviourController.GetRequiredBehaviour<ICollider2D>().OnCollisionDetected.AddListener(OnCollisionDetected);
|
||||
@ -34,11 +28,6 @@ public class Ball : Behaviour2D, IFirstFrameUpdate, ILoadContent, IPhysicsUpdate
|
||||
networkServer = Universe.FindBehaviour<INetworkCommunicatorServer>();
|
||||
}
|
||||
|
||||
public void LoadContent(ContentManager content)
|
||||
{
|
||||
bounceSoundEffect = content.Load<SoundEffect>("Audio/Bounce");
|
||||
}
|
||||
|
||||
public void LaunchBall(Vector2D launchDirection)
|
||||
{
|
||||
ResetBall();
|
||||
@ -70,9 +59,7 @@ public class Ball : Behaviour2D, IFirstFrameUpdate, ILoadContent, IPhysicsUpdate
|
||||
RigidBody.Velocity = information.Detected.Transform.Position.FromTo(information.Detector.Transform.Position).Normalized * RigidBody.Velocity.Magnitude;
|
||||
else
|
||||
RigidBody.Velocity = RigidBody.Velocity.Reflect(information.Normal);
|
||||
|
||||
if (information.Detected.Transform.BehaviourController.GetBehaviour<ScoreWall>() is null)
|
||||
networkServer?.SendToAll(new BallUpdatePacket(this));
|
||||
networkServer?.SendToAll(new BallUpdatePacket(this));
|
||||
}
|
||||
|
||||
public Ball() { }
|
||||
@ -87,9 +74,6 @@ public class Ball : Behaviour2D, IFirstFrameUpdate, ILoadContent, IPhysicsUpdate
|
||||
else
|
||||
Transform.Position = packet.Position;
|
||||
|
||||
if (RigidBody.Velocity.MagnitudeSquared >= .01f)
|
||||
bounceSoundEffect?.Play();
|
||||
|
||||
RigidBody.Velocity = packet.Velocity;
|
||||
physicsEngine2D.StepIndividual(RigidBody, sender.Ping);
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
using Microsoft.Xna.Framework.Input;
|
||||
|
||||
using Engine.Core;
|
||||
using Engine.Integration.MonoGame;
|
||||
using Engine.Systems.Input;
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Integration.MonoGame;
|
||||
using Syntriax.Engine.Systems.Input;
|
||||
|
||||
namespace Pong.Behaviours;
|
||||
|
||||
|
@ -1,9 +1,9 @@
|
||||
using Engine.Core;
|
||||
using Engine.Integration.MonoGame;
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Integration.MonoGame;
|
||||
|
||||
namespace Pong.Behaviours;
|
||||
|
||||
public class DrawableColliderCircle : Engine.Physics2D.Collider2DCircle, IDrawableTriangle
|
||||
public class DrawableColliderCircle : Syntriax.Engine.Physics2D.Collider2DCircle, IDrawableTriangle
|
||||
{
|
||||
private const float CIRCLE_SEGMENT_COUNT = 32f;
|
||||
|
||||
|
@ -1,11 +1,11 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Engine.Core;
|
||||
using Engine.Integration.MonoGame;
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Integration.MonoGame;
|
||||
|
||||
namespace Pong.Behaviours;
|
||||
|
||||
public class DrawableColliderShape : Engine.Physics2D.Collider2DShape, IDrawableTriangle
|
||||
public class DrawableColliderShape : Syntriax.Engine.Physics2D.Collider2DShape, IDrawableTriangle
|
||||
{
|
||||
private readonly IList<Triangle> triangles = [];
|
||||
|
||||
|
@ -1,15 +1,14 @@
|
||||
using Microsoft.Xna.Framework.Content;
|
||||
using Microsoft.Xna.Framework;
|
||||
using Microsoft.Xna.Framework.Graphics;
|
||||
|
||||
using Engine.Core;
|
||||
using Engine.Integration.MonoGame;
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Integration.MonoGame;
|
||||
|
||||
namespace Pong.Behaviours;
|
||||
|
||||
public class Label : Behaviour2D, IDrawableSprite, ILoadContent
|
||||
public class Label : Behaviour2D, IDrawableSprite
|
||||
{
|
||||
public SpriteFont? Font { get; set; } = null;
|
||||
public ColorRGBA Color { get; set; } = new ColorRGBA(255, 255, 255, 255);
|
||||
public int Size { get; set; } = 16;
|
||||
public string Text { get; set; } = string.Empty;
|
||||
|
||||
@ -18,12 +17,7 @@ public class Label : Behaviour2D, IDrawableSprite, ILoadContent
|
||||
if (Font is null)
|
||||
return;
|
||||
|
||||
spriteBatch.DrawString(Font, Text, Transform.Position, Color.ToPreMultipliedColor(), Transform.Rotation, Vector2D.One * .5f, Transform.Scale.Magnitude, SpriteEffects.None, 0f);
|
||||
}
|
||||
|
||||
public void LoadContent(ContentManager content)
|
||||
{
|
||||
Font ??= content.Load<SpriteFont>("UbuntuMono");
|
||||
spriteBatch.DrawString(Font, Text, Transform.Position, Color.White, Transform.Rotation, Vector2D.One * .5f, Transform.Scale.Magnitude, SpriteEffects.None, 0f);
|
||||
}
|
||||
|
||||
public Label() { }
|
||||
|
@ -2,11 +2,11 @@ using System;
|
||||
|
||||
using Microsoft.Xna.Framework.Input;
|
||||
|
||||
using Engine.Core;
|
||||
using Engine.Systems.Network;
|
||||
using Engine.Physics2D;
|
||||
using Engine.Systems.Input;
|
||||
using Engine.Systems.Tween;
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Network;
|
||||
using Syntriax.Engine.Physics2D;
|
||||
using Syntriax.Engine.Systems.Input;
|
||||
using Syntriax.Engine.Systems.Tween;
|
||||
|
||||
namespace Pong.Behaviours;
|
||||
|
||||
@ -61,6 +61,15 @@ public class Paddle(Keys Up, Keys Down, float High, float Low, float Speed) : Be
|
||||
inputs?.RegisterOnRelease(Down, OnDownReleased);
|
||||
}
|
||||
|
||||
protected override void OnFinalize()
|
||||
{
|
||||
inputs?.UnregisterOnPress(Up, OnUpPressed);
|
||||
inputs?.UnregisterOnRelease(Up, OnUpReleased);
|
||||
|
||||
inputs?.UnregisterOnPress(Down, OnDownPressed);
|
||||
inputs?.UnregisterOnRelease(Down, OnDownReleased);
|
||||
}
|
||||
|
||||
private void OnUpPressed(IButtonInputs<Keys> sender, IButtonInputs<Keys>.ButtonCallbackArguments args) { isUpPressed = true; networkClient?.SendToServer(new PaddleKeyStatePacket(this)); }
|
||||
private void OnUpReleased(IButtonInputs<Keys> sender, IButtonInputs<Keys>.ButtonCallbackArguments args) { isUpPressed = false; networkClient?.SendToServer(new PaddleKeyStatePacket(this)); }
|
||||
private void OnDownPressed(IButtonInputs<Keys> sender, IButtonInputs<Keys>.ButtonCallbackArguments args) { isDownPressed = true; networkClient?.SendToServer(new PaddleKeyStatePacket(this)); }
|
||||
|
@ -1,107 +0,0 @@
|
||||
using Microsoft.Xna.Framework.Audio;
|
||||
using Microsoft.Xna.Framework.Content;
|
||||
using Microsoft.Xna.Framework.Input;
|
||||
|
||||
using Engine.Core;
|
||||
using Engine.Core.Debug;
|
||||
using Engine.Integration.MonoGame;
|
||||
using Engine.Systems.Network;
|
||||
using Engine.Systems.Input;
|
||||
using Engine.Systems.Time;
|
||||
using Engine.Systems.Tween;
|
||||
|
||||
namespace Pong.Behaviours;
|
||||
|
||||
public class PongGameStarter : Behaviour, INetworkEntity, IFirstFrameUpdate, ILoadContent,
|
||||
IPacketListenerServer<PongGameStarter.RequestStartPacket>,
|
||||
IPacketListenerClient<PongGameStarter.RequestStartPacket>
|
||||
{
|
||||
private const float START_COUNTDOWN = 3f;
|
||||
|
||||
private INetworkCommunicatorServer? networkServer = null;
|
||||
private INetworkCommunicatorClient? networkClient = null;
|
||||
private ITweenManager? tweenManager = null;
|
||||
private PongManager pongManager = null!;
|
||||
|
||||
private ILogger? logger = null;
|
||||
|
||||
private Label? label = null;
|
||||
private TickerTimer timer = null!;
|
||||
|
||||
private SoundEffectInstance? tickSoundEffect = null;
|
||||
private SoundEffectInstance? startSoundEffect = null;
|
||||
|
||||
public void FirstActiveFrame()
|
||||
{
|
||||
IButtonInputs<Keys>? buttonInputs = Universe.FindBehaviour<IButtonInputs<Keys>>();
|
||||
buttonInputs?.RegisterOnRelease(Keys.Space, (_, _1) => networkClient?.SendToServer(new RequestStartPacket()));
|
||||
|
||||
networkClient = Universe.FindBehaviour<INetworkCommunicatorClient>();
|
||||
networkServer = Universe.FindBehaviour<INetworkCommunicatorServer>();
|
||||
tweenManager = Universe.FindBehaviour<ITweenManager>();
|
||||
pongManager = BehaviourController.GetRequiredBehaviourInParent<PongManager>();
|
||||
label = BehaviourController.GetRequiredBehaviour<Label>();
|
||||
logger = Universe.FindBehaviour<ILogger>();
|
||||
|
||||
if (!BehaviourController.TryGetBehaviour(out timer!))
|
||||
{
|
||||
timer = BehaviourController.AddBehaviour<TickerTimer>();
|
||||
timer.OnStarted.AddListener(OnCountdownStart);
|
||||
timer.OnTick.AddListener(DisplayCountdown);
|
||||
timer.OnStopped.AddListener(StartPong);
|
||||
}
|
||||
}
|
||||
|
||||
public void LoadContent(ContentManager content)
|
||||
{
|
||||
tickSoundEffect = content.Load<SoundEffect>("Audio/TimerTick").CreateInstance();
|
||||
startSoundEffect = content.Load<SoundEffect>("Audio/TimerEnd").CreateInstance();
|
||||
}
|
||||
|
||||
private void OnCountdownStart(IReadOnlyTimer sender)
|
||||
{
|
||||
pongManager.Reset();
|
||||
DisplayCountdown(timer);
|
||||
}
|
||||
|
||||
private void DisplayCountdown(ITicker sender)
|
||||
{
|
||||
tickSoundEffect?.Play();
|
||||
|
||||
if (label != null)
|
||||
{
|
||||
label.Text = $"{START_COUNTDOWN - timer.TickCounter}";
|
||||
label.Color = new ColorRGBA(255, 255, 255, 255);
|
||||
if (tweenManager is not null)
|
||||
label.Color.TweenColor(tweenManager, 1f, new ColorRGBA(255, 255, 255, 0), (x) => label.Color = x);
|
||||
}
|
||||
}
|
||||
|
||||
private void StartPong(IReadOnlyTimer sender)
|
||||
{
|
||||
startSoundEffect?.Play();
|
||||
pongManager.Start();
|
||||
}
|
||||
|
||||
void IPacketListenerServer<RequestStartPacket>.OnServerPacketArrived(IConnection sender, RequestStartPacket packet)
|
||||
{
|
||||
logger?.Log(this, $"{sender} requested start");
|
||||
|
||||
if (pongManager.IsGameInProgress)
|
||||
{
|
||||
logger?.Log(this, $"The game is already in progress");
|
||||
return;
|
||||
}
|
||||
|
||||
timer.Start(START_COUNTDOWN);
|
||||
networkServer?.SendToAll(packet);
|
||||
}
|
||||
|
||||
void IPacketListenerClient<RequestStartPacket>.OnClientPacketArrived(IConnection sender, RequestStartPacket packet)
|
||||
{
|
||||
logger?.Log(this, $"Server is starting the game");
|
||||
timer.Start(START_COUNTDOWN - sender.Ping);
|
||||
}
|
||||
|
||||
private class RequestStartPacket : INetworkPacket;
|
||||
}
|
@ -1,17 +1,16 @@
|
||||
using System;
|
||||
|
||||
using Microsoft.Xna.Framework.Audio;
|
||||
using Microsoft.Xna.Framework.Content;
|
||||
using Microsoft.Xna.Framework.Input;
|
||||
|
||||
using Engine.Core;
|
||||
using Engine.Core.Debug;
|
||||
using Engine.Integration.MonoGame;
|
||||
using Engine.Systems.Network;
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Core.Debug;
|
||||
using Syntriax.Engine.Network;
|
||||
using Syntriax.Engine.Systems.Input;
|
||||
|
||||
namespace Pong.Behaviours;
|
||||
|
||||
public class PongManager : Behaviour, INetworkEntity, IFirstFrameUpdate, ILoadContent,
|
||||
IPacketListenerClient<PongManager.StartPacket>,
|
||||
public class PongManager : Behaviour, INetworkEntity, IFirstFrameUpdate,
|
||||
IPacketListenerServer<PongManager.RequestStartPacket>,
|
||||
IPacketListenerClient<PongManager.ScorePacket>
|
||||
{
|
||||
public Action<PongManager>? OnReset { get; set; } = null;
|
||||
@ -19,78 +18,60 @@ public class PongManager : Behaviour, INetworkEntity, IFirstFrameUpdate, ILoadCo
|
||||
public Action<PongManager>? OnScoreUpdated { get; set; } = null;
|
||||
|
||||
private Random random = new();
|
||||
private Ball ball = null!;
|
||||
|
||||
private INetworkCommunicatorClient? networkClient = null!;
|
||||
private INetworkCommunicatorServer? networkServer = null;
|
||||
private ILogger? logger = null;
|
||||
private SoundEffectInstance? scoreSoundEffect = null;
|
||||
private SoundEffectInstance? gameEndSoundEffect = null;
|
||||
|
||||
public int ScoreLeft { get; private set; } = 0;
|
||||
public int ScoreRight { get; private set; } = 0;
|
||||
public int ScoreSum => ScoreLeft + ScoreRight;
|
||||
|
||||
public int WinScore { get; } = 5;
|
||||
public Ball Ball { get; private set; } = null!;
|
||||
public bool IsGameInProgress { get; private set; } = false;
|
||||
|
||||
public PongManager() => WinScore = 5;
|
||||
public PongManager(int winScore) => WinScore = winScore;
|
||||
|
||||
public void FirstActiveFrame()
|
||||
{
|
||||
Ball = Universe.FindRequiredBehaviour<Ball>();
|
||||
IButtonInputs<Keys>? buttonInputs = Universe.FindBehaviour<IButtonInputs<Keys>>();
|
||||
buttonInputs?.RegisterOnRelease(Keys.Space, (_, _1) => networkClient?.SendToServer(new RequestStartPacket()));
|
||||
|
||||
ball = Universe.FindRequiredBehaviour<Ball>();
|
||||
networkClient = Universe.FindBehaviour<INetworkCommunicatorClient>();
|
||||
networkServer = Universe.FindBehaviour<INetworkCommunicatorServer>();
|
||||
logger = Universe.FindBehaviour<ILogger>();
|
||||
}
|
||||
|
||||
public void LoadContent(ContentManager content)
|
||||
{
|
||||
gameEndSoundEffect = content.Load<SoundEffect>("Audio/Win").CreateInstance();
|
||||
scoreSoundEffect = content.Load<SoundEffect>("Audio/Score").CreateInstance();
|
||||
}
|
||||
|
||||
public void ScoreToLeft()
|
||||
{
|
||||
ScoreLeft++;
|
||||
OnScoreUpdated?.Invoke(this);
|
||||
|
||||
PostScoreUpdate();
|
||||
}
|
||||
|
||||
public void ScoreToRight()
|
||||
{
|
||||
ScoreRight++;
|
||||
OnScoreUpdated?.Invoke(this);
|
||||
|
||||
PostScoreUpdate();
|
||||
}
|
||||
|
||||
public bool Start()
|
||||
{
|
||||
if (networkServer is null)
|
||||
return false;
|
||||
|
||||
if (Ball.RigidBody.Velocity.MagnitudeSquared > 0.01f)
|
||||
return false;
|
||||
|
||||
Reset();
|
||||
IsGameInProgress = true;
|
||||
PostScoreUpdate();
|
||||
networkServer.SendToAll(new StartPacket());
|
||||
logger?.Log(this, $"Game started");
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
ScoreLeft = ScoreRight = 0;
|
||||
IsGameInProgress = false;
|
||||
|
||||
Ball.ResetBall();
|
||||
PostScoreUpdate();
|
||||
|
||||
OnReset?.Invoke(this);
|
||||
}
|
||||
|
||||
private void PostScoreUpdate()
|
||||
{
|
||||
OnScoreUpdated?.Invoke(this);
|
||||
Ball.ResetBall();
|
||||
ball.ResetBall();
|
||||
|
||||
if (networkServer is not null)
|
||||
{
|
||||
@ -101,22 +82,20 @@ public class PongManager : Behaviour, INetworkEntity, IFirstFrameUpdate, ILoadCo
|
||||
int halfwayScore = (int)(WinScore * .5f);
|
||||
if (ScoreLeft > halfwayScore || ScoreRight > halfwayScore)
|
||||
{
|
||||
IsGameInProgress = false;
|
||||
gameEndSoundEffect?.Play();
|
||||
OnFinished?.Invoke(this);
|
||||
logger?.Log(this, $"Game finished: {ScoreLeft} - {ScoreRight}");
|
||||
logger?.Log(this, $"Game finished");
|
||||
return;
|
||||
}
|
||||
|
||||
Ball.LaunchBall(GetBallLaunchDirection());
|
||||
ball.LaunchBall(GetBallLaunchDirection());
|
||||
}
|
||||
|
||||
private Vector2D GetBallLaunchDirection()
|
||||
{
|
||||
const float AllowedRadians = 45f * Engine.Core.Math.DegreeToRadian;
|
||||
const float AllowedRadians = 45f * Syntriax.Engine.Core.Math.DegreeToRadian;
|
||||
float rotation = (float)random.NextDouble() * 2f * AllowedRadians - AllowedRadians;
|
||||
bool isBackwards = (random.Next() % 2) == 1;
|
||||
return Vector2D.Right.Rotate(isBackwards ? rotation + Engine.Core.Math.Pi : rotation);
|
||||
return Vector2D.Right.Rotate(isBackwards ? rotation + Syntriax.Engine.Core.Math.Pi : rotation);
|
||||
}
|
||||
|
||||
void IPacketListenerClient<ScorePacket>.OnClientPacketArrived(IConnection sender, ScorePacket packet)
|
||||
@ -124,21 +103,22 @@ public class PongManager : Behaviour, INetworkEntity, IFirstFrameUpdate, ILoadCo
|
||||
ScoreLeft = packet.Left;
|
||||
ScoreRight = packet.Right;
|
||||
|
||||
PostScoreUpdate();
|
||||
|
||||
if (IsGameInProgress && (ScoreLeft != 0 || ScoreRight != 0))
|
||||
scoreSoundEffect?.Play();
|
||||
|
||||
OnScoreUpdated?.Invoke(this);
|
||||
logger?.Log(this, $"Client score update packet arrived: {packet.Left} - {packet.Right}");
|
||||
}
|
||||
|
||||
void IPacketListenerClient<StartPacket>.OnClientPacketArrived(IConnection sender, StartPacket packet)
|
||||
void IPacketListenerServer<RequestStartPacket>.OnServerPacketArrived(IConnection sender, RequestStartPacket packet)
|
||||
{
|
||||
IsGameInProgress = true;
|
||||
logger?.Log(this, $"{sender} requested start");
|
||||
if (ball.RigidBody.Velocity.MagnitudeSquared > 0.01f)
|
||||
return;
|
||||
|
||||
Reset();
|
||||
ball.LaunchBall(GetBallLaunchDirection());
|
||||
logger?.Log(this, $"Game started");
|
||||
}
|
||||
|
||||
private class StartPacket : INetworkPacket;
|
||||
private class RequestStartPacket : INetworkPacket;
|
||||
private class ScorePacket : INetworkPacket
|
||||
{
|
||||
public int Left { get; set; }
|
||||
|
@ -1,4 +1,7 @@
|
||||
using Engine.Core;
|
||||
using Microsoft.Xna.Framework.Graphics;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Integration.MonoGame;
|
||||
|
||||
namespace Pong.Behaviours;
|
||||
|
||||
@ -10,6 +13,9 @@ public class ScoreLabel(bool IsLeft) : Label, IFirstFrameUpdate
|
||||
|
||||
public void FirstActiveFrame()
|
||||
{
|
||||
MonoGameWindow monoGameWindow = Universe.FindRequiredBehaviour<MonoGameWindowContainer>().Window;
|
||||
Font = monoGameWindow.Content.Load<SpriteFont>("UbuntuMono");
|
||||
|
||||
pongManager = Universe.FindRequiredBehaviour<PongManager>();
|
||||
|
||||
pongManager.OnScoreUpdated += UpdateScores;
|
||||
|
@ -1,7 +1,7 @@
|
||||
using System;
|
||||
|
||||
using Engine.Core;
|
||||
using Engine.Physics2D;
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Physics2D;
|
||||
|
||||
namespace Pong.Behaviours;
|
||||
|
||||
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -13,36 +13,6 @@
|
||||
|
||||
#---------------------------------- Content ---------------------------------#
|
||||
|
||||
#begin Audio/Bounce.wav
|
||||
/importer:WavImporter
|
||||
/processor:SoundEffectProcessor
|
||||
/processorParam:Quality=Best
|
||||
/build:Audio/Bounce.wav
|
||||
|
||||
#begin Audio/Score.wav
|
||||
/importer:WavImporter
|
||||
/processor:SoundEffectProcessor
|
||||
/processorParam:Quality=Best
|
||||
/build:Audio/Score.wav
|
||||
|
||||
#begin Audio/Win.wav
|
||||
/importer:WavImporter
|
||||
/processor:SoundEffectProcessor
|
||||
/processorParam:Quality=Best
|
||||
/build:Audio/Win.wav
|
||||
|
||||
#begin Audio/TimerTick.wav
|
||||
/importer:WavImporter
|
||||
/processor:SoundEffectProcessor
|
||||
/processorParam:Quality=Best
|
||||
/build:Audio/TimerTick.wav
|
||||
|
||||
#begin Audio/TimerEnd.wav
|
||||
/importer:WavImporter
|
||||
/processor:SoundEffectProcessor
|
||||
/processorParam:Quality=Best
|
||||
/build:Audio/TimerEnd.wav
|
||||
|
||||
#begin UbuntuMono.spritefont
|
||||
/importer:FontDescriptionImporter
|
||||
/processor:FontDescriptionProcessor
|
||||
|
12
Shared/Network/Abstract/IConnection.cs
Normal file
12
Shared/Network/Abstract/IConnection.cs
Normal file
@ -0,0 +1,12 @@
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public interface IConnection
|
||||
{
|
||||
string Id { get; }
|
||||
|
||||
float Ping { get; }
|
||||
float RoundTrip { get; }
|
||||
|
||||
int PingMs { get; }
|
||||
int RoundTripMs { get; }
|
||||
}
|
6
Shared/Network/Abstract/IEntityNetworkPacket.cs
Normal file
6
Shared/Network/Abstract/IEntityNetworkPacket.cs
Normal file
@ -0,0 +1,6 @@
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public interface IEntityNetworkPacket : INetworkPacket
|
||||
{
|
||||
string EntityId { get; }
|
||||
}
|
37
Shared/Network/Abstract/INetworkCommunicator.cs
Normal file
37
Shared/Network/Abstract/INetworkCommunicator.cs
Normal file
@ -0,0 +1,37 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public interface INetworkCommunicator
|
||||
{
|
||||
Event<INetworkCommunicator, IConnection> OnConnectionEstablished { get; }
|
||||
Event<INetworkCommunicator, IConnection> OnConnectionAbolished { get; }
|
||||
|
||||
IReadOnlyDictionary<string, IConnection> Connections { get; }
|
||||
|
||||
INetworkCommunicator Stop();
|
||||
|
||||
INetworkCommunicator SubscribeToPackets<T>(Event<IConnection, T>.EventHandler callback);
|
||||
INetworkCommunicator UnsubscribeFromPackets<T>(Event<IConnection, T>.EventHandler callback);
|
||||
}
|
||||
|
||||
public interface INetworkCommunicatorClient : INetworkCommunicator
|
||||
{
|
||||
INetworkCommunicatorClient Connect(string address, int port, string? password = null);
|
||||
|
||||
INetworkCommunicatorClient SendToServer<T>(T packet, PacketDelivery packetDelivery = PacketDelivery.ReliableInOrder) where T : class, new();
|
||||
}
|
||||
|
||||
public interface INetworkCommunicatorServer : INetworkCommunicator
|
||||
{
|
||||
string Password { get; }
|
||||
int MaxConnectionCount { get; }
|
||||
int Port { get; }
|
||||
|
||||
INetworkCommunicatorServer Start(int port, int maxConnectionCount, string? password = null);
|
||||
|
||||
INetworkCommunicatorServer SendToClient<T>(IConnection connection, T packet, PacketDelivery packetDelivery = PacketDelivery.ReliableInOrder) where T : class, new();
|
||||
INetworkCommunicatorServer SendToAll<T>(T packet, PacketDelivery packetDelivery = PacketDelivery.ReliableInOrder) where T : class, new();
|
||||
}
|
5
Shared/Network/Abstract/INetworkEntity.cs
Normal file
5
Shared/Network/Abstract/INetworkEntity.cs
Normal file
@ -0,0 +1,5 @@
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public interface INetworkEntity : IEntity;
|
11
Shared/Network/Abstract/INetworkManager.cs
Normal file
11
Shared/Network/Abstract/INetworkManager.cs
Normal file
@ -0,0 +1,11 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public interface INetworkManager
|
||||
{
|
||||
IReadOnlyDictionary<string, INetworkEntity> NetworkEntities { get; }
|
||||
IBehaviourCollector<INetworkEntity> NetworkEntityCollector { get; }
|
||||
}
|
3
Shared/Network/Abstract/INetworkPacket.cs
Normal file
3
Shared/Network/Abstract/INetworkPacket.cs
Normal file
@ -0,0 +1,3 @@
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public interface INetworkPacket;
|
6
Shared/Network/Abstract/IPacketListenerClient.cs
Normal file
6
Shared/Network/Abstract/IPacketListenerClient.cs
Normal file
@ -0,0 +1,6 @@
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public interface IPacketListenerClient<T> : INetworkEntity
|
||||
{
|
||||
void OnClientPacketArrived(IConnection sender, T packet);
|
||||
}
|
6
Shared/Network/Abstract/IPacketListenerServer.cs
Normal file
6
Shared/Network/Abstract/IPacketListenerServer.cs
Normal file
@ -0,0 +1,6 @@
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public interface IPacketListenerServer<T> : INetworkEntity
|
||||
{
|
||||
void OnServerPacketArrived(IConnection sender, T packet);
|
||||
}
|
9
Shared/Network/Abstract/PacketDelivery.cs
Normal file
9
Shared/Network/Abstract/PacketDelivery.cs
Normal file
@ -0,0 +1,9 @@
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public enum PacketDelivery
|
||||
{
|
||||
ReliableInOrder,
|
||||
ReliableOutOfOrder,
|
||||
UnreliableInOrder,
|
||||
UnreliableOutOfOrder,
|
||||
};
|
89
Shared/Network/LiteNetLib/LiteNetLibClient.cs
Normal file
89
Shared/Network/LiteNetLib/LiteNetLibClient.cs
Normal file
@ -0,0 +1,89 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using LiteNetLib;
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Core.Debug;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public class LiteNetLibClient : LiteNetLibCommunicatorBase, INetworkCommunicatorClient
|
||||
{
|
||||
private readonly NetDataWriter netDataWriter = new();
|
||||
|
||||
private CancellationTokenSource? cancellationTokenSource = null;
|
||||
|
||||
protected override IConnection GetConnection(NetPeer peer) => new LiteNetLibServerConnection(peer);
|
||||
|
||||
public INetworkCommunicatorClient Connect(string address, int port, string? password = null)
|
||||
{
|
||||
if (!UniverseObject.IsInUniverse)
|
||||
throw new($"{nameof(LiteNetLibClient)} must be in an universe to connect");
|
||||
|
||||
password ??= string.Empty;
|
||||
|
||||
// Okay, for some reason sometimes LiteNetLib goes dumb when the server hostname has IPv6 address as well as IPv4
|
||||
// but the client doesn't support IPv6, it still tries to use the v6 unless we explicitly tell the ip to connect to,
|
||||
// which fails to connect... So for the time being I am preferring IPv4 below over IPv6 for clients.
|
||||
// TODO: I think this is something that happens on Linux only? I need to check on Windows as well just to be sure.
|
||||
System.Net.IPAddress[] addresses = System.Net.Dns.GetHostAddresses(address);
|
||||
string connectionAddress = addresses.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork, addresses[0]).ToString();
|
||||
|
||||
logger?.Log(this, $"Connecting to server at '{address}:{port}' with password '{password}'");
|
||||
logger?.Log(this, $"Resolved address for {address}: {connectionAddress}");
|
||||
|
||||
Manager.Start();
|
||||
Manager.Connect(connectionAddress, port, password);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public INetworkCommunicatorClient SendToServer<T>(T packet, PacketDelivery packetDelivery) where T : class, new()
|
||||
{
|
||||
netDataWriter.Reset();
|
||||
netPacketProcessor.Write(netDataWriter, packet);
|
||||
|
||||
switch (packetDelivery)
|
||||
{
|
||||
case PacketDelivery.ReliableInOrder: Manager.FirstPeer.Send(netDataWriter, DeliveryMethod.ReliableOrdered); break;
|
||||
case PacketDelivery.UnreliableInOrder: Manager.FirstPeer.Send(netDataWriter, DeliveryMethod.Sequenced); break;
|
||||
case PacketDelivery.ReliableOutOfOrder: Manager.FirstPeer.Send(netDataWriter, DeliveryMethod.ReliableUnordered); break;
|
||||
case PacketDelivery.UnreliableOutOfOrder: Manager.FirstPeer.Send(netDataWriter, DeliveryMethod.Unreliable); break;
|
||||
default: Manager.FirstPeer.Send(netDataWriter, DeliveryMethod.ReliableOrdered); break;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
protected override void OnEnteredUniverse(IUniverse universe)
|
||||
{
|
||||
base.OnEnteredUniverse(universe);
|
||||
|
||||
cancellationTokenSource = new CancellationTokenSource();
|
||||
PollEvents(cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
protected override void OnExitedUniverse(IUniverse universe)
|
||||
{
|
||||
base.OnExitedUniverse(universe);
|
||||
cancellationTokenSource?.Cancel();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Client needs to send everything as soon as possible so
|
||||
/// the events are polled a separate thread running constantly
|
||||
/// </summary>
|
||||
private async void PollEvents(CancellationToken cancellationToken) => await Task.Run(() =>
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
Manager.PollEvents();
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
}, cancellationToken);
|
||||
}
|
16
Shared/Network/LiteNetLib/LiteNetLibClientConnection.cs
Normal file
16
Shared/Network/LiteNetLib/LiteNetLibClientConnection.cs
Normal file
@ -0,0 +1,16 @@
|
||||
using LiteNetLib;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public record class LiteNetLibClientConnection(NetPeer NetPeer) : IConnection
|
||||
{
|
||||
public string Id { get; } = NetPeer.Id.ToString();
|
||||
|
||||
public float Ping => NetPeer.Ping * .001f;
|
||||
public float RoundTrip => NetPeer.RoundTripTime * .001f;
|
||||
|
||||
public int PingMs => NetPeer.Ping;
|
||||
public int RoundTripMs => NetPeer.RoundTripTime;
|
||||
|
||||
public override string ToString() => $"Connection({Id})";
|
||||
}
|
189
Shared/Network/LiteNetLib/LiteNetLibCommunicatorBase.cs
Normal file
189
Shared/Network/LiteNetLib/LiteNetLibCommunicatorBase.cs
Normal file
@ -0,0 +1,189 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
using LiteNetLib;
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Core.Debug;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public abstract class LiteNetLibCommunicatorBase : Behaviour, INetworkCommunicator
|
||||
{
|
||||
protected readonly NetPacketProcessor netPacketProcessor = new();
|
||||
|
||||
private readonly Dictionary<Type, Event<IConnection, object>> listeners = [];
|
||||
private readonly Dictionary<string, IConnection> _connections = [];
|
||||
|
||||
private readonly Dictionary<int, IConnection> localPeerIdToConnectionDictionary = [];
|
||||
|
||||
protected ILogger? logger = null;
|
||||
|
||||
public IReadOnlyDictionary<string, IConnection> Connections => _connections;
|
||||
public EventBasedNetListener Listener { get; private set; } = null!;
|
||||
public NetManager Manager { get; private set; } = null!;
|
||||
|
||||
public Event<INetworkCommunicator, IConnection> OnConnectionEstablished { get; } = new();
|
||||
public Event<INetworkCommunicator, IConnection> OnConnectionAbolished { get; } = new();
|
||||
|
||||
public INetworkCommunicator Stop()
|
||||
{
|
||||
Manager.Stop();
|
||||
return this;
|
||||
}
|
||||
|
||||
protected override void OnEnteredUniverse(IUniverse universe)
|
||||
{
|
||||
base.OnEnteredUniverse(universe);
|
||||
logger = universe.FindBehaviour<ILogger>();
|
||||
}
|
||||
|
||||
protected override void OnExitedUniverse(IUniverse universe)
|
||||
{
|
||||
base.OnExitedUniverse(universe);
|
||||
logger = null;
|
||||
Stop();
|
||||
}
|
||||
|
||||
protected virtual void OnPacketArrived<T>(T packet, NetPeer peer) where T : INetworkPacket
|
||||
{
|
||||
if (!listeners.TryGetValue(typeof(T), out Event<IConnection, object>? @event))
|
||||
return;
|
||||
|
||||
@event.Invoke(localPeerIdToConnectionDictionary[peer.Id], packet);
|
||||
}
|
||||
|
||||
private void NetworkReceiveEvent(NetPeer peer, NetPacketReader reader, byte channel, DeliveryMethod deliveryMethod)
|
||||
{
|
||||
try { netPacketProcessor.ReadAllPackets(reader, peer); }
|
||||
catch (Exception exception) { logger?.LogException(this, exception, force: true); }
|
||||
}
|
||||
|
||||
protected abstract IConnection GetConnection(NetPeer peer);
|
||||
private void ConnectionEstablished(NetPeer peer)
|
||||
{
|
||||
IConnection connection = GetConnection(peer);
|
||||
|
||||
localPeerIdToConnectionDictionary.Add(peer.Id, connection);
|
||||
_connections.Add(connection.Id, connection);
|
||||
|
||||
logger?.Log(this, $"Connection established with ip '{peer.Address}' and id '{connection.Id}'");
|
||||
OnConnectionEstablished.Invoke(this, connection);
|
||||
}
|
||||
|
||||
|
||||
private void ConnectionAbolished(NetPeer peer, DisconnectInfo disconnectInfo)
|
||||
{
|
||||
if (!localPeerIdToConnectionDictionary.TryGetValue(peer.Id, out var connection))
|
||||
return;
|
||||
|
||||
localPeerIdToConnectionDictionary.Remove(peer.Id);
|
||||
_connections.Remove(connection.Id);
|
||||
|
||||
logger?.Log(this, $"Connection abolished with ip '{peer.Address}' and id '{connection.Id}'");
|
||||
OnConnectionAbolished.Invoke(this, connection);
|
||||
}
|
||||
|
||||
private void SetupPackets()
|
||||
{
|
||||
// Find network packets implementing INetworkPacket
|
||||
IEnumerable<Type> packetTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes())
|
||||
.Where(t => typeof(INetworkPacket).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract && !t.IsGenericType);
|
||||
|
||||
MethodInfo subscribeReusableMethod = typeof(NetPacketProcessor)
|
||||
.GetMethods()
|
||||
.FirstOrDefault(m => m.Name == nameof(NetPacketProcessor.SubscribeReusable) &&
|
||||
m.GetParameters().Length == 1 &&
|
||||
m.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(Action<,>)
|
||||
)!;
|
||||
|
||||
MethodInfo registerNestedTypeMethod = typeof(NetPacketProcessor)
|
||||
.GetMethods()
|
||||
.FirstOrDefault(m => m.Name == nameof(NetPacketProcessor.RegisterNestedType) &&
|
||||
m.GetParameters().Length == 0
|
||||
)!;
|
||||
|
||||
MethodInfo onPacketArrivedMethod = typeof(LiteNetLibCommunicatorBase)
|
||||
.GetMethod(nameof(OnPacketArrived), BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
|
||||
// Register all network packets by calling the methods bellow where T is our found network packet type
|
||||
// NetPacketProcessor.SubscribeReusable<T, NetPeer>(Action<T, NetPeer> onReceive)
|
||||
// NetPacketProcessor.RegisterNestedType<T>()
|
||||
foreach (Type packetType in packetTypes)
|
||||
{
|
||||
if (!packetType.IsClass)
|
||||
{
|
||||
MethodInfo genericRegisterNestedTypeMethod = registerNestedTypeMethod.MakeGenericMethod(packetType);
|
||||
genericRegisterNestedTypeMethod.Invoke(netPacketProcessor, []);
|
||||
continue;
|
||||
}
|
||||
|
||||
MethodInfo genericOnPacketArrivedMethod = onPacketArrivedMethod.MakeGenericMethod(packetType);
|
||||
|
||||
Type delegateType = typeof(Action<,>).MakeGenericType(packetType, typeof(NetPeer));
|
||||
Delegate delegateHandler = Delegate.CreateDelegate(delegateType, this, genericOnPacketArrivedMethod);
|
||||
|
||||
var genericSubscribeReusableMethod = subscribeReusableMethod.MakeGenericMethod(packetType, typeof(NetPeer));
|
||||
genericSubscribeReusableMethod.Invoke(netPacketProcessor, [delegateHandler]);
|
||||
}
|
||||
}
|
||||
|
||||
public LiteNetLibCommunicatorBase()
|
||||
{
|
||||
Listener = new EventBasedNetListener();
|
||||
Manager = new NetManager(Listener);
|
||||
|
||||
Listener.NetworkReceiveEvent += NetworkReceiveEvent;
|
||||
Listener.PeerConnectedEvent += ConnectionEstablished;
|
||||
Listener.PeerDisconnectedEvent += ConnectionAbolished;
|
||||
|
||||
SetupEnginePackets();
|
||||
SetupPackets();
|
||||
}
|
||||
|
||||
private void SetupEnginePackets()
|
||||
{
|
||||
// I know, ugly af. I need to find a better way
|
||||
netPacketProcessor.RegisterNestedType(AABBNetPacker.Write, AABBNetPacker.Read);
|
||||
netPacketProcessor.RegisterNestedType(CircleNetPacker.Write, CircleNetPacker.Read);
|
||||
netPacketProcessor.RegisterNestedType(ColorHSVNetPacker.Write, ColorHSVNetPacker.Read);
|
||||
netPacketProcessor.RegisterNestedType(ColorRGBANetPacker.Write, ColorRGBANetPacker.Read);
|
||||
netPacketProcessor.RegisterNestedType(ColorRGBNetPacker.Write, ColorRGBNetPacker.Read);
|
||||
netPacketProcessor.RegisterNestedType(Line2DEquationNetPacker.Write, Line2DEquationNetPacker.Read);
|
||||
netPacketProcessor.RegisterNestedType(Line2DNetPacker.Write, Line2DNetPacker.Read);
|
||||
netPacketProcessor.RegisterNestedType(Projection1DNetPacker.Write, Projection1DNetPacker.Read);
|
||||
netPacketProcessor.RegisterNestedType(QuaternionNetPacker.Write, QuaternionNetPacker.Read);
|
||||
netPacketProcessor.RegisterNestedType(Shape2DNetPacker.Write, Shape2DNetPacker.Read);
|
||||
netPacketProcessor.RegisterNestedType(TriangleNetPacker.Write, TriangleNetPacker.Read);
|
||||
netPacketProcessor.RegisterNestedType(Vector2DNetPacker.Write, Vector2DNetPacker.Read);
|
||||
netPacketProcessor.RegisterNestedType(Vector3DNetPacker.Write, Vector3DNetPacker.Read);
|
||||
}
|
||||
|
||||
public INetworkCommunicator SubscribeToPackets<T>(Event<IConnection, T>.EventHandler callback)
|
||||
{
|
||||
Type type = typeof(T);
|
||||
if (!listeners.TryGetValue(type, out Event<IConnection, object>? @event))
|
||||
{
|
||||
@event = new();
|
||||
listeners.Add(type, @event);
|
||||
}
|
||||
|
||||
@event.AddListener(EventDelegateWrapper(callback));
|
||||
return this;
|
||||
}
|
||||
|
||||
public INetworkCommunicator UnsubscribeFromPackets<T>(Event<IConnection, T>.EventHandler callback)
|
||||
{
|
||||
Type type = typeof(T);
|
||||
if (!listeners.TryGetValue(type, out Event<IConnection, object>? @event))
|
||||
return this;
|
||||
|
||||
@event.RemoveListener(EventDelegateWrapper(callback));
|
||||
return this;
|
||||
}
|
||||
|
||||
private static Event<IConnection, object>.EventHandler EventDelegateWrapper<T>(Event<IConnection, T>.EventHandler callback) => (sender, @object) => callback.Invoke(sender, (T)@object);
|
||||
}
|
104
Shared/Network/LiteNetLib/LiteNetLibServer.cs
Normal file
104
Shared/Network/LiteNetLib/LiteNetLibServer.cs
Normal file
@ -0,0 +1,104 @@
|
||||
using System.Linq;
|
||||
|
||||
using LiteNetLib;
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Core.Debug;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public class LiteNetLibServer : LiteNetLibCommunicatorBase, INetworkCommunicatorServer
|
||||
{
|
||||
public string Password { get; private set; } = string.Empty;
|
||||
public int MaxConnectionCount { get; private set; } = 2;
|
||||
public int Port { get; private set; } = 8888;
|
||||
|
||||
private readonly NetDataWriter netDataWriter = new();
|
||||
|
||||
public LiteNetLibServer() : this(8888, 2) { }
|
||||
public LiteNetLibServer(int port, int maxConnectionCount) : base()
|
||||
{
|
||||
MaxConnectionCount = maxConnectionCount;
|
||||
Port = port;
|
||||
|
||||
Listener.ConnectionRequestEvent += OnConnectionRequest;
|
||||
}
|
||||
|
||||
protected override IConnection GetConnection(NetPeer peer) => new LiteNetLibClientConnection(peer);
|
||||
|
||||
private void OnConnectionRequest(ConnectionRequest request)
|
||||
{
|
||||
logger?.Log(this, $"Connection request from ip {request.RemoteEndPoint}");
|
||||
logger?.Log(this, $"Current connection count: {Connections.Count}");
|
||||
if (Manager.ConnectedPeersCount < MaxConnectionCount)
|
||||
request.AcceptIfKey(Password);
|
||||
else
|
||||
request.Reject();
|
||||
}
|
||||
|
||||
public INetworkCommunicatorServer Start(int port, int maxConnectionCount, string? password = null)
|
||||
{
|
||||
if (!UniverseObject.IsInUniverse)
|
||||
throw new($"{nameof(LiteNetLibServer)} must be in an universe to start");
|
||||
|
||||
Password = password ?? string.Empty;
|
||||
MaxConnectionCount = maxConnectionCount;
|
||||
Port = port;
|
||||
|
||||
logger?.Log(this, $"Starting server on port '{port}' with password '{Password}' and max connection count '{maxConnectionCount}'");
|
||||
logger?.Log(this, $"Server status: {(Manager.Start(port) ? "Active" : "Failed")}");
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public INetworkCommunicatorServer SendToClient<T>(IConnection connection, T packet, PacketDelivery packetDelivery) where T : class, new()
|
||||
{
|
||||
netDataWriter.Reset();
|
||||
netPacketProcessor.Write(netDataWriter, packet);
|
||||
|
||||
if (Manager.ConnectedPeerList.FirstOrDefault(p => p.Id.CompareTo(connection.Id) == 0) is not NetPeer netPeer)
|
||||
throw new($"Peer {connection} couldn't be found.");
|
||||
|
||||
switch (packetDelivery)
|
||||
{
|
||||
case PacketDelivery.ReliableInOrder: netPeer.Send(netDataWriter, DeliveryMethod.ReliableOrdered); break;
|
||||
case PacketDelivery.UnreliableInOrder: netPeer.Send(netDataWriter, DeliveryMethod.Sequenced); break;
|
||||
case PacketDelivery.ReliableOutOfOrder: netPeer.Send(netDataWriter, DeliveryMethod.ReliableUnordered); break;
|
||||
case PacketDelivery.UnreliableOutOfOrder: netPeer.Send(netDataWriter, DeliveryMethod.Unreliable); break;
|
||||
default: netPeer.Send(netDataWriter, DeliveryMethod.ReliableOrdered); break;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public INetworkCommunicatorServer SendToAll<T>(T packet, PacketDelivery packetDelivery) where T : class, new()
|
||||
{
|
||||
netDataWriter.Reset();
|
||||
netPacketProcessor.Write(netDataWriter, packet);
|
||||
|
||||
switch (packetDelivery)
|
||||
{
|
||||
case PacketDelivery.ReliableInOrder: Manager.SendToAll(netDataWriter, DeliveryMethod.ReliableOrdered); break;
|
||||
case PacketDelivery.UnreliableInOrder: Manager.SendToAll(netDataWriter, DeliveryMethod.Sequenced); break;
|
||||
case PacketDelivery.ReliableOutOfOrder: Manager.SendToAll(netDataWriter, DeliveryMethod.ReliableUnordered); break;
|
||||
case PacketDelivery.UnreliableOutOfOrder: Manager.SendToAll(netDataWriter, DeliveryMethod.Unreliable); break;
|
||||
default: Manager.SendToAll(netDataWriter, DeliveryMethod.ReliableOrdered); break;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
private void PollEvents(IUniverse sender, IUniverse.UpdateArguments args) => Manager.PollEvents();
|
||||
|
||||
protected override void OnEnteredUniverse(IUniverse universe)
|
||||
{
|
||||
base.OnEnteredUniverse(universe);
|
||||
universe.OnPostUpdate.AddListener(PollEvents);
|
||||
}
|
||||
|
||||
protected override void OnExitedUniverse(IUniverse universe)
|
||||
{
|
||||
base.OnExitedUniverse(universe);
|
||||
universe.OnPostUpdate.RemoveListener(PollEvents);
|
||||
}
|
||||
}
|
16
Shared/Network/LiteNetLib/LiteNetLibServerConnection.cs
Normal file
16
Shared/Network/LiteNetLib/LiteNetLibServerConnection.cs
Normal file
@ -0,0 +1,16 @@
|
||||
using LiteNetLib;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public record class LiteNetLibServerConnection(NetPeer NetPeer) : IConnection
|
||||
{
|
||||
public string Id => NetPeer.RemoteId.ToString();
|
||||
|
||||
public float Ping => NetPeer.Ping * .001f;
|
||||
public float RoundTrip => NetPeer.RoundTripTime * .001f;
|
||||
|
||||
public int PingMs => NetPeer.Ping;
|
||||
public int RoundTripMs => NetPeer.RoundTripTime;
|
||||
|
||||
public override string ToString() => $"Connection({Id})";
|
||||
}
|
22
Shared/Network/LiteNetLib/Packers/AABBNetPacker.cs
Normal file
22
Shared/Network/LiteNetLib/Packers/AABBNetPacker.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
internal static class AABBNetPacker
|
||||
{
|
||||
internal static void Write(NetDataWriter writer, AABB data)
|
||||
{
|
||||
Vector2DNetPacker.Write(writer, data.LowerBoundary);
|
||||
Vector2DNetPacker.Write(writer, data.UpperBoundary);
|
||||
}
|
||||
|
||||
internal static AABB Read(NetDataReader reader)
|
||||
{
|
||||
Vector2D lowerBoundary = Vector2DNetPacker.Read(reader);
|
||||
Vector2D upperBoundary = Vector2DNetPacker.Read(reader);
|
||||
|
||||
return new AABB(lowerBoundary, upperBoundary);
|
||||
}
|
||||
}
|
22
Shared/Network/LiteNetLib/Packers/CircleNetPacker.cs
Normal file
22
Shared/Network/LiteNetLib/Packers/CircleNetPacker.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
internal static class CircleNetPacker
|
||||
{
|
||||
internal static void Write(NetDataWriter writer, Circle data)
|
||||
{
|
||||
Vector2DNetPacker.Write(writer, data.Center);
|
||||
writer.Put(data.Radius);
|
||||
}
|
||||
|
||||
internal static Circle Read(NetDataReader reader)
|
||||
{
|
||||
Vector2D center = Vector2DNetPacker.Read(reader);
|
||||
float radius = reader.GetFloat();
|
||||
|
||||
return new Circle(center, radius);
|
||||
}
|
||||
}
|
24
Shared/Network/LiteNetLib/Packers/ColorHSVNetPacker.cs
Normal file
24
Shared/Network/LiteNetLib/Packers/ColorHSVNetPacker.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
internal static class ColorHSVNetPacker
|
||||
{
|
||||
internal static void Write(NetDataWriter writer, ColorHSV data)
|
||||
{
|
||||
writer.Put(data.Hue);
|
||||
writer.Put(data.Saturation);
|
||||
writer.Put(data.Value);
|
||||
}
|
||||
|
||||
internal static ColorHSV Read(NetDataReader reader)
|
||||
{
|
||||
float hue = reader.GetFloat();
|
||||
float saturation = reader.GetFloat();
|
||||
float value = reader.GetFloat();
|
||||
|
||||
return new ColorHSV(hue, saturation, value);
|
||||
}
|
||||
}
|
26
Shared/Network/LiteNetLib/Packers/ColorRGBANetPacker.cs
Normal file
26
Shared/Network/LiteNetLib/Packers/ColorRGBANetPacker.cs
Normal file
@ -0,0 +1,26 @@
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
internal static class ColorRGBANetPacker
|
||||
{
|
||||
internal static void Write(NetDataWriter writer, ColorRGBA data)
|
||||
{
|
||||
writer.Put(data.R);
|
||||
writer.Put(data.G);
|
||||
writer.Put(data.B);
|
||||
writer.Put(data.A);
|
||||
}
|
||||
|
||||
internal static ColorRGBA Read(NetDataReader reader)
|
||||
{
|
||||
byte red = reader.GetByte();
|
||||
byte green = reader.GetByte();
|
||||
byte blue = reader.GetByte();
|
||||
byte alpha = reader.GetByte();
|
||||
|
||||
return new ColorRGBA(red, green, blue, alpha);
|
||||
}
|
||||
}
|
24
Shared/Network/LiteNetLib/Packers/ColorRGBNetPacker.cs
Normal file
24
Shared/Network/LiteNetLib/Packers/ColorRGBNetPacker.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
internal static class ColorRGBNetPacker
|
||||
{
|
||||
internal static void Write(NetDataWriter writer, ColorRGB data)
|
||||
{
|
||||
writer.Put(data.R);
|
||||
writer.Put(data.G);
|
||||
writer.Put(data.B);
|
||||
}
|
||||
|
||||
internal static ColorRGB Read(NetDataReader reader)
|
||||
{
|
||||
byte red = reader.GetByte();
|
||||
byte green = reader.GetByte();
|
||||
byte blue = reader.GetByte();
|
||||
|
||||
return new ColorRGB(red, green, blue);
|
||||
}
|
||||
}
|
22
Shared/Network/LiteNetLib/Packers/Line2DEquationNetPacker.cs
Normal file
22
Shared/Network/LiteNetLib/Packers/Line2DEquationNetPacker.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
internal static class Line2DEquationNetPacker
|
||||
{
|
||||
internal static void Write(NetDataWriter writer, Line2DEquation data)
|
||||
{
|
||||
writer.Put(data.Slope);
|
||||
writer.Put(data.OffsetY);
|
||||
}
|
||||
|
||||
internal static Line2DEquation Read(NetDataReader reader)
|
||||
{
|
||||
float slope = reader.GetFloat();
|
||||
float offsetY = reader.GetFloat();
|
||||
|
||||
return new Line2DEquation(slope, offsetY);
|
||||
}
|
||||
}
|
22
Shared/Network/LiteNetLib/Packers/Line2DNetPacker.cs
Normal file
22
Shared/Network/LiteNetLib/Packers/Line2DNetPacker.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
internal static class Line2DNetPacker
|
||||
{
|
||||
internal static void Write(NetDataWriter writer, Line2D data)
|
||||
{
|
||||
Vector2DNetPacker.Write(writer, data.From);
|
||||
Vector2DNetPacker.Write(writer, data.To);
|
||||
}
|
||||
|
||||
internal static Line2D Read(NetDataReader reader)
|
||||
{
|
||||
Vector2D from = Vector2DNetPacker.Read(reader);
|
||||
Vector2D to = Vector2DNetPacker.Read(reader);
|
||||
|
||||
return new Line2D(from, to);
|
||||
}
|
||||
}
|
22
Shared/Network/LiteNetLib/Packers/Projection1DNetPacker.cs
Normal file
22
Shared/Network/LiteNetLib/Packers/Projection1DNetPacker.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
internal static class Projection1DNetPacker
|
||||
{
|
||||
internal static void Write(NetDataWriter writer, Projection1D data)
|
||||
{
|
||||
writer.Put(data.Min);
|
||||
writer.Put(data.Max);
|
||||
}
|
||||
|
||||
internal static Projection1D Read(NetDataReader reader)
|
||||
{
|
||||
float min = reader.GetFloat();
|
||||
float max = reader.GetFloat();
|
||||
|
||||
return new Projection1D(min, max);
|
||||
}
|
||||
}
|
26
Shared/Network/LiteNetLib/Packers/QuaternionNetPacker.cs
Normal file
26
Shared/Network/LiteNetLib/Packers/QuaternionNetPacker.cs
Normal file
@ -0,0 +1,26 @@
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
internal static class QuaternionNetPacker
|
||||
{
|
||||
internal static void Write(NetDataWriter writer, Quaternion data)
|
||||
{
|
||||
writer.Put(data.X);
|
||||
writer.Put(data.Y);
|
||||
writer.Put(data.Z);
|
||||
writer.Put(data.W);
|
||||
}
|
||||
|
||||
internal static Quaternion Read(NetDataReader reader)
|
||||
{
|
||||
float x = reader.GetFloat();
|
||||
float y = reader.GetFloat();
|
||||
float z = reader.GetFloat();
|
||||
float w = reader.GetFloat();
|
||||
|
||||
return new Quaternion(x, y, z, w);
|
||||
}
|
||||
}
|
28
Shared/Network/LiteNetLib/Packers/Shape2DNetPacker.cs
Normal file
28
Shared/Network/LiteNetLib/Packers/Shape2DNetPacker.cs
Normal file
@ -0,0 +1,28 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
internal static class Shape2DNetPacker
|
||||
{
|
||||
internal static void Write(NetDataWriter writer, Shape2D data)
|
||||
{
|
||||
writer.Put(data.Vertices.Count);
|
||||
foreach (Vector2D vertex in data.Vertices)
|
||||
Vector2DNetPacker.Write(writer, vertex);
|
||||
}
|
||||
|
||||
internal static Shape2D Read(NetDataReader reader)
|
||||
{
|
||||
int verticesCount = reader.GetInt();
|
||||
List<Vector2D> vertices = new(verticesCount);
|
||||
|
||||
for (int i = 0; i < verticesCount; i++)
|
||||
vertices.Add(Vector2DNetPacker.Read(reader));
|
||||
|
||||
return new Shape2D(vertices);
|
||||
}
|
||||
}
|
24
Shared/Network/LiteNetLib/Packers/TriangleNetPacker.cs
Normal file
24
Shared/Network/LiteNetLib/Packers/TriangleNetPacker.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
internal static class TriangleNetPacker
|
||||
{
|
||||
internal static void Write(NetDataWriter writer, Triangle data)
|
||||
{
|
||||
Vector2DNetPacker.Write(writer, data.A);
|
||||
Vector2DNetPacker.Write(writer, data.B);
|
||||
Vector2DNetPacker.Write(writer, data.C);
|
||||
}
|
||||
|
||||
internal static Triangle Read(NetDataReader reader)
|
||||
{
|
||||
Vector2D a = Vector2DNetPacker.Read(reader);
|
||||
Vector2D b = Vector2DNetPacker.Read(reader);
|
||||
Vector2D c = Vector2DNetPacker.Read(reader);
|
||||
|
||||
return new Triangle(a, b, c);
|
||||
}
|
||||
}
|
22
Shared/Network/LiteNetLib/Packers/Vector2DNetPacker.cs
Normal file
22
Shared/Network/LiteNetLib/Packers/Vector2DNetPacker.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
internal static class Vector2DNetPacker
|
||||
{
|
||||
internal static void Write(NetDataWriter writer, Vector2D data)
|
||||
{
|
||||
writer.Put(data.X);
|
||||
writer.Put(data.Y);
|
||||
}
|
||||
|
||||
internal static Vector2D Read(NetDataReader reader)
|
||||
{
|
||||
float x = reader.GetFloat();
|
||||
float y = reader.GetFloat();
|
||||
|
||||
return new Vector2D(x, y);
|
||||
}
|
||||
}
|
24
Shared/Network/LiteNetLib/Packers/Vector3DNetPacker.cs
Normal file
24
Shared/Network/LiteNetLib/Packers/Vector3DNetPacker.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
internal static class Vector3DNetPacker
|
||||
{
|
||||
internal static void Write(NetDataWriter writer, Vector3D data)
|
||||
{
|
||||
writer.Put(data.X);
|
||||
writer.Put(data.Y);
|
||||
writer.Put(data.Z);
|
||||
}
|
||||
|
||||
internal static Vector3D Read(NetDataReader reader)
|
||||
{
|
||||
float x = reader.GetFloat();
|
||||
float y = reader.GetFloat();
|
||||
float z = reader.GetFloat();
|
||||
|
||||
return new Vector3D(x, y, z);
|
||||
}
|
||||
}
|
333
Shared/Network/NetworkManager.cs
Normal file
333
Shared/Network/NetworkManager.cs
Normal file
@ -0,0 +1,333 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
/// <summary>
|
||||
/// Intermediary manager that looks up in it's hierarchy for a <see cref="INetworkCommunicator"/> to route/broadcast it's received packets to their destinations.
|
||||
/// </summary>
|
||||
public class NetworkManager : Behaviour, INetworkManager
|
||||
{
|
||||
private readonly Dictionary<Type, Dictionary<Type, List<MethodInfo>>> clientPacketArrivalMethods = [];
|
||||
private readonly Dictionary<Type, Dictionary<Type, List<MethodInfo>>> serverPacketArrivalMethods = [];
|
||||
|
||||
private readonly Dictionary<Type, Dictionary<string, object>> clientPacketRouters = [];
|
||||
private readonly Dictionary<Type, Dictionary<string, object>> serverPacketRouters = [];
|
||||
|
||||
private readonly List<(Type packetType, Delegate @delegate)> packetRetrievalDelegates = [];
|
||||
|
||||
private readonly Dictionary<Type, MethodInfo> clearRoutesMethods = [];
|
||||
private readonly Dictionary<Type, MethodInfo> registerPacketListenersMethods = [];
|
||||
|
||||
private readonly Dictionary<string, INetworkEntity> _networkEntities = [];
|
||||
public IReadOnlyDictionary<string, INetworkEntity> NetworkEntities => _networkEntities;
|
||||
|
||||
private readonly BehaviourCollector<INetworkEntity> _networkEntityCollector = new();
|
||||
public IBehaviourCollector<INetworkEntity> NetworkEntityCollector => _networkEntityCollector;
|
||||
|
||||
private INetworkCommunicator _networkCommunicator = null!;
|
||||
public INetworkCommunicator NetworkCommunicator
|
||||
{
|
||||
get => _networkCommunicator;
|
||||
set
|
||||
{
|
||||
if (_networkCommunicator == value)
|
||||
return;
|
||||
|
||||
var previousCommunicator = _networkCommunicator;
|
||||
_networkCommunicator = value;
|
||||
|
||||
if (previousCommunicator is not null) UnsubscribeCommunicatorMethods(previousCommunicator);
|
||||
if (_networkCommunicator is not null) SubscribeCommunicatorMethods(_networkCommunicator);
|
||||
}
|
||||
}
|
||||
|
||||
#region Communicator Subscriptions
|
||||
private void SubscribeCommunicatorMethods(INetworkCommunicator networkCommunicator)
|
||||
{
|
||||
MethodInfo subscribeToPacketsMethod = typeof(INetworkCommunicator)
|
||||
.GetMethod(nameof(INetworkCommunicator.SubscribeToPackets), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)!;
|
||||
|
||||
foreach ((Type packetType, Delegate @delegate) in packetRetrievalDelegates)
|
||||
{
|
||||
MethodInfo genericSubscribeMethod = subscribeToPacketsMethod.MakeGenericMethod(packetType);
|
||||
genericSubscribeMethod.Invoke(networkCommunicator, [@delegate]);
|
||||
}
|
||||
}
|
||||
|
||||
private void UnsubscribeCommunicatorMethods(INetworkCommunicator networkCommunicator)
|
||||
{
|
||||
MethodInfo unsubscribeFromPacketsMethod = typeof(INetworkCommunicator)
|
||||
.GetMethod(nameof(INetworkCommunicator.UnsubscribeFromPackets), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)!;
|
||||
|
||||
foreach ((Type packetType, Delegate @delegate) in packetRetrievalDelegates)
|
||||
{
|
||||
MethodInfo genericUnsubscribeMethod = unsubscribeFromPacketsMethod.MakeGenericMethod(packetType);
|
||||
genericUnsubscribeMethod.Invoke(networkCommunicator, [@delegate]);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Packet Routing
|
||||
private void OnPacketReceived<T>(IConnection sender, T entityDataPacket)
|
||||
{
|
||||
if (entityDataPacket is IEntityNetworkPacket entityPacket)
|
||||
RoutePacket(sender, entityDataPacket, entityPacket);
|
||||
else
|
||||
BroadcastPacket(sender, entityDataPacket);
|
||||
}
|
||||
|
||||
private void RoutePacket<T>(IConnection sender, T entityDataPacket, IEntityNetworkPacket entityPacket)
|
||||
{
|
||||
if (NetworkCommunicator is INetworkCommunicatorClient)
|
||||
RoutePacket(clientPacketRouters, entityPacket.EntityId, sender, entityDataPacket);
|
||||
if (NetworkCommunicator is INetworkCommunicatorServer)
|
||||
RoutePacket(serverPacketRouters, entityPacket.EntityId, sender, entityDataPacket);
|
||||
}
|
||||
|
||||
private void BroadcastPacket<T>(IConnection sender, T entityDataPacket)
|
||||
{
|
||||
if (NetworkCommunicator is INetworkCommunicatorClient)
|
||||
BroadcastPacket(clientPacketRouters, sender, entityDataPacket);
|
||||
if (NetworkCommunicator is INetworkCommunicatorServer)
|
||||
BroadcastPacket(serverPacketRouters, sender, entityDataPacket);
|
||||
}
|
||||
|
||||
|
||||
private static void BroadcastPacket<T>(
|
||||
Dictionary<Type, Dictionary<string, object>> packetRouters,
|
||||
IConnection sender,
|
||||
T entityDataPacket)
|
||||
{
|
||||
if (!packetRouters.TryGetValue(entityDataPacket!.GetType(), out Dictionary<string, object>? routers))
|
||||
return;
|
||||
|
||||
foreach ((string behaviourId, object routerEventReference) in routers)
|
||||
{
|
||||
Event<IConnection, T> routerEvent = (Event<IConnection, T>)routerEventReference;
|
||||
routerEvent.Invoke(sender, entityDataPacket!);
|
||||
}
|
||||
}
|
||||
|
||||
private static void RoutePacket<T>(
|
||||
Dictionary<Type, Dictionary<string, object>> packetRouters,
|
||||
string entityId,
|
||||
IConnection sender,
|
||||
T entityDataPacket)
|
||||
{
|
||||
if (!packetRouters.TryGetValue(entityDataPacket!.GetType(), out Dictionary<string, object>? routers))
|
||||
return;
|
||||
|
||||
if (!routers.TryGetValue(entityId, out object? routerEventReference))
|
||||
return;
|
||||
|
||||
Event<IConnection, T> routerEvent = (Event<IConnection, T>)routerEventReference;
|
||||
routerEvent.Invoke(sender, entityDataPacket!);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Packet Routers
|
||||
private void RegisterPacketRoutersFor(
|
||||
INetworkEntity behaviour,
|
||||
Dictionary<Type, Dictionary<string, object>> packetRouters,
|
||||
Dictionary<Type, Dictionary<Type, List<MethodInfo>>> packetArrivalMethods,
|
||||
NetworkType networkType)
|
||||
{
|
||||
if (!packetArrivalMethods.TryGetValue(behaviour.GetType(), out Dictionary<Type, List<MethodInfo>>? arrivalMethods))
|
||||
return;
|
||||
|
||||
foreach ((Type packetType, List<MethodInfo> methods) in arrivalMethods)
|
||||
foreach (MethodInfo receiveMethod in methods)
|
||||
{
|
||||
if (!packetRouters.TryGetValue(packetType, out Dictionary<string, object>? routers))
|
||||
{
|
||||
routers = [];
|
||||
packetRouters.Add(packetType, routers);
|
||||
}
|
||||
|
||||
object packetListenerEvent = CreateEventAndRegister(packetType, behaviour, networkType);
|
||||
routers.Add(behaviour.Id, packetListenerEvent);
|
||||
}
|
||||
}
|
||||
|
||||
private object CreateEventAndRegister(Type packetType, INetworkEntity behaviour, NetworkType networkType)
|
||||
{
|
||||
Type genericEventType = typeof(Event<,>).MakeGenericType(typeof(IConnection), packetType);
|
||||
object packetListenerEvent = Activator.CreateInstance(genericEventType)!;
|
||||
|
||||
if (!registerPacketListenersMethods.TryGetValue(packetType, out MethodInfo? registerPacketListenerMethod))
|
||||
throw new($"{nameof(RegisterPacketListenerEvent)} for {packetType.Name} has not been cached.");
|
||||
|
||||
registerPacketListenerMethod.Invoke(this, [behaviour, packetListenerEvent, networkType]);
|
||||
return packetListenerEvent;
|
||||
}
|
||||
|
||||
private static void RegisterPacketListenerEvent<T>(
|
||||
INetworkEntity behaviour,
|
||||
Event<IConnection, T> packetListenerEvent,
|
||||
NetworkType networkType)
|
||||
{
|
||||
switch (networkType)
|
||||
{
|
||||
case NetworkType.Client: packetListenerEvent.AddListener((sender, packet) => ((IPacketListenerClient<T>)behaviour).OnClientPacketArrived(sender, packet)); break;
|
||||
case NetworkType.Server: packetListenerEvent.AddListener((sender, packet) => ((IPacketListenerServer<T>)behaviour).OnServerPacketArrived(sender, packet)); break;
|
||||
}
|
||||
}
|
||||
|
||||
private void UnregisterPacketRoutersFor(
|
||||
INetworkEntity behaviour,
|
||||
Dictionary<Type, Dictionary<string, object>> packetRouters,
|
||||
Dictionary<Type, Dictionary<Type, List<MethodInfo>>> packetArrivalMethods)
|
||||
{
|
||||
if (!packetArrivalMethods.TryGetValue(behaviour.GetType(), out Dictionary<Type, List<MethodInfo>>? arrivalMethods))
|
||||
return;
|
||||
|
||||
foreach ((Type packetType, List<MethodInfo> methods) in arrivalMethods)
|
||||
{
|
||||
if (!packetRouters.TryGetValue(packetType, out Dictionary<string, object>? routers))
|
||||
continue;
|
||||
|
||||
if (!routers.TryGetValue(behaviour.Id, out object? routerEventReference))
|
||||
continue;
|
||||
|
||||
if (!clearRoutesMethods.TryGetValue(packetType, out MethodInfo? clearRouterMethod))
|
||||
continue;
|
||||
|
||||
clearRouterMethod.Invoke(this, [routerEventReference]);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ClearRouter<T>(object routerEventReference)
|
||||
{
|
||||
Event<IConnection, T> routerEvent = (Event<IConnection, T>)routerEventReference;
|
||||
routerEvent.Clear();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Engine Callbacks
|
||||
private void OnCollected(IBehaviourCollector<INetworkEntity> sender, IBehaviourCollector<INetworkEntity>.BehaviourCollectedArguments args)
|
||||
{
|
||||
INetworkEntity collectedBehaviour = args.BehaviourCollected;
|
||||
|
||||
if (!_networkEntities.TryAdd(collectedBehaviour.Id, collectedBehaviour))
|
||||
throw new($"Unable to add {collectedBehaviour.Id} to {nameof(NetworkManager)}");
|
||||
|
||||
RegisterPacketRoutersFor(collectedBehaviour, clientPacketRouters, clientPacketArrivalMethods, NetworkType.Client);
|
||||
RegisterPacketRoutersFor(collectedBehaviour, serverPacketRouters, serverPacketArrivalMethods, NetworkType.Server);
|
||||
}
|
||||
|
||||
private void OnRemoved(IBehaviourCollector<INetworkEntity> sender, IBehaviourCollector<INetworkEntity>.BehaviourRemovedArguments args)
|
||||
{
|
||||
INetworkEntity removedBehaviour = args.BehaviourRemoved;
|
||||
if (!_networkEntities.Remove(args.BehaviourRemoved.Id))
|
||||
return;
|
||||
|
||||
UnregisterPacketRoutersFor(removedBehaviour, clientPacketRouters, clientPacketArrivalMethods);
|
||||
UnregisterPacketRoutersFor(removedBehaviour, serverPacketRouters, serverPacketArrivalMethods);
|
||||
}
|
||||
|
||||
protected override void OnExitedUniverse(IUniverse universe) => _networkEntityCollector.Unassign();
|
||||
protected override void OnEnteredUniverse(IUniverse universe)
|
||||
{
|
||||
_networkEntityCollector.Assign(universe);
|
||||
NetworkCommunicator = BehaviourController.GetRequiredBehaviourInParent<INetworkCommunicator>();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Initialization
|
||||
public NetworkManager()
|
||||
{
|
||||
CachePacketRetrievalDelegates();
|
||||
CacheRegistrationMethods();
|
||||
CachePacketArrivalMethods();
|
||||
|
||||
_networkEntityCollector.OnCollected.AddListener(OnCollected);
|
||||
_networkEntityCollector.OnRemoved.AddListener(OnRemoved);
|
||||
}
|
||||
|
||||
private void CachePacketRetrievalDelegates()
|
||||
{
|
||||
IEnumerable<Type> packetTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes())
|
||||
.Where(t => typeof(INetworkPacket).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract && !t.IsGenericType);
|
||||
|
||||
MethodInfo onPacketArrivedMethod = GetType()
|
||||
.GetMethod(nameof(OnPacketReceived), BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
|
||||
foreach (Type packetType in packetTypes)
|
||||
{
|
||||
MethodInfo genericOnPacketArrivedMethod = onPacketArrivedMethod.MakeGenericMethod(packetType);
|
||||
|
||||
Type genericDelegateType = typeof(Event<,>.EventHandler).MakeGenericType(typeof(IConnection), packetType);
|
||||
Delegate genericPacketReceivedDelegate = Delegate.CreateDelegate(genericDelegateType, this, genericOnPacketArrivedMethod);
|
||||
|
||||
packetRetrievalDelegates.Add((packetType, genericPacketReceivedDelegate));
|
||||
}
|
||||
}
|
||||
|
||||
private void CacheRegistrationMethods()
|
||||
{
|
||||
CacheRegistrationMethods(registerPacketListenersMethods, nameof(RegisterPacketListenerEvent));
|
||||
CacheRegistrationMethods(clearRoutesMethods, nameof(ClearRouter));
|
||||
}
|
||||
|
||||
private void CacheRegistrationMethods(Dictionary<Type, MethodInfo> registrationMethods, string methodName)
|
||||
{
|
||||
MethodInfo registerPacketMethod = typeof(NetworkManager).GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static)!;
|
||||
foreach ((Type packetType, Delegate @delegate) in packetRetrievalDelegates)
|
||||
{
|
||||
MethodInfo genericMethod = registerPacketMethod.MakeGenericMethod(packetType);
|
||||
registrationMethods.Add(packetType, genericMethod);
|
||||
}
|
||||
}
|
||||
|
||||
private void CachePacketArrivalMethods()
|
||||
{
|
||||
CachePacketArrivalMethods(clientPacketArrivalMethods, typeof(IPacketListenerClient<>), nameof(IPacketListenerClient<INetworkEntity>.OnClientPacketArrived));
|
||||
CachePacketArrivalMethods(serverPacketArrivalMethods, typeof(IPacketListenerServer<>), nameof(IPacketListenerServer<INetworkEntity>.OnServerPacketArrived));
|
||||
}
|
||||
|
||||
private static void CachePacketArrivalMethods(Dictionary<Type, Dictionary<Type, List<MethodInfo>>> packetArrivalMethods, Type listenerType, string packetArrivalMethodName)
|
||||
{
|
||||
foreach (Type listenerClass in GetGenericsWith(listenerType))
|
||||
{
|
||||
Dictionary<Type, List<MethodInfo>> packetRouters = [];
|
||||
packetArrivalMethods.Add(listenerClass, packetRouters);
|
||||
|
||||
foreach (Type packetListener in GetGenericInterfacesWith(listenerType, listenerClass))
|
||||
{
|
||||
Type packetType = packetListener.GetGenericArguments().First();
|
||||
|
||||
List<MethodInfo> arrivalMethods = packetListener
|
||||
.GetMethods()
|
||||
.Where(m => m.Name == packetArrivalMethodName)
|
||||
.ToList();
|
||||
|
||||
packetRouters.Add(packetType, arrivalMethods);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<Type> GetGenericsWith(Type type)
|
||||
=> AppDomain.CurrentDomain
|
||||
.GetAssemblies()
|
||||
.SelectMany(a =>
|
||||
a.GetTypes().Where(
|
||||
t => t.GetInterfaces().Any(
|
||||
i => i.IsGenericType && i.GetGenericTypeDefinition() == type
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
private static IEnumerable<Type> GetGenericInterfacesWith(Type interfaceType, Type type)
|
||||
=> type.GetInterfaces().Where(
|
||||
i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType
|
||||
);
|
||||
#endregion
|
||||
|
||||
private enum NetworkType { Client, Server }
|
||||
}
|
@ -4,12 +4,12 @@ using Microsoft.Xna.Framework.Input;
|
||||
|
||||
using Pong.Behaviours;
|
||||
|
||||
using Engine.Core;
|
||||
using Engine.Core.Factory;
|
||||
using Engine.Integration.MonoGame;
|
||||
using Engine.Systems.Network;
|
||||
using Engine.Physics2D;
|
||||
using Engine.Systems.Tween;
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Core.Factory;
|
||||
using Syntriax.Engine.Integration.MonoGame;
|
||||
using Syntriax.Engine.Network;
|
||||
using Syntriax.Engine.Physics2D;
|
||||
using Syntriax.Engine.Systems.Tween;
|
||||
|
||||
namespace Pong;
|
||||
|
||||
@ -66,11 +66,6 @@ public static class PongUniverse
|
||||
PongManager pongManager = universe.InstantiateUniverseObject().SetUniverseObject("Pong Game Manager")
|
||||
.BehaviourController.AddBehaviour<PongManager>(5);
|
||||
|
||||
universe.InstantiateUniverseObject().SetUniverseObject("Pong Game Starter", parent: pongManager.UniverseObject)
|
||||
.BehaviourController.AddBehaviour<PongGameStarter>()
|
||||
.BehaviourController.AddBehaviour<Transform2D>().SetTransform(position: new Vector2D(-24, 250f), scale: Vector2D.One * .5f)
|
||||
.BehaviourController.AddBehaviour<Label>();
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
universe.InstantiateUniverseObject().SetUniverseObject("Ball")
|
||||
|
@ -2,10 +2,9 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>Pong.Shared</RootNamespace>
|
||||
<AssemblyName>Pong.Shared</AssemblyName>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="LiteNetLib" Version="1.3.1" />
|
||||
<PackageReference Include="MonoGame.Framework.DesktopGL" Version="3.8.2.1105">
|
||||
<PrivateAssets>All</PrivateAssets>
|
||||
</PackageReference>
|
||||
@ -13,6 +12,5 @@
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../Engine/Engine/Engine.csproj" />
|
||||
<ProjectReference Include="../Engine/Engine.Integration/Engine.Integration.MonoGame/Engine.Integration.MonoGame.csproj" />
|
||||
<ProjectReference Include="../Engine/Engine.Integration/Engine.Integration.LiteNetLib/Engine.Integration.LiteNetLib.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
Loading…
x
Reference in New Issue
Block a user