Connection.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  1. //
  2. // Copyright (c) 2008-2018 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. #include "../Precompiled.h"
  23. #include "../Core/Profiler.h"
  24. #include "../IO/File.h"
  25. #include "../IO/FileSystem.h"
  26. #include "../IO/Log.h"
  27. #include "../IO/MemoryBuffer.h"
  28. #include "../IO/PackageFile.h"
  29. #include "../Network/Connection.h"
  30. #include "../Network/Network.h"
  31. #include "../Network/NetworkEvents.h"
  32. #include "../Network/NetworkPriority.h"
  33. #include "../Network/Protocol.h"
  34. #include "../Resource/ResourceCache.h"
  35. #include "../Scene/Scene.h"
  36. #include "../Scene/SceneEvents.h"
  37. #include "../Scene/SmoothedTransform.h"
  38. #include <SLikeNet/peerinterface.h>
  39. #include <SLikeNet/statistics.h>
  40. #ifdef SendMessage
  41. #undef SendMessage
  42. #endif
  43. #include "../DebugNew.h"
  44. #include <cstdio>
  45. namespace Urho3D
  46. {
  47. static const int STATS_INTERVAL_MSEC = 2000;
  48. PackageDownload::PackageDownload() :
  49. totalFragments_(0),
  50. checksum_(0),
  51. initiated_(false)
  52. {
  53. }
  54. PackageUpload::PackageUpload() :
  55. fragment_(0),
  56. totalFragments_(0)
  57. {
  58. }
  59. Connection::Connection(Context* context, bool isClient, const SLNet::AddressOrGUID& address, SLNet::RakPeerInterface* peer) :
  60. Object(context),
  61. timeStamp_(0),
  62. peer_(peer),
  63. sendMode_(OPSM_NONE),
  64. isClient_(isClient),
  65. connectPending_(false),
  66. sceneLoaded_(false),
  67. logStatistics_(false),
  68. address_(nullptr)
  69. {
  70. sceneState_.connection_ = this;
  71. port_ = address.systemAddress.GetPort();
  72. SetAddressOrGUID(address);
  73. }
  74. Connection::~Connection()
  75. {
  76. // Reset scene (remove possible owner references), as this connection is about to be destroyed
  77. SetScene(nullptr);
  78. delete address_;
  79. address_ = nullptr;
  80. }
  81. void Connection::SendMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg, unsigned contentID)
  82. {
  83. SendMessage(msgID, reliable, inOrder, msg.GetData(), msg.GetSize(), contentID);
  84. }
  85. void Connection::SendMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes,
  86. unsigned contentID)
  87. {
  88. /* Make sure not to use SLikeNet(RakNet) internal message ID's
  89. and since RakNet uses 1 byte message ID's, they cannot exceed 255 limit */
  90. if (msgID <= 0x4 || msgID >= 255)
  91. {
  92. URHO3D_LOGERROR("Can not send message with reserved ID");
  93. return;
  94. }
  95. if (numBytes && !data)
  96. {
  97. URHO3D_LOGERROR("Null pointer supplied for network message data");
  98. return;
  99. }
  100. VectorBuffer buffer;
  101. buffer.WriteUByte((unsigned char)msgID);
  102. buffer.Write(data, numBytes);
  103. PacketReliability reliability = reliable ? (inOrder ? RELIABLE_ORDERED : RELIABLE) : (inOrder ? UNRELIABLE_SEQUENCED : UNRELIABLE);
  104. if (peer_) {
  105. peer_->Send((const char *) buffer.GetData(), (int) buffer.GetSize(), HIGH_PRIORITY, reliability, (char) 0, *address_, false);
  106. tempPacketCounter_.y_++;
  107. }
  108. }
  109. void Connection::SendRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData)
  110. {
  111. RemoteEvent queuedEvent;
  112. queuedEvent.senderID_ = 0;
  113. queuedEvent.eventType_ = eventType;
  114. queuedEvent.eventData_ = eventData;
  115. queuedEvent.inOrder_ = inOrder;
  116. remoteEvents_.Push(queuedEvent);
  117. }
  118. void Connection::SendRemoteEvent(Node* node, StringHash eventType, bool inOrder, const VariantMap& eventData)
  119. {
  120. if (!node)
  121. {
  122. URHO3D_LOGERROR("Null sender node for remote node event");
  123. return;
  124. }
  125. if (node->GetScene() != scene_)
  126. {
  127. URHO3D_LOGERROR("Sender node is not in the connection's scene, can not send remote node event");
  128. return;
  129. }
  130. if (!node->IsReplicated())
  131. {
  132. URHO3D_LOGERROR("Sender node has a local ID, can not send remote node event");
  133. return;
  134. }
  135. RemoteEvent queuedEvent;
  136. queuedEvent.senderID_ = node->GetID();
  137. queuedEvent.eventType_ = eventType;
  138. queuedEvent.eventData_ = eventData;
  139. queuedEvent.inOrder_ = inOrder;
  140. remoteEvents_.Push(queuedEvent);
  141. }
  142. void Connection::SetScene(Scene* newScene)
  143. {
  144. if (scene_)
  145. {
  146. // Remove replication states and owner references from the previous scene
  147. scene_->CleanupConnection(this);
  148. }
  149. scene_ = newScene;
  150. sceneLoaded_ = false;
  151. UnsubscribeFromEvent(E_ASYNCLOADFINISHED);
  152. if (!scene_)
  153. return;
  154. if (isClient_)
  155. {
  156. sceneState_.Clear();
  157. // When scene is assigned on the server, instruct the client to load it. This may require downloading packages
  158. const Vector<SharedPtr<PackageFile> >& packages = scene_->GetRequiredPackageFiles();
  159. unsigned numPackages = packages.Size();
  160. msg_.Clear();
  161. msg_.WriteString(scene_->GetFileName());
  162. msg_.WriteVLE(numPackages);
  163. for (unsigned i = 0; i < numPackages; ++i)
  164. {
  165. PackageFile* package = packages[i];
  166. msg_.WriteString(GetFileNameAndExtension(package->GetName()));
  167. msg_.WriteUInt(package->GetTotalSize());
  168. msg_.WriteUInt(package->GetChecksum());
  169. }
  170. SendMessage(MSG_LOADSCENE, true, true, msg_);
  171. }
  172. else
  173. {
  174. // Make sure there is no existing async loading
  175. scene_->StopAsyncLoading();
  176. SubscribeToEvent(scene_, E_ASYNCLOADFINISHED, URHO3D_HANDLER(Connection, HandleAsyncLoadFinished));
  177. }
  178. }
  179. void Connection::SetIdentity(const VariantMap& identity)
  180. {
  181. identity_ = identity;
  182. }
  183. void Connection::SetControls(const Controls& newControls)
  184. {
  185. controls_ = newControls;
  186. }
  187. void Connection::SetPosition(const Vector3& position)
  188. {
  189. position_ = position;
  190. if (sendMode_ == OPSM_NONE)
  191. sendMode_ = OPSM_POSITION;
  192. }
  193. void Connection::SetRotation(const Quaternion& rotation)
  194. {
  195. rotation_ = rotation;
  196. if (sendMode_ != OPSM_POSITION_ROTATION)
  197. sendMode_ = OPSM_POSITION_ROTATION;
  198. }
  199. void Connection::SetConnectPending(bool connectPending)
  200. {
  201. connectPending_ = connectPending;
  202. }
  203. void Connection::SetLogStatistics(bool enable)
  204. {
  205. logStatistics_ = enable;
  206. }
  207. void Connection::Disconnect(int waitMSec)
  208. {
  209. peer_->CloseConnection(*address_, true);
  210. }
  211. void Connection::SendServerUpdate()
  212. {
  213. if (!scene_ || !sceneLoaded_)
  214. return;
  215. // Always check the root node (scene) first so that the scene-wide components get sent first,
  216. // and all other replicated nodes get added to the dirty set for sending the initial state
  217. unsigned sceneID = scene_->GetID();
  218. nodesToProcess_.Insert(sceneID);
  219. ProcessNode(sceneID);
  220. // Then go through all dirtied nodes
  221. nodesToProcess_.Insert(sceneState_.dirtyNodes_);
  222. nodesToProcess_.Erase(sceneID); // Do not process the root node twice
  223. while (nodesToProcess_.Size())
  224. {
  225. unsigned nodeID = nodesToProcess_.Front();
  226. ProcessNode(nodeID);
  227. }
  228. }
  229. void Connection::SendClientUpdate()
  230. {
  231. if (!scene_ || !sceneLoaded_)
  232. return;
  233. msg_.Clear();
  234. msg_.WriteUInt(controls_.buttons_);
  235. msg_.WriteFloat(controls_.yaw_);
  236. msg_.WriteFloat(controls_.pitch_);
  237. msg_.WriteVariantMap(controls_.extraData_);
  238. msg_.WriteUByte(timeStamp_);
  239. if (sendMode_ >= OPSM_POSITION)
  240. msg_.WriteVector3(position_);
  241. if (sendMode_ >= OPSM_POSITION_ROTATION)
  242. msg_.WritePackedQuaternion(rotation_);
  243. SendMessage(MSG_CONTROLS, false, false, msg_, CONTROLS_CONTENT_ID);
  244. ++timeStamp_;
  245. }
  246. void Connection::SendRemoteEvents()
  247. {
  248. #ifdef URHO3D_LOGGING
  249. if (logStatistics_ && statsTimer_.GetMSec(false) > STATS_INTERVAL_MSEC)
  250. {
  251. statsTimer_.Reset();
  252. char statsBuffer[256];
  253. sprintf(statsBuffer, "RTT %.3f ms Pkt in %i Pkt out %i Data in %.3f KB/s Data out %.3f KB/s, Last heard %u", GetRoundTripTime(),
  254. GetPacketsInPerSec(),
  255. GetPacketsOutPerSec(),
  256. GetBytesInPerSec(),
  257. GetBytesOutPerSec(),
  258. GetLastHeardTime());
  259. URHO3D_LOGINFO(statsBuffer);
  260. }
  261. #endif
  262. if (packetCounterTimer_.GetMSec(false) > 1000)
  263. {
  264. packetCounterTimer_.Reset();
  265. packetCounter_ = tempPacketCounter_;
  266. tempPacketCounter_ = IntVector2::ZERO;
  267. }
  268. if (remoteEvents_.Empty())
  269. return;
  270. URHO3D_PROFILE(SendRemoteEvents);
  271. for (Vector<RemoteEvent>::ConstIterator i = remoteEvents_.Begin(); i != remoteEvents_.End(); ++i)
  272. {
  273. msg_.Clear();
  274. if (!i->senderID_)
  275. {
  276. msg_.WriteStringHash(i->eventType_);
  277. msg_.WriteVariantMap(i->eventData_);
  278. SendMessage(MSG_REMOTEEVENT, true, i->inOrder_, msg_);
  279. }
  280. else
  281. {
  282. msg_.WriteNetID(i->senderID_);
  283. msg_.WriteStringHash(i->eventType_);
  284. msg_.WriteVariantMap(i->eventData_);
  285. SendMessage(MSG_REMOTENODEEVENT, true, i->inOrder_, msg_);
  286. }
  287. }
  288. remoteEvents_.Clear();
  289. }
  290. void Connection::SendPackages()
  291. {
  292. while (!uploads_.Empty())
  293. {
  294. unsigned char buffer[PACKAGE_FRAGMENT_SIZE];
  295. for (HashMap<StringHash, PackageUpload>::Iterator i = uploads_.Begin(); i != uploads_.End();)
  296. {
  297. HashMap<StringHash, PackageUpload>::Iterator current = i++;
  298. PackageUpload& upload = current->second_;
  299. auto fragmentSize =
  300. (unsigned)Min((int)(upload.file_->GetSize() - upload.file_->GetPosition()), (int)PACKAGE_FRAGMENT_SIZE);
  301. upload.file_->Read(buffer, fragmentSize);
  302. msg_.Clear();
  303. msg_.WriteStringHash(current->first_);
  304. msg_.WriteUInt(upload.fragment_++);
  305. msg_.Write(buffer, fragmentSize);
  306. SendMessage(MSG_PACKAGEDATA, true, false, msg_);
  307. // Check if upload finished
  308. if (upload.fragment_ == upload.totalFragments_)
  309. uploads_.Erase(current);
  310. }
  311. }
  312. }
  313. void Connection::ProcessPendingLatestData()
  314. {
  315. if (!scene_ || !sceneLoaded_)
  316. return;
  317. // Iterate through pending node data and see if we can find the nodes now
  318. for (HashMap<unsigned, PODVector<unsigned char> >::Iterator i = nodeLatestData_.Begin(); i != nodeLatestData_.End();)
  319. {
  320. HashMap<unsigned, PODVector<unsigned char> >::Iterator current = i++;
  321. Node* node = scene_->GetNode(current->first_);
  322. if (node)
  323. {
  324. MemoryBuffer msg(current->second_);
  325. msg.ReadNetID(); // Skip the node ID
  326. node->ReadLatestDataUpdate(msg);
  327. // ApplyAttributes() is deliberately skipped, as Node has no attributes that require late applying.
  328. // Furthermore it would propagate to components and child nodes, which is not desired in this case
  329. nodeLatestData_.Erase(current);
  330. }
  331. }
  332. // Iterate through pending component data and see if we can find the components now
  333. for (HashMap<unsigned, PODVector<unsigned char> >::Iterator i = componentLatestData_.Begin(); i != componentLatestData_.End();)
  334. {
  335. HashMap<unsigned, PODVector<unsigned char> >::Iterator current = i++;
  336. Component* component = scene_->GetComponent(current->first_);
  337. if (component)
  338. {
  339. MemoryBuffer msg(current->second_);
  340. msg.ReadNetID(); // Skip the component ID
  341. if (component->ReadLatestDataUpdate(msg))
  342. component->ApplyAttributes();
  343. componentLatestData_.Erase(current);
  344. }
  345. }
  346. }
  347. bool Connection::ProcessMessage(int msgID, MemoryBuffer& msg)
  348. {
  349. URHO3D_LOGINFO("Process message " + String(msgID));
  350. // New incomming message, reset last heard timer
  351. lastHeardTimer_.Reset();
  352. tempPacketCounter_.x_++;
  353. bool processed = true;
  354. switch (msgID)
  355. {
  356. case MSG_IDENTITY:
  357. ProcessIdentity(msgID, msg);
  358. break;
  359. case MSG_CONTROLS:
  360. ProcessControls(msgID, msg);
  361. break;
  362. case MSG_SCENELOADED:
  363. ProcessSceneLoaded(msgID, msg);
  364. break;
  365. case MSG_REQUESTPACKAGE:
  366. case MSG_PACKAGEDATA:
  367. ProcessPackageDownload(msgID, msg);
  368. break;
  369. case MSG_LOADSCENE:
  370. ProcessLoadScene(msgID, msg);
  371. break;
  372. case MSG_SCENECHECKSUMERROR:
  373. ProcessSceneChecksumError(msgID, msg);
  374. break;
  375. case MSG_CREATENODE:
  376. case MSG_NODEDELTAUPDATE:
  377. case MSG_NODELATESTDATA:
  378. case MSG_REMOVENODE:
  379. case MSG_CREATECOMPONENT:
  380. case MSG_COMPONENTDELTAUPDATE:
  381. case MSG_COMPONENTLATESTDATA:
  382. case MSG_REMOVECOMPONENT:
  383. ProcessSceneUpdate(msgID, msg);
  384. break;
  385. case MSG_REMOTEEVENT:
  386. case MSG_REMOTENODEEVENT:
  387. ProcessRemoteEvent(msgID, msg);
  388. break;
  389. case MSG_PACKAGEINFO:
  390. ProcessPackageInfo(msgID, msg);
  391. break;
  392. default:
  393. processed = false;
  394. break;
  395. }
  396. return processed;
  397. }
  398. void Connection::Ban()
  399. {
  400. if (peer_)
  401. {
  402. peer_->AddToBanList(address_->ToString(false), 0);
  403. }
  404. }
  405. void Connection::ProcessLoadScene(int msgID, MemoryBuffer& msg)
  406. {
  407. if (IsClient())
  408. {
  409. URHO3D_LOGWARNING("Received unexpected LoadScene message from client " + ToString());
  410. return;
  411. }
  412. if (!scene_)
  413. {
  414. URHO3D_LOGERROR("Can not handle LoadScene message without an assigned scene");
  415. return;
  416. }
  417. // Store the scene file name we need to eventually load
  418. sceneFileName_ = msg.ReadString();
  419. // Clear previous pending latest data and package downloads if any
  420. nodeLatestData_.Clear();
  421. componentLatestData_.Clear();
  422. downloads_.Clear();
  423. // In case we have joined other scenes in this session, remove first all downloaded package files from the resource system
  424. // to prevent resource conflicts
  425. auto* cache = GetSubsystem<ResourceCache>();
  426. const String& packageCacheDir = GetSubsystem<Network>()->GetPackageCacheDir();
  427. Vector<SharedPtr<PackageFile> > packages = cache->GetPackageFiles();
  428. for (unsigned i = 0; i < packages.Size(); ++i)
  429. {
  430. PackageFile* package = packages[i];
  431. if (!package->GetName().Find(packageCacheDir))
  432. cache->RemovePackageFile(package, true);
  433. }
  434. // Now check which packages we have in the resource cache or in the download cache, and which we need to download
  435. unsigned numPackages = msg.ReadVLE();
  436. if (!RequestNeededPackages(numPackages, msg))
  437. {
  438. OnSceneLoadFailed();
  439. return;
  440. }
  441. // If no downloads were queued, can load the scene directly
  442. if (downloads_.Empty())
  443. OnPackagesReady();
  444. }
  445. void Connection::ProcessSceneChecksumError(int msgID, MemoryBuffer& msg)
  446. {
  447. if (IsClient())
  448. {
  449. URHO3D_LOGWARNING("Received unexpected SceneChecksumError message from client " + ToString());
  450. return;
  451. }
  452. URHO3D_LOGERROR("Scene checksum error");
  453. OnSceneLoadFailed();
  454. }
  455. void Connection::ProcessSceneUpdate(int msgID, MemoryBuffer& msg)
  456. {
  457. /// \todo On mobile devices processing this message may potentially cause a crash if it attempts to load new GPU resources
  458. /// while the application is minimized
  459. if (IsClient())
  460. {
  461. URHO3D_LOGWARNING("Received unexpected SceneUpdate message from client " + ToString());
  462. return;
  463. }
  464. if (!scene_)
  465. return;
  466. switch (msgID)
  467. {
  468. case MSG_CREATENODE:
  469. {
  470. unsigned nodeID = msg.ReadNetID();
  471. // In case of the root node (scene), it should already exist. Do not create in that case
  472. Node* node = scene_->GetNode(nodeID);
  473. if (!node)
  474. {
  475. // Add initially to the root level. May be moved as we receive the parent attribute
  476. node = scene_->CreateChild(nodeID, REPLICATED);
  477. // Create smoothed transform component
  478. node->CreateComponent<SmoothedTransform>(LOCAL);
  479. }
  480. // Read initial attributes, then snap the motion smoothing immediately to the end
  481. node->ReadDeltaUpdate(msg);
  482. auto* transform = node->GetComponent<SmoothedTransform>();
  483. if (transform)
  484. transform->Update(1.0f, 0.0f);
  485. // Read initial user variables
  486. unsigned numVars = msg.ReadVLE();
  487. while (numVars)
  488. {
  489. StringHash key = msg.ReadStringHash();
  490. node->SetVar(key, msg.ReadVariant());
  491. --numVars;
  492. }
  493. // Read components
  494. unsigned numComponents = msg.ReadVLE();
  495. while (numComponents)
  496. {
  497. --numComponents;
  498. StringHash type = msg.ReadStringHash();
  499. unsigned componentID = msg.ReadNetID();
  500. // Check if the component by this ID and type already exists in this node
  501. Component* component = scene_->GetComponent(componentID);
  502. if (!component || component->GetType() != type || component->GetNode() != node)
  503. {
  504. if (component)
  505. component->Remove();
  506. component = node->CreateComponent(type, REPLICATED, componentID);
  507. }
  508. // If was unable to create the component, would desync the message and therefore have to abort
  509. if (!component)
  510. {
  511. URHO3D_LOGERROR("CreateNode message parsing aborted due to unknown component");
  512. return;
  513. }
  514. // Read initial attributes and apply
  515. component->ReadDeltaUpdate(msg);
  516. component->ApplyAttributes();
  517. }
  518. }
  519. break;
  520. case MSG_NODEDELTAUPDATE:
  521. {
  522. unsigned nodeID = msg.ReadNetID();
  523. Node* node = scene_->GetNode(nodeID);
  524. if (node)
  525. {
  526. node->ReadDeltaUpdate(msg);
  527. // ApplyAttributes() is deliberately skipped, as Node has no attributes that require late applying.
  528. // Furthermore it would propagate to components and child nodes, which is not desired in this case
  529. unsigned changedVars = msg.ReadVLE();
  530. while (changedVars)
  531. {
  532. StringHash key = msg.ReadStringHash();
  533. node->SetVar(key, msg.ReadVariant());
  534. --changedVars;
  535. }
  536. }
  537. else
  538. URHO3D_LOGWARNING("NodeDeltaUpdate message received for missing node " + String(nodeID));
  539. }
  540. break;
  541. case MSG_NODELATESTDATA:
  542. {
  543. unsigned nodeID = msg.ReadNetID();
  544. Node* node = scene_->GetNode(nodeID);
  545. if (node)
  546. {
  547. node->ReadLatestDataUpdate(msg);
  548. // ApplyAttributes() is deliberately skipped, as Node has no attributes that require late applying.
  549. // Furthermore it would propagate to components and child nodes, which is not desired in this case
  550. }
  551. else
  552. {
  553. // Latest data messages may be received out-of-order relative to node creation, so cache if necessary
  554. PODVector<unsigned char>& data = nodeLatestData_[nodeID];
  555. data.Resize(msg.GetSize());
  556. memcpy(&data[0], msg.GetData(), msg.GetSize());
  557. }
  558. }
  559. break;
  560. case MSG_REMOVENODE:
  561. {
  562. unsigned nodeID = msg.ReadNetID();
  563. Node* node = scene_->GetNode(nodeID);
  564. if (node)
  565. node->Remove();
  566. nodeLatestData_.Erase(nodeID);
  567. }
  568. break;
  569. case MSG_CREATECOMPONENT:
  570. {
  571. unsigned nodeID = msg.ReadNetID();
  572. Node* node = scene_->GetNode(nodeID);
  573. if (node)
  574. {
  575. StringHash type = msg.ReadStringHash();
  576. unsigned componentID = msg.ReadNetID();
  577. // Check if the component by this ID and type already exists in this node
  578. Component* component = scene_->GetComponent(componentID);
  579. if (!component || component->GetType() != type || component->GetNode() != node)
  580. {
  581. if (component)
  582. component->Remove();
  583. component = node->CreateComponent(type, REPLICATED, componentID);
  584. }
  585. // If was unable to create the component, would desync the message and therefore have to abort
  586. if (!component)
  587. {
  588. URHO3D_LOGERROR("CreateComponent message parsing aborted due to unknown component");
  589. return;
  590. }
  591. // Read initial attributes and apply
  592. component->ReadDeltaUpdate(msg);
  593. component->ApplyAttributes();
  594. }
  595. else
  596. URHO3D_LOGWARNING("CreateComponent message received for missing node " + String(nodeID));
  597. }
  598. break;
  599. case MSG_COMPONENTDELTAUPDATE:
  600. {
  601. unsigned componentID = msg.ReadNetID();
  602. Component* component = scene_->GetComponent(componentID);
  603. if (component)
  604. {
  605. component->ReadDeltaUpdate(msg);
  606. component->ApplyAttributes();
  607. }
  608. else
  609. URHO3D_LOGWARNING("ComponentDeltaUpdate message received for missing component " + String(componentID));
  610. }
  611. break;
  612. case MSG_COMPONENTLATESTDATA:
  613. {
  614. unsigned componentID = msg.ReadNetID();
  615. Component* component = scene_->GetComponent(componentID);
  616. if (component)
  617. {
  618. if (component->ReadLatestDataUpdate(msg))
  619. component->ApplyAttributes();
  620. }
  621. else
  622. {
  623. // Latest data messages may be received out-of-order relative to component creation, so cache if necessary
  624. PODVector<unsigned char>& data = componentLatestData_[componentID];
  625. data.Resize(msg.GetSize());
  626. memcpy(&data[0], msg.GetData(), msg.GetSize());
  627. }
  628. }
  629. break;
  630. case MSG_REMOVECOMPONENT:
  631. {
  632. unsigned componentID = msg.ReadNetID();
  633. Component* component = scene_->GetComponent(componentID);
  634. if (component)
  635. component->Remove();
  636. componentLatestData_.Erase(componentID);
  637. }
  638. break;
  639. default: break;
  640. }
  641. }
  642. void Connection::ProcessPackageDownload(int msgID, MemoryBuffer& msg)
  643. {
  644. switch (msgID)
  645. {
  646. case MSG_REQUESTPACKAGE:
  647. if (!IsClient())
  648. {
  649. URHO3D_LOGWARNING("Received unexpected RequestPackage message from server");
  650. return;
  651. }
  652. else
  653. {
  654. String name = msg.ReadString();
  655. if (!scene_)
  656. {
  657. URHO3D_LOGWARNING("Received a RequestPackage message without an assigned scene from client " + ToString());
  658. return;
  659. }
  660. // The package must be one of those required by the scene
  661. const Vector<SharedPtr<PackageFile> >& packages = scene_->GetRequiredPackageFiles();
  662. for (unsigned i = 0; i < packages.Size(); ++i)
  663. {
  664. PackageFile* package = packages[i];
  665. const String& packageFullName = package->GetName();
  666. if (!GetFileNameAndExtension(packageFullName).Compare(name, false))
  667. {
  668. StringHash nameHash(name);
  669. // Do not restart upload if already exists
  670. if (uploads_.Contains(nameHash))
  671. {
  672. URHO3D_LOGWARNING("Received a request for package " + name + " already in transfer");
  673. return;
  674. }
  675. // Try to open the file now
  676. SharedPtr<File> file(new File(context_, packageFullName));
  677. if (!file->IsOpen())
  678. {
  679. URHO3D_LOGERROR("Failed to transmit package file " + name);
  680. SendPackageError(name);
  681. return;
  682. }
  683. URHO3D_LOGINFO("Transmitting package file " + name + " to client " + ToString());
  684. uploads_[nameHash].file_ = file;
  685. uploads_[nameHash].fragment_ = 0;
  686. uploads_[nameHash].totalFragments_ = (file->GetSize() + PACKAGE_FRAGMENT_SIZE - 1) / PACKAGE_FRAGMENT_SIZE;
  687. return;
  688. }
  689. }
  690. URHO3D_LOGERROR("Client requested an unexpected package file " + name);
  691. // Send the name hash only to indicate a failed download
  692. SendPackageError(name);
  693. return;
  694. }
  695. break;
  696. case MSG_PACKAGEDATA:
  697. if (IsClient())
  698. {
  699. URHO3D_LOGWARNING("Received unexpected PackageData message from client");
  700. return;
  701. }
  702. else
  703. {
  704. StringHash nameHash = msg.ReadStringHash();
  705. HashMap<StringHash, PackageDownload>::Iterator i = downloads_.Find(nameHash);
  706. // In case of being unable to create the package file into the cache, we will still receive all data from the server.
  707. // Simply disregard it
  708. if (i == downloads_.End())
  709. return;
  710. PackageDownload& download = i->second_;
  711. // If no further data, this is an error reply
  712. if (msg.IsEof())
  713. {
  714. OnPackageDownloadFailed(download.name_);
  715. return;
  716. }
  717. // If file has not yet been opened, try to open now. Prepend the checksum to the filename to allow multiple versions
  718. if (!download.file_)
  719. {
  720. download.file_ = new File(context_,
  721. GetSubsystem<Network>()->GetPackageCacheDir() + ToStringHex(download.checksum_) + "_" + download.name_,
  722. FILE_WRITE);
  723. if (!download.file_->IsOpen())
  724. {
  725. OnPackageDownloadFailed(download.name_);
  726. return;
  727. }
  728. }
  729. // Write the fragment data to the proper index
  730. unsigned char buffer[PACKAGE_FRAGMENT_SIZE];
  731. unsigned index = msg.ReadUInt();
  732. unsigned fragmentSize = msg.GetSize() - msg.GetPosition();
  733. msg.Read(buffer, fragmentSize);
  734. download.file_->Seek(index * PACKAGE_FRAGMENT_SIZE);
  735. download.file_->Write(buffer, fragmentSize);
  736. download.receivedFragments_.Insert(index);
  737. // Check if all fragments received
  738. if (download.receivedFragments_.Size() == download.totalFragments_)
  739. {
  740. URHO3D_LOGINFO("Package " + download.name_ + " downloaded successfully");
  741. // Instantiate the package and add to the resource system, as we will need it to load the scene
  742. download.file_->Close();
  743. GetSubsystem<ResourceCache>()->AddPackageFile(download.file_->GetName(), 0);
  744. // Then start the next download if there are more
  745. downloads_.Erase(i);
  746. if (downloads_.Empty())
  747. OnPackagesReady();
  748. else
  749. {
  750. PackageDownload& nextDownload = downloads_.Begin()->second_;
  751. URHO3D_LOGINFO("Requesting package " + nextDownload.name_ + " from server");
  752. msg_.Clear();
  753. msg_.WriteString(nextDownload.name_);
  754. SendMessage(MSG_REQUESTPACKAGE, true, true, msg_);
  755. nextDownload.initiated_ = true;
  756. }
  757. }
  758. }
  759. break;
  760. default: break;
  761. }
  762. }
  763. void Connection::ProcessIdentity(int msgID, MemoryBuffer& msg)
  764. {
  765. if (!IsClient())
  766. {
  767. URHO3D_LOGWARNING("Received unexpected Identity message from server");
  768. return;
  769. }
  770. identity_ = msg.ReadVariantMap();
  771. using namespace ClientIdentity;
  772. VariantMap eventData = identity_;
  773. eventData[P_CONNECTION] = this;
  774. eventData[P_ALLOW] = true;
  775. SendEvent(E_CLIENTIDENTITY, eventData);
  776. // If connection was denied as a response to the identity event, disconnect now
  777. if (!eventData[P_ALLOW].GetBool())
  778. Disconnect();
  779. }
  780. void Connection::ProcessControls(int msgID, MemoryBuffer& msg)
  781. {
  782. if (!IsClient())
  783. {
  784. URHO3D_LOGWARNING("Received unexpected Controls message from server");
  785. return;
  786. }
  787. Controls newControls;
  788. newControls.buttons_ = msg.ReadUInt();
  789. newControls.yaw_ = msg.ReadFloat();
  790. newControls.pitch_ = msg.ReadFloat();
  791. newControls.extraData_ = msg.ReadVariantMap();
  792. SetControls(newControls);
  793. timeStamp_ = msg.ReadUByte();
  794. // Client may or may not send observer position & rotation for interest management
  795. if (!msg.IsEof())
  796. position_ = msg.ReadVector3();
  797. if (!msg.IsEof())
  798. rotation_ = msg.ReadPackedQuaternion();
  799. }
  800. void Connection::ProcessSceneLoaded(int msgID, MemoryBuffer& msg)
  801. {
  802. if (!IsClient())
  803. {
  804. URHO3D_LOGWARNING("Received unexpected SceneLoaded message from server");
  805. return;
  806. }
  807. if (!scene_)
  808. {
  809. URHO3D_LOGWARNING("Received a SceneLoaded message without an assigned scene from client " + ToString());
  810. return;
  811. }
  812. unsigned checksum = msg.ReadUInt();
  813. if (checksum != scene_->GetChecksum())
  814. {
  815. URHO3D_LOGINFO("Scene checksum error from client " + ToString());
  816. msg_.Clear();
  817. SendMessage(MSG_SCENECHECKSUMERROR, true, true, msg_);
  818. OnSceneLoadFailed();
  819. }
  820. else
  821. {
  822. sceneLoaded_ = true;
  823. using namespace ClientSceneLoaded;
  824. VariantMap& eventData = GetEventDataMap();
  825. eventData[P_CONNECTION] = this;
  826. SendEvent(E_CLIENTSCENELOADED, eventData);
  827. }
  828. }
  829. void Connection::ProcessRemoteEvent(int msgID, MemoryBuffer& msg)
  830. {
  831. using namespace RemoteEventData;
  832. if (msgID == MSG_REMOTEEVENT)
  833. {
  834. StringHash eventType = msg.ReadStringHash();
  835. if (!GetSubsystem<Network>()->CheckRemoteEvent(eventType))
  836. {
  837. URHO3D_LOGWARNING("Discarding not allowed remote event " + eventType.ToString());
  838. return;
  839. }
  840. VariantMap eventData = msg.ReadVariantMap();
  841. eventData[P_CONNECTION] = this;
  842. SendEvent(eventType, eventData);
  843. }
  844. else
  845. {
  846. if (!scene_)
  847. {
  848. URHO3D_LOGERROR("Can not receive remote node event without an assigned scene");
  849. return;
  850. }
  851. unsigned nodeID = msg.ReadNetID();
  852. StringHash eventType = msg.ReadStringHash();
  853. if (!GetSubsystem<Network>()->CheckRemoteEvent(eventType))
  854. {
  855. URHO3D_LOGWARNING("Discarding not allowed remote event " + eventType.ToString());
  856. return;
  857. }
  858. VariantMap eventData = msg.ReadVariantMap();
  859. Node* sender = scene_->GetNode(nodeID);
  860. if (!sender)
  861. {
  862. URHO3D_LOGWARNING("Missing sender for remote node event, discarding");
  863. return;
  864. }
  865. eventData[P_CONNECTION] = this;
  866. sender->SendEvent(eventType, eventData);
  867. }
  868. }
  869. Scene* Connection::GetScene() const
  870. {
  871. return scene_;
  872. }
  873. bool Connection::IsConnected() const
  874. {
  875. return peer_ && peer_->IsActive();
  876. }
  877. float Connection::GetRoundTripTime() const
  878. {
  879. if (peer_)
  880. {
  881. SLNet::RakNetStatistics stats{};
  882. if (peer_->GetStatistics(address_->systemAddress, &stats))
  883. return (float)peer_->GetAveragePing(*address_);
  884. }
  885. return 0.0f;
  886. }
  887. unsigned Connection::GetLastHeardTime() const
  888. {
  889. return const_cast<Timer&>(lastHeardTimer_).GetMSec(false);
  890. }
  891. float Connection::GetBytesInPerSec() const
  892. {
  893. if (peer_)
  894. {
  895. SLNet::RakNetStatistics stats{};
  896. if (peer_->GetStatistics(address_->systemAddress, &stats))
  897. return (float)stats.valueOverLastSecond[SLNet::ACTUAL_BYTES_RECEIVED];
  898. }
  899. return 0.0f;
  900. }
  901. float Connection::GetBytesOutPerSec() const
  902. {
  903. if (peer_)
  904. {
  905. SLNet::RakNetStatistics stats{};
  906. if (peer_->GetStatistics(address_->systemAddress, &stats))
  907. return (float)stats.valueOverLastSecond[SLNet::ACTUAL_BYTES_SENT];
  908. }
  909. return 0.0f;
  910. }
  911. int Connection::GetPacketsInPerSec() const
  912. {
  913. return packetCounter_.x_;
  914. }
  915. int Connection::GetPacketsOutPerSec() const
  916. {
  917. return packetCounter_.y_;
  918. }
  919. String Connection::ToString() const
  920. {
  921. return GetAddress() + ":" + String(GetPort());
  922. }
  923. unsigned Connection::GetNumDownloads() const
  924. {
  925. return downloads_.Size();
  926. }
  927. const String& Connection::GetDownloadName() const
  928. {
  929. for (HashMap<StringHash, PackageDownload>::ConstIterator i = downloads_.Begin(); i != downloads_.End(); ++i)
  930. {
  931. if (i->second_.initiated_)
  932. return i->second_.name_;
  933. }
  934. return String::EMPTY;
  935. }
  936. float Connection::GetDownloadProgress() const
  937. {
  938. for (HashMap<StringHash, PackageDownload>::ConstIterator i = downloads_.Begin(); i != downloads_.End(); ++i)
  939. {
  940. if (i->second_.initiated_)
  941. return (float)i->second_.receivedFragments_.Size() / (float)i->second_.totalFragments_;
  942. }
  943. return 1.0f;
  944. }
  945. void Connection::SendPackageToClient(PackageFile* package)
  946. {
  947. if (!scene_)
  948. return;
  949. if (!IsClient())
  950. {
  951. URHO3D_LOGERROR("SendPackageToClient can be called on the server only");
  952. return;
  953. }
  954. if (!package)
  955. {
  956. URHO3D_LOGERROR("Null package specified for SendPackageToClient");
  957. return;
  958. }
  959. msg_.Clear();
  960. String filename = GetFileNameAndExtension(package->GetName());
  961. msg_.WriteString(filename);
  962. msg_.WriteUInt(package->GetTotalSize());
  963. msg_.WriteUInt(package->GetChecksum());
  964. SendMessage(MSG_PACKAGEINFO, true, true, msg_);
  965. }
  966. void Connection::ConfigureNetworkSimulator(int latencyMs, float packetLoss)
  967. {
  968. if (peer_)
  969. peer_->ApplyNetworkSimulator(packetLoss, latencyMs, 0);
  970. }
  971. void Connection::HandleAsyncLoadFinished(StringHash eventType, VariantMap& eventData)
  972. {
  973. sceneLoaded_ = true;
  974. // Clear all replicated nodes
  975. scene_->Clear(true, false);
  976. msg_.Clear();
  977. msg_.WriteUInt(scene_->GetChecksum());
  978. SendMessage(MSG_SCENELOADED, true, true, msg_);
  979. }
  980. void Connection::ProcessNode(unsigned nodeID)
  981. {
  982. // Check that we have not already processed this due to dependency recursion
  983. if (!nodesToProcess_.Erase(nodeID))
  984. return;
  985. // Find replication state for the node
  986. HashMap<unsigned, NodeReplicationState>::Iterator i = sceneState_.nodeStates_.Find(nodeID);
  987. if (i != sceneState_.nodeStates_.End())
  988. {
  989. // Replication state found: the node is either be existing or removed
  990. Node* node = i->second_.node_;
  991. if (!node)
  992. {
  993. msg_.Clear();
  994. msg_.WriteNetID(nodeID);
  995. // Note: we will send MSG_REMOVENODE redundantly for each node in the hierarchy, even if removing the root node
  996. // would be enough. However, this may be better due to the client not possibly having updated parenting
  997. // information at the time of receiving this message
  998. SendMessage(MSG_REMOVENODE, true, true, msg_);
  999. sceneState_.nodeStates_.Erase(nodeID);
  1000. }
  1001. else
  1002. ProcessExistingNode(node, i->second_);
  1003. }
  1004. else
  1005. {
  1006. // Replication state not found: this is a new node
  1007. Node* node = scene_->GetNode(nodeID);
  1008. if (node)
  1009. ProcessNewNode(node);
  1010. else
  1011. {
  1012. // Did not find the new node (may have been created, then removed immediately): erase from dirty set.
  1013. sceneState_.dirtyNodes_.Erase(nodeID);
  1014. }
  1015. }
  1016. }
  1017. void Connection::ProcessNewNode(Node* node)
  1018. {
  1019. // Process depended upon nodes first, if they are dirty
  1020. const PODVector<Node*>& dependencyNodes = node->GetDependencyNodes();
  1021. for (PODVector<Node*>::ConstIterator i = dependencyNodes.Begin(); i != dependencyNodes.End(); ++i)
  1022. {
  1023. unsigned nodeID = (*i)->GetID();
  1024. if (sceneState_.dirtyNodes_.Contains(nodeID))
  1025. ProcessNode(nodeID);
  1026. }
  1027. msg_.Clear();
  1028. msg_.WriteNetID(node->GetID());
  1029. NodeReplicationState& nodeState = sceneState_.nodeStates_[node->GetID()];
  1030. nodeState.connection_ = this;
  1031. nodeState.sceneState_ = &sceneState_;
  1032. nodeState.node_ = node;
  1033. node->AddReplicationState(&nodeState);
  1034. // Write node's attributes
  1035. node->WriteInitialDeltaUpdate(msg_, timeStamp_);
  1036. // Write node's user variables
  1037. const VariantMap& vars = node->GetVars();
  1038. msg_.WriteVLE(vars.Size());
  1039. for (VariantMap::ConstIterator i = vars.Begin(); i != vars.End(); ++i)
  1040. {
  1041. msg_.WriteStringHash(i->first_);
  1042. msg_.WriteVariant(i->second_);
  1043. }
  1044. // Write node's components
  1045. msg_.WriteVLE(node->GetNumNetworkComponents());
  1046. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  1047. for (unsigned i = 0; i < components.Size(); ++i)
  1048. {
  1049. Component* component = components[i];
  1050. // Check if component is not to be replicated
  1051. if (!component->IsReplicated())
  1052. continue;
  1053. ComponentReplicationState& componentState = nodeState.componentStates_[component->GetID()];
  1054. componentState.connection_ = this;
  1055. componentState.nodeState_ = &nodeState;
  1056. componentState.component_ = component;
  1057. component->AddReplicationState(&componentState);
  1058. msg_.WriteStringHash(component->GetType());
  1059. msg_.WriteNetID(component->GetID());
  1060. component->WriteInitialDeltaUpdate(msg_, timeStamp_);
  1061. }
  1062. SendMessage(MSG_CREATENODE, true, true, msg_);
  1063. nodeState.markedDirty_ = false;
  1064. sceneState_.dirtyNodes_.Erase(node->GetID());
  1065. }
  1066. void Connection::ProcessExistingNode(Node* node, NodeReplicationState& nodeState)
  1067. {
  1068. // Process depended upon nodes first, if they are dirty
  1069. const PODVector<Node*>& dependencyNodes = node->GetDependencyNodes();
  1070. for (PODVector<Node*>::ConstIterator i = dependencyNodes.Begin(); i != dependencyNodes.End(); ++i)
  1071. {
  1072. unsigned nodeID = (*i)->GetID();
  1073. if (sceneState_.dirtyNodes_.Contains(nodeID))
  1074. ProcessNode(nodeID);
  1075. }
  1076. // Check from the interest management component, if exists, whether should update
  1077. /// \todo Searching for the component is a potential CPU hotspot. It should be cached
  1078. auto* priority = node->GetComponent<NetworkPriority>();
  1079. if (priority && (!priority->GetAlwaysUpdateOwner() || node->GetOwner() != this))
  1080. {
  1081. float distance = (node->GetWorldPosition() - position_).Length();
  1082. if (!priority->CheckUpdate(distance, nodeState.priorityAcc_))
  1083. return;
  1084. }
  1085. // Check if attributes have changed
  1086. if (nodeState.dirtyAttributes_.Count() || nodeState.dirtyVars_.Size())
  1087. {
  1088. const Vector<AttributeInfo>* attributes = node->GetNetworkAttributes();
  1089. unsigned numAttributes = attributes->Size();
  1090. bool hasLatestData = false;
  1091. for (unsigned i = 0; i < numAttributes; ++i)
  1092. {
  1093. if (nodeState.dirtyAttributes_.IsSet(i) && (attributes->At(i).mode_ & AM_LATESTDATA))
  1094. {
  1095. hasLatestData = true;
  1096. nodeState.dirtyAttributes_.Clear(i);
  1097. }
  1098. }
  1099. // Send latestdata message if necessary
  1100. if (hasLatestData)
  1101. {
  1102. msg_.Clear();
  1103. msg_.WriteNetID(node->GetID());
  1104. node->WriteLatestDataUpdate(msg_, timeStamp_);
  1105. SendMessage(MSG_NODELATESTDATA, true, false, msg_, node->GetID());
  1106. }
  1107. // Send deltaupdate if remaining dirty bits, or vars have changed
  1108. if (nodeState.dirtyAttributes_.Count() || nodeState.dirtyVars_.Size())
  1109. {
  1110. msg_.Clear();
  1111. msg_.WriteNetID(node->GetID());
  1112. node->WriteDeltaUpdate(msg_, nodeState.dirtyAttributes_, timeStamp_);
  1113. // Write changed variables
  1114. msg_.WriteVLE(nodeState.dirtyVars_.Size());
  1115. const VariantMap& vars = node->GetVars();
  1116. for (HashSet<StringHash>::ConstIterator i = nodeState.dirtyVars_.Begin(); i != nodeState.dirtyVars_.End(); ++i)
  1117. {
  1118. VariantMap::ConstIterator j = vars.Find(*i);
  1119. if (j != vars.End())
  1120. {
  1121. msg_.WriteStringHash(j->first_);
  1122. msg_.WriteVariant(j->second_);
  1123. }
  1124. else
  1125. {
  1126. // Variable has been marked dirty, but is removed (which is unsupported): send a dummy variable in place
  1127. URHO3D_LOGWARNING("Sending dummy user variable as original value was removed");
  1128. msg_.WriteStringHash(StringHash());
  1129. msg_.WriteVariant(Variant::EMPTY);
  1130. }
  1131. }
  1132. SendMessage(MSG_NODEDELTAUPDATE, true, true, msg_);
  1133. nodeState.dirtyAttributes_.ClearAll();
  1134. nodeState.dirtyVars_.Clear();
  1135. }
  1136. }
  1137. // Check for removed or changed components
  1138. for (HashMap<unsigned, ComponentReplicationState>::Iterator i = nodeState.componentStates_.Begin();
  1139. i != nodeState.componentStates_.End();)
  1140. {
  1141. HashMap<unsigned, ComponentReplicationState>::Iterator current = i++;
  1142. ComponentReplicationState& componentState = current->second_;
  1143. Component* component = componentState.component_;
  1144. if (!component)
  1145. {
  1146. // Removed component
  1147. msg_.Clear();
  1148. msg_.WriteNetID(current->first_);
  1149. SendMessage(MSG_REMOVECOMPONENT, true, true, msg_);
  1150. nodeState.componentStates_.Erase(current);
  1151. }
  1152. else
  1153. {
  1154. // Existing component. Check if attributes have changed
  1155. if (componentState.dirtyAttributes_.Count())
  1156. {
  1157. const Vector<AttributeInfo>* attributes = component->GetNetworkAttributes();
  1158. unsigned numAttributes = attributes->Size();
  1159. bool hasLatestData = false;
  1160. for (unsigned i = 0; i < numAttributes; ++i)
  1161. {
  1162. if (componentState.dirtyAttributes_.IsSet(i) && (attributes->At(i).mode_ & AM_LATESTDATA))
  1163. {
  1164. hasLatestData = true;
  1165. componentState.dirtyAttributes_.Clear(i);
  1166. }
  1167. }
  1168. // Send latestdata message if necessary
  1169. if (hasLatestData)
  1170. {
  1171. msg_.Clear();
  1172. msg_.WriteNetID(component->GetID());
  1173. component->WriteLatestDataUpdate(msg_, timeStamp_);
  1174. SendMessage(MSG_COMPONENTLATESTDATA, true, false, msg_, component->GetID());
  1175. }
  1176. // Send deltaupdate if remaining dirty bits
  1177. if (componentState.dirtyAttributes_.Count())
  1178. {
  1179. msg_.Clear();
  1180. msg_.WriteNetID(component->GetID());
  1181. component->WriteDeltaUpdate(msg_, componentState.dirtyAttributes_, timeStamp_);
  1182. SendMessage(MSG_COMPONENTDELTAUPDATE, true, true, msg_);
  1183. componentState.dirtyAttributes_.ClearAll();
  1184. }
  1185. }
  1186. }
  1187. }
  1188. // Check for new components
  1189. if (nodeState.componentStates_.Size() != node->GetNumNetworkComponents())
  1190. {
  1191. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  1192. for (unsigned i = 0; i < components.Size(); ++i)
  1193. {
  1194. Component* component = components[i];
  1195. // Check if component is not to be replicated
  1196. if (!component->IsReplicated())
  1197. continue;
  1198. HashMap<unsigned, ComponentReplicationState>::Iterator j = nodeState.componentStates_.Find(component->GetID());
  1199. if (j == nodeState.componentStates_.End())
  1200. {
  1201. // New component
  1202. ComponentReplicationState& componentState = nodeState.componentStates_[component->GetID()];
  1203. componentState.connection_ = this;
  1204. componentState.nodeState_ = &nodeState;
  1205. componentState.component_ = component;
  1206. component->AddReplicationState(&componentState);
  1207. msg_.Clear();
  1208. msg_.WriteNetID(node->GetID());
  1209. msg_.WriteStringHash(component->GetType());
  1210. msg_.WriteNetID(component->GetID());
  1211. component->WriteInitialDeltaUpdate(msg_, timeStamp_);
  1212. SendMessage(MSG_CREATECOMPONENT, true, true, msg_);
  1213. }
  1214. }
  1215. }
  1216. nodeState.markedDirty_ = false;
  1217. sceneState_.dirtyNodes_.Erase(node->GetID());
  1218. }
  1219. bool Connection::RequestNeededPackages(unsigned numPackages, MemoryBuffer& msg)
  1220. {
  1221. auto* cache = GetSubsystem<ResourceCache>();
  1222. const String& packageCacheDir = GetSubsystem<Network>()->GetPackageCacheDir();
  1223. Vector<SharedPtr<PackageFile> > packages = cache->GetPackageFiles();
  1224. Vector<String> downloadedPackages;
  1225. bool packagesScanned = false;
  1226. for (unsigned i = 0; i < numPackages; ++i)
  1227. {
  1228. String name = msg.ReadString();
  1229. unsigned fileSize = msg.ReadUInt();
  1230. unsigned checksum = msg.ReadUInt();
  1231. String checksumString = ToStringHex(checksum);
  1232. bool found = false;
  1233. // Check first the resource cache
  1234. for (unsigned j = 0; j < packages.Size(); ++j)
  1235. {
  1236. PackageFile* package = packages[j];
  1237. if (!GetFileNameAndExtension(package->GetName()).Compare(name, false) && package->GetTotalSize() == fileSize &&
  1238. package->GetChecksum() == checksum)
  1239. {
  1240. found = true;
  1241. break;
  1242. }
  1243. }
  1244. if (found)
  1245. continue;
  1246. if (!packagesScanned)
  1247. {
  1248. if (packageCacheDir.Empty())
  1249. {
  1250. URHO3D_LOGERROR("Can not check/download required packages, as package cache directory is not set");
  1251. return false;
  1252. }
  1253. GetSubsystem<FileSystem>()->ScanDir(downloadedPackages, packageCacheDir, "*.*", SCAN_FILES, false);
  1254. packagesScanned = true;
  1255. }
  1256. // Then the download cache
  1257. for (unsigned j = 0; j < downloadedPackages.Size(); ++j)
  1258. {
  1259. const String& fileName = downloadedPackages[j];
  1260. // In download cache, package file name format is checksum_packagename
  1261. if (!fileName.Find(checksumString) && !fileName.Substring(9).Compare(name, false))
  1262. {
  1263. // Name matches. Check file size and actual checksum to be sure
  1264. SharedPtr<PackageFile> newPackage(new PackageFile(context_, packageCacheDir + fileName));
  1265. if (newPackage->GetTotalSize() == fileSize && newPackage->GetChecksum() == checksum)
  1266. {
  1267. // Add the package to the resource system now, as we will need it to load the scene
  1268. cache->AddPackageFile(newPackage, 0);
  1269. found = true;
  1270. break;
  1271. }
  1272. }
  1273. }
  1274. // Package not found, need to request a download
  1275. if (!found)
  1276. RequestPackage(name, fileSize, checksum);
  1277. }
  1278. return true;
  1279. }
  1280. void Connection::RequestPackage(const String& name, unsigned fileSize, unsigned checksum)
  1281. {
  1282. StringHash nameHash(name);
  1283. if (downloads_.Contains(nameHash))
  1284. return; // Download already exists
  1285. PackageDownload& download = downloads_[nameHash];
  1286. download.name_ = name;
  1287. download.totalFragments_ = (fileSize + PACKAGE_FRAGMENT_SIZE - 1) / PACKAGE_FRAGMENT_SIZE;
  1288. download.checksum_ = checksum;
  1289. // Start download now only if no existing downloads, else wait for the existing ones to finish
  1290. if (downloads_.Size() == 1)
  1291. {
  1292. URHO3D_LOGINFO("Requesting package " + name + " from server");
  1293. msg_.Clear();
  1294. msg_.WriteString(name);
  1295. SendMessage(MSG_REQUESTPACKAGE, true, true, msg_);
  1296. download.initiated_ = true;
  1297. }
  1298. }
  1299. void Connection::SendPackageError(const String& name)
  1300. {
  1301. msg_.Clear();
  1302. msg_.WriteStringHash(name);
  1303. SendMessage(MSG_PACKAGEDATA, true, false, msg_);
  1304. }
  1305. void Connection::OnSceneLoadFailed()
  1306. {
  1307. sceneLoaded_ = false;
  1308. using namespace NetworkSceneLoadFailed;
  1309. VariantMap& eventData = GetEventDataMap();
  1310. eventData[P_CONNECTION] = this;
  1311. SendEvent(E_NETWORKSCENELOADFAILED, eventData);
  1312. }
  1313. void Connection::OnPackageDownloadFailed(const String& name)
  1314. {
  1315. URHO3D_LOGERROR("Download of package " + name + " failed");
  1316. // As one package failed, we can not join the scene in any case. Clear the downloads
  1317. downloads_.Clear();
  1318. OnSceneLoadFailed();
  1319. }
  1320. void Connection::OnPackagesReady()
  1321. {
  1322. if (!scene_)
  1323. return;
  1324. // If sceneLoaded_ is true, we may have received additional package downloads while already joined in a scene.
  1325. // In that case the scene should not be loaded.
  1326. if (sceneLoaded_)
  1327. return;
  1328. if (sceneFileName_.Empty())
  1329. {
  1330. // If the scene filename is empty, just clear the scene of all existing replicated content, and send the loaded reply
  1331. scene_->Clear(true, false);
  1332. sceneLoaded_ = true;
  1333. msg_.Clear();
  1334. msg_.WriteUInt(scene_->GetChecksum());
  1335. SendMessage(MSG_SCENELOADED, true, true, msg_);
  1336. }
  1337. else
  1338. {
  1339. // Otherwise start the async loading process
  1340. String extension = GetExtension(sceneFileName_);
  1341. SharedPtr<File> file = GetSubsystem<ResourceCache>()->GetFile(sceneFileName_);
  1342. bool success;
  1343. if (extension == ".xml")
  1344. success = scene_->LoadAsyncXML(file);
  1345. else
  1346. success = scene_->LoadAsync(file);
  1347. if (!success)
  1348. OnSceneLoadFailed();
  1349. }
  1350. }
  1351. void Connection::ProcessPackageInfo(int msgID, MemoryBuffer& msg)
  1352. {
  1353. if (!scene_)
  1354. return;
  1355. if (IsClient())
  1356. {
  1357. URHO3D_LOGWARNING("Received unexpected packages info message from client");
  1358. return;
  1359. }
  1360. RequestNeededPackages(1, msg);
  1361. }
  1362. String Connection::GetAddress() const {
  1363. return String(address_->ToString(false /*write port*/));
  1364. }
  1365. void Connection::SetAddressOrGUID(const SLNet::AddressOrGUID& addr)
  1366. {
  1367. delete address_;
  1368. address_ = nullptr;
  1369. address_ = new SLNet::AddressOrGUID(addr);
  1370. }
  1371. }