Connection.cpp 49 KB

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