Connection.cpp 46 KB

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