2
0

Connection.cpp 53 KB

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