Connection.h 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #pragma once
  24. #include "Controls.h"
  25. #include "HashSet.h"
  26. #include "Object.h"
  27. #include "ReplicationState.h"
  28. #include "Timer.h"
  29. #include "VectorBuffer.h"
  30. #include <kNetFwd.h>
  31. #include <kNet/SharedPtr.h>
  32. #ifdef SendMessage
  33. #undef SendMessage
  34. #endif
  35. class File;
  36. class MemoryBuffer;
  37. class Node;
  38. class Scene;
  39. class Serializable;
  40. /// Queued remote event.
  41. struct RemoteEvent
  42. {
  43. /// Receiver node ID (0 if not a remote node event.)
  44. unsigned receiverID_;
  45. /// Event type.
  46. StringHash eventType_;
  47. /// Event data.
  48. VariantMap eventData_;
  49. /// In order flag.
  50. bool inOrder_;
  51. };
  52. /// Package file receive transfer.
  53. struct PackageDownload
  54. {
  55. /// Construct with defaults.
  56. PackageDownload();
  57. /// Destination file.
  58. SharedPtr<File> file_;
  59. /// Already received fragments.
  60. HashSet<unsigned> receivedFragments_;
  61. /// Package name.
  62. String name_;
  63. /// Total number of fragments.
  64. unsigned totalFragments_;
  65. /// Checksum.
  66. unsigned checksum_;
  67. /// Download initiated flag.
  68. bool initiated_;
  69. };
  70. /// Package file send transfer.
  71. struct PackageUpload
  72. {
  73. /// Construct with defaults.
  74. PackageUpload();
  75. /// Source file.
  76. SharedPtr<File> file_;
  77. /// Current fragment index.
  78. unsigned fragment_;
  79. /// Total number of fragments
  80. unsigned totalFragments_;
  81. };
  82. /// %Connection to a remote network host.
  83. class Connection : public Object
  84. {
  85. OBJECT(Connection);
  86. public:
  87. /// Construct with context and kNet message connection pointers.
  88. Connection(Context* context, bool isClient, kNet::SharedPtr<kNet::MessageConnection> connection);
  89. /// Destruct.
  90. ~Connection();
  91. /// Send a message.
  92. void SendMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg, unsigned contentID = 0);
  93. /// Send a message.
  94. void SendMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes, unsigned contentID = 0);
  95. /// Send a remote event.
  96. void SendRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData = VariantMap());
  97. /// Send a remote node event.
  98. void SendRemoteEvent(Node* receiver, StringHash eventType, bool inOrder, const VariantMap& eventData = VariantMap());
  99. /// Assign scene. On the server, this will cause the client to load it.
  100. void SetScene(Scene* newScene);
  101. /// Assign identity. Called by Network.
  102. void SetIdentity(const VariantMap& identity);
  103. /// %Set new controls.
  104. void SetControls(const Controls& newControls);
  105. /// %Set the observer position for interest management.
  106. void SetPosition(const Vector3& position);
  107. /// %Set the connection pending status. Called by Network.
  108. void SetConnectPending(bool connectPending);
  109. /// %Set whether to log data in/out statistics.
  110. void SetLogStatistics(bool enable);
  111. /// Disconnect. If wait time is non-zero, will block while waiting for disconnect to finish.
  112. void Disconnect(int waitMSec = 0);
  113. /// Send scene update messages. Called by Network.
  114. void SendServerUpdate();
  115. /// Send latest controls from the client. Called by Network.
  116. void SendClientUpdate();
  117. /// Send queued remote events. Called by Network.
  118. void SendRemoteEvents();
  119. /// Send package files to client. Called by network.
  120. void SendPackages();
  121. /// Process pending latest data for nodes and components.
  122. void ProcessPendingLatestData();
  123. /// Process a LoadScene message from the server. Called by Network.
  124. void ProcessLoadScene(int msgID, MemoryBuffer& msg);
  125. /// Process a SceneChecksumError message from the server. Called by Network.
  126. void ProcessSceneChecksumError(int msgID, MemoryBuffer& msg);
  127. /// Process a scene update message from the server. Called by Network.
  128. void ProcessSceneUpdate(int msgID, MemoryBuffer& msg);
  129. /// Process package download related messages. Called by Network.
  130. void ProcessPackageDownload(int msgID, MemoryBuffer& msg);
  131. /// Process an Identity message from the client. Called by Network.
  132. void ProcessIdentity(int msgID, MemoryBuffer& msg);
  133. /// Process a Controls message from the client. Called by Network.
  134. void ProcessControls(int msgID, MemoryBuffer& msg);
  135. /// Process a SceneLoaded message from the client. Called by Network.
  136. void ProcessSceneLoaded(int msgID, MemoryBuffer& msg);
  137. /// Process a remote event message from the client or server. Called by Network.
  138. void ProcessRemoteEvent(int msgID, MemoryBuffer& msg);
  139. /// Return the kNet message connection.
  140. kNet::MessageConnection* GetMessageConnection() const;
  141. /// Return client identity.
  142. const VariantMap& GetIdentity() const { return identity_; }
  143. /// Return the scene used by this connection.
  144. Scene* GetScene() const;
  145. /// Return the client controls of this connection.
  146. const Controls& GetControls() const { return controls_; }
  147. /// Return the observer position for interest management.
  148. const Vector3& GetPosition() const { return position_; }
  149. /// Return whether is a client connection.
  150. bool IsClient() const { return isClient_; }
  151. /// Return whether is fully connected.
  152. bool IsConnected() const;
  153. /// Return whether connection is pending.
  154. bool IsConnectPending() const { return connectPending_; }
  155. /// Return whether the scene is loaded and ready to receive server updates.
  156. bool IsSceneLoaded() const { return sceneLoaded_; }
  157. /// Return whether to log data in/out statistics.
  158. bool GetLogStatistics() const { return logStatistics_; }
  159. /// Return remote address.
  160. String GetAddress() const;
  161. /// Return remote port.
  162. unsigned short GetPort() const;
  163. /// Return an address:port string.
  164. String ToString() const;
  165. /// Return number of package downloads remaining.
  166. unsigned GetNumDownloads() const;
  167. /// Return name of current package download, or empty if no downloads.
  168. const String& GetDownloadName() const;
  169. /// Return progress of current package download, or 1.0 if no downloads.
  170. float GetDownloadProgress() const;
  171. /// Observer position for interest management.
  172. Vector3 position_;
  173. /// Current controls.
  174. Controls controls_;
  175. /// Identity map.
  176. VariantMap identity_;
  177. private:
  178. /// Handle scene loaded event.
  179. void HandleAsyncLoadFinished(StringHash eventType, VariantMap& eventData);
  180. /// Process a node for sending a network update. Recurses to process depended on node(s) first.
  181. void ProcessNode(unsigned nodeID);
  182. /// Process a node that the client has not yet received.
  183. void ProcessNewNode(Node* node);
  184. /// Process a node that the client has already received.
  185. void ProcessExistingNode(Node* node, NodeReplicationState& nodeState);
  186. /// Initiate a package download.
  187. void RequestPackage(const String& name, unsigned fileSize, unsigned checksum);
  188. /// Send an error reply for a package download.
  189. void SendPackageError(const String& name);
  190. /// Handle scene load failure on the server or client.
  191. void OnSceneLoadFailed();
  192. /// Handle a package download failure on the client.
  193. void OnPackageDownloadFailed(const String& name);
  194. /// Handle all packages loaded successfully. Also called directly on MSG_LOADSCENE if there are none.
  195. void OnPackagesReady();
  196. /// kNet message connection.
  197. kNet::SharedPtr<kNet::MessageConnection> connection_;
  198. /// Scene.
  199. WeakPtr<Scene> scene_;
  200. /// Network replication state of the scene.
  201. SceneReplicationState sceneState_;
  202. /// Waiting or ongoing package file receive transfers.
  203. HashMap<StringHash, PackageDownload> downloads_;
  204. /// Ongoing package send transfers.
  205. HashMap<StringHash, PackageUpload> uploads_;
  206. /// Pending latest data for not yet received nodes.
  207. HashMap<unsigned, PODVector<unsigned char> > nodeLatestData_;
  208. /// Pending latest data for not yet received components.
  209. HashMap<unsigned, PODVector<unsigned char> > componentLatestData_;
  210. /// Node ID's to process during a replication update.
  211. HashSet<unsigned> nodesToProcess_;
  212. /// Reusable message buffer.
  213. VectorBuffer msg_;
  214. /// Queued remote events.
  215. Vector<RemoteEvent> remoteEvents_;
  216. /// Scene file to load once all packages (if any) have been downloaded.
  217. String sceneFileName_;
  218. /// Statistics timer.
  219. Timer statsTimer_;
  220. /// Client connection flag.
  221. bool isClient_;
  222. /// Connection pending flag.
  223. bool connectPending_;
  224. /// Scene loaded flag.
  225. bool sceneLoaded_;
  226. /// Show statistics flag.
  227. bool logStatistics_;
  228. };