Connection.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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. #include "Precompiled.h"
  24. #include "Component.h"
  25. #include "Connection.h"
  26. #include "Log.h"
  27. #include "Protocol.h"
  28. #include "Scene.h"
  29. #include <kNet.h>
  30. #include "DebugNew.h"
  31. OBJECTTYPESTATIC(Connection);
  32. Connection::Connection(Context* context, bool isClient, kNet::SharedPtr<kNet::MessageConnection> connection) :
  33. Object(context),
  34. connection_(connection),
  35. frameNumber_(0),
  36. isClient_(isClient),
  37. connectPending_(false),
  38. sceneLoaded_(false)
  39. {
  40. }
  41. Connection::~Connection()
  42. {
  43. // Reset owner from the scene, as this connection is about to be destroyed
  44. if (scene_)
  45. scene_->ResetOwner(this);
  46. }
  47. void Connection::SendMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes)
  48. {
  49. // Make sure not to use kNet internal message ID's
  50. if (msgID <= 0x4 || msgID >= 0x3ffffffe)
  51. {
  52. LOGERROR("Can not send message with reserved ID");
  53. return;
  54. }
  55. connection_->SendMessage(msgID, reliable, inOrder, 0, 0, (const char*)data, numBytes);
  56. }
  57. void Connection::SendMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg)
  58. {
  59. SendMessage(msgID, reliable, inOrder, msg.GetData(), msg.GetSize());
  60. }
  61. void Connection::SendMessage(int msgID, unsigned contentID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes)
  62. {
  63. // Make sure not to use kNet internal message ID's
  64. if (msgID <= 0x4 || msgID >= 0x3ffffffe)
  65. {
  66. LOGERROR("Can not send message with reserved ID");
  67. return;
  68. }
  69. connection_->SendMessage(msgID, reliable, inOrder, 0, contentID, (const char*)data, numBytes);
  70. }
  71. void Connection::SendMessage(int msgID, unsigned contentID, bool reliable, bool inOrder, const VectorBuffer& msg)
  72. {
  73. SendMessage(msgID, contentID, reliable, inOrder, msg.GetData(), msg.GetSize());
  74. }
  75. void Connection::SendRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData)
  76. {
  77. msg_.Clear();
  78. msg_.WriteStringHash(eventType);
  79. msg_.WriteVariantMap(eventData);
  80. SendMessage(MSG_REMOTEEVENT, true, inOrder, msg_);
  81. }
  82. void Connection::SendRemoteEvent(Node* receiver, StringHash eventType, bool inOrder, const VariantMap& eventData)
  83. {
  84. if (!receiver)
  85. {
  86. LOGERROR("Null node for remote node event");
  87. return;
  88. }
  89. if (receiver->GetScene() != scene_)
  90. {
  91. LOGERROR("Node is not in the connection's scene, can not send remote node event");
  92. return;
  93. }
  94. if (receiver->GetID() >= FIRST_LOCAL_ID)
  95. {
  96. LOGERROR("Node has a local ID, can not send remote node event");
  97. return;
  98. }
  99. msg_.Clear();
  100. msg_.WriteVLE(receiver->GetID());
  101. msg_.WriteStringHash(eventType);
  102. msg_.WriteVariantMap(eventData);
  103. SendMessage(MSG_REMOTENODEEVENT, true, inOrder, msg_);
  104. }
  105. void Connection::SetScene(Scene* newScene)
  106. {
  107. if (scene_ == newScene)
  108. return;
  109. // Reset the owner reference from the previous scene's nodes
  110. if (scene_)
  111. scene_->ResetOwner(this);
  112. scene_ = newScene;
  113. sceneLoaded_ = false;
  114. if (!scene_)
  115. return;
  116. if (isClient_)
  117. {
  118. sceneState_.Clear();
  119. // When scene is assigned on the server, instruct the client to load it
  120. /// \todo Download package(s) needed for the scene, if they do not exist already on the client
  121. msg_.Clear();
  122. msg_.WriteString(scene_->GetFileName());
  123. SendMessage(MSG_LOADSCENE, true, true, msg_);
  124. }
  125. else
  126. {
  127. // Make sure there is no existing async loading
  128. scene_->StopAsyncLoading();
  129. }
  130. }
  131. void Connection::SetSceneLoaded(bool loaded)
  132. {
  133. sceneLoaded_ = loaded;
  134. }
  135. void Connection::SetIdentity(const VariantMap& identity)
  136. {
  137. identity_ = identity;
  138. }
  139. void Connection::SetControls(const Controls& newControls)
  140. {
  141. previousControls_ = controls_;
  142. controls_ = newControls;
  143. }
  144. void Connection::SetConnectPending(bool connectPending)
  145. {
  146. connectPending_ = connectPending;
  147. }
  148. void Connection::Disconnect(int waitMSec)
  149. {
  150. connection_->Disconnect(waitMSec);
  151. }
  152. void Connection::ProcessReplication()
  153. {
  154. if (!isClient_ || !scene_ || !sceneLoaded_)
  155. return;
  156. const Map<unsigned, Node*>& nodes = scene_->GetAllNodes();
  157. // Check for new or changed nodes
  158. // Start from the root node (scene) so that the scene-wide components get sent first
  159. processedNodes_.Clear();
  160. ProcessNode(scene_);
  161. // Then go through the rest of the nodes
  162. for (Map<unsigned, Node*>::ConstIterator i = nodes.Begin(); i != nodes.End() && i->first_ < FIRST_LOCAL_ID; ++i)
  163. ProcessNode(i->second_);
  164. // Check for removed nodes
  165. for (Map<unsigned, NodeReplicationState>::Iterator i = sceneState_.Begin(); i != sceneState_.End();)
  166. {
  167. Map<unsigned, NodeReplicationState>::Iterator current = i++;
  168. if (current->second_.frameNumber_ != frameNumber_)
  169. {
  170. msg_.Clear();
  171. msg_.WriteVLE(current->first_);
  172. SendMessage(MSG_REMOVENODE, true, true, msg_);
  173. sceneState_.Erase(current);
  174. }
  175. }
  176. ++frameNumber_;
  177. }
  178. kNet::MessageConnection* Connection::GetMessageConnection() const
  179. {
  180. return const_cast<kNet::MessageConnection*>(connection_.ptr());
  181. }
  182. Scene* Connection::GetScene() const
  183. {
  184. return scene_;
  185. }
  186. bool Connection::IsConnected() const
  187. {
  188. return connection_->GetConnectionState() == kNet::ConnectionOK;
  189. }
  190. String Connection::GetAddress() const
  191. {
  192. const unsigned char* ip = connection_->RemoteEndPoint().ip;
  193. char str[256];
  194. sprintf(str, "%d.%d.%d.%d", (unsigned)ip[0], (unsigned)ip[1], (unsigned)ip[2], (unsigned)ip[3]);
  195. return String(str);
  196. }
  197. unsigned short Connection::GetPort() const
  198. {
  199. return connection_->RemoteEndPoint().port;
  200. }
  201. String Connection::ToString() const
  202. {
  203. return GetAddress() + ":" + String(GetPort());
  204. }
  205. void Connection::ProcessNode(Node* node)
  206. {
  207. unsigned nodeID = node->GetID();
  208. if (processedNodes_.Contains(nodeID))
  209. return;
  210. processedNodes_.Insert(nodeID);
  211. // Process parent node first
  212. Node* parent = node->GetParent();
  213. if (parent)
  214. {
  215. // If parent is local, proceed to first non-local node in hierarchy
  216. while (parent->GetID() >= FIRST_LOCAL_ID)
  217. parent = parent->GetParent();
  218. ProcessNode(parent);
  219. }
  220. // Check if the client's scene state already has this node
  221. if (sceneState_.Find(nodeID) != sceneState_.End())
  222. ProcessExistingNode(node);
  223. else
  224. ProcessNewNode(node);
  225. }
  226. void Connection::ProcessNewNode(Node* node)
  227. {
  228. msg_.Clear();
  229. msg_.WriteVLE(node->GetID());
  230. NodeReplicationState newNodeState;
  231. newNodeState.frameNumber_ = frameNumber_;
  232. // Write node's attributes
  233. WriteInitialAttributes(msg_, node, newNodeState.attributes_);
  234. // Write node's variable map
  235. const VariantMap& vars = node->GetVars();
  236. msg_.WriteVLE(vars.Size());
  237. for (VariantMap::ConstIterator i = vars.Begin(); i != vars.End(); ++i)
  238. {
  239. msg_.WriteShortStringHash(i->first_);
  240. msg_.WriteVariant(i->second_);
  241. newNodeState.vars_[i->first_] = i->second_;
  242. }
  243. // Write node's components
  244. msg_.WriteVLE(node->GetNumNetworkComponents());
  245. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  246. for (unsigned i = 0; i < components.Size(); ++i)
  247. {
  248. Component* component = components[i];
  249. if (component->GetID() >= FIRST_LOCAL_ID)
  250. continue;
  251. msg_.WriteShortStringHash(component->GetType());
  252. msg_.WriteVLE(component->GetID());
  253. ComponentReplicationState newComponentState;
  254. newComponentState.frameNumber_ = frameNumber_;
  255. newComponentState.type_ = component->GetType();
  256. // Write component's attributes
  257. WriteInitialAttributes(msg_, component, newComponentState.attributes_);
  258. newNodeState.components_[component->GetID()] = newComponentState;
  259. }
  260. SendMessage(MSG_CREATENODE, true, true, msg_);
  261. sceneState_[node->GetID()] = newNodeState;
  262. }
  263. void Connection::ProcessExistingNode(Node* node)
  264. {
  265. NodeReplicationState& nodeState = sceneState_[node->GetID()];
  266. nodeState.frameNumber_ = frameNumber_;
  267. // Check if attributes have changed
  268. bool deltaUpdate = false;
  269. bool latestData = false;
  270. const Vector<AttributeInfo>* attributes = node->GetAttributes();
  271. deltaUpdateBits_.Resize((node->GetNumNetworkAttributes() + 7) >> 3);
  272. for (unsigned i = 0; i < deltaUpdateBits_.Size(); ++i)
  273. deltaUpdateBits_[i] = 0;
  274. unsigned index = 0;
  275. for (unsigned i = 0; i < attributes->Size(); ++i)
  276. {
  277. const AttributeInfo& attr = attributes->At(i);
  278. if (!(attr.mode_ & AM_NET))
  279. continue;
  280. // Check for attribute change
  281. Variant value = node->GetAttribute(i);
  282. if (value != nodeState.attributes_[index])
  283. {
  284. nodeState.attributes_[index] = value;
  285. if (attr.mode_ & AM_LATESTDATA)
  286. latestData = true;
  287. else
  288. {
  289. deltaUpdate = true;
  290. deltaUpdateBits_[index >> 3] |= 1 << (index & 7);
  291. }
  292. }
  293. ++index;
  294. }
  295. // Check if variable map has changed. Note: variable removal is not supported
  296. changedVars_.Clear();
  297. const VariantMap& vars = node->GetVars();
  298. for (VariantMap::ConstIterator i = vars.Begin(); i != vars.End(); ++i)
  299. {
  300. VariantMap::Iterator j = nodeState.vars_.Find(i->first_);
  301. if (j == nodeState.vars_.End() || i->second_ != j->second_)
  302. {
  303. j->second_ = i->second_;
  304. changedVars_.Insert(i->first_);
  305. deltaUpdate = true;
  306. }
  307. }
  308. // Send deltaupdate message if necessary
  309. if (deltaUpdate)
  310. {
  311. msg_.Clear();
  312. msg_.WriteVLE(node->GetID());
  313. // Write changed attributes
  314. msg_.Write(&deltaUpdateBits_[0], deltaUpdateBits_.Size());
  315. index = 0;
  316. for (unsigned i = 0; i < attributes->Size(); ++i)
  317. {
  318. const AttributeInfo& attr = attributes->At(i);
  319. if (!(attr.mode_ & AM_NET))
  320. continue;
  321. if (deltaUpdateBits_[index << 3] & (1 << (index & 7)))
  322. msg_.WriteVariantData(nodeState.attributes_[index]);
  323. ++index;
  324. }
  325. // Write changed variables
  326. msg_.WriteVLE(changedVars_.Size());
  327. for (HashSet<ShortStringHash>::ConstIterator i = changedVars_.Begin(); i != changedVars_.End(); ++i)
  328. {
  329. VariantMap::ConstIterator j = vars.Find(*i);
  330. msg_.WriteShortStringHash(j->first_);
  331. msg_.WriteVariant(j->second_);
  332. }
  333. SendMessage(MSG_NODEDELTAUPDATE, true, true, msg_);
  334. }
  335. // Send latestdata message if necessary
  336. if (latestData)
  337. {
  338. // If at least one latest data attribute changes, send all of them
  339. msg_.Clear();
  340. msg_.WriteVLE(node->GetID());
  341. index = 0;
  342. for (unsigned i = 0; i < attributes->Size(); ++i)
  343. {
  344. const AttributeInfo& attr = attributes->At(i);
  345. if (!(attr.mode_ & AM_NET))
  346. continue;
  347. if (attr.mode_ & AM_LATESTDATA)
  348. msg_.WriteVariantData(nodeState.attributes_[index]);
  349. ++index;
  350. }
  351. SendMessage(MSG_NODELATESTDATA, node->GetID(), true, false, msg_);
  352. }
  353. // Check for new or changed components
  354. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  355. for (unsigned i = 0; i < components.Size(); ++i)
  356. {
  357. Component* component = components[i];
  358. if (component->GetID() >= FIRST_LOCAL_ID)
  359. continue;
  360. Map<unsigned, ComponentReplicationState>::Iterator j = nodeState.components_.Find(component->GetID());
  361. if (j == nodeState.components_.End())
  362. {
  363. // New component
  364. msg_.Clear();
  365. msg_.WriteVLE(node->GetID());
  366. msg_.WriteShortStringHash(component->GetType());
  367. msg_.WriteVLE(component->GetID());
  368. ComponentReplicationState newComponentState;
  369. newComponentState.frameNumber_ = frameNumber_;
  370. newComponentState.type_ = component->GetType();
  371. // Write component's attributes
  372. WriteInitialAttributes(msg_, component, newComponentState.attributes_);
  373. SendMessage(MSG_CREATECOMPONENT, true, true, msg_);
  374. nodeState.components_[component->GetID()] = newComponentState;
  375. }
  376. else
  377. {
  378. // Existing component
  379. ComponentReplicationState& componentState = j->second_;
  380. componentState.frameNumber_ = frameNumber_;
  381. deltaUpdate = false;
  382. latestData = false;
  383. const Vector<AttributeInfo>* attributes = component->GetAttributes();
  384. deltaUpdateBits_.Resize((component->GetNumNetworkAttributes() + 7) >> 3);
  385. for (unsigned k = 0; k < deltaUpdateBits_.Size(); ++k)
  386. deltaUpdateBits_[k] = 0;
  387. index = 0;
  388. for (unsigned k = 0; k < attributes->Size(); ++k)
  389. {
  390. const AttributeInfo& attr = attributes->At(k);
  391. if (!(attr.mode_ & AM_NET))
  392. continue;
  393. // Check for attribute change
  394. Variant value = component->GetAttribute(k);
  395. if (value != componentState.attributes_[index])
  396. {
  397. componentState.attributes_[index] = value;
  398. if (attr.mode_ & AM_LATESTDATA)
  399. latestData = true;
  400. else
  401. {
  402. deltaUpdate = true;
  403. deltaUpdateBits_[index >> 3] |= 1 << (index & 7);
  404. }
  405. }
  406. ++index;
  407. }
  408. // Send deltaupdate message if necessary
  409. if (deltaUpdate)
  410. {
  411. msg_.Clear();
  412. msg_.WriteVLE(component->GetID());
  413. // Write changed attributes
  414. msg_.Write(&deltaUpdateBits_[0], deltaUpdateBits_.Size());
  415. index = 0;
  416. for (unsigned k = 0; k < attributes->Size(); ++k)
  417. {
  418. const AttributeInfo& attr = attributes->At(k);
  419. if (!(attr.mode_ & AM_NET))
  420. continue;
  421. if (deltaUpdateBits_[index << 3] & (1 << (index & 7)))
  422. msg_.WriteVariantData(componentState.attributes_[index]);
  423. ++index;
  424. }
  425. SendMessage(MSG_COMPONENTDELTAUPDATE, true, true, msg_);
  426. }
  427. // Send latestdata message if necessary
  428. if (latestData)
  429. {
  430. // If at least one latest data attribute changes, send all of them
  431. msg_.Clear();
  432. msg_.WriteVLE(component->GetID());
  433. index = 0;
  434. for (unsigned k = 0; k < attributes->Size(); ++k)
  435. {
  436. const AttributeInfo& attr = attributes->At(k);
  437. if (!(attr.mode_ & AM_NET))
  438. continue;
  439. if (attr.mode_ & AM_LATESTDATA)
  440. msg_.WriteVariantData(componentState.attributes_[index]);
  441. ++index;
  442. }
  443. SendMessage(MSG_COMPONENTLATESTDATA, component->GetID(), true, false, msg_);
  444. }
  445. }
  446. }
  447. // Check for removed components
  448. for (Map<unsigned, ComponentReplicationState>::Iterator i = nodeState.components_.Begin(); i != nodeState.components_.End();)
  449. {
  450. Map<unsigned, ComponentReplicationState>::Iterator current = i++;
  451. if (current->second_.frameNumber_ != frameNumber_)
  452. {
  453. msg_.Clear();
  454. msg_.WriteVLE(node->GetID());
  455. msg_.WriteVLE(current->first_);
  456. SendMessage(MSG_REMOVECOMPONENT, true, true, msg_);
  457. nodeState.components_.Erase(current);
  458. }
  459. }
  460. }
  461. void Connection::WriteInitialAttributes(VectorBuffer& msg, Serializable* serializable, Vector<Variant>& attributeState)
  462. {
  463. const Vector<AttributeInfo>* attributes = serializable->GetAttributes();
  464. unsigned numAttributes = serializable->GetNumNetworkAttributes();
  465. if (!numAttributes)
  466. return;
  467. attributeState.Resize(numAttributes);
  468. deltaUpdateBits_.Resize((numAttributes + 7) >> 3);
  469. for (unsigned i = 0; i < deltaUpdateBits_.Size(); ++i)
  470. deltaUpdateBits_[i] = 0;
  471. unsigned index = 0;
  472. for (unsigned i = 0; i < attributes->Size(); ++i)
  473. {
  474. const AttributeInfo& attr = attributes->At(i);
  475. if (!(attr.mode_ & AM_NET))
  476. continue;
  477. Variant value = serializable->GetAttribute(i);
  478. if (value != attr.defaultValue_)
  479. {
  480. attributeState[index] = value;
  481. deltaUpdateBits_[index >> 3] |= (1 << (index & 7));
  482. }
  483. else
  484. attributeState[index] = attr.defaultValue_;
  485. ++index;
  486. }
  487. msg.Write(&deltaUpdateBits_[0], deltaUpdateBits_.Size());
  488. index = 0;
  489. for (unsigned i = 0; i < attributes->Size(); ++i)
  490. {
  491. const AttributeInfo& attr = attributes->At(i);
  492. if (!(attr.mode_ & AM_NET))
  493. continue;
  494. if (deltaUpdateBits_[index << 3] & (1 << (index & 7)))
  495. msg.WriteVariantData(attributeState[index]);
  496. ++index;
  497. }
  498. }