Scene.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Component.h"
  25. #include "Context.h"
  26. #include "CoreEvents.h"
  27. #include "File.h"
  28. #include "Log.h"
  29. #include "PackageFile.h"
  30. #include "Profiler.h"
  31. #include "ReplicationState.h"
  32. #include "Scene.h"
  33. #include "SceneEvents.h"
  34. #include "SmoothedTransform.h"
  35. #include "WorkQueue.h"
  36. #include "XMLFile.h"
  37. #include "DebugNew.h"
  38. namespace Urho3D
  39. {
  40. static const int ASYNC_LOAD_MIN_FPS = 30;
  41. static const int ASYNC_LOAD_MAX_MSEC = (int)(1000.0f / ASYNC_LOAD_MIN_FPS);
  42. static const float DEFAULT_SMOOTHING_CONSTANT = 50.0f;
  43. static const float DEFAULT_SNAP_THRESHOLD = 5.0f;
  44. OBJECTTYPESTATIC(Scene);
  45. Scene::Scene(Context* context) :
  46. Node(context),
  47. replicatedNodeID_(FIRST_REPLICATED_ID),
  48. replicatedComponentID_(FIRST_REPLICATED_ID),
  49. localNodeID_(FIRST_LOCAL_ID),
  50. localComponentID_(FIRST_LOCAL_ID),
  51. checksum_(0),
  52. smoothingConstant_(DEFAULT_SMOOTHING_CONSTANT),
  53. snapThreshold_(DEFAULT_SNAP_THRESHOLD),
  54. active_(true),
  55. asyncLoading_(false),
  56. threadedUpdate_(false)
  57. {
  58. // Assign an ID to self so that nodes can refer to this node as a parent
  59. SetID(GetFreeNodeID(REPLICATED));
  60. NodeAdded(this);
  61. SubscribeToEvent(E_UPDATE, HANDLER(Scene, HandleUpdate));
  62. }
  63. Scene::~Scene()
  64. {
  65. RemoveAllChildren();
  66. RemoveAllComponents();
  67. // Remove scene reference and owner from all nodes that still exist
  68. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  69. {
  70. i->second_->SetID(0);
  71. i->second_->SetScene(0);
  72. i->second_->SetOwner(0);
  73. }
  74. for (HashMap<unsigned, Node*>::Iterator i = localNodes_.Begin(); i != localNodes_.End(); ++i)
  75. {
  76. i->second_->SetID(0);
  77. i->second_->SetScene(0);
  78. i->second_->SetOwner(0);
  79. }
  80. }
  81. void Scene::RegisterObject(Context* context)
  82. {
  83. context->RegisterFactory<Scene>();
  84. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_STRING, "Name", GetName, SetName, String, String(), AM_DEFAULT);
  85. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_VECTOR3, "Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_DEFAULT | AM_LATESTDATA);
  86. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_QUATERNION, "Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  87. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_VECTOR3, "Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  88. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Smoothing Constant", GetSmoothingConstant, SetSmoothingConstant, float, DEFAULT_SMOOTHING_CONSTANT, AM_DEFAULT);
  89. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Snap Threshold", GetSnapThreshold, SetSnapThreshold, float, DEFAULT_SNAP_THRESHOLD, AM_DEFAULT);
  90. ATTRIBUTE(Scene, VAR_INT, "Next Replicated Node ID", replicatedNodeID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  91. ATTRIBUTE(Scene, VAR_INT, "Next Replicated Component ID", replicatedComponentID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  92. ATTRIBUTE(Scene, VAR_INT, "Next Local Node ID", localNodeID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  93. ATTRIBUTE(Scene, VAR_INT, "Next Local Component ID", localComponentID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  94. ATTRIBUTE(Scene, VAR_VARIANTMAP, "Variables", vars_, VariantMap(), AM_FILE); // Network replication of vars uses custom data
  95. ACCESSOR_ATTRIBUTE(Scene, VAR_STRING, "Variable Names", GetVarNamesAttr, SetVarNamesAttr, String, String(), AM_FILE | AM_NOEDIT);
  96. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_NET | AM_LATESTDATA | AM_NOEDIT);
  97. }
  98. bool Scene::Load(Deserializer& source)
  99. {
  100. PROFILE(LoadScene);
  101. StopAsyncLoading();
  102. // Check ID
  103. if (source.ReadFileID() != "USCN")
  104. {
  105. LOGERROR(source.GetName() + " is not a valid scene file");
  106. return false;
  107. }
  108. LOGINFO("Loading scene from " + source.GetName());
  109. // Load the whole scene, then perform post-load if successfully loaded
  110. if (Node::Load(source))
  111. {
  112. FinishLoading(&source);
  113. return true;
  114. }
  115. else
  116. return false;
  117. }
  118. bool Scene::Save(Serializer& dest)
  119. {
  120. PROFILE(SaveScene);
  121. // Write ID first
  122. if (!dest.WriteFileID("USCN"))
  123. {
  124. LOGERROR("Could not save scene, writing to stream failed");
  125. return false;
  126. }
  127. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  128. if (ptr)
  129. LOGINFO("Saving scene to " + ptr->GetName());
  130. return Node::Save(dest);
  131. }
  132. bool Scene::LoadXML(const XMLElement& source)
  133. {
  134. PROFILE(LoadSceneXML);
  135. StopAsyncLoading();
  136. // Load the whole scene, then perform post-load if successfully loaded
  137. // Note: the scene filename and checksum can not be set, as we only used an XML element
  138. if (Node::LoadXML(source))
  139. {
  140. FinishLoading(0);
  141. return true;
  142. }
  143. else
  144. return false;
  145. }
  146. void Scene::AddReplicationState(NodeReplicationState* state)
  147. {
  148. Node::AddReplicationState(state);
  149. // This is the first update for a new connection. Mark all replicated nodes dirty
  150. for (HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  151. state->sceneState_->dirtyNodes_.Insert(i->first_);
  152. }
  153. bool Scene::LoadXML(Deserializer& source)
  154. {
  155. PROFILE(LoadSceneXML);
  156. StopAsyncLoading();
  157. SharedPtr<XMLFile> xml(new XMLFile(context_));
  158. if (!xml->Load(source))
  159. return false;
  160. LOGINFO("Loading scene from " + source.GetName());
  161. if (Node::LoadXML(xml->GetRoot()))
  162. {
  163. FinishLoading(&source);
  164. return true;
  165. }
  166. else
  167. return false;
  168. }
  169. bool Scene::SaveXML(Serializer& dest)
  170. {
  171. PROFILE(SaveSceneXML);
  172. SharedPtr<XMLFile> xml(new XMLFile(context_));
  173. XMLElement rootElem = xml->CreateRoot("scene");
  174. if (!SaveXML(rootElem))
  175. return false;
  176. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  177. if (ptr)
  178. LOGINFO("Saving scene to " + ptr->GetName());
  179. return xml->Save(dest);
  180. }
  181. bool Scene::LoadAsync(File* file)
  182. {
  183. if (!file)
  184. {
  185. LOGERROR("Null file for async loading");
  186. return false;
  187. }
  188. StopAsyncLoading();
  189. // Check ID
  190. if (file->ReadFileID() != "USCN")
  191. {
  192. LOGERROR(file->GetName() + " is not a valid scene file");
  193. return false;
  194. }
  195. LOGINFO("Loading scene from " + file->GetName());
  196. Clear();
  197. // Store own old ID for resolving possible root node references
  198. unsigned nodeID = file->ReadUInt();
  199. resolver_.AddNode(nodeID, this);
  200. // Load root level components first
  201. if (!Node::Load(*file, resolver_, false))
  202. return false;
  203. // Then prepare for loading all root level child nodes in the async update
  204. asyncLoading_ = true;
  205. asyncProgress_.file_ = file;
  206. asyncProgress_.xmlFile_.Reset();
  207. asyncProgress_.xmlElement_ = XMLElement();
  208. asyncProgress_.loadedNodes_ = 0;
  209. asyncProgress_.totalNodes_ = file->ReadVLE();
  210. return true;
  211. }
  212. bool Scene::LoadAsyncXML(File* file)
  213. {
  214. if (!file)
  215. {
  216. LOGERROR("Null file for async loading");
  217. return false;
  218. }
  219. StopAsyncLoading();
  220. SharedPtr<XMLFile> xml(new XMLFile(context_));
  221. if (!xml->Load(*file))
  222. return false;
  223. LOGINFO("Loading scene from " + file->GetName());
  224. Clear();
  225. XMLElement rootElement = xml->GetRoot();
  226. // Store own old ID for resolving possible root node references
  227. unsigned nodeID = rootElement.GetInt("id");
  228. resolver_.AddNode(nodeID, this);
  229. // Load the root level components first
  230. if (!Node::LoadXML(rootElement, resolver_, false))
  231. return false;
  232. // Then prepare for loading all root level child nodes in the async update
  233. XMLElement childNodeElement = rootElement.GetChild("node");
  234. asyncLoading_ = true;
  235. asyncProgress_.file_ = file;
  236. asyncProgress_.xmlFile_ = xml;
  237. asyncProgress_.xmlElement_ = childNodeElement;
  238. asyncProgress_.loadedNodes_ = 0;
  239. asyncProgress_.totalNodes_ = 0;
  240. // Count the amount of child nodes
  241. while (childNodeElement)
  242. {
  243. ++asyncProgress_.totalNodes_;
  244. childNodeElement = childNodeElement.GetNext("node");
  245. }
  246. return true;
  247. }
  248. void Scene::StopAsyncLoading()
  249. {
  250. asyncLoading_ = false;
  251. asyncProgress_.file_.Reset();
  252. asyncProgress_.xmlFile_.Reset();
  253. asyncProgress_.xmlElement_ = XMLElement();
  254. resolver_.Reset();
  255. }
  256. Node* Scene::Instantiate(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  257. {
  258. PROFILE(Instantiate);
  259. SceneResolver resolver;
  260. unsigned nodeID = source.ReadInt();
  261. // Rewrite IDs when instantiating
  262. Node* node = CreateChild(0, mode);
  263. resolver.AddNode(nodeID, node);
  264. if (node->Load(source, resolver, true, true, mode))
  265. {
  266. resolver.Resolve();
  267. node->ApplyAttributes();
  268. node->SetTransform(position, rotation);
  269. return node;
  270. }
  271. else
  272. {
  273. node->Remove();
  274. return 0;
  275. }
  276. }
  277. Node* Scene::InstantiateXML(const XMLElement& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  278. {
  279. PROFILE(InstantiateXML);
  280. SceneResolver resolver;
  281. unsigned nodeID = source.GetInt("id");
  282. // Rewrite IDs when instantiating
  283. Node* node = CreateChild(0, mode);
  284. resolver.AddNode(nodeID, node);
  285. if (node->LoadXML(source, resolver, true, true, mode))
  286. {
  287. resolver.Resolve();
  288. node->ApplyAttributes();
  289. node->SetTransform(position, rotation);
  290. return node;
  291. }
  292. else
  293. {
  294. node->Remove();
  295. return 0;
  296. }
  297. }
  298. Node* Scene::InstantiateXML(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  299. {
  300. SharedPtr<XMLFile> xml(new XMLFile(context_));
  301. if (!xml->Load(source))
  302. return false;
  303. return InstantiateXML(xml->GetRoot(), position, rotation, mode);
  304. }
  305. void Scene::Clear()
  306. {
  307. StopAsyncLoading();
  308. RemoveAllChildren();
  309. RemoveAllComponents();
  310. fileName_ = String();
  311. checksum_ = 0;
  312. replicatedNodeID_ = FIRST_REPLICATED_ID;
  313. replicatedComponentID_ = FIRST_REPLICATED_ID;
  314. localNodeID_ = FIRST_LOCAL_ID;
  315. localComponentID_ = FIRST_LOCAL_ID;
  316. }
  317. void Scene::SetActive(bool enable)
  318. {
  319. active_ = enable;
  320. }
  321. void Scene::SetSmoothingConstant(float constant)
  322. {
  323. smoothingConstant_ = Max(constant, M_EPSILON);
  324. Node::MarkNetworkUpdate();
  325. }
  326. void Scene::SetSnapThreshold(float threshold)
  327. {
  328. snapThreshold_ = Max(threshold, 0.0f);
  329. Node::MarkNetworkUpdate();
  330. }
  331. void Scene::AddRequiredPackageFile(PackageFile* package)
  332. {
  333. // Do not add packages that failed to load
  334. if (!package || !package->GetNumFiles())
  335. return;
  336. requiredPackageFiles_.Push(SharedPtr<PackageFile>(package));
  337. }
  338. void Scene::ClearRequiredPackageFiles()
  339. {
  340. requiredPackageFiles_.Clear();
  341. }
  342. void Scene::RegisterVar(const String& name)
  343. {
  344. varNames_[ShortStringHash(name)] = name;
  345. }
  346. void Scene::UnregisterVar(const String& name)
  347. {
  348. varNames_.Erase(ShortStringHash(name));
  349. }
  350. void Scene::UnregisterAllVars()
  351. {
  352. varNames_.Clear();
  353. }
  354. Node* Scene::GetNode(unsigned id) const
  355. {
  356. if (id < FIRST_LOCAL_ID)
  357. {
  358. HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Find(id);
  359. if (i != replicatedNodes_.End())
  360. return i->second_;
  361. else
  362. return 0;
  363. }
  364. else
  365. {
  366. HashMap<unsigned, Node*>::ConstIterator i = localNodes_.Find(id);
  367. if (i != localNodes_.End())
  368. return i->second_;
  369. else
  370. return 0;
  371. }
  372. }
  373. Component* Scene::GetComponent(unsigned id) const
  374. {
  375. if (id < FIRST_LOCAL_ID)
  376. {
  377. HashMap<unsigned, Component*>::ConstIterator i = replicatedComponents_.Find(id);
  378. if (i != replicatedComponents_.End())
  379. return i->second_;
  380. else
  381. return 0;
  382. }
  383. else
  384. {
  385. HashMap<unsigned, Component*>::ConstIterator i = localComponents_.Find(id);
  386. if (i != localComponents_.End())
  387. return i->second_;
  388. else
  389. return 0;
  390. }
  391. }
  392. float Scene::GetAsyncProgress() const
  393. {
  394. if (!asyncLoading_ || !asyncProgress_.totalNodes_)
  395. return 1.0f;
  396. else
  397. return (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  398. }
  399. const String& Scene::GetVarName(ShortStringHash hash) const
  400. {
  401. HashMap<ShortStringHash, String>::ConstIterator i = varNames_.Find(hash);
  402. return i != varNames_.End() ? i->second_ : String::EMPTY;
  403. }
  404. void Scene::Update(float timeStep)
  405. {
  406. if (asyncLoading_)
  407. {
  408. UpdateAsyncLoading();
  409. return;
  410. }
  411. PROFILE(UpdateScene);
  412. using namespace SceneUpdate;
  413. VariantMap eventData;
  414. eventData[P_SCENE] = (void*)this;
  415. eventData[P_TIMESTEP] = timeStep;
  416. // Update variable timestep logic
  417. SendEvent(E_SCENEUPDATE, eventData);
  418. // Update scene subsystems. If a physics world is present, it will be updated, triggering fixed timestep logic updates
  419. SendEvent(E_SCENESUBSYSTEMUPDATE, eventData);
  420. // Update transform smoothing
  421. {
  422. PROFILE(UpdateSmoothing);
  423. float constant = 1.0f - Clamp(powf(2.0f, -timeStep * smoothingConstant_), 0.0f, 1.0f);
  424. float squaredSnapThreshold = snapThreshold_ * snapThreshold_;
  425. using namespace UpdateSmoothing;
  426. VariantMap eventData;
  427. eventData[P_CONSTANT] = constant;
  428. eventData[P_SQUAREDSNAPTHRESHOLD] = squaredSnapThreshold;
  429. SendEvent(E_UPDATESMOOTHING, eventData);
  430. }
  431. // Post-update variable timestep logic
  432. SendEvent(E_SCENEPOSTUPDATE, eventData);
  433. }
  434. void Scene::BeginThreadedUpdate()
  435. {
  436. // Check the work queue subsystem whether it actually has created worker threads. If not, do not enter threaded mode.
  437. if (GetSubsystem<WorkQueue>()->GetNumThreads())
  438. threadedUpdate_ = true;
  439. }
  440. void Scene::EndThreadedUpdate()
  441. {
  442. if (!threadedUpdate_)
  443. return;
  444. threadedUpdate_ = false;
  445. if (!delayedDirtyComponents_.Empty())
  446. {
  447. PROFILE(EndThreadedUpdate);
  448. for (PODVector<Component*>::ConstIterator i = delayedDirtyComponents_.Begin(); i != delayedDirtyComponents_.End(); ++i)
  449. (*i)->OnMarkedDirty((*i)->GetNode());
  450. delayedDirtyComponents_.Clear();
  451. }
  452. }
  453. void Scene::DelayedMarkedDirty(Component* component)
  454. {
  455. MutexLock lock(sceneMutex_);
  456. delayedDirtyComponents_.Push(component);
  457. }
  458. unsigned Scene::GetFreeNodeID(CreateMode mode)
  459. {
  460. if (mode == REPLICATED)
  461. {
  462. for (;;)
  463. {
  464. if (!replicatedNodes_.Contains(replicatedNodeID_))
  465. return replicatedNodeID_;
  466. if (replicatedNodeID_ != LAST_REPLICATED_ID)
  467. ++replicatedNodeID_;
  468. else
  469. replicatedNodeID_ = FIRST_REPLICATED_ID;
  470. }
  471. }
  472. else
  473. {
  474. for (;;)
  475. {
  476. if (!localNodes_.Contains(localNodeID_))
  477. return localNodeID_;
  478. if (localNodeID_ != LAST_LOCAL_ID)
  479. ++localNodeID_;
  480. else
  481. localNodeID_ = FIRST_LOCAL_ID;
  482. }
  483. }
  484. }
  485. unsigned Scene::GetFreeComponentID(CreateMode mode)
  486. {
  487. if (mode == REPLICATED)
  488. {
  489. for (;;)
  490. {
  491. if (!replicatedComponents_.Contains(replicatedComponentID_))
  492. return replicatedComponentID_;
  493. if (replicatedComponentID_ != LAST_REPLICATED_ID)
  494. ++replicatedComponentID_;
  495. else
  496. replicatedComponentID_ = FIRST_REPLICATED_ID;
  497. }
  498. }
  499. else
  500. {
  501. for (;;)
  502. {
  503. if (!localComponents_.Contains(localComponentID_))
  504. return localComponentID_;
  505. if (localComponentID_ != LAST_LOCAL_ID)
  506. ++localComponentID_;
  507. else
  508. localComponentID_ = FIRST_LOCAL_ID;
  509. }
  510. }
  511. }
  512. void Scene::NodeAdded(Node* node)
  513. {
  514. if (!node || node->GetScene())
  515. return;
  516. node->SetScene(this);
  517. // If we already have an existing node with the same ID, must remove the scene reference from it
  518. unsigned id = node->GetID();
  519. if (id < FIRST_LOCAL_ID)
  520. {
  521. HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Find(id);
  522. if (i != replicatedNodes_.End() && i->second_ != node)
  523. {
  524. LOGWARNING("Overwriting node with ID " + String(id));
  525. i->second_->SetID(0);
  526. i->second_->SetScene(0);
  527. i->second_->SetOwner(0);
  528. }
  529. replicatedNodes_[id] = node;
  530. MarkNetworkUpdate(node);
  531. MarkReplicationDirty(node);
  532. }
  533. else
  534. {
  535. HashMap<unsigned, Node*>::Iterator i = localNodes_.Find(id);
  536. if (i != localNodes_.End() && i->second_ != node)
  537. {
  538. LOGWARNING("Overwriting node with ID " + String(id));
  539. i->second_->SetID(0);
  540. i->second_->SetScene(0);
  541. i->second_->SetOwner(0);
  542. }
  543. localNodes_[id] = node;
  544. }
  545. }
  546. void Scene::NodeRemoved(Node* node)
  547. {
  548. if (!node || node->GetScene() != this)
  549. return;
  550. unsigned id = node->GetID();
  551. if (id < FIRST_LOCAL_ID)
  552. {
  553. replicatedNodes_.Erase(id);
  554. MarkReplicationDirty(node);
  555. }
  556. else
  557. localNodes_.Erase(id);
  558. node->SetID(0);
  559. node->SetScene(0);
  560. }
  561. void Scene::ComponentAdded(Component* component)
  562. {
  563. if (!component)
  564. return;
  565. unsigned id = component->GetID();
  566. if (id < FIRST_LOCAL_ID)
  567. {
  568. HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Find(id);
  569. if (i != replicatedComponents_.End() && i->second_ != component)
  570. {
  571. LOGWARNING("Overwriting component with ID " + String(id));
  572. i->second_->SetID(0);
  573. }
  574. replicatedComponents_[id] = component;
  575. }
  576. else
  577. {
  578. HashMap<unsigned, Component*>::Iterator i = localComponents_.Find(id);
  579. if (i != localComponents_.End() && i->second_ != component)
  580. {
  581. LOGWARNING("Overwriting component with ID " + String(id));
  582. i->second_->SetID(0);
  583. }
  584. localComponents_[id] = component;
  585. }
  586. }
  587. void Scene::ComponentRemoved(Component* component)
  588. {
  589. if (!component)
  590. return;
  591. unsigned id = component->GetID();
  592. if (id < FIRST_LOCAL_ID)
  593. replicatedComponents_.Erase(id);
  594. else
  595. localComponents_.Erase(id);
  596. component->SetID(0);
  597. }
  598. void Scene::SetVarNamesAttr(String value)
  599. {
  600. Vector<String> varNames = value.Split(';');
  601. varNames_.Clear();
  602. for (Vector<String>::ConstIterator i = varNames.Begin(); i != varNames.End(); ++i)
  603. varNames_[ShortStringHash(*i)] = *i;
  604. }
  605. String Scene::GetVarNamesAttr() const
  606. {
  607. String ret;
  608. for (HashMap<ShortStringHash, String>::ConstIterator i = varNames_.Begin(); i != varNames_.End(); ++i)
  609. {
  610. if (i != varNames_.Begin())
  611. ret += ';';
  612. ret += i->second_;
  613. }
  614. return ret;
  615. }
  616. void Scene::PrepareNetworkUpdate()
  617. {
  618. for (HashSet<unsigned>::Iterator i = networkUpdateNodes_.Begin(); i != networkUpdateNodes_.End(); ++i)
  619. {
  620. Node* node = GetNode(*i);
  621. if (node)
  622. node->PrepareNetworkUpdate();
  623. }
  624. for (HashSet<unsigned>::Iterator i = networkUpdateComponents_.Begin(); i != networkUpdateComponents_.End(); ++i)
  625. {
  626. Component* component = GetComponent(*i);
  627. if (component)
  628. component->PrepareNetworkUpdate();
  629. }
  630. networkUpdateNodes_.Clear();
  631. networkUpdateComponents_.Clear();
  632. }
  633. void Scene::CleanupConnection(Connection* connection)
  634. {
  635. Node::CleanupConnection(connection);
  636. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  637. i->second_->CleanupConnection(connection);
  638. for (HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Begin(); i != replicatedComponents_.End(); ++i)
  639. i->second_->CleanupConnection(connection);
  640. }
  641. void Scene::MarkNetworkUpdate(Node* node)
  642. {
  643. if (node)
  644. networkUpdateNodes_.Insert(node->GetID());
  645. }
  646. void Scene::MarkNetworkUpdate(Component* component)
  647. {
  648. if (component)
  649. networkUpdateComponents_.Insert(component->GetID());
  650. }
  651. void Scene::MarkReplicationDirty(Node* node)
  652. {
  653. unsigned id = node->GetID();
  654. if (id < FIRST_LOCAL_ID && networkState_)
  655. {
  656. for (PODVector<ReplicationState*>::Iterator i = networkState_->replicationStates_.Begin(); i !=
  657. networkState_->replicationStates_.End(); ++i)
  658. {
  659. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*i);
  660. nodeState->sceneState_->dirtyNodes_.Insert(id);
  661. }
  662. }
  663. }
  664. void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  665. {
  666. using namespace Update;
  667. if (active_)
  668. Update(eventData[P_TIMESTEP].GetFloat());
  669. }
  670. void Scene::UpdateAsyncLoading()
  671. {
  672. PROFILE(UpdateAsyncLoading);
  673. Timer asyncLoadTimer;
  674. for (;;)
  675. {
  676. if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
  677. {
  678. FinishAsyncLoading();
  679. return;
  680. }
  681. // Read one child node with its full sub-hierarchy from either from binary or XML
  682. if (!asyncProgress_.xmlFile_)
  683. {
  684. unsigned nodeID = asyncProgress_.file_->ReadUInt();
  685. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  686. resolver_.AddNode(nodeID, newNode);
  687. newNode->Load(*asyncProgress_.file_, resolver_);
  688. }
  689. else
  690. {
  691. unsigned nodeID = asyncProgress_.xmlElement_.GetInt("id");
  692. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  693. resolver_.AddNode(nodeID, newNode);
  694. newNode->LoadXML(asyncProgress_.xmlElement_, resolver_);
  695. asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNext("node");
  696. }
  697. ++asyncProgress_.loadedNodes_;
  698. // Break if time limit exceeded, so that we keep sufficient FPS
  699. if (asyncLoadTimer.GetMSec(false) >= ASYNC_LOAD_MAX_MSEC)
  700. break;
  701. }
  702. using namespace AsyncLoadProgress;
  703. VariantMap eventData;
  704. eventData[P_SCENE] = (void*)this;
  705. eventData[P_PROGRESS] = (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  706. eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
  707. eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
  708. SendEvent(E_ASYNCLOADPROGRESS, eventData);
  709. }
  710. void Scene::FinishAsyncLoading()
  711. {
  712. resolver_.Resolve();
  713. ApplyAttributes();
  714. FinishLoading(asyncProgress_.file_);
  715. StopAsyncLoading();
  716. using namespace AsyncLoadFinished;
  717. VariantMap eventData;
  718. eventData[P_SCENE] = (void*)this;
  719. SendEvent(E_ASYNCLOADFINISHED, eventData);
  720. }
  721. void Scene::FinishLoading(Deserializer* source)
  722. {
  723. if (source)
  724. {
  725. fileName_ = source->GetName();
  726. checksum_ = source->GetChecksum();
  727. }
  728. }
  729. void RegisterSceneLibrary(Context* context)
  730. {
  731. Node::RegisterObject(context);
  732. Scene::RegisterObject(context);
  733. SmoothedTransform::RegisterObject(context);
  734. }
  735. }