Connection.cpp 49 KB

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