Scene.cpp 26 KB

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