Scene.cpp 27 KB

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