Scene.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. //
  2. // Copyright (c) 2008-2013 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 "Context.h"
  25. #include "CoreEvents.h"
  26. #include "File.h"
  27. #include "Log.h"
  28. #include "PackageFile.h"
  29. #include "Profiler.h"
  30. #include "ReplicationState.h"
  31. #include "Scene.h"
  32. #include "SceneEvents.h"
  33. #include "SmoothedTransform.h"
  34. #include "WorkQueue.h"
  35. #include "XMLFile.h"
  36. #include "DebugNew.h"
  37. namespace Urho3D
  38. {
  39. const char* SCENE_CATEGORY = "Scene";
  40. const char* LOGIC_CATEGORY = "Logic";
  41. const char* SUBSYSTEM_CATEGORY = "Subsystem";
  42. static const int ASYNC_LOAD_MIN_FPS = 30;
  43. static const int ASYNC_LOAD_MAX_MSEC = (int)(1000.0f / ASYNC_LOAD_MIN_FPS);
  44. static const float DEFAULT_SMOOTHING_CONSTANT = 50.0f;
  45. static const float DEFAULT_SNAP_THRESHOLD = 5.0f;
  46. Scene::Scene(Context* context) :
  47. Node(context),
  48. replicatedNodeID_(FIRST_REPLICATED_ID),
  49. replicatedComponentID_(FIRST_REPLICATED_ID),
  50. localNodeID_(FIRST_LOCAL_ID),
  51. localComponentID_(FIRST_LOCAL_ID),
  52. checksum_(0),
  53. timeScale_(1.0f),
  54. elapsedTime_(0),
  55. smoothingConstant_(DEFAULT_SMOOTHING_CONSTANT),
  56. snapThreshold_(DEFAULT_SNAP_THRESHOLD),
  57. updateEnabled_(true),
  58. asyncLoading_(false),
  59. threadedUpdate_(false)
  60. {
  61. // Assign an ID to self so that nodes can refer to this node as a parent
  62. SetID(GetFreeNodeID(REPLICATED));
  63. NodeAdded(this);
  64. SubscribeToEvent(E_UPDATE, HANDLER(Scene, HandleUpdate));
  65. }
  66. Scene::~Scene()
  67. {
  68. // Remove root-level components first, so that scene subsystems such as the octree destroy themselves. This will speed up
  69. // the removal of child nodes' components
  70. RemoveAllComponents();
  71. RemoveAllChildren();
  72. // Remove scene reference and owner from all nodes that still exist
  73. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  74. i->second_->ResetScene();
  75. for (HashMap<unsigned, Node*>::Iterator i = localNodes_.Begin(); i != localNodes_.End(); ++i)
  76. i->second_->ResetScene();
  77. }
  78. void Scene::RegisterObject(Context* context)
  79. {
  80. context->RegisterFactory<Scene>();
  81. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_STRING, "Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT);
  82. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Time Scale", GetTimeScale, SetTimeScale, float, 1.0f, AM_DEFAULT);
  83. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Smoothing Constant", GetSmoothingConstant, SetSmoothingConstant, float, DEFAULT_SMOOTHING_CONSTANT, AM_DEFAULT);
  84. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Snap Threshold", GetSnapThreshold, SetSnapThreshold, float, DEFAULT_SNAP_THRESHOLD, AM_DEFAULT);
  85. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Elapsed Time", GetElapsedTime, SetElapsedTime, float, 0.0f, AM_FILE);
  86. ATTRIBUTE(Scene, VAR_INT, "Next Replicated Node ID", replicatedNodeID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  87. ATTRIBUTE(Scene, VAR_INT, "Next Replicated Component ID", replicatedComponentID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  88. ATTRIBUTE(Scene, VAR_INT, "Next Local Node ID", localNodeID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  89. ATTRIBUTE(Scene, VAR_INT, "Next Local Component ID", localComponentID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  90. ATTRIBUTE(Scene, VAR_VARIANTMAP, "Variables", vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data
  91. ACCESSOR_ATTRIBUTE(Scene, VAR_STRING, "Variable Names", GetVarNamesAttr, SetVarNamesAttr, String, String::EMPTY, AM_FILE | AM_NOEDIT);
  92. }
  93. bool Scene::Load(Deserializer& source, bool setInstanceDefault)
  94. {
  95. PROFILE(LoadScene);
  96. StopAsyncLoading();
  97. // Check ID
  98. if (source.ReadFileID() != "USCN")
  99. {
  100. LOGERROR(source.GetName() + " is not a valid scene file");
  101. return false;
  102. }
  103. LOGINFO("Loading scene from " + source.GetName());
  104. Clear();
  105. // Load the whole scene, then perform post-load if successfully loaded
  106. if (Node::Load(source, setInstanceDefault))
  107. {
  108. FinishLoading(&source);
  109. return true;
  110. }
  111. else
  112. return false;
  113. }
  114. bool Scene::Save(Serializer& dest) const
  115. {
  116. PROFILE(SaveScene);
  117. // Write ID first
  118. if (!dest.WriteFileID("USCN"))
  119. {
  120. LOGERROR("Could not save scene, writing to stream failed");
  121. return false;
  122. }
  123. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  124. if (ptr)
  125. LOGINFO("Saving scene to " + ptr->GetName());
  126. if (Node::Save(dest))
  127. {
  128. FinishSaving(&dest);
  129. return true;
  130. }
  131. else
  132. return false;
  133. }
  134. bool Scene::LoadXML(const XMLElement& source, bool setInstanceDefault)
  135. {
  136. PROFILE(LoadSceneXML);
  137. StopAsyncLoading();
  138. // Load the whole scene, then perform post-load if successfully loaded
  139. // Note: the scene filename and checksum can not be set, as we only used an XML element
  140. if (Node::LoadXML(source, setInstanceDefault))
  141. {
  142. FinishLoading(0);
  143. return true;
  144. }
  145. else
  146. return false;
  147. }
  148. void Scene::AddReplicationState(NodeReplicationState* state)
  149. {
  150. Node::AddReplicationState(state);
  151. // This is the first update for a new connection. Mark all replicated nodes dirty
  152. for (HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  153. state->sceneState_->dirtyNodes_.Insert(i->first_);
  154. }
  155. bool Scene::LoadXML(Deserializer& source)
  156. {
  157. PROFILE(LoadSceneXML);
  158. StopAsyncLoading();
  159. SharedPtr<XMLFile> xml(new XMLFile(context_));
  160. if (!xml->Load(source))
  161. return false;
  162. LOGINFO("Loading scene from " + source.GetName());
  163. Clear();
  164. if (Node::LoadXML(xml->GetRoot()))
  165. {
  166. FinishLoading(&source);
  167. return true;
  168. }
  169. else
  170. return false;
  171. }
  172. bool Scene::SaveXML(Serializer& dest) const
  173. {
  174. PROFILE(SaveSceneXML);
  175. SharedPtr<XMLFile> xml(new XMLFile(context_));
  176. XMLElement rootElem = xml->CreateRoot("scene");
  177. if (!SaveXML(rootElem))
  178. return false;
  179. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  180. if (ptr)
  181. LOGINFO("Saving scene to " + ptr->GetName());
  182. if (xml->Save(dest))
  183. {
  184. FinishSaving(&dest);
  185. return true;
  186. }
  187. else
  188. return false;
  189. }
  190. bool Scene::LoadAsync(File* file)
  191. {
  192. if (!file)
  193. {
  194. LOGERROR("Null file for async loading");
  195. return false;
  196. }
  197. StopAsyncLoading();
  198. // Check ID
  199. if (file->ReadFileID() != "USCN")
  200. {
  201. LOGERROR(file->GetName() + " is not a valid scene file");
  202. return false;
  203. }
  204. LOGINFO("Loading scene from " + file->GetName());
  205. Clear();
  206. // Store own old ID for resolving possible root node references
  207. unsigned nodeID = file->ReadUInt();
  208. resolver_.AddNode(nodeID, this);
  209. // Load root level components first
  210. if (!Node::Load(*file, resolver_, false))
  211. return false;
  212. // Then prepare for loading all root level child nodes in the async update
  213. asyncLoading_ = true;
  214. asyncProgress_.file_ = file;
  215. asyncProgress_.loadedNodes_ = 0;
  216. asyncProgress_.totalNodes_ = file->ReadVLE();
  217. return true;
  218. }
  219. bool Scene::LoadAsyncXML(File* file)
  220. {
  221. if (!file)
  222. {
  223. LOGERROR("Null file for async loading");
  224. return false;
  225. }
  226. StopAsyncLoading();
  227. SharedPtr<XMLFile> xml(new XMLFile(context_));
  228. if (!xml->Load(*file))
  229. return false;
  230. LOGINFO("Loading scene from " + file->GetName());
  231. Clear();
  232. XMLElement rootElement = xml->GetRoot();
  233. // Store own old ID for resolving possible root node references
  234. unsigned nodeID = rootElement.GetInt("id");
  235. resolver_.AddNode(nodeID, this);
  236. // Load the root level components first
  237. if (!Node::LoadXML(rootElement, resolver_, false))
  238. return false;
  239. // Then prepare for loading all root level child nodes in the async update
  240. XMLElement childNodeElement = rootElement.GetChild("node");
  241. asyncLoading_ = true;
  242. asyncProgress_.file_ = file;
  243. asyncProgress_.xmlFile_ = xml;
  244. asyncProgress_.xmlElement_ = childNodeElement;
  245. asyncProgress_.loadedNodes_ = 0;
  246. asyncProgress_.totalNodes_ = 0;
  247. // Count the amount of child nodes
  248. while (childNodeElement)
  249. {
  250. ++asyncProgress_.totalNodes_;
  251. childNodeElement = childNodeElement.GetNext("node");
  252. }
  253. return true;
  254. }
  255. void Scene::StopAsyncLoading()
  256. {
  257. asyncLoading_ = false;
  258. asyncProgress_.file_.Reset();
  259. asyncProgress_.xmlFile_.Reset();
  260. asyncProgress_.xmlElement_ = XMLElement::EMPTY;
  261. resolver_.Reset();
  262. }
  263. Node* Scene::Instantiate(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  264. {
  265. PROFILE(Instantiate);
  266. SceneResolver resolver;
  267. unsigned nodeID = source.ReadInt();
  268. // Rewrite IDs when instantiating
  269. Node* node = CreateChild(0, mode);
  270. resolver.AddNode(nodeID, node);
  271. if (node->Load(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(const XMLElement& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  285. {
  286. PROFILE(InstantiateXML);
  287. SceneResolver resolver;
  288. unsigned nodeID = source.GetInt("id");
  289. // Rewrite IDs when instantiating
  290. Node* node = CreateChild(0, mode);
  291. resolver.AddNode(nodeID, node);
  292. if (node->LoadXML(source, resolver, true, true, mode))
  293. {
  294. resolver.Resolve();
  295. node->ApplyAttributes();
  296. node->SetTransform(position, rotation);
  297. return node;
  298. }
  299. else
  300. {
  301. node->Remove();
  302. return 0;
  303. }
  304. }
  305. Node* Scene::InstantiateXML(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  306. {
  307. SharedPtr<XMLFile> xml(new XMLFile(context_));
  308. if (!xml->Load(source))
  309. return 0;
  310. return InstantiateXML(xml->GetRoot(), position, rotation, mode);
  311. }
  312. void Scene::Clear(bool clearReplicated, bool clearLocal)
  313. {
  314. StopAsyncLoading();
  315. RemoveChildren(clearReplicated, clearLocal, true);
  316. RemoveComponents(clearReplicated, clearLocal);
  317. // Only clear name etc. if clearing completely
  318. if (clearReplicated && clearLocal)
  319. {
  320. UnregisterAllVars();
  321. SetName(String::EMPTY);
  322. fileName_.Clear();
  323. checksum_ = 0;
  324. }
  325. // Reset ID generators
  326. if (clearReplicated)
  327. {
  328. replicatedNodeID_ = FIRST_REPLICATED_ID;
  329. replicatedComponentID_ = FIRST_REPLICATED_ID;
  330. }
  331. if (clearLocal)
  332. {
  333. localNodeID_ = FIRST_LOCAL_ID;
  334. localComponentID_ = FIRST_LOCAL_ID;
  335. }
  336. }
  337. void Scene::SetUpdateEnabled(bool enable)
  338. {
  339. updateEnabled_ = enable;
  340. }
  341. void Scene::SetTimeScale(float scale)
  342. {
  343. timeScale_ = Max(scale, M_EPSILON);
  344. Node::MarkNetworkUpdate();
  345. }
  346. void Scene::SetSmoothingConstant(float constant)
  347. {
  348. smoothingConstant_ = Max(constant, M_EPSILON);
  349. Node::MarkNetworkUpdate();
  350. }
  351. void Scene::SetSnapThreshold(float threshold)
  352. {
  353. snapThreshold_ = Max(threshold, 0.0f);
  354. Node::MarkNetworkUpdate();
  355. }
  356. void Scene::SetElapsedTime(float time)
  357. {
  358. elapsedTime_ = time;
  359. }
  360. void Scene::AddRequiredPackageFile(PackageFile* package)
  361. {
  362. // Do not add packages that failed to load
  363. if (!package || !package->GetNumFiles())
  364. return;
  365. requiredPackageFiles_.Push(SharedPtr<PackageFile>(package));
  366. }
  367. void Scene::ClearRequiredPackageFiles()
  368. {
  369. requiredPackageFiles_.Clear();
  370. }
  371. void Scene::RegisterVar(const String& name)
  372. {
  373. varNames_[name] = name;
  374. }
  375. void Scene::UnregisterVar(const String& name)
  376. {
  377. varNames_.Erase(name);
  378. }
  379. void Scene::UnregisterAllVars()
  380. {
  381. varNames_.Clear();
  382. }
  383. Node* Scene::GetNode(unsigned id) const
  384. {
  385. if (id < FIRST_LOCAL_ID)
  386. {
  387. HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Find(id);
  388. if (i != replicatedNodes_.End())
  389. return i->second_;
  390. else
  391. return 0;
  392. }
  393. else
  394. {
  395. HashMap<unsigned, Node*>::ConstIterator i = localNodes_.Find(id);
  396. if (i != localNodes_.End())
  397. return i->second_;
  398. else
  399. return 0;
  400. }
  401. }
  402. Component* Scene::GetComponent(unsigned id) const
  403. {
  404. if (id < FIRST_LOCAL_ID)
  405. {
  406. HashMap<unsigned, Component*>::ConstIterator i = replicatedComponents_.Find(id);
  407. if (i != replicatedComponents_.End())
  408. return i->second_;
  409. else
  410. return 0;
  411. }
  412. else
  413. {
  414. HashMap<unsigned, Component*>::ConstIterator i = localComponents_.Find(id);
  415. if (i != localComponents_.End())
  416. return i->second_;
  417. else
  418. return 0;
  419. }
  420. }
  421. float Scene::GetAsyncProgress() const
  422. {
  423. if (!asyncLoading_ || !asyncProgress_.totalNodes_)
  424. return 1.0f;
  425. else
  426. return (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  427. }
  428. const String& Scene::GetVarName(ShortStringHash hash) const
  429. {
  430. HashMap<ShortStringHash, String>::ConstIterator i = varNames_.Find(hash);
  431. return i != varNames_.End() ? i->second_ : String::EMPTY;
  432. }
  433. void Scene::Update(float timeStep)
  434. {
  435. if (asyncLoading_)
  436. {
  437. UpdateAsyncLoading();
  438. return;
  439. }
  440. PROFILE(UpdateScene);
  441. timeStep *= timeScale_;
  442. using namespace SceneUpdate;
  443. VariantMap eventData;
  444. eventData[P_SCENE] = (void*)this;
  445. eventData[P_TIMESTEP] = timeStep;
  446. // Update variable timestep logic
  447. SendEvent(E_SCENEUPDATE, eventData);
  448. // Update scene subsystems. If a physics world is present, it will be updated, triggering fixed timestep logic updates
  449. SendEvent(E_SCENESUBSYSTEMUPDATE, eventData);
  450. // Update transform smoothing
  451. {
  452. PROFILE(UpdateSmoothing);
  453. float constant = 1.0f - Clamp(powf(2.0f, -timeStep * smoothingConstant_), 0.0f, 1.0f);
  454. float squaredSnapThreshold = snapThreshold_ * snapThreshold_;
  455. using namespace UpdateSmoothing;
  456. VariantMap eventData;
  457. eventData[P_CONSTANT] = constant;
  458. eventData[P_SQUAREDSNAPTHRESHOLD] = squaredSnapThreshold;
  459. SendEvent(E_UPDATESMOOTHING, eventData);
  460. }
  461. // Post-update variable timestep logic
  462. SendEvent(E_SCENEPOSTUPDATE, eventData);
  463. // Note: using a float for elapsed time accumulation is inherently inaccurate. The purpose of this value is
  464. // primarily to update material animation effects, as it is available to shaders. It can be reset by calling
  465. // SetElapsedTime()
  466. elapsedTime_ += timeStep;
  467. }
  468. void Scene::BeginThreadedUpdate()
  469. {
  470. // Check the work queue subsystem whether it actually has created worker threads. If not, do not enter threaded mode.
  471. if (GetSubsystem<WorkQueue>()->GetNumThreads())
  472. threadedUpdate_ = true;
  473. }
  474. void Scene::EndThreadedUpdate()
  475. {
  476. if (!threadedUpdate_)
  477. return;
  478. threadedUpdate_ = false;
  479. if (!delayedDirtyComponents_.Empty())
  480. {
  481. PROFILE(EndThreadedUpdate);
  482. for (PODVector<Component*>::ConstIterator i = delayedDirtyComponents_.Begin(); i != delayedDirtyComponents_.End(); ++i)
  483. (*i)->OnMarkedDirty((*i)->GetNode());
  484. delayedDirtyComponents_.Clear();
  485. }
  486. }
  487. void Scene::DelayedMarkedDirty(Component* component)
  488. {
  489. MutexLock lock(sceneMutex_);
  490. delayedDirtyComponents_.Push(component);
  491. }
  492. unsigned Scene::GetFreeNodeID(CreateMode mode)
  493. {
  494. if (mode == REPLICATED)
  495. {
  496. for (;;)
  497. {
  498. unsigned ret = replicatedNodeID_;
  499. if (replicatedNodeID_ < LAST_REPLICATED_ID)
  500. ++replicatedNodeID_;
  501. else
  502. replicatedNodeID_ = FIRST_REPLICATED_ID;
  503. if (!replicatedNodes_.Contains(ret))
  504. return ret;
  505. }
  506. }
  507. else
  508. {
  509. for (;;)
  510. {
  511. unsigned ret = localNodeID_;
  512. if (localNodeID_ < LAST_LOCAL_ID)
  513. ++localNodeID_;
  514. else
  515. localNodeID_ = FIRST_LOCAL_ID;
  516. if (!localNodes_.Contains(ret))
  517. return ret;
  518. }
  519. }
  520. }
  521. unsigned Scene::GetFreeComponentID(CreateMode mode)
  522. {
  523. if (mode == REPLICATED)
  524. {
  525. for (;;)
  526. {
  527. unsigned ret = replicatedComponentID_;
  528. if (replicatedComponentID_ < LAST_REPLICATED_ID)
  529. ++replicatedComponentID_;
  530. else
  531. replicatedComponentID_ = FIRST_REPLICATED_ID;
  532. if (!replicatedComponents_.Contains(ret))
  533. return ret;
  534. }
  535. }
  536. else
  537. {
  538. for (;;)
  539. {
  540. unsigned ret = localComponentID_;
  541. if (localComponentID_ < LAST_LOCAL_ID)
  542. ++localComponentID_;
  543. else
  544. localComponentID_ = FIRST_LOCAL_ID;
  545. if (!localComponents_.Contains(ret))
  546. return ret;
  547. }
  548. }
  549. }
  550. void Scene::NodeAdded(Node* node)
  551. {
  552. if (!node || node->GetScene() == this)
  553. return;
  554. // If node already exists in another scene, remove. This is unsupported, as components will not reinitialize themselves
  555. // to use the new scene
  556. Scene* oldScene = node->GetScene();
  557. if (oldScene)
  558. {
  559. LOGERROR("Moving a node from one scene to another is unsupported");
  560. oldScene->NodeRemoved(node);
  561. }
  562. node->SetScene(this);
  563. // If we already have an existing node with the same ID, must remove the scene reference from it
  564. unsigned id = node->GetID();
  565. if (id < FIRST_LOCAL_ID)
  566. {
  567. HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Find(id);
  568. if (i != replicatedNodes_.End() && i->second_ != node)
  569. {
  570. LOGWARNING("Overwriting node with ID " + String(id));
  571. i->second_->ResetScene();
  572. }
  573. replicatedNodes_[id] = node;
  574. MarkNetworkUpdate(node);
  575. MarkReplicationDirty(node);
  576. }
  577. else
  578. {
  579. HashMap<unsigned, Node*>::Iterator i = localNodes_.Find(id);
  580. if (i != localNodes_.End() && i->second_ != node)
  581. {
  582. LOGWARNING("Overwriting node with ID " + String(id));
  583. i->second_->ResetScene();
  584. }
  585. localNodes_[id] = node;
  586. }
  587. }
  588. void Scene::NodeRemoved(Node* node)
  589. {
  590. if (!node || node->GetScene() != this)
  591. return;
  592. unsigned id = node->GetID();
  593. if (id < FIRST_LOCAL_ID)
  594. {
  595. replicatedNodes_.Erase(id);
  596. MarkReplicationDirty(node);
  597. }
  598. else
  599. localNodes_.Erase(id);
  600. node->SetID(0);
  601. node->SetScene(0);
  602. }
  603. void Scene::ComponentAdded(Component* component)
  604. {
  605. if (!component)
  606. return;
  607. unsigned id = component->GetID();
  608. if (id < FIRST_LOCAL_ID)
  609. {
  610. HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Find(id);
  611. if (i != replicatedComponents_.End() && i->second_ != component)
  612. {
  613. LOGWARNING("Overwriting component with ID " + String(id));
  614. i->second_->SetID(0);
  615. }
  616. replicatedComponents_[id] = component;
  617. }
  618. else
  619. {
  620. HashMap<unsigned, Component*>::Iterator i = localComponents_.Find(id);
  621. if (i != localComponents_.End() && i->second_ != component)
  622. {
  623. LOGWARNING("Overwriting component with ID " + String(id));
  624. i->second_->SetID(0);
  625. }
  626. localComponents_[id] = component;
  627. }
  628. }
  629. void Scene::ComponentRemoved(Component* component)
  630. {
  631. if (!component)
  632. return;
  633. unsigned id = component->GetID();
  634. if (id < FIRST_LOCAL_ID)
  635. replicatedComponents_.Erase(id);
  636. else
  637. localComponents_.Erase(id);
  638. component->SetID(0);
  639. }
  640. void Scene::SetVarNamesAttr(String value)
  641. {
  642. Vector<String> varNames = value.Split(';');
  643. varNames_.Clear();
  644. for (Vector<String>::ConstIterator i = varNames.Begin(); i != varNames.End(); ++i)
  645. varNames_[*i] = *i;
  646. }
  647. String Scene::GetVarNamesAttr() const
  648. {
  649. String ret;
  650. if (!varNames_.Empty())
  651. {
  652. for (HashMap<ShortStringHash, String>::ConstIterator i = varNames_.Begin(); i != varNames_.End(); ++i)
  653. ret += i->second_ + ';';
  654. ret.Resize(ret.Length() - 1);
  655. }
  656. return ret;
  657. }
  658. void Scene::PrepareNetworkUpdate()
  659. {
  660. for (HashSet<unsigned>::Iterator i = networkUpdateNodes_.Begin(); i != networkUpdateNodes_.End(); ++i)
  661. {
  662. Node* node = GetNode(*i);
  663. if (node)
  664. node->PrepareNetworkUpdate();
  665. }
  666. for (HashSet<unsigned>::Iterator i = networkUpdateComponents_.Begin(); i != networkUpdateComponents_.End(); ++i)
  667. {
  668. Component* component = GetComponent(*i);
  669. if (component)
  670. component->PrepareNetworkUpdate();
  671. }
  672. networkUpdateNodes_.Clear();
  673. networkUpdateComponents_.Clear();
  674. }
  675. void Scene::CleanupConnection(Connection* connection)
  676. {
  677. Node::CleanupConnection(connection);
  678. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  679. i->second_->CleanupConnection(connection);
  680. for (HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Begin(); i != replicatedComponents_.End(); ++i)
  681. i->second_->CleanupConnection(connection);
  682. }
  683. void Scene::MarkNetworkUpdate(Node* node)
  684. {
  685. if (node)
  686. {
  687. if (!threadedUpdate_)
  688. networkUpdateNodes_.Insert(node->GetID());
  689. else
  690. {
  691. MutexLock lock(sceneMutex_);
  692. networkUpdateNodes_.Insert(node->GetID());
  693. }
  694. }
  695. }
  696. void Scene::MarkNetworkUpdate(Component* component)
  697. {
  698. if (component)
  699. {
  700. if (!threadedUpdate_)
  701. networkUpdateComponents_.Insert(component->GetID());
  702. else
  703. {
  704. MutexLock lock(sceneMutex_);
  705. networkUpdateComponents_.Insert(component->GetID());
  706. }
  707. }
  708. }
  709. void Scene::MarkReplicationDirty(Node* node)
  710. {
  711. unsigned id = node->GetID();
  712. if (id < FIRST_LOCAL_ID && networkState_)
  713. {
  714. for (PODVector<ReplicationState*>::Iterator i = networkState_->replicationStates_.Begin(); i !=
  715. networkState_->replicationStates_.End(); ++i)
  716. {
  717. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*i);
  718. nodeState->sceneState_->dirtyNodes_.Insert(id);
  719. }
  720. }
  721. }
  722. void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  723. {
  724. using namespace Update;
  725. if (updateEnabled_)
  726. Update(eventData[P_TIMESTEP].GetFloat());
  727. }
  728. void Scene::UpdateAsyncLoading()
  729. {
  730. PROFILE(UpdateAsyncLoading);
  731. Timer asyncLoadTimer;
  732. for (;;)
  733. {
  734. if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
  735. {
  736. FinishAsyncLoading();
  737. return;
  738. }
  739. // Read one child node with its full sub-hierarchy either from binary or XML
  740. /// \todo Works poorly in scenes where one root-level child node contains all content
  741. if (!asyncProgress_.xmlFile_)
  742. {
  743. unsigned nodeID = asyncProgress_.file_->ReadUInt();
  744. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  745. resolver_.AddNode(nodeID, newNode);
  746. newNode->Load(*asyncProgress_.file_, resolver_);
  747. }
  748. else
  749. {
  750. unsigned nodeID = asyncProgress_.xmlElement_.GetInt("id");
  751. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  752. resolver_.AddNode(nodeID, newNode);
  753. newNode->LoadXML(asyncProgress_.xmlElement_, resolver_);
  754. asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNext("node");
  755. }
  756. ++asyncProgress_.loadedNodes_;
  757. // Break if time limit exceeded, so that we keep sufficient FPS
  758. if (asyncLoadTimer.GetMSec(false) >= ASYNC_LOAD_MAX_MSEC)
  759. break;
  760. }
  761. using namespace AsyncLoadProgress;
  762. VariantMap eventData;
  763. eventData[P_SCENE] = (void*)this;
  764. eventData[P_PROGRESS] = (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  765. eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
  766. eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
  767. SendEvent(E_ASYNCLOADPROGRESS, eventData);
  768. }
  769. void Scene::FinishAsyncLoading()
  770. {
  771. resolver_.Resolve();
  772. ApplyAttributes();
  773. FinishLoading(asyncProgress_.file_);
  774. StopAsyncLoading();
  775. using namespace AsyncLoadFinished;
  776. VariantMap eventData;
  777. eventData[P_SCENE] = (void*)this;
  778. SendEvent(E_ASYNCLOADFINISHED, eventData);
  779. }
  780. void Scene::FinishLoading(Deserializer* source)
  781. {
  782. if (source)
  783. {
  784. fileName_ = source->GetName();
  785. checksum_ = source->GetChecksum();
  786. }
  787. }
  788. void Scene::FinishSaving(Serializer* dest) const
  789. {
  790. Deserializer* ptr = dynamic_cast<Deserializer*>(dest);
  791. if (ptr)
  792. {
  793. fileName_ = ptr->GetName();
  794. checksum_ = ptr->GetChecksum();
  795. }
  796. }
  797. void RegisterSceneLibrary(Context* context)
  798. {
  799. Node::RegisterObject(context);
  800. Scene::RegisterObject(context);
  801. SmoothedTransform::RegisterObject(context);
  802. }
  803. }