Connection.cpp 47 KB

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