Connection.h 9.9 KB

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