Connection.cpp 52 KB

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