Connection.cpp 51 KB

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