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. break;
  353. }
  354. return processed;
  355. }
  356. void Connection::ProcessLoadScene(int msgID, MemoryBuffer& msg)
  357. {
  358. if (IsClient())
  359. {
  360. LOGWARNING("Received unexpected LoadScene message from client " + ToString());
  361. return;
  362. }
  363. if (!scene_)
  364. {
  365. LOGERROR("Can not handle LoadScene message without an assigned scene");
  366. return;
  367. }
  368. // Store the scene file name we need to eventually load
  369. sceneFileName_ = msg.ReadString();
  370. // Clear previous pending latest data and package downloads if any
  371. nodeLatestData_.Clear();
  372. componentLatestData_.Clear();
  373. downloads_.Clear();
  374. // In case we have joined other scenes in this session, remove first all downloaded package files from the resource system
  375. // to prevent resource conflicts
  376. const String& packageCacheDir = GetSubsystem<Network>()->GetPackageCacheDir();
  377. ResourceCache* cache = GetSubsystem<ResourceCache>();
  378. Vector<SharedPtr<PackageFile> > packages = cache->GetPackageFiles();
  379. for (unsigned i = 0; i < packages.Size(); ++i)
  380. {
  381. PackageFile* package = packages[i];
  382. if (!package->GetName().Find(packageCacheDir))
  383. cache->RemovePackageFile(package, true);
  384. }
  385. // Now check which packages we have in the resource cache or in the download cache, and which we need to download
  386. unsigned numPackages = msg.ReadVLE();
  387. packages = cache->GetPackageFiles(); // Refresh resource cache's package list after possible removals
  388. Vector<String> downloadedPackages;
  389. if (!packageCacheDir.Empty())
  390. GetSubsystem<FileSystem>()->ScanDir(downloadedPackages, packageCacheDir, "*.*", SCAN_FILES, false);
  391. for (unsigned i = 0; i < numPackages; ++i)
  392. {
  393. String name = msg.ReadString();
  394. unsigned fileSize = msg.ReadUInt();
  395. unsigned checksum = msg.ReadUInt();
  396. String checksumString = ToStringHex(checksum);
  397. bool found = false;
  398. // Check first the resource cache
  399. for (unsigned j = 0; j < packages.Size(); ++j)
  400. {
  401. PackageFile* package = packages[j];
  402. if (!GetFileNameAndExtension(package->GetName()).Compare(name, false) && package->GetTotalSize() == fileSize &&
  403. package->GetChecksum() == checksum)
  404. {
  405. found = true;
  406. break;
  407. }
  408. }
  409. // Then the download cache
  410. for (unsigned j = 0; j < downloadedPackages.Size(); ++j)
  411. {
  412. const String& fileName = downloadedPackages[j];
  413. if (!fileName.Find(checksumString) && !fileName.Substring(9).Compare(name, false))
  414. {
  415. // Name matches. Check filesize and actual checksum to be sure
  416. SharedPtr<PackageFile> newPackage(new PackageFile(context_, packageCacheDir + fileName));
  417. if (newPackage->GetTotalSize() == fileSize && newPackage->GetChecksum() == checksum)
  418. {
  419. // Add the package to the resource system now, as we will need it to load the scene
  420. cache->AddPackageFile(newPackage, true);
  421. found = true;
  422. break;
  423. }
  424. }
  425. }
  426. // Package not found, need to request a download
  427. if (!found)
  428. {
  429. if (!packageCacheDir.Empty())
  430. RequestPackage(name, fileSize, checksum);
  431. else
  432. {
  433. LOGERROR("Can not download required packages, as package cache directory is not set");
  434. OnSceneLoadFailed();
  435. return;
  436. }
  437. }
  438. }
  439. // If no downloads were queued, can load the scene directly
  440. if (downloads_.Empty())
  441. OnPackagesReady();
  442. }
  443. void Connection::ProcessSceneChecksumError(int msgID, MemoryBuffer& msg)
  444. {
  445. if (IsClient())
  446. {
  447. LOGWARNING("Received unexpected SceneChecksumError message from client " + ToString());
  448. return;
  449. }
  450. LOGERROR("Scene checksum error");
  451. OnSceneLoadFailed();
  452. }
  453. void Connection::ProcessSceneUpdate(int msgID, MemoryBuffer& msg)
  454. {
  455. /// \todo On mobile devices processing this message may potentially cause a crash if it attempts to load new GPU resources
  456. /// while the application is minimized
  457. if (IsClient())
  458. {
  459. LOGWARNING("Received unexpected SceneUpdate message from client " + ToString());
  460. return;
  461. }
  462. if (!scene_)
  463. return;
  464. switch (msgID)
  465. {
  466. case MSG_CREATENODE:
  467. {
  468. unsigned nodeID = msg.ReadNetID();
  469. // In case of the root node (scene), it should already exist. Do not create in that case
  470. Node* node = scene_->GetNode(nodeID);
  471. if (!node)
  472. {
  473. // Add initially to the root level. May be moved as we receive the parent attribute
  474. node = scene_->CreateChild(nodeID, REPLICATED);
  475. // Create smoothed transform component
  476. node->CreateComponent<SmoothedTransform>(LOCAL);
  477. }
  478. // Read initial attributes, then snap the motion smoothing immediately to the end
  479. node->ReadDeltaUpdate(msg);
  480. SmoothedTransform* transform = node->GetComponent<SmoothedTransform>();
  481. if (transform)
  482. transform->Update(1.0f, 0.0f);
  483. // Read initial user variables
  484. unsigned numVars = msg.ReadVLE();
  485. while (numVars)
  486. {
  487. ShortStringHash key = msg.ReadShortStringHash();
  488. node->SetVar(key, msg.ReadVariant());
  489. --numVars;
  490. }
  491. // Read components
  492. unsigned numComponents = msg.ReadVLE();
  493. while (numComponents)
  494. {
  495. --numComponents;
  496. ShortStringHash type = msg.ReadShortStringHash();
  497. unsigned componentID = msg.ReadNetID();
  498. // Check if the component by this ID and type already exists in this node
  499. Component* component = scene_->GetComponent(componentID);
  500. if (!component || component->GetType() != type || component->GetNode() != node)
  501. {
  502. if (component)
  503. component->Remove();
  504. component = node->CreateComponent(type, REPLICATED, componentID);
  505. }
  506. // If was unable to create the component, would desync the message and therefore have to abort
  507. if (!component)
  508. {
  509. LOGERROR("CreateNode message parsing aborted due to unknown component");
  510. return;
  511. }
  512. // Read initial attributes and apply
  513. component->ReadDeltaUpdate(msg);
  514. component->ApplyAttributes();
  515. }
  516. }
  517. break;
  518. case MSG_NODEDELTAUPDATE:
  519. {
  520. unsigned nodeID = msg.ReadNetID();
  521. Node* node = scene_->GetNode(nodeID);
  522. if (node)
  523. {
  524. node->ReadDeltaUpdate(msg);
  525. // ApplyAttributes() is deliberately skipped, as Node has no attributes that require late applying.
  526. // Furthermore it would propagate to components and child nodes, which is not desired in this case
  527. unsigned changedVars = msg.ReadVLE();
  528. while (changedVars)
  529. {
  530. ShortStringHash key = msg.ReadShortStringHash();
  531. node->SetVar(key, msg.ReadVariant());
  532. --changedVars;
  533. }
  534. }
  535. else
  536. LOGWARNING("NodeDeltaUpdate message received for missing node " + String(nodeID));
  537. }
  538. break;
  539. case MSG_NODELATESTDATA:
  540. {
  541. unsigned nodeID = msg.ReadNetID();
  542. Node* node = scene_->GetNode(nodeID);
  543. if (node)
  544. {
  545. node->ReadLatestDataUpdate(msg);
  546. // ApplyAttributes() is deliberately skipped, as Node has no attributes that require late applying.
  547. // Furthermore it would propagate to components and child nodes, which is not desired in this case
  548. }
  549. else
  550. {
  551. // Latest data messages may be received out-of-order relative to node creation, so cache if necessary
  552. PODVector<unsigned char>& data = nodeLatestData_[nodeID];
  553. data.Resize(msg.GetSize());
  554. memcpy(&data[0], msg.GetData(), msg.GetSize());
  555. }
  556. }
  557. break;
  558. case MSG_REMOVENODE:
  559. {
  560. unsigned nodeID = msg.ReadNetID();
  561. Node* node = scene_->GetNode(nodeID);
  562. if (node)
  563. node->Remove();
  564. nodeLatestData_.Erase(nodeID);
  565. }
  566. break;
  567. case MSG_CREATECOMPONENT:
  568. {
  569. unsigned nodeID = msg.ReadNetID();
  570. Node* node = scene_->GetNode(nodeID);
  571. if (node)
  572. {
  573. ShortStringHash type = msg.ReadShortStringHash();
  574. unsigned componentID = msg.ReadNetID();
  575. // Check if the component by this ID and type already exists in this node
  576. Component* component = scene_->GetComponent(componentID);
  577. if (!component || component->GetType() != type || component->GetNode() != node)
  578. {
  579. if (component)
  580. component->Remove();
  581. component = node->CreateComponent(type, REPLICATED, componentID);
  582. }
  583. // If was unable to create the component, would desync the message and therefore have to abort
  584. if (!component)
  585. {
  586. LOGERROR("CreateComponent message parsing aborted due to unknown component");
  587. return;
  588. }
  589. // Read initial attributes and apply
  590. component->ReadDeltaUpdate(msg);
  591. component->ApplyAttributes();
  592. }
  593. else
  594. LOGWARNING("CreateComponent message received for missing node " + String(nodeID));
  595. }
  596. break;
  597. case MSG_COMPONENTDELTAUPDATE:
  598. {
  599. unsigned componentID = msg.ReadNetID();
  600. Component* component = scene_->GetComponent(componentID);
  601. if (component)
  602. {
  603. component->ReadDeltaUpdate(msg);
  604. component->ApplyAttributes();
  605. }
  606. else
  607. LOGWARNING("ComponentDeltaUpdate message received for missing component " + String(componentID));
  608. }
  609. break;
  610. case MSG_COMPONENTLATESTDATA:
  611. {
  612. unsigned componentID = msg.ReadNetID();
  613. Component* component = scene_->GetComponent(componentID);
  614. if (component)
  615. {
  616. component->ReadLatestDataUpdate(msg);
  617. component->ApplyAttributes();
  618. }
  619. else
  620. {
  621. // Latest data messages may be received out-of-order relative to component creation, so cache if necessary
  622. PODVector<unsigned char>& data = componentLatestData_[componentID];
  623. data.Resize(msg.GetSize());
  624. memcpy(&data[0], msg.GetData(), msg.GetSize());
  625. }
  626. }
  627. break;
  628. case MSG_REMOVECOMPONENT:
  629. {
  630. unsigned componentID = msg.ReadNetID();
  631. Component* component = scene_->GetComponent(componentID);
  632. if (component)
  633. component->Remove();
  634. componentLatestData_.Erase(componentID);
  635. }
  636. break;
  637. }
  638. }
  639. void Connection::ProcessPackageDownload(int msgID, MemoryBuffer& msg)
  640. {
  641. switch (msgID)
  642. {
  643. case MSG_REQUESTPACKAGE:
  644. if (!IsClient())
  645. {
  646. LOGWARNING("Received unexpected RequestPackage message from server");
  647. return;
  648. }
  649. else
  650. {
  651. String name = msg.ReadString();
  652. if (!scene_)
  653. {
  654. LOGWARNING("Received a RequestPackage message without an assigned scene from client " + ToString());
  655. return;
  656. }
  657. // The package must be one of those required by the scene
  658. const Vector<SharedPtr<PackageFile> >& packages = scene_->GetRequiredPackageFiles();
  659. for (unsigned i = 0; i < packages.Size(); ++i)
  660. {
  661. PackageFile* package = packages[i];
  662. String packageFullName = package->GetName();
  663. if (!GetFileNameAndExtension(packageFullName).Compare(name, false))
  664. {
  665. StringHash nameHash(name);
  666. // Do not restart upload if already exists
  667. if (uploads_.Contains(nameHash))
  668. {
  669. LOGWARNING("Received a request for package " + name + " already in transfer");
  670. return;
  671. }
  672. // Try to open the file now
  673. SharedPtr<File> file(new File(context_, packageFullName));
  674. if (!file->IsOpen())
  675. {
  676. LOGERROR("Failed to transmit package file " + name);
  677. SendPackageError(name);
  678. return;
  679. }
  680. LOGINFO("Transmitting package file " + name + " to client " + ToString());
  681. uploads_[nameHash].file_ = file;
  682. uploads_[nameHash].fragment_ = 0;
  683. uploads_[nameHash].totalFragments_ = (file->GetSize() + PACKAGE_FRAGMENT_SIZE - 1) / PACKAGE_FRAGMENT_SIZE;
  684. return;
  685. }
  686. }
  687. LOGERROR("Client requested an unexpected package file " + name);
  688. // Send the name hash only to indicate a failed download
  689. SendPackageError(name);
  690. return;
  691. }
  692. break;
  693. case MSG_PACKAGEDATA:
  694. if (IsClient())
  695. {
  696. LOGWARNING("Received unexpected PackageData message from client");
  697. return;
  698. }
  699. else
  700. {
  701. StringHash nameHash = msg.ReadStringHash();
  702. HashMap<StringHash, PackageDownload>::Iterator i = downloads_.Find(nameHash);
  703. // In case of being unable to create the package file into the cache, we will still receive all data from the server.
  704. // Simply disregard it
  705. if (i == downloads_.End())
  706. return;
  707. PackageDownload& download = i->second_;
  708. // If no further data, this is an error reply
  709. if (msg.IsEof())
  710. {
  711. OnPackageDownloadFailed(download.name_);
  712. return;
  713. }
  714. // If file has not yet been opened, try to open now. Prepend the checksum to the filename to allow multiple versions
  715. if (!download.file_)
  716. {
  717. download.file_ = new File(context_, GetSubsystem<Network>()->GetPackageCacheDir() + ToStringHex(download.checksum_) + "_" + download.name_, FILE_WRITE);
  718. if (!download.file_->IsOpen())
  719. {
  720. OnPackageDownloadFailed(download.name_);
  721. return;
  722. }
  723. }
  724. // Write the fragment data to the proper index
  725. unsigned char buffer[PACKAGE_FRAGMENT_SIZE];
  726. unsigned index = msg.ReadUInt();
  727. unsigned fragmentSize = msg.GetSize() - msg.GetPosition();
  728. msg.Read(buffer, fragmentSize);
  729. download.file_->Seek(index * PACKAGE_FRAGMENT_SIZE);
  730. download.file_->Write(buffer, fragmentSize);
  731. download.receivedFragments_.Insert(index);
  732. // Check if all fragments received
  733. if (download.receivedFragments_.Size() == download.totalFragments_)
  734. {
  735. LOGINFO("Package " + download.name_ + " downloaded successfully");
  736. // Instantiate the package and add to the resource system, as we will need it to load the scene
  737. download.file_->Close();
  738. SharedPtr<PackageFile> newPackage(new PackageFile(context_, download.file_->GetName()));
  739. GetSubsystem<ResourceCache>()->AddPackageFile(newPackage, true);
  740. // Then start the next download if there are more
  741. downloads_.Erase(i);
  742. if (downloads_.Empty())
  743. OnPackagesReady();
  744. else
  745. {
  746. PackageDownload& nextDownload = downloads_.Begin()->second_;
  747. LOGINFO("Requesting package " + nextDownload.name_ + " from server");
  748. msg_.Clear();
  749. msg_.WriteString(nextDownload.name_);
  750. SendMessage(MSG_REQUESTPACKAGE, true, true, msg_);
  751. nextDownload.initiated_ = true;
  752. }
  753. }
  754. }
  755. break;
  756. }
  757. }
  758. void Connection::ProcessIdentity(int msgID, MemoryBuffer& msg)
  759. {
  760. if (!IsClient())
  761. {
  762. LOGWARNING("Received unexpected Identity message from server");
  763. return;
  764. }
  765. identity_ = msg.ReadVariantMap();
  766. using namespace ClientIdentity;
  767. VariantMap eventData = identity_;
  768. eventData[P_CONNECTION] = (void*)this;
  769. eventData[P_ALLOW] = true;
  770. SendEvent(E_CLIENTIDENTITY, eventData);
  771. // If connection was denied as a response to the identity event, disconnect now
  772. if (!eventData[P_ALLOW].GetBool())
  773. Disconnect();
  774. }
  775. void Connection::ProcessControls(int msgID, MemoryBuffer& msg)
  776. {
  777. if (!IsClient())
  778. {
  779. LOGWARNING("Received unexpected Controls message from server");
  780. return;
  781. }
  782. Controls newControls;
  783. newControls.buttons_ = msg.ReadUInt();
  784. newControls.yaw_ = msg.ReadFloat();
  785. newControls.pitch_ = msg.ReadFloat();
  786. newControls.extraData_ = msg.ReadVariantMap();
  787. SetControls(newControls);
  788. SetPosition(msg.ReadVector3());
  789. }
  790. void Connection::ProcessSceneLoaded(int msgID, MemoryBuffer& msg)
  791. {
  792. if (!IsClient())
  793. {
  794. LOGWARNING("Received unexpected SceneLoaded message from server");
  795. return;
  796. }
  797. if (!scene_)
  798. {
  799. LOGWARNING("Received a SceneLoaded message without an assigned scene from client " + ToString());
  800. return;
  801. }
  802. unsigned checksum = msg.ReadUInt();
  803. if (checksum != scene_->GetChecksum())
  804. {
  805. LOGINFO("Scene checksum error from client " + ToString());
  806. msg_.Clear();
  807. SendMessage(MSG_SCENECHECKSUMERROR, true, true, msg_);
  808. OnSceneLoadFailed();
  809. }
  810. else
  811. {
  812. sceneLoaded_ = true;
  813. using namespace ClientSceneLoaded;
  814. VariantMap eventData;
  815. eventData[P_CONNECTION] = (void*)this;
  816. SendEvent(E_CLIENTSCENELOADED, eventData);
  817. }
  818. }
  819. void Connection::ProcessRemoteEvent(int msgID, MemoryBuffer& msg)
  820. {
  821. using namespace RemoteEventData;
  822. if (msgID == MSG_REMOTEEVENT)
  823. {
  824. StringHash eventType = msg.ReadStringHash();
  825. if (!GetSubsystem<Network>()->CheckRemoteEvent(eventType))
  826. {
  827. LOGWARNING("Discarding not allowed remote event " + eventType.ToString());
  828. return;
  829. }
  830. VariantMap eventData = msg.ReadVariantMap();
  831. eventData[P_CONNECTION] = (void*)this;
  832. SendEvent(eventType, eventData);
  833. }
  834. else
  835. {
  836. if (!scene_)
  837. {
  838. LOGERROR("Can not receive remote node event without an assigned scene");
  839. return;
  840. }
  841. unsigned nodeID = msg.ReadNetID();
  842. StringHash eventType = msg.ReadStringHash();
  843. if (!GetSubsystem<Network>()->CheckRemoteEvent(eventType))
  844. {
  845. LOGWARNING("Discarding not allowed remote event " + eventType.ToString());
  846. return;
  847. }
  848. VariantMap eventData = msg.ReadVariantMap();
  849. Node* sender = scene_->GetNode(nodeID);
  850. if (!sender)
  851. {
  852. LOGWARNING("Missing sender for remote node event, discarding");
  853. return;
  854. }
  855. eventData[P_CONNECTION] = (void*)this;
  856. sender->SendEvent(eventType, eventData);
  857. }
  858. }
  859. kNet::MessageConnection* Connection::GetMessageConnection() const
  860. {
  861. return const_cast<kNet::MessageConnection*>(connection_.ptr());
  862. }
  863. Scene* Connection::GetScene() const
  864. {
  865. return scene_;
  866. }
  867. bool Connection::IsConnected() const
  868. {
  869. return connection_->GetConnectionState() == kNet::ConnectionOK;
  870. }
  871. String Connection::GetAddress() const
  872. {
  873. kNet::EndPoint endPoint = connection_->RemoteEndPoint();
  874. ///\todo Not IPv6-capable.
  875. return Urho3D::ToString("%d.%d.%d.%d", endPoint.ip[0], endPoint.ip[1], endPoint.ip[2], endPoint.ip[3]);
  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::EMPTY);
  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(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. }