Skip to content

Commit

Permalink
feat: smart broadcasting
Browse files Browse the repository at this point in the history
  • Loading branch information
BlenMiner committed Jan 8, 2024
1 parent 60a9e27 commit a1b13ec
Show file tree
Hide file tree
Showing 38 changed files with 3,184 additions and 31 deletions.
14 changes: 14 additions & 0 deletions 3d-pixels-client/Assets/Prefabs/NetworkManager.prefab
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ GameObject:
- component: {fileID: 6465356862352285968}
- component: {fileID: 7752941384277873744}
- component: {fileID: 2530163867034958643}
- component: {fileID: 4590104621216713435}
m_Layer: 0
m_Name: NetworkManager
m_TagString: Untagged
Expand Down Expand Up @@ -63,3 +64,16 @@ MonoBehaviour:
m_host: 3dpixels.riten.dev
m_port: 443
m_chatClient: {fileID: 0}
--- !u!114 &4590104621216713435
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 34817936119359000}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 04604e790efe5d04081e84e15df00ab4, type: 3}
m_Name:
m_EditorClassIdentifier:
m_client: {fileID: 7752941384277873744}
2 changes: 1 addition & 1 deletion 3d-pixels-client/Assets/Scenes/SampleScene.unity
Original file line number Diff line number Diff line change
Expand Up @@ -1343,7 +1343,7 @@ PrefabInstance:
- target: {fileID: 2530163867034958643, guid: 84488ffec075cd0498e2642533b000e1,
type: 3}
propertyPath: m_useLocalhost
value: 0
value: 1
objectReference: {fileID: 0}
- target: {fileID: 6465356862352285968, guid: 84488ffec075cd0498e2642533b000e1,
type: 3}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
"rootNamespace": "",
"references": [
"GUID:3b5390adca4e2bb4791cb930316d6f3e",
"GUID:6055be8ebefd69e48b49212b09b47b2f"
"GUID:6055be8ebefd69e48b49212b09b47b2f",
"GUID:3a23db0368d05404ea14df190dc23f46",
"GUID:fa83786801a6e0c4cb7945f2ed478186"
],
"includePlatforms": [],
"excludePlatforms": [],
Expand Down
50 changes: 50 additions & 0 deletions 3d-pixels-client/Assets/Scripts/Broadcaster.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using System;
using UnityEngine;

public sealed class Broadcaster : MonoBehaviour, ISendData, IReceiveData
{
static Broadcaster s_instance;

[SerializeField] NetworkClient m_client;

private SessionBroadcaster m_broadcaster;

void Awake()
{
s_instance = this;

m_broadcaster = new SessionBroadcaster(this, this);
}

public event Action<byte[], int, int> OnReceivedData;

private void OnEnable()
{
m_client.OnDataReceived += OnDataReceived;
}

private void OnDisable()
{
m_client.OnDataReceived -= OnDataReceived;
}

private void OnDataReceived(ArraySegment<byte> obj)
{
OnReceivedData?.Invoke(obj.Array, obj.Offset, obj.Count);
}

public void Send(byte[] data, int offset, int size)
{
m_client.Send(new ArraySegment<byte>(data, offset, size));
}

public static void Send<T>(T message) where T : struct, INetworked
{
s_instance.m_broadcaster.Send(message);
}

public static void Register<T>(Action<T> callback) where T : struct, INetworked
{
s_instance.m_broadcaster.Register(callback);
}
}
11 changes: 11 additions & 0 deletions 3d-pixels-client/Assets/Scripts/Broadcaster.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions 3d-pixels-client/Assets/Scripts/GameBootstrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ private void OnEnable()
{
Debug.LogWarning("ChatClient is not set");
}

Test.Speak();
}

private void OnDisable()
Expand All @@ -29,8 +31,8 @@ private void OnDisable()
}

private void OnMessageSubmited(string message)
{
m_client.Send(message);
{
Broadcaster.Send(new MessageA { value = 4269 });
}

private void Start()
Expand Down
7 changes: 4 additions & 3 deletions 3d-pixels-client/Assets/Scripts/NetworkClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@

public class NetworkClient : MonoBehaviour
{
public event Action<ArraySegment<byte>> OnDataReceived;

public bool IsConnected { get; private set; }

private SimpleWebClient m_client;

void Awake()
Expand Down Expand Up @@ -40,9 +43,7 @@ void OnReceivedData(ArraySegment<byte> data)
{
if (data.Array == null) return;

string message = Encoding.UTF8.GetString(data.Array, data.Offset, data.Count);

Debug.Log($"Data from Server: {message}");
OnDataReceived?.Invoke(data);
}

public void Connect(bool wss = false, string host = "localhost", int port = 8080)
Expand Down
5 changes: 3 additions & 2 deletions 3d-pixels-client/Packages/manifest.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"dependencies": {
"com.james-frowen.simplewebtransport": "git+https://github.com/James-Frowen/SimpleWebTransport?path=source",
"com.unity.collab-proxy": "2.2.0",
"com.unity.ide.rider": "3.0.25",
"com.unity.ide.visualstudio": "2.0.21",
Expand All @@ -10,6 +11,7 @@
"com.unity.timeline": "1.7.6",
"com.unity.ugui": "1.0.0",
"com.unity.visualscripting": "1.9.1",
"dev.riten.3dpixels": "file:E:/3DPixels/web-3d-pixels/3d-pixels-server/Shared",
"com.unity.modules.ai": "1.0.0",
"com.unity.modules.androidjni": "1.0.0",
"com.unity.modules.animation": "1.0.0",
Expand Down Expand Up @@ -40,7 +42,6 @@
"com.unity.modules.video": "1.0.0",
"com.unity.modules.vr": "1.0.0",
"com.unity.modules.wind": "1.0.0",
"com.unity.modules.xr": "1.0.0",
"com.james-frowen.simplewebtransport": "git+https://github.com/James-Frowen/SimpleWebTransport?path=source"
"com.unity.modules.xr": "1.0.0"
}
}
6 changes: 6 additions & 0 deletions 3d-pixels-client/Packages/packages-lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,12 @@
},
"url": "https://packages.unity.com"
},
"dev.riten.3dpixels": {
"version": "file:E:/3DPixels/web-3d-pixels/3d-pixels-server/Shared",
"depth": 0,
"source": "local",
"dependencies": {}
},
"com.unity.modules.ai": {
"version": "1.0.0",
"depth": 0,
Expand Down
24 changes: 18 additions & 6 deletions 3d-pixels-client/ProjectSettings/EditorSettings.asset
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,45 @@
--- !u!159 &1
EditorSettings:
m_ObjectHideFlags: 0
serializedVersion: 9
m_ExternalVersionControlSupport: Visible Meta Files
serializedVersion: 12
m_SerializationMode: 2
m_LineEndingsForNewScripts: 2
m_DefaultBehaviorMode: 0
m_PrefabRegularEnvironment: {fileID: 0}
m_PrefabUIEnvironment: {fileID: 0}
m_SpritePackerMode: 0
m_SpritePackerCacheSize: 10
m_SpritePackerPaddingPower: 1
m_Bc7TextureCompressor: 0
m_EtcTextureCompressorBehavior: 1
m_EtcTextureFastCompressor: 1
m_EtcTextureNormalCompressor: 2
m_EtcTextureBestCompressor: 4
m_ProjectGenerationIncludedExtensions: txt;xml;fnt;cd;asmdef;asmref;rsp
m_ProjectGenerationRootNamespace:
m_CollabEditorSettings:
inProgressEnabled: 1
m_EnableTextureStreamingInEditMode: 1
m_EnableTextureStreamingInPlayMode: 1
m_EnableEditorAsyncCPUTextureLoading: 0
m_AsyncShaderCompilation: 1
m_EnterPlayModeOptionsEnabled: 0
m_PrefabModeAllowAutoSave: 1
m_EnterPlayModeOptionsEnabled: 1
m_EnterPlayModeOptions: 3
m_ShowLightmapResolutionOverlay: 1
m_GameObjectNamingDigits: 1
m_GameObjectNamingScheme: 0
m_AssetNamingUsesSpace: 1
m_InspectorUseIMGUIDefaultInspector: 0
m_UseLegacyProbeSampleCount: 0
m_SerializeInlineMappingsOnOneLine: 0
m_DisableCookiesInLightmapper: 1
m_AssetPipelineMode: 1
m_RefreshImportMode: 0
m_CacheServerMode: 0
m_CacheServerEndpoint:
m_CacheServerNamespacePrefix: default
m_CacheServerEnableDownload: 1
m_CacheServerEnableUpload: 1
m_CacheServerEnableAuth: 0
m_CacheServerEnableTls: 0
m_CacheServerValidationMode: 2
m_CacheServerDownloadBatchSize: 128
m_EnableEnlightenBakedGI: 0
3 changes: 2 additions & 1 deletion 3d-pixels-client/ProjectSettings/ProjectSettings.asset
Original file line number Diff line number Diff line change
Expand Up @@ -804,7 +804,8 @@ PlayerSettings:
webGLMemoryGeometricGrowthStep: 0.2
webGLMemoryGeometricGrowthCap: 96
webGLPowerPreference: 2
scriptingDefineSymbols: {}
scriptingDefineSymbols:
WebGL: UNITY
additionalCompilerArguments: {}
platformArchitecture: {}
scriptingBackend: {}
Expand Down
1 change: 1 addition & 0 deletions 3d-pixels-server/3d-pixels-server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<RootNamespace>PixelsServer</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

<ItemGroup>
Expand Down
41 changes: 26 additions & 15 deletions 3d-pixels-server/PixelsServerSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

namespace PixelsServer
{
class PixelsServerSession : WsSession
class PixelsServerSession : WsSession, ISendData, IReceiveData
{
private readonly OAuthSecrets m_secrets;

Expand All @@ -15,39 +15,50 @@ class PixelsServerSession : WsSession

private readonly RessourcesCache m_cache;

public event Action<byte[], int, int>? OnReceivedData;

private readonly SessionBroadcaster m_broadcaster;

public PixelsServerSession(WsServer server, RessourcesCache cache, Database db, OAuthSecrets oauthSecrets) : base(server)
{
m_secrets = oauthSecrets;
m_database = db;
m_cache = cache;

m_broadcaster = new SessionBroadcaster(this, this);
m_broadcaster.Register<MessageA>(OnMessageAReceived);
m_broadcaster.Register<MessageB>(OnMessageBReceived);
}

public override void OnWsConnected(HttpRequest request)
private void OnMessageAReceived(MessageA b)
{
Console.WriteLine($"Chat WebSocket session with Id {Id} connected!");
Logger.Log($"Received message A: {b.value}");
}

private void OnMessageBReceived(MessageB b)
{
Logger.Log($"Received message B: {b.value}");
}

// Send invite message
string message = "Please send a message or '!' to disconnect the client!";

SendBinaryAsync(message);
public override void OnWsConnected(HttpRequest request)
{
Console.WriteLine($"Chat WebSocket session with Id {Id} connected!");
}

public override void OnWsDisconnected()
{
Console.WriteLine($"Chat WebSocket session with Id {Id} disconnected!");
}

public override void OnWsReceived(byte[] buffer, long offset, long size)
public void Send(byte[] data, int offset, int size)
{
string message = Encoding.UTF8.GetString(buffer, (int)offset, (int)size);
Console.WriteLine("Incoming: " + message);

// Multicast message to all connected sessions
((WsServer)Server).MulticastBinary(buffer, offset, size);
SendBinaryAsync(data, offset, size);
}

// If the buffer starts with '!' the disconnect the current session
if (message == "!")
Close(1000);
public override void OnWsReceived(byte[] buffer, long offset, long size)
{
OnReceivedData?.Invoke(buffer, (int)offset, (int)size);
}

protected override void OnError(SocketError error)
Expand Down

0 comments on commit a1b13ec

Please sign in to comment.