Scene.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Component.h"
  24. #include "Context.h"
  25. #include "CoreEvents.h"
  26. #include "File.h"
  27. #include "Log.h"
  28. #include "PackageFile.h"
  29. #include "Profiler.h"
  30. #include "ReplicationState.h"
  31. #include "Scene.h"
  32. #include "SceneEvents.h"
  33. #include "SmoothedTransform.h"
  34. #include "WorkQueue.h"
  35. #include "XMLFile.h"
  36. #include "DebugNew.h"
  37. namespace Urho3D
  38. {
  39. const char* SCENE_CATEGORY = "Scene";
  40. const char* LOGIC_CATEGORY = "Logic";
  41. const char* SUBSYSTEM_CATEGORY = "Subsystem";
  42. static const int ASYNC_LOAD_MIN_FPS = 30;
  43. static const int ASYNC_LOAD_MAX_MSEC = (int)(1000.0f / ASYNC_LOAD_MIN_FPS);
  44. static const float DEFAULT_SMOOTHING_CONSTANT = 50.0f;
  45. static const float DEFAULT_SNAP_THRESHOLD = 5.0f;
  46. Scene::Scene(Context* context) :
  47. Node(context),
  48. replicatedNodeID_(FIRST_REPLICATED_ID),
  49. replicatedComponentID_(FIRST_REPLICATED_ID),
  50. localNodeID_(FIRST_LOCAL_ID),
  51. localComponentID_(FIRST_LOCAL_ID),
  52. checksum_(0),
  53. timeScale_(1.0f),
  54. elapsedTime_(0),
  55. smoothingConstant_(DEFAULT_SMOOTHING_CONSTANT),
  56. snapThreshold_(DEFAULT_SNAP_THRESHOLD),
  57. updateEnabled_(true),
  58. asyncLoading_(false),
  59. threadedUpdate_(false)
  60. {
  61. // Assign an ID to self so that nodes can refer to this node as a parent
  62. SetID(GetFreeNodeID(REPLICATED));
  63. NodeAdded(this);
  64. SubscribeToEvent(E_UPDATE, HANDLER(Scene, HandleUpdate));
  65. }
  66. Scene::~Scene()
  67. {
  68. RemoveAllChildren();
  69. RemoveAllComponents();
  70. // Remove scene reference and owner from all nodes that still exist
  71. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  72. i->second_->ResetScene();
  73. for (HashMap<unsigned, Node*>::Iterator i = localNodes_.Begin(); i != localNodes_.End(); ++i)
  74. i->second_->ResetScene();
  75. }
  76. void Scene::RegisterObject(Context* context)
  77. {
  78. context->RegisterFactory<Scene>();
  79. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_STRING, "Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT);
  80. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_VECTOR3, "Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_DEFAULT | AM_LATESTDATA);
  81. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_QUATERNION, "Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  82. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_VECTOR3, "Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  83. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Time Scale", GetTimeScale, SetTimeScale, float, 1.0f, AM_DEFAULT);
  84. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Smoothing Constant", GetSmoothingConstant, SetSmoothingConstant, float, DEFAULT_SMOOTHING_CONSTANT, AM_DEFAULT);
  85. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Snap Threshold", GetSnapThreshold, SetSnapThreshold, float, DEFAULT_SNAP_THRESHOLD, AM_DEFAULT);
  86. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Elapsed Time", GetElapsedTime, SetElapsedTime, float, 0.0f, AM_FILE);
  87. ATTRIBUTE(Scene, VAR_INT, "Next Replicated Node ID", replicatedNodeID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  88. ATTRIBUTE(Scene, VAR_INT, "Next Replicated Component ID", replicatedComponentID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  89. ATTRIBUTE(Scene, VAR_INT, "Next Local Node ID", localNodeID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  90. ATTRIBUTE(Scene, VAR_INT, "Next Local Component ID", localComponentID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  91. ATTRIBUTE(Scene, VAR_VARIANTMAP, "Variables", vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data
  92. ACCESSOR_ATTRIBUTE(Scene, VAR_STRING, "Variable Names", GetVarNamesAttr, SetVarNamesAttr, String, String::EMPTY, AM_FILE | AM_NOEDIT);
  93. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_LATESTDATA | 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;
  446. eventData[P_SCENE] = (void*)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. VariantMap eventData;
  459. eventData[P_CONSTANT] = constant;
  460. eventData[P_SQUAREDSNAPTHRESHOLD] = squaredSnapThreshold;
  461. SendEvent(E_UPDATESMOOTHING, eventData);
  462. }
  463. // Post-update variable timestep logic
  464. SendEvent(E_SCENEPOSTUPDATE, eventData);
  465. // Note: using a float for elapsed time accumulation is inherently inaccurate. The purpose of this value is
  466. // primarily to update material animation effects, as it is available to shaders. It can be reset by calling
  467. // SetElapsedTime()
  468. elapsedTime_ += timeStep;
  469. }
  470. void Scene::BeginThreadedUpdate()
  471. {
  472. // Check the work queue subsystem whether it actually has created worker threads. If not, do not enter threaded mode.
  473. if (GetSubsystem<WorkQueue>()->GetNumThreads())
  474. threadedUpdate_ = true;
  475. }
  476. void Scene::EndThreadedUpdate()
  477. {
  478. if (!threadedUpdate_)
  479. return;
  480. threadedUpdate_ = false;
  481. if (!delayedDirtyComponents_.Empty())
  482. {
  483. PROFILE(EndThreadedUpdate);
  484. for (PODVector<Component*>::ConstIterator i = delayedDirtyComponents_.Begin(); i != delayedDirtyComponents_.End(); ++i)
  485. (*i)->OnMarkedDirty((*i)->GetNode());
  486. delayedDirtyComponents_.Clear();
  487. }
  488. }
  489. void Scene::DelayedMarkedDirty(Component* component)
  490. {
  491. MutexLock lock(sceneMutex_);
  492. delayedDirtyComponents_.Push(component);
  493. }
  494. unsigned Scene::GetFreeNodeID(CreateMode mode)
  495. {
  496. if (mode == REPLICATED)
  497. {
  498. for (;;)
  499. {
  500. unsigned ret = replicatedNodeID_;
  501. if (replicatedNodeID_ < LAST_REPLICATED_ID)
  502. ++replicatedNodeID_;
  503. else
  504. replicatedNodeID_ = FIRST_REPLICATED_ID;
  505. if (!replicatedNodes_.Contains(ret))
  506. return ret;
  507. }
  508. }
  509. else
  510. {
  511. for (;;)
  512. {
  513. unsigned ret = localNodeID_;
  514. if (localNodeID_ < LAST_LOCAL_ID)
  515. ++localNodeID_;
  516. else
  517. localNodeID_ = FIRST_LOCAL_ID;
  518. if (!localNodes_.Contains(ret))
  519. return ret;
  520. }
  521. }
  522. }
  523. unsigned Scene::GetFreeComponentID(CreateMode mode)
  524. {
  525. if (mode == REPLICATED)
  526. {
  527. for (;;)
  528. {
  529. unsigned ret = replicatedComponentID_;
  530. if (replicatedComponentID_ < LAST_REPLICATED_ID)
  531. ++replicatedComponentID_;
  532. else
  533. replicatedComponentID_ = FIRST_REPLICATED_ID;
  534. if (!replicatedComponents_.Contains(ret))
  535. return ret;
  536. }
  537. }
  538. else
  539. {
  540. for (;;)
  541. {
  542. unsigned ret = localComponentID_;
  543. if (localComponentID_ < LAST_LOCAL_ID)
  544. ++localComponentID_;
  545. else
  546. localComponentID_ = FIRST_LOCAL_ID;
  547. if (!localComponents_.Contains(ret))
  548. return ret;
  549. }
  550. }
  551. }
  552. void Scene::NodeAdded(Node* node)
  553. {
  554. if (!node || node->GetScene() == this)
  555. return;
  556. // If node already exists in another scene, remove. This is unsupported, as components will not reinitialize themselves
  557. // to use the new scene
  558. Scene* oldScene = node->GetScene();
  559. if (oldScene)
  560. {
  561. LOGERROR("Moving a node from one scene to another is unsupported");
  562. oldScene->NodeRemoved(node);
  563. }
  564. node->SetScene(this);
  565. // If we already have an existing node with the same ID, must remove the scene reference from it
  566. unsigned id = node->GetID();
  567. if (id < FIRST_LOCAL_ID)
  568. {
  569. HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Find(id);
  570. if (i != replicatedNodes_.End() && i->second_ != node)
  571. {
  572. LOGWARNING("Overwriting node with ID " + String(id));
  573. i->second_->ResetScene();
  574. }
  575. replicatedNodes_[id] = node;
  576. MarkNetworkUpdate(node);
  577. MarkReplicationDirty(node);
  578. }
  579. else
  580. {
  581. HashMap<unsigned, Node*>::Iterator i = localNodes_.Find(id);
  582. if (i != localNodes_.End() && i->second_ != node)
  583. {
  584. LOGWARNING("Overwriting node with ID " + String(id));
  585. i->second_->ResetScene();
  586. }
  587. localNodes_[id] = node;
  588. }
  589. }
  590. void Scene::NodeRemoved(Node* node)
  591. {
  592. if (!node || node->GetScene() != this)
  593. return;
  594. unsigned id = node->GetID();
  595. if (id < FIRST_LOCAL_ID)
  596. {
  597. replicatedNodes_.Erase(id);
  598. MarkReplicationDirty(node);
  599. }
  600. else
  601. localNodes_.Erase(id);
  602. node->SetID(0);
  603. node->SetScene(0);
  604. }
  605. void Scene::ComponentAdded(Component* component)
  606. {
  607. if (!component)
  608. return;
  609. unsigned id = component->GetID();
  610. if (id < FIRST_LOCAL_ID)
  611. {
  612. HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Find(id);
  613. if (i != replicatedComponents_.End() && i->second_ != component)
  614. {
  615. LOGWARNING("Overwriting component with ID " + String(id));
  616. i->second_->SetID(0);
  617. }
  618. replicatedComponents_[id] = component;
  619. }
  620. else
  621. {
  622. HashMap<unsigned, Component*>::Iterator i = localComponents_.Find(id);
  623. if (i != localComponents_.End() && i->second_ != component)
  624. {
  625. LOGWARNING("Overwriting component with ID " + String(id));
  626. i->second_->SetID(0);
  627. }
  628. localComponents_[id] = component;
  629. }
  630. }
  631. void Scene::ComponentRemoved(Component* component)
  632. {
  633. if (!component)
  634. return;
  635. unsigned id = component->GetID();
  636. if (id < FIRST_LOCAL_ID)
  637. replicatedComponents_.Erase(id);
  638. else
  639. localComponents_.Erase(id);
  640. component->SetID(0);
  641. }
  642. void Scene::SetVarNamesAttr(String value)
  643. {
  644. Vector<String> varNames = value.Split(';');
  645. varNames_.Clear();
  646. for (Vector<String>::ConstIterator i = varNames.Begin(); i != varNames.End(); ++i)
  647. varNames_[*i] = *i;
  648. }
  649. String Scene::GetVarNamesAttr() const
  650. {
  651. String ret;
  652. if (!varNames_.Empty())
  653. {
  654. for (HashMap<ShortStringHash, String>::ConstIterator i = varNames_.Begin(); i != varNames_.End(); ++i)
  655. ret += i->second_ + ';';
  656. ret.Resize(ret.Length() - 1);
  657. }
  658. return ret;
  659. }
  660. void Scene::PrepareNetworkUpdate()
  661. {
  662. for (HashSet<unsigned>::Iterator i = networkUpdateNodes_.Begin(); i != networkUpdateNodes_.End(); ++i)
  663. {
  664. Node* node = GetNode(*i);
  665. if (node)
  666. node->PrepareNetworkUpdate();
  667. }
  668. for (HashSet<unsigned>::Iterator i = networkUpdateComponents_.Begin(); i != networkUpdateComponents_.End(); ++i)
  669. {
  670. Component* component = GetComponent(*i);
  671. if (component)
  672. component->PrepareNetworkUpdate();
  673. }
  674. networkUpdateNodes_.Clear();
  675. networkUpdateComponents_.Clear();
  676. }
  677. void Scene::CleanupConnection(Connection* connection)
  678. {
  679. Node::CleanupConnection(connection);
  680. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  681. i->second_->CleanupConnection(connection);
  682. for (HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Begin(); i != replicatedComponents_.End(); ++i)
  683. i->second_->CleanupConnection(connection);
  684. }
  685. void Scene::MarkNetworkUpdate(Node* node)
  686. {
  687. if (node)
  688. networkUpdateNodes_.Insert(node->GetID());
  689. }
  690. void Scene::MarkNetworkUpdate(Component* component)
  691. {
  692. if (component)
  693. networkUpdateComponents_.Insert(component->GetID());
  694. }
  695. void Scene::MarkReplicationDirty(Node* node)
  696. {
  697. unsigned id = node->GetID();
  698. if (id < FIRST_LOCAL_ID && networkState_)
  699. {
  700. for (PODVector<ReplicationState*>::Iterator i = networkState_->replicationStates_.Begin(); i !=
  701. networkState_->replicationStates_.End(); ++i)
  702. {
  703. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*i);
  704. nodeState->sceneState_->dirtyNodes_.Insert(id);
  705. }
  706. }
  707. }
  708. void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  709. {
  710. using namespace Update;
  711. if (updateEnabled_)
  712. Update(eventData[P_TIMESTEP].GetFloat());
  713. }
  714. void Scene::UpdateAsyncLoading()
  715. {
  716. PROFILE(UpdateAsyncLoading);
  717. Timer asyncLoadTimer;
  718. for (;;)
  719. {
  720. if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
  721. {
  722. FinishAsyncLoading();
  723. return;
  724. }
  725. // Read one child node with its full sub-hierarchy either from binary or XML
  726. if (!asyncProgress_.xmlFile_)
  727. {
  728. unsigned nodeID = asyncProgress_.file_->ReadUInt();
  729. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  730. resolver_.AddNode(nodeID, newNode);
  731. newNode->Load(*asyncProgress_.file_, resolver_);
  732. }
  733. else
  734. {
  735. unsigned nodeID = asyncProgress_.xmlElement_.GetInt("id");
  736. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  737. resolver_.AddNode(nodeID, newNode);
  738. newNode->LoadXML(asyncProgress_.xmlElement_, resolver_);
  739. asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNext("node");
  740. }
  741. ++asyncProgress_.loadedNodes_;
  742. // Break if time limit exceeded, so that we keep sufficient FPS
  743. if (asyncLoadTimer.GetMSec(false) >= ASYNC_LOAD_MAX_MSEC)
  744. break;
  745. }
  746. using namespace AsyncLoadProgress;
  747. VariantMap eventData;
  748. eventData[P_SCENE] = (void*)this;
  749. eventData[P_PROGRESS] = (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  750. eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
  751. eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
  752. SendEvent(E_ASYNCLOADPROGRESS, eventData);
  753. }
  754. void Scene::FinishAsyncLoading()
  755. {
  756. resolver_.Resolve();
  757. ApplyAttributes();
  758. FinishLoading(asyncProgress_.file_);
  759. StopAsyncLoading();
  760. using namespace AsyncLoadFinished;
  761. VariantMap eventData;
  762. eventData[P_SCENE] = (void*)this;
  763. SendEvent(E_ASYNCLOADFINISHED, eventData);
  764. }
  765. void Scene::FinishLoading(Deserializer* source)
  766. {
  767. if (source)
  768. {
  769. fileName_ = source->GetName();
  770. checksum_ = source->GetChecksum();
  771. }
  772. }
  773. void Scene::FinishSaving(Serializer* dest) const
  774. {
  775. Deserializer* ptr = dynamic_cast<Deserializer*>(dest);
  776. if (ptr)
  777. {
  778. fileName_ = ptr->GetName();
  779. checksum_ = ptr->GetChecksum();
  780. }
  781. }
  782. void RegisterSceneLibrary(Context* context)
  783. {
  784. Node::RegisterObject(context);
  785. Scene::RegisterObject(context);
  786. SmoothedTransform::RegisterObject(context);
  787. }
  788. }