Connection.cpp 49 KB

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