working on actors
This commit is contained in:
@@ -10,40 +10,25 @@ namespace RebootKit.Engine.Main {
|
||||
public abstract class Game : NetworkBehaviour {
|
||||
static readonly Logger s_GameLogger = new Logger(nameof(Game));
|
||||
|
||||
protected NetworkVariable<FixedString128Bytes> m_CurrentWorldID =
|
||||
new NetworkVariable<FixedString128Bytes>(new FixedString128Bytes(""));
|
||||
|
||||
// Server only callbacks
|
||||
protected virtual void OnPlayerBecameReady(ulong clientID) {
|
||||
}
|
||||
|
||||
// Event callbacks
|
||||
public virtual void OnWorldLoaded() {
|
||||
}
|
||||
|
||||
public virtual void OnWorldUnload() {
|
||||
}
|
||||
|
||||
public virtual void OnChatMessage(string message) {
|
||||
protected virtual void OnChatMessage(string message) {
|
||||
s_GameLogger.Info($"Chat: {message}");
|
||||
}
|
||||
|
||||
// Network
|
||||
|
||||
// NGO callbacks
|
||||
public override void OnNetworkSpawn() {
|
||||
base.OnNetworkSpawn();
|
||||
RR.GameInstance = this;
|
||||
|
||||
m_CurrentWorldID.OnValueChanged += OnCurrentWorldIDChanged;
|
||||
LoadWorld(m_CurrentWorldID.Value.Value);
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn() {
|
||||
base.OnNetworkDespawn();
|
||||
|
||||
m_CurrentWorldID.OnValueChanged -= OnCurrentWorldIDChanged;
|
||||
RR.GameInstance = null;
|
||||
}
|
||||
|
||||
[ServerRpc]
|
||||
public void SetCurrentWorldServerRpc(string worldID) {
|
||||
m_CurrentWorldID.Value = new FixedString128Bytes(worldID);
|
||||
}
|
||||
|
||||
// Chat
|
||||
[Rpc(SendTo.Server)]
|
||||
@@ -55,24 +40,14 @@ namespace RebootKit.Engine.Main {
|
||||
void PrintChatMessageClientRpc(string message) {
|
||||
OnChatMessage(message);
|
||||
}
|
||||
|
||||
void OnCurrentWorldIDChanged(FixedString128Bytes previousValue, FixedString128Bytes newValue) {
|
||||
string worldID = newValue.Value;
|
||||
LoadWorld(worldID);
|
||||
}
|
||||
|
||||
void LoadWorld(string worldID) {
|
||||
if (string.IsNullOrEmpty(worldID)) {
|
||||
RR.World.Unload();
|
||||
} else {
|
||||
WorldConfigAsset worldConfigAsset = RR.GetWorldConfigAsset(worldID);
|
||||
if (worldConfigAsset is not null) {
|
||||
RR.CloseMainMenu();
|
||||
RR.World.LoadAsync(worldConfigAsset.Config, Application.exitCancellationToken).Forget();
|
||||
} else {
|
||||
s_GameLogger.Error($"World config asset for '{worldID}' not found.");
|
||||
}
|
||||
internal void PlayerBecameReady(ulong clientID) {
|
||||
if (!IsServer) {
|
||||
s_GameLogger.Error("PlayerBecameReady called on client, but this should only be called on the server.");
|
||||
return;
|
||||
}
|
||||
|
||||
OnPlayerBecameReady(clientID);
|
||||
}
|
||||
}
|
||||
}
|
||||
200
Runtime/Engine/Code/Main/NetworkSystem.cs
Normal file
200
Runtime/Engine/Code/Main/NetworkSystem.cs
Normal file
@@ -0,0 +1,200 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using RebootKit.Engine.Services.Simulation;
|
||||
using RebootKit.Engine.Simulation;
|
||||
using Unity.Collections;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
using Logger = RebootKit.Engine.Foundation.Logger;
|
||||
|
||||
namespace RebootKit.Engine.Main {
|
||||
class NetworkClientState {
|
||||
public ulong ClientID;
|
||||
public bool IsWorldLoaded;
|
||||
public bool AreActorsSynced;
|
||||
public bool IsReadyForActorsSync;
|
||||
public int ActorsSyncPacketsLeft;
|
||||
|
||||
public bool IsReady;
|
||||
}
|
||||
|
||||
public class NetworkSystem : NetworkBehaviour {
|
||||
static readonly Logger s_Logger = new Logger(nameof(NetworkSystem));
|
||||
|
||||
[field: SerializeField] public ActorsManager Actors { get; private set; }
|
||||
|
||||
readonly Dictionary<ulong, NetworkClientState> m_Clients = new Dictionary<ulong, NetworkClientState>();
|
||||
|
||||
FixedString512Bytes m_WorldID = new FixedString512Bytes("");
|
||||
bool m_IsChangingWorld = false;
|
||||
|
||||
void Awake() {
|
||||
RR.NetworkSystemInstance = this;
|
||||
}
|
||||
|
||||
public override void OnNetworkSpawn() {
|
||||
base.OnNetworkSpawn();
|
||||
|
||||
NetworkManager.Singleton.OnClientConnectedCallback += OnClientConnected;
|
||||
NetworkManager.Singleton.OnClientDisconnectCallback += OnClientDisconnect;
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn() {
|
||||
base.OnNetworkDespawn();
|
||||
|
||||
NetworkManager.Singleton.OnClientConnectedCallback -= OnClientConnected;
|
||||
NetworkManager.Singleton.OnClientDisconnectCallback -= OnClientDisconnect;
|
||||
}
|
||||
|
||||
void OnClientConnected(ulong clientID) {
|
||||
if (!IsServer) {
|
||||
return;
|
||||
}
|
||||
|
||||
s_Logger.Info($"OnClientConnected: {clientID}");
|
||||
|
||||
NetworkClientState newClientState = new NetworkClientState {
|
||||
ClientID = clientID,
|
||||
IsWorldLoaded = false,
|
||||
AreActorsSynced = false,
|
||||
IsReadyForActorsSync = false,
|
||||
IsReady = false
|
||||
};
|
||||
m_Clients.Add(clientID, newClientState);
|
||||
|
||||
if (!m_WorldID.IsEmpty) {
|
||||
s_Logger.Info($"Synchronizing world load for client {clientID} with world ID '{m_WorldID}'");
|
||||
ClientLoadWorldRpc(m_WorldID.ToString(), RpcTarget.Single(clientID, RpcTargetUse.Temp));
|
||||
}
|
||||
}
|
||||
|
||||
void OnClientDisconnect(ulong clientID) {
|
||||
if (!IsServer) {
|
||||
return;
|
||||
}
|
||||
|
||||
s_Logger.Info($"OnClientDisconnect: {clientID}");
|
||||
m_Clients.Remove(clientID);
|
||||
}
|
||||
|
||||
internal NetworkClientState GetClientState(ulong clientID) {
|
||||
if (m_Clients.TryGetValue(clientID, out NetworkClientState clientState)) {
|
||||
return clientState;
|
||||
}
|
||||
|
||||
s_Logger.Error($"Client state for {clientID} not found.");
|
||||
return null;
|
||||
}
|
||||
|
||||
public void SetCurrentWorld(string worldID) {
|
||||
if (!IsServer) {
|
||||
s_Logger.Error("Only server can set the current world.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_IsChangingWorld) {
|
||||
s_Logger.Error($"Already changing world to '{m_WorldID}'. Please wait until the current world change is complete.");
|
||||
return;
|
||||
}
|
||||
|
||||
WorldConfigAsset worldConfigAsset = RR.GetWorldConfigAsset(worldID);
|
||||
if (worldConfigAsset is null) {
|
||||
s_Logger.Error($"Failed to set current world: World config asset for '{worldID}' not found.");
|
||||
return;
|
||||
}
|
||||
|
||||
m_WorldID = worldID;
|
||||
|
||||
foreach (KeyValuePair<ulong, NetworkClientState> kv in m_Clients) {
|
||||
kv.Value.IsWorldLoaded = false;
|
||||
kv.Value.AreActorsSynced = false;
|
||||
kv.Value.IsReadyForActorsSync = false;
|
||||
kv.Value.IsReady = false;
|
||||
}
|
||||
|
||||
ServerLoadWorldAsync(worldConfigAsset, destroyCancellationToken).Forget();
|
||||
}
|
||||
|
||||
async UniTask ServerLoadWorldAsync(WorldConfigAsset asset, CancellationToken cancellationToken) {
|
||||
s_Logger.Info($"ServerLoadWorldAsync: {asset.Config.name}");
|
||||
|
||||
m_IsChangingWorld = true;
|
||||
|
||||
RR.World.Unload();
|
||||
RR.CloseMainMenu();
|
||||
|
||||
await RR.World.LoadAsync(asset.Config, cancellationToken);
|
||||
|
||||
m_IsChangingWorld = false;
|
||||
|
||||
NetworkClientState localClientState = GetClientState(NetworkManager.Singleton.LocalClientId);
|
||||
localClientState.IsReady = true;
|
||||
|
||||
RR.GameInstance.PlayerBecameReady(localClientState.ClientID);
|
||||
|
||||
ClientLoadWorldRpc(asset.name, RpcTarget.NotMe);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.SpecifiedInParams, Delivery = RpcDelivery.Reliable)]
|
||||
void ClientLoadWorldRpc(string worldID, RpcParams rpcParams) {
|
||||
WorldConfigAsset worldConfigAsset = RR.GetWorldConfigAsset(worldID);
|
||||
if (worldConfigAsset is null) {
|
||||
s_Logger.Error($"World config asset for '{worldID}' not found.");
|
||||
RR.Disconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
ClientLoadWorldAsync(worldID, destroyCancellationToken).Forget();
|
||||
}
|
||||
|
||||
async UniTask ClientLoadWorldAsync(string worldID, CancellationToken cancellationToken) {
|
||||
s_Logger.Info($"ClientLoadWorldAsync: {worldID}");
|
||||
|
||||
WorldConfigAsset worldConfigAsset = RR.GetWorldConfigAsset(worldID);
|
||||
if (worldConfigAsset is null) {
|
||||
s_Logger.Error($"World config asset for '{worldID}' not found.");
|
||||
return;
|
||||
}
|
||||
|
||||
RR.World.Unload();
|
||||
RR.CloseMainMenu();
|
||||
|
||||
await RR.World.LoadAsync(worldConfigAsset.Config, cancellationToken);
|
||||
|
||||
m_WorldID = worldID;
|
||||
ClientLoadedWorldRpc(worldID);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server, Delivery = RpcDelivery.Reliable)]
|
||||
void ClientLoadedWorldRpc(string worldID, RpcParams rpcParams = default) {
|
||||
ulong clientID = rpcParams.Receive.SenderClientId;
|
||||
|
||||
if (!m_WorldID.Equals(worldID)) {
|
||||
s_Logger.Error($"Client {clientID} tried to load world '{worldID}', but server is in world '{m_WorldID}'.");
|
||||
NetworkManager.Singleton.DisconnectClient(clientID, "World mismatch!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_Clients.TryGetValue(clientID, out NetworkClientState clientState)) {
|
||||
clientState.IsWorldLoaded = true;
|
||||
clientState.IsReadyForActorsSync = false;
|
||||
Actors.SynchronizeActorsForClient(clientID);
|
||||
} else {
|
||||
NetworkManager.Singleton.DisconnectClient(clientID, "Client is not registered!");
|
||||
}
|
||||
}
|
||||
|
||||
internal void ClientSynchronizedActors(ulong clientID) {
|
||||
NetworkClientState clientState = GetClientState(clientID);
|
||||
if (clientState is null) {
|
||||
s_Logger.Error($"Client state for {clientID} not found.");
|
||||
return;
|
||||
}
|
||||
|
||||
clientState.IsReady = true;
|
||||
RR.GameInstance.PlayerBecameReady(clientID);
|
||||
}
|
||||
}
|
||||
}
|
||||
3
Runtime/Engine/Code/Main/NetworkSystem.cs.meta
Normal file
3
Runtime/Engine/Code/Main/NetworkSystem.cs.meta
Normal file
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1f967d37c17e4704b80849c305a53be9
|
||||
timeCreated: 1751411566
|
||||
@@ -27,7 +27,7 @@ namespace RebootKit.Engine.Main {
|
||||
[ConfigVar("con.write_log", 1, "Enables writing game log to console output")]
|
||||
static ConfigVar s_writeLogToConsole;
|
||||
|
||||
[ConfigVar("sv.tick_rate", 60, "Server tick rate in Hz")]
|
||||
[ConfigVar("sv.tick_rate", 24, "Server tick rate in Hz")]
|
||||
public static ConfigVar TickRate;
|
||||
|
||||
internal static EngineConfigAsset EngineConfig;
|
||||
@@ -37,6 +37,9 @@ namespace RebootKit.Engine.Main {
|
||||
|
||||
static AsyncOperationHandle<SceneInstance> s_mainMenuSceneHandle;
|
||||
|
||||
static NetworkSystem s_networkSystemPrefab;
|
||||
internal static NetworkSystem NetworkSystemInstance;
|
||||
|
||||
internal static ConsoleService Console { get; private set; }
|
||||
public static InputService Input { get; private set; }
|
||||
public static WorldService World { get; private set; }
|
||||
@@ -60,7 +63,7 @@ namespace RebootKit.Engine.Main {
|
||||
s_Logger.Info("Initializing");
|
||||
s_servicesBag = new DisposableBag();
|
||||
s_disposableBag = new DisposableBag();
|
||||
|
||||
|
||||
s_Logger.Info("Registering core services");
|
||||
Console = CreateService(EngineConfig.coreServices.consoleService);
|
||||
Input = CreateService(EngineConfig.coreServices.inputService);
|
||||
@@ -68,11 +71,14 @@ namespace RebootKit.Engine.Main {
|
||||
|
||||
await InitializeAssetsAsync(cancellationToken);
|
||||
|
||||
await SteamManager.InitializeAsync(cancellationToken);
|
||||
// await SteamManager.InitializeAsync(cancellationToken);
|
||||
}
|
||||
|
||||
// @NOTE: This method is called after the main scene is loaded.
|
||||
internal static async UniTask RunAsync(CancellationToken cancellationToken) {
|
||||
s_networkSystemPrefab =
|
||||
Resources.Load<NetworkSystem>(RConsts.k_CoreNetworkGameSystemsResourcesPath);
|
||||
|
||||
NetworkManager.Singleton.OnConnectionEvent += OnConnectionEvent;
|
||||
NetworkManager.Singleton.OnServerStarted += OnServerStarted;
|
||||
NetworkManager.Singleton.OnServerStopped += OnServerStopped;
|
||||
@@ -111,7 +117,7 @@ namespace RebootKit.Engine.Main {
|
||||
NetworkManager.Singleton.OnServerStopped -= OnServerStopped;
|
||||
}
|
||||
|
||||
SteamManager.Shutdown();
|
||||
// SteamManager.Shutdown();
|
||||
|
||||
s_servicesBag.Dispose();
|
||||
s_disposableBag.Dispose();
|
||||
@@ -138,7 +144,7 @@ namespace RebootKit.Engine.Main {
|
||||
|
||||
WorldConfigAsset worldConfig =
|
||||
s_WorldConfigsAssets.Find(asset => asset.Config.name.Equals(name, StringComparison.Ordinal));
|
||||
if (!worldConfig) {
|
||||
if (worldConfig is null) {
|
||||
throw new KeyNotFoundException($"World config '{name}' not found");
|
||||
}
|
||||
|
||||
@@ -187,7 +193,29 @@ namespace RebootKit.Engine.Main {
|
||||
return;
|
||||
}
|
||||
|
||||
GameInstance.SetCurrentWorldServerRpc(worldID);
|
||||
NetworkSystemInstance.SetCurrentWorld(worldID);
|
||||
}
|
||||
|
||||
public static void SpawnActor(AssetReferenceGameObject assetReference,
|
||||
Vector3 position,
|
||||
Quaternion rotation) {
|
||||
if (!IsServer()) {
|
||||
s_Logger.Error("Cannot spawn actor. Not a server instance.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (NetworkSystemInstance is null) {
|
||||
s_Logger.Error("NetworkSystemInstance is not initialized. Cannot spawn actor.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!assetReference.RuntimeKeyIsValid()) {
|
||||
s_Logger.Error("Asset reference is not valid. Cannot spawn actor.");
|
||||
return;
|
||||
}
|
||||
|
||||
s_Logger.Info($"Spawning actor from asset reference: {assetReference.RuntimeKey}");
|
||||
NetworkSystemInstance.Actors.SpawnActor(assetReference, position, rotation);
|
||||
}
|
||||
|
||||
// Service API
|
||||
@@ -343,8 +371,6 @@ namespace RebootKit.Engine.Main {
|
||||
|
||||
TickCount++;
|
||||
}
|
||||
|
||||
World.Tick(deltaTime);
|
||||
}
|
||||
|
||||
static void OnConnectionEvent(NetworkManager network, ConnectionEventData data) {
|
||||
@@ -356,6 +382,9 @@ namespace RebootKit.Engine.Main {
|
||||
|
||||
GameInstance = Object.Instantiate(EngineConfig.gamePrefab);
|
||||
GameInstance.NetworkObject.Spawn();
|
||||
|
||||
NetworkSystemInstance = Object.Instantiate(s_networkSystemPrefab);
|
||||
NetworkSystemInstance.NetworkObject.Spawn();
|
||||
}
|
||||
|
||||
static void OnServerStopped(bool obj) {
|
||||
@@ -363,10 +392,13 @@ namespace RebootKit.Engine.Main {
|
||||
|
||||
if (GameInstance is not null) {
|
||||
GameInstance.NetworkObject.Despawn();
|
||||
Object.Destroy(GameInstance.gameObject);
|
||||
GameInstance = null;
|
||||
}
|
||||
|
||||
if (NetworkSystemInstance is not null) {
|
||||
NetworkSystemInstance.NetworkObject.Despawn();
|
||||
NetworkSystemInstance = null;
|
||||
}
|
||||
|
||||
GameInstance = null;
|
||||
}
|
||||
|
||||
// Console Commands
|
||||
|
||||
Reference in New Issue
Block a user