Connection.cpp 51 KB

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