Connection.cpp 59 KB

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