Connection.cpp 49 KB

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