Scene.cpp 27 KB

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