Scene.cpp 27 KB

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