Scene.cpp 28 KB

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