Connection.cpp 52 KB

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