NetworkServer.cs 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Mirror.RemoteCalls;
  5. using UnityEngine;
  6. namespace Mirror
  7. {
  8. /// <summary>NetworkServer handles remote connections and has a local connection for a local client.</summary>
  9. public static class NetworkServer
  10. {
  11. static bool initialized;
  12. public static int maxConnections;
  13. /// <summary>Connection to host mode client (if any)</summary>
  14. public static NetworkConnectionToClient localConnection { get; private set; }
  15. /// <summary>True is a local client is currently active on the server</summary>
  16. public static bool localClientActive => localConnection != null;
  17. /// <summary>Dictionary of all server connections, with connectionId as key</summary>
  18. public static Dictionary<int, NetworkConnectionToClient> connections =
  19. new Dictionary<int, NetworkConnectionToClient>();
  20. /// <summary>Message Handlers dictionary, with mesageId as key</summary>
  21. internal static Dictionary<ushort, NetworkMessageDelegate> handlers =
  22. new Dictionary<ushort, NetworkMessageDelegate>();
  23. /// <summary>All spawned NetworkIdentities by netId.</summary>
  24. // server sees ALL spawned ones.
  25. public static readonly Dictionary<uint, NetworkIdentity> spawned =
  26. new Dictionary<uint, NetworkIdentity>();
  27. /// <summary>Single player mode can use dontListen to not accept incoming connections</summary>
  28. // see also: https://github.com/vis2k/Mirror/pull/2595
  29. public static bool dontListen;
  30. /// <summary>active checks if the server has been started</summary>
  31. public static bool active { get; internal set; }
  32. // scene loading
  33. public static bool isLoadingScene;
  34. // interest management component (optional)
  35. // by default, everyone observes everyone
  36. public static InterestManagement aoi;
  37. // OnConnected / OnDisconnected used to be NetworkMessages that were
  38. // invoked. this introduced a bug where external clients could send
  39. // Connected/Disconnected messages over the network causing undefined
  40. // behaviour.
  41. // => public so that custom NetworkManagers can hook into it
  42. public static Action<NetworkConnectionToClient> OnConnectedEvent;
  43. public static Action<NetworkConnectionToClient> OnDisconnectedEvent;
  44. public static Action<NetworkConnectionToClient, Exception> OnErrorEvent;
  45. // initialization / shutdown ///////////////////////////////////////////
  46. static void Initialize()
  47. {
  48. if (initialized)
  49. return;
  50. // Debug.Log($"NetworkServer Created version {Version.Current}");
  51. //Make sure connections are cleared in case any old connections references exist from previous sessions
  52. connections.Clear();
  53. // reset Interest Management so that rebuild intervals
  54. // start at 0 when starting again.
  55. if (aoi != null) aoi.Reset();
  56. // reset NetworkTime
  57. NetworkTime.ResetStatics();
  58. Debug.Assert(Transport.activeTransport != null, "There was no active transport when calling NetworkServer.Listen, If you are calling Listen manually then make sure to set 'Transport.activeTransport' first");
  59. AddTransportHandlers();
  60. initialized = true;
  61. }
  62. static void AddTransportHandlers()
  63. {
  64. // += so that other systems can also hook into it (i.e. statistics)
  65. Transport.activeTransport.OnServerConnected += OnTransportConnected;
  66. Transport.activeTransport.OnServerDataReceived += OnTransportData;
  67. Transport.activeTransport.OnServerDisconnected += OnTransportDisconnected;
  68. Transport.activeTransport.OnServerError += OnError;
  69. }
  70. static void RemoveTransportHandlers()
  71. {
  72. // -= so that other systems can also hook into it (i.e. statistics)
  73. Transport.activeTransport.OnServerConnected -= OnTransportConnected;
  74. Transport.activeTransport.OnServerDataReceived -= OnTransportData;
  75. Transport.activeTransport.OnServerDisconnected -= OnTransportDisconnected;
  76. Transport.activeTransport.OnServerError -= OnError;
  77. }
  78. // calls OnStartClient for all SERVER objects in host mode once.
  79. // client doesn't get spawn messages for those, so need to call manually.
  80. public static void ActivateHostScene()
  81. {
  82. foreach (NetworkIdentity identity in spawned.Values)
  83. {
  84. if (!identity.isClient)
  85. {
  86. // Debug.Log($"ActivateHostScene {identity.netId} {identity}");
  87. identity.OnStartClient();
  88. }
  89. }
  90. }
  91. internal static void RegisterMessageHandlers()
  92. {
  93. RegisterHandler<ReadyMessage>(OnClientReadyMessage);
  94. RegisterHandler<CommandMessage>(OnCommandMessage);
  95. RegisterHandler<NetworkPingMessage>(NetworkTime.OnServerPing, false);
  96. }
  97. /// <summary>Starts server and listens to incoming connections with max connections limit.</summary>
  98. public static void Listen(int maxConns)
  99. {
  100. Initialize();
  101. maxConnections = maxConns;
  102. // only start server if we want to listen
  103. if (!dontListen)
  104. {
  105. Transport.activeTransport.ServerStart();
  106. //Debug.Log("Server started listening");
  107. }
  108. active = true;
  109. RegisterMessageHandlers();
  110. }
  111. // Note: NetworkClient.DestroyAllClientObjects does the same on client.
  112. static void CleanupSpawned()
  113. {
  114. // iterate a COPY of spawned.
  115. // DestroyObject removes them from the original collection.
  116. // removing while iterating is not allowed.
  117. foreach (NetworkIdentity identity in spawned.Values.ToList())
  118. {
  119. if (identity != null)
  120. {
  121. // scene object
  122. if (identity.sceneId != 0)
  123. {
  124. // spawned scene objects are unspawned and reset.
  125. // afterwards we disable them again.
  126. // (they always stay in the scene, we don't destroy them)
  127. DestroyObject(identity, DestroyMode.Reset);
  128. identity.gameObject.SetActive(false);
  129. }
  130. // spawned prefabs
  131. else
  132. {
  133. // spawned prefabs are unspawned and destroyed.
  134. DestroyObject(identity, DestroyMode.Destroy);
  135. }
  136. }
  137. }
  138. spawned.Clear();
  139. }
  140. /// <summary>Shuts down the server and disconnects all clients</summary>
  141. // RuntimeInitializeOnLoadMethod -> fast playmode without domain reload
  142. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
  143. public static void Shutdown()
  144. {
  145. if (initialized)
  146. {
  147. DisconnectAll();
  148. // stop the server.
  149. // we do NOT call Transport.Shutdown, because someone only
  150. // called NetworkServer.Shutdown. we can't assume that the
  151. // client is supposed to be shut down too!
  152. //
  153. // NOTE: stop no matter what, even if 'dontListen':
  154. // someone might enabled dontListen at runtime.
  155. // but we still need to stop the server.
  156. // fixes https://github.com/vis2k/Mirror/issues/2536
  157. Transport.activeTransport.ServerStop();
  158. // transport handlers are hooked into when initializing.
  159. // so only remove them when shutting down.
  160. RemoveTransportHandlers();
  161. initialized = false;
  162. }
  163. // Reset all statics here....
  164. dontListen = false;
  165. active = false;
  166. isLoadingScene = false;
  167. localConnection = null;
  168. connections.Clear();
  169. connectionsCopy.Clear();
  170. handlers.Clear();
  171. newObservers.Clear();
  172. // this calls spawned.Clear()
  173. CleanupSpawned();
  174. // sets nextNetworkId to 1
  175. // sets clientAuthorityCallback to null
  176. // sets previousLocalPlayer to null
  177. NetworkIdentity.ResetStatics();
  178. // clear events. someone might have hooked into them before, but
  179. // we don't want to use those hooks after Shutdown anymore.
  180. OnConnectedEvent = null;
  181. OnDisconnectedEvent = null;
  182. OnErrorEvent = null;
  183. if (aoi != null) aoi.Reset();
  184. }
  185. // connections /////////////////////////////////////////////////////////
  186. /// <summary>Add a connection and setup callbacks. Returns true if not added yet.</summary>
  187. public static bool AddConnection(NetworkConnectionToClient conn)
  188. {
  189. if (!connections.ContainsKey(conn.connectionId))
  190. {
  191. // connection cannot be null here or conn.connectionId
  192. // would throw NRE
  193. connections[conn.connectionId] = conn;
  194. return true;
  195. }
  196. // already a connection with this id
  197. return false;
  198. }
  199. /// <summary>Removes a connection by connectionId. Returns true if removed.</summary>
  200. public static bool RemoveConnection(int connectionId) =>
  201. connections.Remove(connectionId);
  202. // called by LocalClient to add itself. don't call directly.
  203. // TODO consider internal setter instead?
  204. internal static void SetLocalConnection(LocalConnectionToClient conn)
  205. {
  206. if (localConnection != null)
  207. {
  208. Debug.LogError("Local Connection already exists");
  209. return;
  210. }
  211. localConnection = conn;
  212. }
  213. // removes local connection to client
  214. internal static void RemoveLocalConnection()
  215. {
  216. if (localConnection != null)
  217. {
  218. localConnection.Disconnect();
  219. localConnection = null;
  220. }
  221. RemoveConnection(0);
  222. }
  223. /// <summary>True if we have no external connections (host is allowed)</summary>
  224. // DEPRECATED 2022-02-05
  225. [Obsolete("Use !HasExternalConnections() instead of NoExternalConnections() to avoid double negatives.")]
  226. public static bool NoExternalConnections() => !HasExternalConnections();
  227. /// <summary>True if we have external connections (that are not host)</summary>
  228. public static bool HasExternalConnections()
  229. {
  230. // any connections?
  231. if (connections.Count > 0)
  232. {
  233. // only host connection?
  234. if (connections.Count == 1 && localConnection != null)
  235. return false;
  236. // otherwise we have real external connections
  237. return true;
  238. }
  239. return false;
  240. }
  241. // send ////////////////////////////////////////////////////////////////
  242. /// <summary>Send a message to all clients, even those that haven't joined the world yet (non ready)</summary>
  243. public static void SendToAll<T>(T message, int channelId = Channels.Reliable, bool sendToReadyOnly = false)
  244. where T : struct, NetworkMessage
  245. {
  246. if (!active)
  247. {
  248. Debug.LogWarning("Can not send using NetworkServer.SendToAll<T>(T msg) because NetworkServer is not active");
  249. return;
  250. }
  251. // Debug.Log($"Server.SendToAll {typeof(T)}");
  252. using (NetworkWriterPooled writer = NetworkWriterPool.Get())
  253. {
  254. // pack message only once
  255. MessagePacking.Pack(message, writer);
  256. ArraySegment<byte> segment = writer.ToArraySegment();
  257. // filter and then send to all internet connections at once
  258. // -> makes code more complicated, but is HIGHLY worth it to
  259. // avoid allocations, allow for multicast, etc.
  260. int count = 0;
  261. foreach (NetworkConnectionToClient conn in connections.Values)
  262. {
  263. if (sendToReadyOnly && !conn.isReady)
  264. continue;
  265. count++;
  266. conn.Send(segment, channelId);
  267. }
  268. NetworkDiagnostics.OnSend(message, channelId, segment.Count, count);
  269. }
  270. }
  271. /// <summary>Send a message to all clients which have joined the world (are ready).</summary>
  272. // TODO put rpcs into NetworkServer.Update WorldState packet, then finally remove SendToReady!
  273. public static void SendToReady<T>(T message, int channelId = Channels.Reliable)
  274. where T : struct, NetworkMessage
  275. {
  276. if (!active)
  277. {
  278. Debug.LogWarning("Can not send using NetworkServer.SendToReady<T>(T msg) because NetworkServer is not active");
  279. return;
  280. }
  281. SendToAll(message, channelId, true);
  282. }
  283. // this is like SendToReadyObservers - but it doesn't check the ready flag on the connection.
  284. // this is used for ObjectDestroy messages.
  285. static void SendToObservers<T>(NetworkIdentity identity, T message, int channelId = Channels.Reliable)
  286. where T : struct, NetworkMessage
  287. {
  288. // Debug.Log($"Server.SendToObservers {typeof(T)}");
  289. if (identity == null || identity.observers == null || identity.observers.Count == 0)
  290. return;
  291. using (NetworkWriterPooled writer = NetworkWriterPool.Get())
  292. {
  293. // pack message into byte[] once
  294. MessagePacking.Pack(message, writer);
  295. ArraySegment<byte> segment = writer.ToArraySegment();
  296. foreach (NetworkConnection conn in identity.observers.Values)
  297. {
  298. conn.Send(segment, channelId);
  299. }
  300. NetworkDiagnostics.OnSend(message, channelId, segment.Count, identity.observers.Count);
  301. }
  302. }
  303. /// <summary>Send a message to only clients which are ready with option to include the owner of the object identity</summary>
  304. // TODO put rpcs into NetworkServer.Update WorldState packet, then finally remove SendToReady!
  305. public static void SendToReadyObservers<T>(NetworkIdentity identity, T message, bool includeOwner = true, int channelId = Channels.Reliable)
  306. where T : struct, NetworkMessage
  307. {
  308. // Debug.Log($"Server.SendToReady {typeof(T)}");
  309. if (identity == null || identity.observers == null || identity.observers.Count == 0)
  310. return;
  311. using (NetworkWriterPooled writer = NetworkWriterPool.Get())
  312. {
  313. // pack message only once
  314. MessagePacking.Pack(message, writer);
  315. ArraySegment<byte> segment = writer.ToArraySegment();
  316. int count = 0;
  317. foreach (NetworkConnection conn in identity.observers.Values)
  318. {
  319. bool isOwner = conn == identity.connectionToClient;
  320. if ((!isOwner || includeOwner) && conn.isReady)
  321. {
  322. count++;
  323. conn.Send(segment, channelId);
  324. }
  325. }
  326. NetworkDiagnostics.OnSend(message, channelId, segment.Count, count);
  327. }
  328. }
  329. // Deprecated 2021-09-19
  330. [Obsolete("SendToReady(identity, message, ...) was renamed to SendToReadyObservers because that's what it does.")]
  331. public static void SendToReady<T>(NetworkIdentity identity, T message, bool includeOwner = true, int channelId = Channels.Reliable)
  332. where T : struct, NetworkMessage =>
  333. SendToReadyObservers(identity, message, includeOwner, channelId);
  334. /// <summary>Send a message to only clients which are ready including the owner of the NetworkIdentity</summary>
  335. // TODO put rpcs into NetworkServer.Update WorldState packet, then finally remove SendToReady!
  336. public static void SendToReadyObservers<T>(NetworkIdentity identity, T message, int channelId)
  337. where T : struct, NetworkMessage
  338. {
  339. SendToReadyObservers(identity, message, true, channelId);
  340. }
  341. // Deprecated 2021-09-19
  342. [Obsolete("SendToReady(identity, message, ...) was renamed to SendToReadyObservers because that's what it does.")]
  343. public static void SendToReady<T>(NetworkIdentity identity, T message, int channelId)
  344. where T : struct, NetworkMessage =>
  345. SendToReadyObservers(identity, message, channelId);
  346. // transport events ////////////////////////////////////////////////////
  347. // called by transport
  348. static void OnTransportConnected(int connectionId)
  349. {
  350. // Debug.Log($"Server accepted client:{connectionId}");
  351. // connectionId needs to be != 0 because 0 is reserved for local player
  352. // note that some transports like kcp generate connectionId by
  353. // hashing which can be < 0 as well, so we need to allow < 0!
  354. if (connectionId == 0)
  355. {
  356. Debug.LogError($"Server.HandleConnect: invalid connectionId: {connectionId} . Needs to be != 0, because 0 is reserved for local player.");
  357. Transport.activeTransport.ServerDisconnect(connectionId);
  358. return;
  359. }
  360. // connectionId not in use yet?
  361. if (connections.ContainsKey(connectionId))
  362. {
  363. Transport.activeTransport.ServerDisconnect(connectionId);
  364. // Debug.Log($"Server connectionId {connectionId} already in use...kicked client");
  365. return;
  366. }
  367. // are more connections allowed? if not, kick
  368. // (it's easier to handle this in Mirror, so Transports can have
  369. // less code and third party transport might not do that anyway)
  370. // (this way we could also send a custom 'tooFull' message later,
  371. // Transport can't do that)
  372. if (connections.Count < maxConnections)
  373. {
  374. // add connection
  375. NetworkConnectionToClient conn = new NetworkConnectionToClient(connectionId);
  376. OnConnected(conn);
  377. }
  378. else
  379. {
  380. // kick
  381. Transport.activeTransport.ServerDisconnect(connectionId);
  382. // Debug.Log($"Server full, kicked client {connectionId}");
  383. }
  384. }
  385. internal static void OnConnected(NetworkConnectionToClient conn)
  386. {
  387. // Debug.Log($"Server accepted client:{conn}");
  388. // add connection and invoke connected event
  389. AddConnection(conn);
  390. OnConnectedEvent?.Invoke(conn);
  391. }
  392. static bool UnpackAndInvoke(NetworkConnectionToClient connection, NetworkReader reader, int channelId)
  393. {
  394. if (MessagePacking.Unpack(reader, out ushort msgType))
  395. {
  396. // try to invoke the handler for that message
  397. if (handlers.TryGetValue(msgType, out NetworkMessageDelegate handler))
  398. {
  399. handler.Invoke(connection, reader, channelId);
  400. connection.lastMessageTime = Time.time;
  401. return true;
  402. }
  403. else
  404. {
  405. // message in a batch are NOT length prefixed to save bandwidth.
  406. // every message needs to be handled and read until the end.
  407. // otherwise it would overlap into the next message.
  408. // => need to warn and disconnect to avoid undefined behaviour.
  409. // => WARNING, not error. can happen if attacker sends random data.
  410. Debug.LogWarning($"Unknown message id: {msgType} for connection: {connection}. This can happen if no handler was registered for this message.");
  411. // simply return false. caller is responsible for disconnecting.
  412. //connection.Disconnect();
  413. return false;
  414. }
  415. }
  416. else
  417. {
  418. // => WARNING, not error. can happen if attacker sends random data.
  419. Debug.LogWarning($"Invalid message header for connection: {connection}.");
  420. // simply return false. caller is responsible for disconnecting.
  421. //connection.Disconnect();
  422. return false;
  423. }
  424. }
  425. // called by transport
  426. internal static void OnTransportData(int connectionId, ArraySegment<byte> data, int channelId)
  427. {
  428. if (connections.TryGetValue(connectionId, out NetworkConnectionToClient connection))
  429. {
  430. // client might batch multiple messages into one packet.
  431. // feed it to the Unbatcher.
  432. // NOTE: we don't need to associate a channelId because we
  433. // always process all messages in the batch.
  434. if (!connection.unbatcher.AddBatch(data))
  435. {
  436. Debug.LogWarning($"NetworkServer: received Message was too short (messages should start with message id)");
  437. connection.Disconnect();
  438. return;
  439. }
  440. // process all messages in the batch.
  441. // only while NOT loading a scene.
  442. // if we get a scene change message, then we need to stop
  443. // processing. otherwise we might apply them to the old scene.
  444. // => fixes https://github.com/vis2k/Mirror/issues/2651
  445. //
  446. // NOTE: if scene starts loading, then the rest of the batch
  447. // would only be processed when OnTransportData is called
  448. // the next time.
  449. // => consider moving processing to NetworkEarlyUpdate.
  450. while (!isLoadingScene &&
  451. connection.unbatcher.GetNextMessage(out NetworkReader reader, out double remoteTimestamp))
  452. {
  453. // enough to read at least header size?
  454. if (reader.Remaining >= MessagePacking.HeaderSize)
  455. {
  456. // make remoteTimeStamp available to the user
  457. connection.remoteTimeStamp = remoteTimestamp;
  458. // handle message
  459. if (!UnpackAndInvoke(connection, reader, channelId))
  460. {
  461. // warn, disconnect and return if failed
  462. // -> warning because attackers might send random data
  463. // -> messages in a batch aren't length prefixed.
  464. // failing to read one would cause undefined
  465. // behaviour for every message afterwards.
  466. // so we need to disconnect.
  467. // -> return to avoid the below unbatches.count error.
  468. // we already disconnected and handled it.
  469. Debug.LogWarning($"NetworkServer: failed to unpack and invoke message. Disconnecting {connectionId}.");
  470. connection.Disconnect();
  471. return;
  472. }
  473. }
  474. // otherwise disconnect
  475. else
  476. {
  477. // WARNING, not error. can happen if attacker sends random data.
  478. Debug.LogWarning($"NetworkServer: received Message was too short (messages should start with message id). Disconnecting {connectionId}");
  479. connection.Disconnect();
  480. return;
  481. }
  482. }
  483. // if we weren't interrupted by a scene change,
  484. // then all batched messages should have been processed now.
  485. // otherwise batches would silently grow.
  486. // we need to log an error to avoid debugging hell.
  487. //
  488. // EXAMPLE: https://github.com/vis2k/Mirror/issues/2882
  489. // -> UnpackAndInvoke silently returned because no handler for id
  490. // -> Reader would never be read past the end
  491. // -> Batch would never be retired because end is never reached
  492. //
  493. // NOTE: prefixing every message in a batch with a length would
  494. // avoid ever not reading to the end. for extra bandwidth.
  495. //
  496. // IMPORTANT: always keep this check to detect memory leaks.
  497. // this took half a day to debug last time.
  498. if (!isLoadingScene && connection.unbatcher.BatchesCount > 0)
  499. {
  500. Debug.LogError($"Still had {connection.unbatcher.BatchesCount} batches remaining after processing, even though processing was not interrupted by a scene change. This should never happen, as it would cause ever growing batches.\nPossible reasons:\n* A message didn't deserialize as much as it serialized\n*There was no message handler for a message id, so the reader wasn't read until the end.");
  501. }
  502. }
  503. else Debug.LogError($"HandleData Unknown connectionId:{connectionId}");
  504. }
  505. // called by transport
  506. // IMPORTANT: often times when disconnecting, we call this from Mirror
  507. // too because we want to remove the connection and handle
  508. // the disconnect immediately.
  509. // => which is fine as long as we guarantee it only runs once
  510. // => which we do by removing the connection!
  511. internal static void OnTransportDisconnected(int connectionId)
  512. {
  513. // Debug.Log($"Server disconnect client:{connectionId}");
  514. if (connections.TryGetValue(connectionId, out NetworkConnectionToClient conn))
  515. {
  516. RemoveConnection(connectionId);
  517. // Debug.Log($"Server lost client:{connectionId}");
  518. // NetworkManager hooks into OnDisconnectedEvent to make
  519. // DestroyPlayerForConnection(conn) optional, e.g. for PvP MMOs
  520. // where players shouldn't be able to escape combat instantly.
  521. if (OnDisconnectedEvent != null)
  522. {
  523. OnDisconnectedEvent.Invoke(conn);
  524. }
  525. // if nobody hooked into it, then simply call DestroyPlayerForConnection
  526. else
  527. {
  528. DestroyPlayerForConnection(conn);
  529. }
  530. }
  531. }
  532. static void OnError(int connectionId, Exception exception)
  533. {
  534. Debug.LogException(exception);
  535. // try get connection. passes null otherwise.
  536. connections.TryGetValue(connectionId, out NetworkConnectionToClient conn);
  537. OnErrorEvent?.Invoke(conn, exception);
  538. }
  539. // message handlers ////////////////////////////////////////////////////
  540. /// <summary>Register a handler for message type T. Most should require authentication.</summary>
  541. // TODO obsolete this some day to always use the channelId version.
  542. // all handlers in this version are wrapped with 1 extra action.
  543. public static void RegisterHandler<T>(Action<NetworkConnectionToClient, T> handler, bool requireAuthentication = true)
  544. where T : struct, NetworkMessage
  545. {
  546. ushort msgType = MessagePacking.GetId<T>();
  547. if (handlers.ContainsKey(msgType))
  548. {
  549. Debug.LogWarning($"NetworkServer.RegisterHandler replacing handler for {typeof(T).FullName}, id={msgType}. If replacement is intentional, use ReplaceHandler instead to avoid this warning.");
  550. }
  551. handlers[msgType] = MessagePacking.WrapHandler(handler, requireAuthentication);
  552. }
  553. /// <summary>Register a handler for message type T. Most should require authentication.</summary>
  554. // This version passes channelId to the handler.
  555. public static void RegisterHandler<T>(Action<NetworkConnectionToClient, T, int> handler, bool requireAuthentication = true)
  556. where T : struct, NetworkMessage
  557. {
  558. ushort msgType = MessagePacking.GetId<T>();
  559. if (handlers.ContainsKey(msgType))
  560. {
  561. Debug.LogWarning($"NetworkServer.RegisterHandler replacing handler for {typeof(T).FullName}, id={msgType}. If replacement is intentional, use ReplaceHandler instead to avoid this warning.");
  562. }
  563. handlers[msgType] = MessagePacking.WrapHandler(handler, requireAuthentication);
  564. }
  565. /// <summary>Replace a handler for message type T. Most should require authentication.</summary>
  566. public static void ReplaceHandler<T>(Action<NetworkConnectionToClient, T> handler, bool requireAuthentication = true)
  567. where T : struct, NetworkMessage
  568. {
  569. ushort msgType = MessagePacking.GetId<T>();
  570. handlers[msgType] = MessagePacking.WrapHandler(handler, requireAuthentication);
  571. }
  572. /// <summary>Replace a handler for message type T. Most should require authentication.</summary>
  573. public static void ReplaceHandler<T>(Action<T> handler, bool requireAuthentication = true)
  574. where T : struct, NetworkMessage
  575. {
  576. ReplaceHandler<T>((_, value) => { handler(value); }, requireAuthentication);
  577. }
  578. /// <summary>Unregister a handler for a message type T.</summary>
  579. public static void UnregisterHandler<T>()
  580. where T : struct, NetworkMessage
  581. {
  582. ushort msgType = MessagePacking.GetId<T>();
  583. handlers.Remove(msgType);
  584. }
  585. /// <summary>Clears all registered message handlers.</summary>
  586. public static void ClearHandlers() => handlers.Clear();
  587. internal static bool GetNetworkIdentity(GameObject go, out NetworkIdentity identity)
  588. {
  589. identity = go.GetComponent<NetworkIdentity>();
  590. if (identity == null)
  591. {
  592. Debug.LogError($"GameObject {go.name} doesn't have NetworkIdentity.");
  593. return false;
  594. }
  595. return true;
  596. }
  597. // disconnect //////////////////////////////////////////////////////////
  598. /// <summary>Disconnect all connections, including the local connection.</summary>
  599. // synchronous: handles disconnect events and cleans up fully before returning!
  600. public static void DisconnectAll()
  601. {
  602. // disconnect and remove all connections.
  603. // we can not use foreach here because if
  604. // conn.Disconnect -> Transport.ServerDisconnect calls
  605. // OnDisconnect -> NetworkServer.OnDisconnect(connectionId)
  606. // immediately then OnDisconnect would remove the connection while
  607. // we are iterating here.
  608. // see also: https://github.com/vis2k/Mirror/issues/2357
  609. // this whole process should be simplified some day.
  610. // until then, let's copy .Values to avoid InvalidOperatinException.
  611. // note that this is only called when stopping the server, so the
  612. // copy is no performance problem.
  613. foreach (NetworkConnectionToClient conn in connections.Values.ToList())
  614. {
  615. // disconnect via connection->transport
  616. conn.Disconnect();
  617. // we want this function to be synchronous: handle disconnect
  618. // events and clean up fully before returning.
  619. // -> OnTransportDisconnected can safely be called without
  620. // waiting for the Transport's callback.
  621. // -> it has checks to only run once.
  622. // call OnDisconnected unless local player in host mod
  623. // TODO unnecessary check?
  624. if (conn.connectionId != NetworkConnection.LocalConnectionId)
  625. OnTransportDisconnected(conn.connectionId);
  626. }
  627. // cleanup
  628. connections.Clear();
  629. localConnection = null;
  630. active = false;
  631. }
  632. // add/remove/replace player ///////////////////////////////////////////
  633. /// <summary>Called by server after AddPlayer message to add the player for the connection.</summary>
  634. // When a player is added for a connection, the client for that
  635. // connection is made ready automatically. The player object is
  636. // automatically spawned, so you do not need to call NetworkServer.Spawn
  637. // for that object. This function is used for "adding" a player, not for
  638. // "replacing" the player on a connection. If there is already a player
  639. // on this playerControllerId for this connection, this will fail.
  640. public static bool AddPlayerForConnection(NetworkConnectionToClient conn, GameObject player)
  641. {
  642. NetworkIdentity identity = player.GetComponent<NetworkIdentity>();
  643. if (identity == null)
  644. {
  645. Debug.LogWarning($"AddPlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to {player}");
  646. return false;
  647. }
  648. // cannot have a player object in "Add" version
  649. if (conn.identity != null)
  650. {
  651. Debug.Log("AddPlayer: player object already exists");
  652. return false;
  653. }
  654. // make sure we have a controller before we call SetClientReady
  655. // because the observers will be rebuilt only if we have a controller
  656. conn.identity = identity;
  657. // Set the connection on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients)
  658. identity.SetClientOwner(conn);
  659. // special case, we are in host mode, set hasAuthority to true so that all overrides see it
  660. if (conn is LocalConnectionToClient)
  661. {
  662. identity.hasAuthority = true;
  663. NetworkClient.InternalAddPlayer(identity);
  664. }
  665. // set ready if not set yet
  666. SetClientReady(conn);
  667. // Debug.Log($"Adding new playerGameObject object netId: {identity.netId} asset ID: {identity.assetId}");
  668. Respawn(identity);
  669. return true;
  670. }
  671. /// <summary>Called by server after AddPlayer message to add the player for the connection.</summary>
  672. // When a player is added for a connection, the client for that
  673. // connection is made ready automatically. The player object is
  674. // automatically spawned, so you do not need to call NetworkServer.Spawn
  675. // for that object. This function is used for "adding" a player, not for
  676. // "replacing" the player on a connection. If there is already a player
  677. // on this playerControllerId for this connection, this will fail.
  678. public static bool AddPlayerForConnection(NetworkConnectionToClient conn, GameObject player, Guid assetId)
  679. {
  680. if (GetNetworkIdentity(player, out NetworkIdentity identity))
  681. {
  682. identity.assetId = assetId;
  683. }
  684. return AddPlayerForConnection(conn, player);
  685. }
  686. /// <summary>Replaces connection's player object. The old object is not destroyed.</summary>
  687. // This does NOT change the ready state of the connection, so it can
  688. // safely be used while changing scenes.
  689. public static bool ReplacePlayerForConnection(NetworkConnectionToClient conn, GameObject player, bool keepAuthority = false)
  690. {
  691. NetworkIdentity identity = player.GetComponent<NetworkIdentity>();
  692. if (identity == null)
  693. {
  694. Debug.LogError($"ReplacePlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to {player}");
  695. return false;
  696. }
  697. if (identity.connectionToClient != null && identity.connectionToClient != conn)
  698. {
  699. Debug.LogError($"Cannot replace player for connection. New player is already owned by a different connection{player}");
  700. return false;
  701. }
  702. //NOTE: there can be an existing player
  703. //Debug.Log("NetworkServer ReplacePlayer");
  704. NetworkIdentity previousPlayer = conn.identity;
  705. conn.identity = identity;
  706. // Set the connection on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients)
  707. identity.SetClientOwner(conn);
  708. // special case, we are in host mode, set hasAuthority to true so that all overrides see it
  709. if (conn is LocalConnectionToClient)
  710. {
  711. identity.hasAuthority = true;
  712. NetworkClient.InternalAddPlayer(identity);
  713. }
  714. // add connection to observers AFTER the playerController was set.
  715. // by definition, there is nothing to observe if there is no player
  716. // controller.
  717. //
  718. // IMPORTANT: do this in AddPlayerForConnection & ReplacePlayerForConnection!
  719. SpawnObserversForConnection(conn);
  720. //Debug.Log($"Replacing playerGameObject object netId:{player.GetComponent<NetworkIdentity>().netId} asset ID {player.GetComponent<NetworkIdentity>().assetId}");
  721. Respawn(identity);
  722. if (keepAuthority)
  723. {
  724. // This needs to be sent to clear isLocalPlayer on
  725. // client while keeping hasAuthority true
  726. SendChangeOwnerMessage(previousPlayer, conn);
  727. }
  728. else
  729. {
  730. // This clears both isLocalPlayer and hasAuthority on client
  731. previousPlayer.RemoveClientAuthority();
  732. }
  733. return true;
  734. }
  735. /// <summary>Replaces connection's player object. The old object is not destroyed.</summary>
  736. // This does NOT change the ready state of the connection, so it can
  737. // safely be used while changing scenes.
  738. public static bool ReplacePlayerForConnection(NetworkConnectionToClient conn, GameObject player, Guid assetId, bool keepAuthority = false)
  739. {
  740. if (GetNetworkIdentity(player, out NetworkIdentity identity))
  741. {
  742. identity.assetId = assetId;
  743. }
  744. return ReplacePlayerForConnection(conn, player, keepAuthority);
  745. }
  746. // ready ///////////////////////////////////////////////////////////////
  747. /// <summary>Flags client connection as ready (=joined world).</summary>
  748. // When a client has signaled that it is ready, this method tells the
  749. // server that the client is ready to receive spawned objects and state
  750. // synchronization updates. This is usually called in a handler for the
  751. // SYSTEM_READY message. If there is not specific action a game needs to
  752. // take for this message, relying on the default ready handler function
  753. // is probably fine, so this call wont be needed.
  754. public static void SetClientReady(NetworkConnectionToClient conn)
  755. {
  756. // Debug.Log($"SetClientReadyInternal for conn:{conn}");
  757. // set ready
  758. conn.isReady = true;
  759. // client is ready to start spawning objects
  760. if (conn.identity != null)
  761. SpawnObserversForConnection(conn);
  762. }
  763. /// <summary>Marks the client of the connection to be not-ready.</summary>
  764. // Clients that are not ready do not receive spawned objects or state
  765. // synchronization updates. They client can be made ready again by
  766. // calling SetClientReady().
  767. public static void SetClientNotReady(NetworkConnectionToClient conn)
  768. {
  769. conn.isReady = false;
  770. conn.RemoveFromObservingsObservers();
  771. conn.Send(new NotReadyMessage());
  772. }
  773. /// <summary>Marks all connected clients as no longer ready.</summary>
  774. // All clients will no longer be sent state synchronization updates. The
  775. // player's clients can call ClientManager.Ready() again to re-enter the
  776. // ready state. This is useful when switching scenes.
  777. public static void SetAllClientsNotReady()
  778. {
  779. foreach (NetworkConnectionToClient conn in connections.Values)
  780. {
  781. SetClientNotReady(conn);
  782. }
  783. }
  784. // default ready handler.
  785. static void OnClientReadyMessage(NetworkConnectionToClient conn, ReadyMessage msg)
  786. {
  787. // Debug.Log($"Default handler for ready message from {conn}");
  788. SetClientReady(conn);
  789. }
  790. // show / hide for connection //////////////////////////////////////////
  791. internal static void ShowForConnection(NetworkIdentity identity, NetworkConnection conn)
  792. {
  793. if (conn.isReady)
  794. SendSpawnMessage(identity, conn);
  795. }
  796. internal static void HideForConnection(NetworkIdentity identity, NetworkConnection conn)
  797. {
  798. ObjectHideMessage msg = new ObjectHideMessage
  799. {
  800. netId = identity.netId
  801. };
  802. conn.Send(msg);
  803. }
  804. /// <summary>Removes the player object from the connection</summary>
  805. // destroyServerObject: Indicates whether the server object should be destroyed
  806. public static void RemovePlayerForConnection(NetworkConnection conn, bool destroyServerObject)
  807. {
  808. if (conn.identity != null)
  809. {
  810. if (destroyServerObject)
  811. Destroy(conn.identity.gameObject);
  812. else
  813. UnSpawn(conn.identity.gameObject);
  814. conn.identity = null;
  815. }
  816. //else Debug.Log($"Connection {conn} has no identity");
  817. }
  818. // remote calls ////////////////////////////////////////////////////////
  819. // Handle command from specific player, this could be one of multiple
  820. // players on a single client
  821. static void OnCommandMessage(NetworkConnectionToClient conn, CommandMessage msg, int channelId)
  822. {
  823. if (!conn.isReady)
  824. {
  825. // Clients may be set NotReady due to scene change or other game logic by user, e.g. respawning.
  826. // Ignore commands that may have been in flight before client received NotReadyMessage message.
  827. // Unreliable messages may be out of order, so don't spam warnings for those.
  828. if (channelId == Channels.Reliable)
  829. Debug.LogWarning("Command received while client is not ready.\nThis may be ignored if client intentionally set NotReady.");
  830. return;
  831. }
  832. if (!spawned.TryGetValue(msg.netId, out NetworkIdentity identity))
  833. {
  834. // over reliable channel, commands should always come after spawn.
  835. // over unreliable, they might come in before the object was spawned.
  836. // for example, NetworkTransform.
  837. // let's not spam the console for unreliable out of order messages.
  838. if (channelId == Channels.Reliable)
  839. Debug.LogWarning($"Spawned object not found when handling Command message [netId={msg.netId}]");
  840. return;
  841. }
  842. // Commands can be for player objects, OR other objects with client-authority
  843. // -> so if this connection's controller has a different netId then
  844. // only allow the command if clientAuthorityOwner
  845. bool requiresAuthority = RemoteProcedureCalls.CommandRequiresAuthority(msg.functionHash);
  846. if (requiresAuthority && identity.connectionToClient != conn)
  847. {
  848. Debug.LogWarning($"Command for object without authority [netId={msg.netId}]");
  849. return;
  850. }
  851. // Debug.Log($"OnCommandMessage for netId:{msg.netId} conn:{conn}");
  852. using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(msg.payload))
  853. identity.HandleRemoteCall(msg.componentIndex, msg.functionHash, RemoteCallType.Command, networkReader, conn as NetworkConnectionToClient);
  854. }
  855. // spawning ////////////////////////////////////////////////////////////
  856. static ArraySegment<byte> CreateSpawnMessagePayload(bool isOwner, NetworkIdentity identity, NetworkWriterPooled ownerWriter, NetworkWriterPooled observersWriter)
  857. {
  858. // Only call OnSerializeAllSafely if there are NetworkBehaviours
  859. if (identity.NetworkBehaviours.Length == 0)
  860. {
  861. return default;
  862. }
  863. // serialize all components with initialState = true
  864. // (can be null if has none)
  865. identity.OnSerializeAllSafely(true, ownerWriter, observersWriter);
  866. // convert to ArraySegment to avoid reader allocations
  867. // if nothing was written, .ToArraySegment returns an empty segment.
  868. ArraySegment<byte> ownerSegment = ownerWriter.ToArraySegment();
  869. ArraySegment<byte> observersSegment = observersWriter.ToArraySegment();
  870. // use owner segment if 'conn' owns this identity, otherwise
  871. // use observers segment
  872. ArraySegment<byte> payload = isOwner ? ownerSegment : observersSegment;
  873. return payload;
  874. }
  875. internal static void SendSpawnMessage(NetworkIdentity identity, NetworkConnection conn)
  876. {
  877. if (identity.serverOnly) return;
  878. //Debug.Log($"Server SendSpawnMessage: name:{identity.name} sceneId:{identity.sceneId:X} netid:{identity.netId}");
  879. // one writer for owner, one for observers
  880. using (NetworkWriterPooled ownerWriter = NetworkWriterPool.Get(), observersWriter = NetworkWriterPool.Get())
  881. {
  882. bool isOwner = identity.connectionToClient == conn;
  883. ArraySegment<byte> payload = CreateSpawnMessagePayload(isOwner, identity, ownerWriter, observersWriter);
  884. SpawnMessage message = new SpawnMessage
  885. {
  886. netId = identity.netId,
  887. isLocalPlayer = conn.identity == identity,
  888. isOwner = isOwner,
  889. sceneId = identity.sceneId,
  890. assetId = identity.assetId,
  891. // use local values for VR support
  892. position = identity.transform.localPosition,
  893. rotation = identity.transform.localRotation,
  894. scale = identity.transform.localScale,
  895. payload = payload
  896. };
  897. conn.Send(message);
  898. }
  899. }
  900. internal static void SendChangeOwnerMessage(NetworkIdentity identity, NetworkConnectionToClient conn)
  901. {
  902. // Don't send if identity isn't spawned or only exists on server
  903. if (identity.netId == 0 || identity.serverOnly) return;
  904. // Don't send if conn doesn't have the identity spawned yet
  905. // May be excluded from the client by interest management
  906. if (!conn.observing.Contains(identity)) return;
  907. //Debug.Log($"Server SendChangeOwnerMessage: name={identity.name} netid={identity.netId}");
  908. conn.Send(new ChangeOwnerMessage
  909. {
  910. netId = identity.netId,
  911. isOwner = identity.connectionToClient == conn,
  912. isLocalPlayer = conn.identity == identity
  913. });
  914. }
  915. static void SpawnObject(GameObject obj, NetworkConnection ownerConnection)
  916. {
  917. // verify if we can spawn this
  918. if (Utils.IsPrefab(obj))
  919. {
  920. Debug.LogError($"GameObject {obj.name} is a prefab, it can't be spawned. Instantiate it first.");
  921. return;
  922. }
  923. if (!active)
  924. {
  925. Debug.LogError($"SpawnObject for {obj}, NetworkServer is not active. Cannot spawn objects without an active server.");
  926. return;
  927. }
  928. NetworkIdentity identity = obj.GetComponent<NetworkIdentity>();
  929. if (identity == null)
  930. {
  931. Debug.LogError($"SpawnObject {obj} has no NetworkIdentity. Please add a NetworkIdentity to {obj}");
  932. return;
  933. }
  934. if (identity.SpawnedFromInstantiate)
  935. {
  936. // Using Instantiate on SceneObject is not allowed, so stop spawning here
  937. // NetworkIdentity.Awake already logs error, no need to log a second error here
  938. return;
  939. }
  940. identity.connectionToClient = (NetworkConnectionToClient)ownerConnection;
  941. // special case to make sure hasAuthority is set
  942. // on start server in host mode
  943. if (ownerConnection is LocalConnectionToClient)
  944. identity.hasAuthority = true;
  945. identity.OnStartServer();
  946. // Debug.Log($"SpawnObject instance ID {identity.netId} asset ID {identity.assetId}");
  947. if (aoi)
  948. {
  949. // This calls user code which might throw exceptions
  950. // We don't want this to leave us in bad state
  951. try
  952. {
  953. aoi.OnSpawned(identity);
  954. }
  955. catch (Exception e)
  956. {
  957. Debug.LogException(e);
  958. }
  959. }
  960. RebuildObservers(identity, true);
  961. }
  962. /// <summary>Spawn the given game object on all clients which are ready.</summary>
  963. // This will cause a new object to be instantiated from the registered
  964. // prefab, or from a custom spawn function.
  965. public static void Spawn(GameObject obj, NetworkConnection ownerConnection = null)
  966. {
  967. SpawnObject(obj, ownerConnection);
  968. }
  969. /// <summary>Spawns an object and also assigns Client Authority to the specified client.</summary>
  970. // This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object.
  971. public static void Spawn(GameObject obj, GameObject ownerPlayer)
  972. {
  973. NetworkIdentity identity = ownerPlayer.GetComponent<NetworkIdentity>();
  974. if (identity == null)
  975. {
  976. Debug.LogError("Player object has no NetworkIdentity");
  977. return;
  978. }
  979. if (identity.connectionToClient == null)
  980. {
  981. Debug.LogError("Player object is not a player.");
  982. return;
  983. }
  984. Spawn(obj, identity.connectionToClient);
  985. }
  986. /// <summary>Spawns an object and also assigns Client Authority to the specified client.</summary>
  987. // This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object.
  988. public static void Spawn(GameObject obj, Guid assetId, NetworkConnection ownerConnection = null)
  989. {
  990. if (GetNetworkIdentity(obj, out NetworkIdentity identity))
  991. {
  992. identity.assetId = assetId;
  993. }
  994. SpawnObject(obj, ownerConnection);
  995. }
  996. internal static bool ValidateSceneObject(NetworkIdentity identity)
  997. {
  998. if (identity.gameObject.hideFlags == HideFlags.NotEditable ||
  999. identity.gameObject.hideFlags == HideFlags.HideAndDontSave)
  1000. return false;
  1001. #if UNITY_EDITOR
  1002. if (UnityEditor.EditorUtility.IsPersistent(identity.gameObject))
  1003. return false;
  1004. #endif
  1005. // If not a scene object
  1006. return identity.sceneId != 0;
  1007. }
  1008. /// <summary>Spawns NetworkIdentities in the scene on the server.</summary>
  1009. // NetworkIdentity objects in a scene are disabled by default. Calling
  1010. // SpawnObjects() causes these scene objects to be enabled and spawned.
  1011. // It is like calling NetworkServer.Spawn() for each of them.
  1012. public static bool SpawnObjects()
  1013. {
  1014. // only if server active
  1015. if (!active)
  1016. return false;
  1017. NetworkIdentity[] identities = Resources.FindObjectsOfTypeAll<NetworkIdentity>();
  1018. // first pass: activate all scene objects
  1019. foreach (NetworkIdentity identity in identities)
  1020. {
  1021. if (ValidateSceneObject(identity))
  1022. {
  1023. // Debug.Log($"SpawnObjects sceneId:{identity.sceneId:X} name:{identity.gameObject.name}");
  1024. identity.gameObject.SetActive(true);
  1025. // fix https://github.com/vis2k/Mirror/issues/2778:
  1026. // -> SetActive(true) does NOT call Awake() if the parent
  1027. // is inactive
  1028. // -> we need Awake() to initialize NetworkBehaviours[] etc.
  1029. // because our second pass below spawns and works with it
  1030. // => detect this situation and manually call Awake for
  1031. // proper initialization
  1032. if (!identity.gameObject.activeInHierarchy)
  1033. identity.Awake();
  1034. }
  1035. }
  1036. // second pass: spawn all scene objects
  1037. foreach (NetworkIdentity identity in identities)
  1038. {
  1039. if (ValidateSceneObject(identity))
  1040. // pass connection so that authority is not lost when server loads a scene
  1041. // https://github.com/vis2k/Mirror/pull/2987
  1042. Spawn(identity.gameObject, identity.connectionToClient);
  1043. }
  1044. return true;
  1045. }
  1046. static void Respawn(NetworkIdentity identity)
  1047. {
  1048. if (identity.netId == 0)
  1049. {
  1050. // If the object has not been spawned, then do a full spawn and update observers
  1051. Spawn(identity.gameObject, identity.connectionToClient);
  1052. }
  1053. else
  1054. {
  1055. // otherwise just replace his data
  1056. SendSpawnMessage(identity, identity.connectionToClient);
  1057. }
  1058. }
  1059. static void SpawnObserversForConnection(NetworkConnectionToClient conn)
  1060. {
  1061. //Debug.Log($"Spawning {spawned.Count} objects for conn {conn}");
  1062. if (!conn.isReady)
  1063. {
  1064. // client needs to finish initializing before we can spawn objects
  1065. // otherwise it would not find them.
  1066. return;
  1067. }
  1068. // let connection know that we are about to start spawning...
  1069. conn.Send(new ObjectSpawnStartedMessage());
  1070. // add connection to each nearby NetworkIdentity's observers, which
  1071. // internally sends a spawn message for each one to the connection.
  1072. foreach (NetworkIdentity identity in spawned.Values)
  1073. {
  1074. // try with far away ones in ummorpg!
  1075. if (identity.gameObject.activeSelf) //TODO this is different
  1076. {
  1077. //Debug.Log($"Sending spawn message for current server objects name:{identity.name} netId:{identity.netId} sceneId:{identity.sceneId:X}");
  1078. // we need to support three cases:
  1079. // - legacy system (identity has .visibility)
  1080. // - new system (networkserver has .aoi)
  1081. // - default case: no .visibility and no .aoi means add all
  1082. // connections by default)
  1083. //
  1084. // ForceHidden/ForceShown overwrite all systems so check it
  1085. // first!
  1086. // ForceShown: add no matter what
  1087. if (identity.visible == Visibility.ForceShown)
  1088. {
  1089. identity.AddObserver(conn);
  1090. }
  1091. // ForceHidden: don't show no matter what
  1092. else if (identity.visible == Visibility.ForceHidden)
  1093. {
  1094. // do nothing
  1095. }
  1096. // default: legacy system / new system / no system support
  1097. else if (identity.visible == Visibility.Default)
  1098. {
  1099. // aoi system
  1100. if (aoi != null)
  1101. {
  1102. // call OnCheckObserver
  1103. if (aoi.OnCheckObserver(identity, conn))
  1104. identity.AddObserver(conn);
  1105. }
  1106. // no system: add all observers by default
  1107. else
  1108. {
  1109. identity.AddObserver(conn);
  1110. }
  1111. }
  1112. }
  1113. }
  1114. // let connection know that we finished spawning, so it can call
  1115. // OnStartClient on each one (only after all were spawned, which
  1116. // is how Unity's Start() function works too)
  1117. conn.Send(new ObjectSpawnFinishedMessage());
  1118. }
  1119. /// <summary>This takes an object that has been spawned and un-spawns it.</summary>
  1120. // The object will be removed from clients that it was spawned on, or
  1121. // the custom spawn handler function on the client will be called for
  1122. // the object.
  1123. // Unlike when calling NetworkServer.Destroy(), on the server the object
  1124. // will NOT be destroyed. This allows the server to re-use the object,
  1125. // even spawn it again later.
  1126. public static void UnSpawn(GameObject obj) => DestroyObject(obj, DestroyMode.Reset);
  1127. // destroy /////////////////////////////////////////////////////////////
  1128. /// <summary>Destroys all of the connection's owned objects on the server.</summary>
  1129. // This is used when a client disconnects, to remove the players for
  1130. // that client. This also destroys non-player objects that have client
  1131. // authority set for this connection.
  1132. public static void DestroyPlayerForConnection(NetworkConnectionToClient conn)
  1133. {
  1134. // destroy all objects owned by this connection, including the player object
  1135. conn.DestroyOwnedObjects();
  1136. // remove connection from all of its observing entities observers
  1137. // fixes https://github.com/vis2k/Mirror/issues/2737
  1138. // -> cleaning those up in NetworkConnection.Disconnect is NOT enough
  1139. // because voluntary disconnects from the other end don't call
  1140. // NetworkConnectionn.Disconnect()
  1141. conn.RemoveFromObservingsObservers();
  1142. conn.identity = null;
  1143. }
  1144. // sometimes we want to GameObject.Destroy it.
  1145. // sometimes we want to just unspawn on clients and .Reset() it on server.
  1146. // => 'bool destroy' isn't obvious enough. it's really destroy OR reset!
  1147. enum DestroyMode { Destroy, Reset }
  1148. static void DestroyObject(NetworkIdentity identity, DestroyMode mode)
  1149. {
  1150. // Debug.Log($"DestroyObject instance:{identity.netId}");
  1151. // only call OnRebuildObservers while active,
  1152. // not while shutting down
  1153. // (https://github.com/vis2k/Mirror/issues/2977)
  1154. if (active && aoi)
  1155. {
  1156. // This calls user code which might throw exceptions
  1157. // We don't want this to leave us in bad state
  1158. try
  1159. {
  1160. aoi.OnDestroyed(identity);
  1161. }
  1162. catch (Exception e)
  1163. {
  1164. Debug.LogException(e);
  1165. }
  1166. }
  1167. // remove from NetworkServer (this) dictionary
  1168. spawned.Remove(identity.netId);
  1169. identity.connectionToClient?.RemoveOwnedObject(identity);
  1170. // send object destroy message to all observers, clear observers
  1171. SendToObservers(identity, new ObjectDestroyMessage{netId = identity.netId});
  1172. identity.ClearObservers();
  1173. // in host mode, call OnStopClient/OnStopLocalPlayer manually
  1174. if (NetworkClient.active && localClientActive)
  1175. {
  1176. if (identity.isLocalPlayer)
  1177. identity.OnStopLocalPlayer();
  1178. identity.OnStopClient();
  1179. // The object may have been spawned with host client ownership,
  1180. // e.g. a pet so we need to clear hasAuthority and call
  1181. // NotifyAuthority which invokes OnStopAuthority if hasAuthority.
  1182. identity.hasAuthority = false;
  1183. identity.NotifyAuthority();
  1184. // remove from NetworkClient dictionary
  1185. NetworkClient.spawned.Remove(identity.netId);
  1186. }
  1187. // we are on the server. call OnStopServer.
  1188. identity.OnStopServer();
  1189. // are we supposed to GameObject.Destroy() it completely?
  1190. if (mode == DestroyMode.Destroy)
  1191. {
  1192. identity.destroyCalled = true;
  1193. // Destroy if application is running
  1194. if (Application.isPlaying)
  1195. {
  1196. UnityEngine.Object.Destroy(identity.gameObject);
  1197. }
  1198. // Destroy can't be used in Editor during tests. use DestroyImmediate.
  1199. else
  1200. {
  1201. GameObject.DestroyImmediate(identity.gameObject);
  1202. }
  1203. }
  1204. // otherwise simply .Reset() and set inactive again
  1205. else if (mode == DestroyMode.Reset)
  1206. {
  1207. identity.Reset();
  1208. }
  1209. }
  1210. static void DestroyObject(GameObject obj, DestroyMode mode)
  1211. {
  1212. if (obj == null)
  1213. {
  1214. Debug.Log("NetworkServer DestroyObject is null");
  1215. return;
  1216. }
  1217. if (GetNetworkIdentity(obj, out NetworkIdentity identity))
  1218. {
  1219. DestroyObject(identity, mode);
  1220. }
  1221. }
  1222. /// <summary>Destroys this object and corresponding objects on all clients.</summary>
  1223. // In some cases it is useful to remove an object but not delete it on
  1224. // the server. For that, use NetworkServer.UnSpawn() instead of
  1225. // NetworkServer.Destroy().
  1226. public static void Destroy(GameObject obj) => DestroyObject(obj, DestroyMode.Destroy);
  1227. // interest management /////////////////////////////////////////////////
  1228. // Helper function to add all server connections as observers.
  1229. // This is used if none of the components provides their own
  1230. // OnRebuildObservers function.
  1231. internal static void AddAllReadyServerConnectionsToObservers(NetworkIdentity identity)
  1232. {
  1233. // add all server connections
  1234. foreach (NetworkConnectionToClient conn in connections.Values)
  1235. {
  1236. // only if authenticated (don't send to people during logins)
  1237. if (conn.isReady)
  1238. identity.AddObserver(conn);
  1239. }
  1240. // add local host connection (if any)
  1241. if (localConnection != null && localConnection.isReady)
  1242. {
  1243. identity.AddObserver(localConnection);
  1244. }
  1245. }
  1246. // allocate newObservers helper HashSet only once
  1247. // internal for tests
  1248. internal static readonly HashSet<NetworkConnectionToClient> newObservers = new HashSet<NetworkConnectionToClient>();
  1249. // rebuild observers default method (no AOI) - adds all connections
  1250. static void RebuildObserversDefault(NetworkIdentity identity, bool initialize)
  1251. {
  1252. // only add all connections when rebuilding the first time.
  1253. // second time we just keep them without rebuilding anything.
  1254. if (initialize)
  1255. {
  1256. // not force hidden?
  1257. if (identity.visible != Visibility.ForceHidden)
  1258. {
  1259. AddAllReadyServerConnectionsToObservers(identity);
  1260. }
  1261. }
  1262. }
  1263. // rebuild observers via interest management system
  1264. static void RebuildObserversCustom(NetworkIdentity identity, bool initialize)
  1265. {
  1266. // clear newObservers hashset before using it
  1267. newObservers.Clear();
  1268. // not force hidden?
  1269. if (identity.visible != Visibility.ForceHidden)
  1270. {
  1271. aoi.OnRebuildObservers(identity, newObservers);
  1272. }
  1273. // IMPORTANT: AFTER rebuilding add own player connection in any case
  1274. // to ensure player always sees himself no matter what.
  1275. // -> OnRebuildObservers might clear observers, so we need to add
  1276. // the player's own connection AFTER. 100% fail safe.
  1277. // -> fixes https://github.com/vis2k/Mirror/issues/692 where a
  1278. // player might teleport out of the ProximityChecker's cast,
  1279. // losing the own connection as observer.
  1280. if (identity.connectionToClient != null)
  1281. {
  1282. newObservers.Add(identity.connectionToClient);
  1283. }
  1284. bool changed = false;
  1285. // add all newObservers that aren't in .observers yet
  1286. foreach (NetworkConnectionToClient conn in newObservers)
  1287. {
  1288. // only add ready connections.
  1289. // otherwise the player might not be in the world yet or anymore
  1290. if (conn != null && conn.isReady)
  1291. {
  1292. if (initialize || !identity.observers.ContainsKey(conn.connectionId))
  1293. {
  1294. // new observer
  1295. conn.AddToObserving(identity);
  1296. // Debug.Log($"New Observer for {gameObject} {conn}");
  1297. changed = true;
  1298. }
  1299. }
  1300. }
  1301. // remove all old .observers that aren't in newObservers anymore
  1302. foreach (NetworkConnectionToClient conn in identity.observers.Values)
  1303. {
  1304. if (!newObservers.Contains(conn))
  1305. {
  1306. // removed observer
  1307. conn.RemoveFromObserving(identity, false);
  1308. // Debug.Log($"Removed Observer for {gameObjec} {conn}");
  1309. changed = true;
  1310. }
  1311. }
  1312. // copy new observers to observers
  1313. if (changed)
  1314. {
  1315. identity.observers.Clear();
  1316. foreach (NetworkConnectionToClient conn in newObservers)
  1317. {
  1318. if (conn != null && conn.isReady)
  1319. identity.observers.Add(conn.connectionId, conn);
  1320. }
  1321. }
  1322. // special case for host mode: we use SetHostVisibility to hide
  1323. // NetworkIdentities that aren't in observer range from host.
  1324. // this is what games like Dota/Counter-Strike do too, where a host
  1325. // does NOT see all players by default. they are in memory, but
  1326. // hidden to the host player.
  1327. //
  1328. // this code is from UNET, it's a bit strange but it works:
  1329. // * it hides newly connected identities in host mode
  1330. // => that part was the intended behaviour
  1331. // * it hides ALL NetworkIdentities in host mode when the host
  1332. // connects but hasn't selected a character yet
  1333. // => this only works because we have no .localConnection != null
  1334. // check. at this stage, localConnection is null because
  1335. // StartHost starts the server first, then calls this code,
  1336. // then starts the client and sets .localConnection. so we can
  1337. // NOT add a null check without breaking host visibility here.
  1338. // * it hides ALL NetworkIdentities in server-only mode because
  1339. // observers never contain the 'null' .localConnection
  1340. // => that was not intended, but let's keep it as it is so we
  1341. // don't break anything in host mode. it's way easier than
  1342. // iterating all identities in a special function in StartHost.
  1343. if (initialize)
  1344. {
  1345. if (!newObservers.Contains(localConnection))
  1346. {
  1347. if (aoi != null)
  1348. aoi.SetHostVisibility(identity, false);
  1349. }
  1350. }
  1351. }
  1352. // RebuildObservers does a local rebuild for the NetworkIdentity.
  1353. // This causes the set of players that can see this object to be rebuild.
  1354. //
  1355. // IMPORTANT:
  1356. // => global rebuild would be more simple, BUT
  1357. // => local rebuild is way faster for spawn/despawn because we can
  1358. // simply rebuild a select NetworkIdentity only
  1359. // => having both .observers and .observing is necessary for local
  1360. // rebuilds
  1361. //
  1362. // in other words, this is the perfect solution even though it's not
  1363. // completely simple (due to .observers & .observing)
  1364. //
  1365. // Mirror maintains .observing automatically in the background. best of
  1366. // both worlds without any worrying now!
  1367. public static void RebuildObservers(NetworkIdentity identity, bool initialize)
  1368. {
  1369. // observers are null until OnStartServer creates them
  1370. if (identity.observers == null)
  1371. return;
  1372. // if there is no interest management system,
  1373. // or if 'force shown' then add all connections
  1374. if (aoi == null || identity.visible == Visibility.ForceShown)
  1375. {
  1376. RebuildObserversDefault(identity, initialize);
  1377. }
  1378. // otherwise let interest management system rebuild
  1379. else
  1380. {
  1381. RebuildObserversCustom(identity, initialize);
  1382. }
  1383. }
  1384. // broadcasting ////////////////////////////////////////////////////////
  1385. // helper function to get the right serialization for a connection
  1386. static NetworkWriter GetEntitySerializationForConnection(NetworkIdentity identity, NetworkConnectionToClient connection)
  1387. {
  1388. // get serialization for this entity (cached)
  1389. // IMPORTANT: int tick avoids floating point inaccuracy over days/weeks
  1390. NetworkIdentitySerialization serialization = identity.GetSerializationAtTick(Time.frameCount);
  1391. // is this entity owned by this connection?
  1392. bool owned = identity.connectionToClient == connection;
  1393. // send serialized data
  1394. // owner writer if owned
  1395. if (owned)
  1396. {
  1397. // was it dirty / did we actually serialize anything?
  1398. if (serialization.ownerWriter.Position > 0)
  1399. return serialization.ownerWriter;
  1400. }
  1401. // observers writer if not owned
  1402. else
  1403. {
  1404. // was it dirty / did we actually serialize anything?
  1405. if (serialization.observersWriter.Position > 0)
  1406. return serialization.observersWriter;
  1407. }
  1408. // nothing was serialized
  1409. return null;
  1410. }
  1411. // helper function to broadcast the world to a connection
  1412. static void BroadcastToConnection(NetworkConnectionToClient connection)
  1413. {
  1414. // for each entity that this connection is seeing
  1415. foreach (NetworkIdentity identity in connection.observing)
  1416. {
  1417. // make sure it's not null or destroyed.
  1418. // (which can happen if someone uses
  1419. // GameObject.Destroy instead of
  1420. // NetworkServer.Destroy)
  1421. if (identity != null)
  1422. {
  1423. // get serialization for this entity viewed by this connection
  1424. // (if anything was serialized this time)
  1425. NetworkWriter serialization = GetEntitySerializationForConnection(identity, connection);
  1426. if (serialization != null)
  1427. {
  1428. EntityStateMessage message = new EntityStateMessage
  1429. {
  1430. netId = identity.netId,
  1431. payload = serialization.ToArraySegment()
  1432. };
  1433. connection.Send(message);
  1434. }
  1435. }
  1436. // spawned list should have no null entries because we
  1437. // always call Remove in OnObjectDestroy everywhere.
  1438. // if it does have null then someone used
  1439. // GameObject.Destroy instead of NetworkServer.Destroy.
  1440. else Debug.LogWarning($"Found 'null' entry in observing list for connectionId={connection.connectionId}. Please call NetworkServer.Destroy to destroy networked objects. Don't use GameObject.Destroy.");
  1441. }
  1442. }
  1443. // NetworkLateUpdate called after any Update/FixedUpdate/LateUpdate
  1444. // (we add this to the UnityEngine in NetworkLoop)
  1445. // internal for tests
  1446. internal static readonly List<NetworkConnectionToClient> connectionsCopy =
  1447. new List<NetworkConnectionToClient>();
  1448. static void Broadcast()
  1449. {
  1450. // copy all connections into a helper collection so that
  1451. // OnTransportDisconnected can be called while iterating.
  1452. // -> OnTransportDisconnected removes from the collection
  1453. // -> which would throw 'can't modify while iterating' errors
  1454. // => see also: https://github.com/vis2k/Mirror/issues/2739
  1455. // (copy nonalloc)
  1456. // TODO remove this when we move to 'lite' transports with only
  1457. // socket send/recv later.
  1458. connectionsCopy.Clear();
  1459. connections.Values.CopyTo(connectionsCopy);
  1460. // go through all connections
  1461. foreach (NetworkConnectionToClient connection in connectionsCopy)
  1462. {
  1463. // has this connection joined the world yet?
  1464. // for each READY connection:
  1465. // pull in UpdateVarsMessage for each entity it observes
  1466. if (connection.isReady)
  1467. {
  1468. // broadcast world state to this connection
  1469. BroadcastToConnection(connection);
  1470. }
  1471. // update connection to flush out batched messages
  1472. connection.Update();
  1473. }
  1474. // TODO this is way too slow because we iterate ALL spawned :/
  1475. // TODO this is way too complicated :/
  1476. // to understand what this tries to prevent, consider this example:
  1477. // monster has health=100
  1478. // we change health=200, dirty bit is set
  1479. // player comes in range, gets full serialization spawn packet.
  1480. // next Broadcast(), player gets the health=200 change because dirty bit was set.
  1481. //
  1482. // this code clears all dirty bits if no players are around to prevent it.
  1483. // BUT there are two issues:
  1484. // 1. what if a playerB was around the whole time?
  1485. // 2. why don't we handle broadcast and spawn packets both HERE?
  1486. // handling spawn separately is why we need this complex magic
  1487. //
  1488. // see test: DirtyBitsAreClearedForSpawnedWithoutObservers()
  1489. // see test: SyncObjectChanges_DontGrowWithoutObservers()
  1490. //
  1491. // PAUL: we also do this to avoid ever growing SyncList .changes
  1492. //ClearSpawnedDirtyBits();
  1493. //
  1494. // this was moved to NetworkIdentity.AddObserver!
  1495. // same result, but no more O(N) loop in here!
  1496. // TODO remove this comment after moving spawning into Broadcast()!
  1497. }
  1498. // update //////////////////////////////////////////////////////////////
  1499. // NetworkEarlyUpdate called before any Update/FixedUpdate
  1500. // (we add this to the UnityEngine in NetworkLoop)
  1501. internal static void NetworkEarlyUpdate()
  1502. {
  1503. // process all incoming messages first before updating the world
  1504. if (Transport.activeTransport != null)
  1505. Transport.activeTransport.ServerEarlyUpdate();
  1506. }
  1507. internal static void NetworkLateUpdate()
  1508. {
  1509. // only broadcast world if active
  1510. if (active)
  1511. Broadcast();
  1512. // process all outgoing messages after updating the world
  1513. // (even if not active. still want to process disconnects etc.)
  1514. if (Transport.activeTransport != null)
  1515. Transport.activeTransport.ServerLateUpdate();
  1516. }
  1517. }
  1518. }