Scene.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  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()
  315. {
  316. StopAsyncLoading();
  317. RemoveAllChildren();
  318. RemoveAllComponents();
  319. UnregisterAllVars();
  320. SetName(String::EMPTY);
  321. fileName_.Clear();
  322. checksum_ = 0;
  323. replicatedNodeID_ = FIRST_REPLICATED_ID;
  324. replicatedComponentID_ = FIRST_REPLICATED_ID;
  325. localNodeID_ = FIRST_LOCAL_ID;
  326. localComponentID_ = FIRST_LOCAL_ID;
  327. }
  328. void Scene::SetUpdateEnabled(bool enable)
  329. {
  330. updateEnabled_ = enable;
  331. }
  332. void Scene::SetTimeScale(float scale)
  333. {
  334. timeScale_ = Max(scale, M_EPSILON);
  335. Node::MarkNetworkUpdate();
  336. }
  337. void Scene::SetSmoothingConstant(float constant)
  338. {
  339. smoothingConstant_ = Max(constant, M_EPSILON);
  340. Node::MarkNetworkUpdate();
  341. }
  342. void Scene::SetSnapThreshold(float threshold)
  343. {
  344. snapThreshold_ = Max(threshold, 0.0f);
  345. Node::MarkNetworkUpdate();
  346. }
  347. void Scene::SetElapsedTime(float time)
  348. {
  349. elapsedTime_ = time;
  350. }
  351. void Scene::AddRequiredPackageFile(PackageFile* package)
  352. {
  353. // Do not add packages that failed to load
  354. if (!package || !package->GetNumFiles())
  355. return;
  356. requiredPackageFiles_.Push(SharedPtr<PackageFile>(package));
  357. }
  358. void Scene::ClearRequiredPackageFiles()
  359. {
  360. requiredPackageFiles_.Clear();
  361. }
  362. void Scene::RegisterVar(const String& name)
  363. {
  364. varNames_[name] = name;
  365. }
  366. void Scene::UnregisterVar(const String& name)
  367. {
  368. varNames_.Erase(name);
  369. }
  370. void Scene::UnregisterAllVars()
  371. {
  372. varNames_.Clear();
  373. }
  374. Node* Scene::GetNode(unsigned id) const
  375. {
  376. if (id < FIRST_LOCAL_ID)
  377. {
  378. HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Find(id);
  379. if (i != replicatedNodes_.End())
  380. return i->second_;
  381. else
  382. return 0;
  383. }
  384. else
  385. {
  386. HashMap<unsigned, Node*>::ConstIterator i = localNodes_.Find(id);
  387. if (i != localNodes_.End())
  388. return i->second_;
  389. else
  390. return 0;
  391. }
  392. }
  393. Component* Scene::GetComponent(unsigned id) const
  394. {
  395. if (id < FIRST_LOCAL_ID)
  396. {
  397. HashMap<unsigned, Component*>::ConstIterator i = replicatedComponents_.Find(id);
  398. if (i != replicatedComponents_.End())
  399. return i->second_;
  400. else
  401. return 0;
  402. }
  403. else
  404. {
  405. HashMap<unsigned, Component*>::ConstIterator i = localComponents_.Find(id);
  406. if (i != localComponents_.End())
  407. return i->second_;
  408. else
  409. return 0;
  410. }
  411. }
  412. float Scene::GetAsyncProgress() const
  413. {
  414. if (!asyncLoading_ || !asyncProgress_.totalNodes_)
  415. return 1.0f;
  416. else
  417. return (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  418. }
  419. const String& Scene::GetVarName(ShortStringHash hash) const
  420. {
  421. HashMap<ShortStringHash, String>::ConstIterator i = varNames_.Find(hash);
  422. return i != varNames_.End() ? i->second_ : String::EMPTY;
  423. }
  424. void Scene::Update(float timeStep)
  425. {
  426. if (asyncLoading_)
  427. {
  428. UpdateAsyncLoading();
  429. return;
  430. }
  431. PROFILE(UpdateScene);
  432. timeStep *= timeScale_;
  433. using namespace SceneUpdate;
  434. VariantMap eventData;
  435. eventData[P_SCENE] = (void*)this;
  436. eventData[P_TIMESTEP] = timeStep;
  437. // Update variable timestep logic
  438. SendEvent(E_SCENEUPDATE, eventData);
  439. // Update scene subsystems. If a physics world is present, it will be updated, triggering fixed timestep logic updates
  440. SendEvent(E_SCENESUBSYSTEMUPDATE, eventData);
  441. // Update transform smoothing
  442. {
  443. PROFILE(UpdateSmoothing);
  444. float constant = 1.0f - Clamp(powf(2.0f, -timeStep * smoothingConstant_), 0.0f, 1.0f);
  445. float squaredSnapThreshold = snapThreshold_ * snapThreshold_;
  446. using namespace UpdateSmoothing;
  447. VariantMap eventData;
  448. eventData[P_CONSTANT] = constant;
  449. eventData[P_SQUAREDSNAPTHRESHOLD] = squaredSnapThreshold;
  450. SendEvent(E_UPDATESMOOTHING, eventData);
  451. }
  452. // Post-update variable timestep logic
  453. SendEvent(E_SCENEPOSTUPDATE, eventData);
  454. // Note: using a float for elapsed time accumulation is inherently inaccurate. The purpose of this value is
  455. // primarily to update material animation effects, as it is available to shaders. It can be reset by calling
  456. // SetElapsedTime()
  457. elapsedTime_ += timeStep;
  458. }
  459. void Scene::BeginThreadedUpdate()
  460. {
  461. // Check the work queue subsystem whether it actually has created worker threads. If not, do not enter threaded mode.
  462. if (GetSubsystem<WorkQueue>()->GetNumThreads())
  463. threadedUpdate_ = true;
  464. }
  465. void Scene::EndThreadedUpdate()
  466. {
  467. if (!threadedUpdate_)
  468. return;
  469. threadedUpdate_ = false;
  470. if (!delayedDirtyComponents_.Empty())
  471. {
  472. PROFILE(EndThreadedUpdate);
  473. for (PODVector<Component*>::ConstIterator i = delayedDirtyComponents_.Begin(); i != delayedDirtyComponents_.End(); ++i)
  474. (*i)->OnMarkedDirty((*i)->GetNode());
  475. delayedDirtyComponents_.Clear();
  476. }
  477. }
  478. void Scene::DelayedMarkedDirty(Component* component)
  479. {
  480. MutexLock lock(sceneMutex_);
  481. delayedDirtyComponents_.Push(component);
  482. }
  483. unsigned Scene::GetFreeNodeID(CreateMode mode)
  484. {
  485. if (mode == REPLICATED)
  486. {
  487. for (;;)
  488. {
  489. unsigned ret = replicatedNodeID_;
  490. if (replicatedNodeID_ < LAST_REPLICATED_ID)
  491. ++replicatedNodeID_;
  492. else
  493. replicatedNodeID_ = FIRST_REPLICATED_ID;
  494. if (!replicatedNodes_.Contains(ret))
  495. return ret;
  496. }
  497. }
  498. else
  499. {
  500. for (;;)
  501. {
  502. unsigned ret = localNodeID_;
  503. if (localNodeID_ < LAST_LOCAL_ID)
  504. ++localNodeID_;
  505. else
  506. localNodeID_ = FIRST_LOCAL_ID;
  507. if (!localNodes_.Contains(ret))
  508. return ret;
  509. }
  510. }
  511. }
  512. unsigned Scene::GetFreeComponentID(CreateMode mode)
  513. {
  514. if (mode == REPLICATED)
  515. {
  516. for (;;)
  517. {
  518. unsigned ret = replicatedComponentID_;
  519. if (replicatedComponentID_ < LAST_REPLICATED_ID)
  520. ++replicatedComponentID_;
  521. else
  522. replicatedComponentID_ = FIRST_REPLICATED_ID;
  523. if (!replicatedComponents_.Contains(ret))
  524. return ret;
  525. }
  526. }
  527. else
  528. {
  529. for (;;)
  530. {
  531. unsigned ret = localComponentID_;
  532. if (localComponentID_ < LAST_LOCAL_ID)
  533. ++localComponentID_;
  534. else
  535. localComponentID_ = FIRST_LOCAL_ID;
  536. if (!localComponents_.Contains(ret))
  537. return ret;
  538. }
  539. }
  540. }
  541. void Scene::NodeAdded(Node* node)
  542. {
  543. if (!node || node->GetScene() == this)
  544. return;
  545. // If node already exists in another scene, remove. This is unsupported, as components will not reinitialize themselves
  546. // to use the new scene
  547. Scene* oldScene = node->GetScene();
  548. if (oldScene)
  549. {
  550. LOGERROR("Moving a node from one scene to another is unsupported");
  551. oldScene->NodeRemoved(node);
  552. }
  553. node->SetScene(this);
  554. // If we already have an existing node with the same ID, must remove the scene reference from it
  555. unsigned id = node->GetID();
  556. if (id < FIRST_LOCAL_ID)
  557. {
  558. HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Find(id);
  559. if (i != replicatedNodes_.End() && i->second_ != node)
  560. {
  561. LOGWARNING("Overwriting node with ID " + String(id));
  562. i->second_->ResetScene();
  563. }
  564. replicatedNodes_[id] = node;
  565. MarkNetworkUpdate(node);
  566. MarkReplicationDirty(node);
  567. }
  568. else
  569. {
  570. HashMap<unsigned, Node*>::Iterator i = localNodes_.Find(id);
  571. if (i != localNodes_.End() && i->second_ != node)
  572. {
  573. LOGWARNING("Overwriting node with ID " + String(id));
  574. i->second_->ResetScene();
  575. }
  576. localNodes_[id] = node;
  577. }
  578. }
  579. void Scene::NodeRemoved(Node* node)
  580. {
  581. if (!node || node->GetScene() != this)
  582. return;
  583. unsigned id = node->GetID();
  584. if (id < FIRST_LOCAL_ID)
  585. {
  586. replicatedNodes_.Erase(id);
  587. MarkReplicationDirty(node);
  588. }
  589. else
  590. localNodes_.Erase(id);
  591. node->SetID(0);
  592. node->SetScene(0);
  593. }
  594. void Scene::ComponentAdded(Component* component)
  595. {
  596. if (!component)
  597. return;
  598. unsigned id = component->GetID();
  599. if (id < FIRST_LOCAL_ID)
  600. {
  601. HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Find(id);
  602. if (i != replicatedComponents_.End() && i->second_ != component)
  603. {
  604. LOGWARNING("Overwriting component with ID " + String(id));
  605. i->second_->SetID(0);
  606. }
  607. replicatedComponents_[id] = component;
  608. }
  609. else
  610. {
  611. HashMap<unsigned, Component*>::Iterator i = localComponents_.Find(id);
  612. if (i != localComponents_.End() && i->second_ != component)
  613. {
  614. LOGWARNING("Overwriting component with ID " + String(id));
  615. i->second_->SetID(0);
  616. }
  617. localComponents_[id] = component;
  618. }
  619. }
  620. void Scene::ComponentRemoved(Component* component)
  621. {
  622. if (!component)
  623. return;
  624. unsigned id = component->GetID();
  625. if (id < FIRST_LOCAL_ID)
  626. replicatedComponents_.Erase(id);
  627. else
  628. localComponents_.Erase(id);
  629. component->SetID(0);
  630. }
  631. void Scene::SetVarNamesAttr(String value)
  632. {
  633. Vector<String> varNames = value.Split(';');
  634. varNames_.Clear();
  635. for (Vector<String>::ConstIterator i = varNames.Begin(); i != varNames.End(); ++i)
  636. varNames_[*i] = *i;
  637. }
  638. String Scene::GetVarNamesAttr() const
  639. {
  640. String ret;
  641. if (!varNames_.Empty())
  642. {
  643. for (HashMap<ShortStringHash, String>::ConstIterator i = varNames_.Begin(); i != varNames_.End(); ++i)
  644. ret += i->second_ + ';';
  645. ret.Resize(ret.Length() - 1);
  646. }
  647. return ret;
  648. }
  649. void Scene::PrepareNetworkUpdate()
  650. {
  651. for (HashSet<unsigned>::Iterator i = networkUpdateNodes_.Begin(); i != networkUpdateNodes_.End(); ++i)
  652. {
  653. Node* node = GetNode(*i);
  654. if (node)
  655. node->PrepareNetworkUpdate();
  656. }
  657. for (HashSet<unsigned>::Iterator i = networkUpdateComponents_.Begin(); i != networkUpdateComponents_.End(); ++i)
  658. {
  659. Component* component = GetComponent(*i);
  660. if (component)
  661. component->PrepareNetworkUpdate();
  662. }
  663. networkUpdateNodes_.Clear();
  664. networkUpdateComponents_.Clear();
  665. }
  666. void Scene::CleanupConnection(Connection* connection)
  667. {
  668. Node::CleanupConnection(connection);
  669. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  670. i->second_->CleanupConnection(connection);
  671. for (HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Begin(); i != replicatedComponents_.End(); ++i)
  672. i->second_->CleanupConnection(connection);
  673. }
  674. void Scene::MarkNetworkUpdate(Node* node)
  675. {
  676. if (node)
  677. networkUpdateNodes_.Insert(node->GetID());
  678. }
  679. void Scene::MarkNetworkUpdate(Component* component)
  680. {
  681. if (component)
  682. networkUpdateComponents_.Insert(component->GetID());
  683. }
  684. void Scene::MarkReplicationDirty(Node* node)
  685. {
  686. unsigned id = node->GetID();
  687. if (id < FIRST_LOCAL_ID && networkState_)
  688. {
  689. for (PODVector<ReplicationState*>::Iterator i = networkState_->replicationStates_.Begin(); i !=
  690. networkState_->replicationStates_.End(); ++i)
  691. {
  692. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*i);
  693. nodeState->sceneState_->dirtyNodes_.Insert(id);
  694. }
  695. }
  696. }
  697. void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  698. {
  699. using namespace Update;
  700. if (updateEnabled_)
  701. Update(eventData[P_TIMESTEP].GetFloat());
  702. }
  703. void Scene::UpdateAsyncLoading()
  704. {
  705. PROFILE(UpdateAsyncLoading);
  706. Timer asyncLoadTimer;
  707. for (;;)
  708. {
  709. if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
  710. {
  711. FinishAsyncLoading();
  712. return;
  713. }
  714. // Read one child node with its full sub-hierarchy either from binary or XML
  715. if (!asyncProgress_.xmlFile_)
  716. {
  717. unsigned nodeID = asyncProgress_.file_->ReadUInt();
  718. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  719. resolver_.AddNode(nodeID, newNode);
  720. newNode->Load(*asyncProgress_.file_, resolver_);
  721. }
  722. else
  723. {
  724. unsigned nodeID = asyncProgress_.xmlElement_.GetInt("id");
  725. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  726. resolver_.AddNode(nodeID, newNode);
  727. newNode->LoadXML(asyncProgress_.xmlElement_, resolver_);
  728. asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNext("node");
  729. }
  730. ++asyncProgress_.loadedNodes_;
  731. // Break if time limit exceeded, so that we keep sufficient FPS
  732. if (asyncLoadTimer.GetMSec(false) >= ASYNC_LOAD_MAX_MSEC)
  733. break;
  734. }
  735. using namespace AsyncLoadProgress;
  736. VariantMap eventData;
  737. eventData[P_SCENE] = (void*)this;
  738. eventData[P_PROGRESS] = (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  739. eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
  740. eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
  741. SendEvent(E_ASYNCLOADPROGRESS, eventData);
  742. }
  743. void Scene::FinishAsyncLoading()
  744. {
  745. resolver_.Resolve();
  746. ApplyAttributes();
  747. FinishLoading(asyncProgress_.file_);
  748. StopAsyncLoading();
  749. using namespace AsyncLoadFinished;
  750. VariantMap eventData;
  751. eventData[P_SCENE] = (void*)this;
  752. SendEvent(E_ASYNCLOADFINISHED, eventData);
  753. }
  754. void Scene::FinishLoading(Deserializer* source)
  755. {
  756. if (source)
  757. {
  758. fileName_ = source->GetName();
  759. checksum_ = source->GetChecksum();
  760. }
  761. }
  762. void Scene::FinishSaving(Serializer* dest) const
  763. {
  764. Deserializer* ptr = dynamic_cast<Deserializer*>(dest);
  765. if (ptr)
  766. {
  767. fileName_ = ptr->GetName();
  768. checksum_ = ptr->GetChecksum();
  769. }
  770. }
  771. void RegisterSceneLibrary(Context* context)
  772. {
  773. Node::RegisterObject(context);
  774. Scene::RegisterObject(context);
  775. SmoothedTransform::RegisterObject(context);
  776. }
  777. }