Scene.cpp 23 KB

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