Scene.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Component.h"
  25. #include "Context.h"
  26. #include "CoreEvents.h"
  27. #include "File.h"
  28. #include "Log.h"
  29. #include "PackageFile.h"
  30. #include "Profiler.h"
  31. #include "ReplicationState.h"
  32. #include "Scene.h"
  33. #include "SceneEvents.h"
  34. #include "SmoothedTransform.h"
  35. #include "WorkQueue.h"
  36. #include "XMLFile.h"
  37. static const int ASYNC_LOAD_MIN_FPS = 30;
  38. static const int ASYNC_LOAD_MAX_MSEC = (int)(1000.0f / ASYNC_LOAD_MIN_FPS);
  39. static const float DEFAULT_SMOOTHING_CONSTANT = 50.0f;
  40. static const float DEFAULT_SNAP_THRESHOLD = 1.0f;
  41. static const String emptyVarName;
  42. OBJECTTYPESTATIC(Scene);
  43. Scene::Scene(Context* context) :
  44. Node(context),
  45. replicatedNodeID_(FIRST_REPLICATED_ID),
  46. replicatedComponentID_(FIRST_REPLICATED_ID),
  47. localNodeID_(FIRST_LOCAL_ID),
  48. localComponentID_(FIRST_LOCAL_ID),
  49. smoothingConstant_(DEFAULT_SMOOTHING_CONSTANT),
  50. snapThreshold_(DEFAULT_SNAP_THRESHOLD),
  51. checksum_(0),
  52. active_(true),
  53. asyncLoading_(false),
  54. threadedUpdate_(false)
  55. {
  56. // Assign an ID to self so that nodes can refer to this node as a parent
  57. SetID(GetFreeNodeID(REPLICATED));
  58. NodeAdded(this);
  59. SubscribeToEvent(E_UPDATE, HANDLER(Scene, HandleUpdate));
  60. }
  61. Scene::~Scene()
  62. {
  63. // Remove scene reference and owner from all nodes that still exist
  64. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  65. {
  66. i->second_->SetScene(0);
  67. i->second_->SetOwner(0);
  68. }
  69. for (HashMap<unsigned, Node*>::Iterator i = localNodes_.Begin(); i != localNodes_.End(); ++i)
  70. {
  71. i->second_->SetScene(0);
  72. i->second_->SetOwner(0);
  73. }
  74. }
  75. void Scene::RegisterObject(Context* context)
  76. {
  77. context->RegisterFactory<Scene>();
  78. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_STRING, "Name", GetName, SetName, String, String(), AM_DEFAULT);
  79. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_VECTOR3, "Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_DEFAULT | AM_LATESTDATA);
  80. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_QUATERNION, "Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  81. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_VECTOR3, "Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  82. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Smoothing Constant", GetSmoothingConstant, SetSmoothingConstant, float, DEFAULT_SMOOTHING_CONSTANT, AM_DEFAULT);
  83. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Snap Threshold", GetSnapThreshold, SetSnapThreshold, float, DEFAULT_SNAP_THRESHOLD, AM_DEFAULT);
  84. ATTRIBUTE(Scene, VAR_INT, "Next Replicated Node ID", replicatedNodeID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  85. ATTRIBUTE(Scene, VAR_INT, "Next Replicated Component ID", replicatedComponentID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  86. ATTRIBUTE(Scene, VAR_INT, "Next Local Node ID", localNodeID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  87. ATTRIBUTE(Scene, VAR_INT, "Next Local Component ID", localComponentID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  88. ATTRIBUTE(Scene, VAR_VARIANTMAP, "Variables", vars_, VariantMap(), AM_FILE); // Network replication of vars uses custom data
  89. ACCESSOR_ATTRIBUTE(Scene, VAR_STRING, "Variable Names", GetVarNamesAttr, SetVarNamesAttr, String, String(), AM_FILE | AM_NOEDIT);
  90. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_NET | AM_LATESTDATA | AM_NOEDIT);
  91. }
  92. bool Scene::Load(Deserializer& source)
  93. {
  94. PROFILE(LoadScene);
  95. StopAsyncLoading();
  96. // Check ID
  97. if (source.ReadFileID() != "USCN")
  98. {
  99. LOGERROR(source.GetName() + " is not a valid scene file");
  100. return false;
  101. }
  102. LOGINFO("Loading scene from " + source.GetName());
  103. // Load the whole scene, then perform post-load if successfully loaded
  104. if (Node::Load(source))
  105. {
  106. FinishLoading(&source);
  107. return true;
  108. }
  109. else
  110. return false;
  111. }
  112. bool Scene::Save(Serializer& dest)
  113. {
  114. PROFILE(SaveScene);
  115. // Write ID first
  116. if (!dest.WriteFileID("USCN"))
  117. {
  118. LOGERROR("Could not save scene, writing to stream failed");
  119. return false;
  120. }
  121. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  122. if (ptr)
  123. LOGINFO("Saving scene to " + ptr->GetName());
  124. return Node::Save(dest);
  125. }
  126. bool Scene::LoadXML(const XMLElement& source)
  127. {
  128. PROFILE(LoadSceneXML);
  129. StopAsyncLoading();
  130. // Load the whole scene, then perform post-load if successfully loaded
  131. // Note: the scene filename and checksum can not be set, as we only used an XML element
  132. if (Node::LoadXML(source))
  133. {
  134. FinishLoading(0);
  135. return true;
  136. }
  137. else
  138. return false;
  139. }
  140. void Scene::AddReplicationState(NodeReplicationState* state)
  141. {
  142. Node::AddReplicationState(state);
  143. // This is the first update for a new connection. Mark all replicated nodes dirty
  144. for (HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  145. state->sceneState_->dirtyNodes_.Insert(i->first_);
  146. }
  147. bool Scene::LoadXML(Deserializer& source)
  148. {
  149. PROFILE(LoadSceneXML);
  150. StopAsyncLoading();
  151. SharedPtr<XMLFile> xml(new XMLFile(context_));
  152. if (!xml->Load(source))
  153. return false;
  154. LOGINFO("Loading scene from " + source.GetName());
  155. if (Node::LoadXML(xml->GetRoot()))
  156. {
  157. FinishLoading(&source);
  158. return true;
  159. }
  160. else
  161. return false;
  162. }
  163. bool Scene::SaveXML(Serializer& dest)
  164. {
  165. PROFILE(SaveSceneXML);
  166. SharedPtr<XMLFile> xml(new XMLFile(context_));
  167. XMLElement rootElem = xml->CreateRoot("scene");
  168. if (!SaveXML(rootElem))
  169. return false;
  170. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  171. if (ptr)
  172. LOGINFO("Saving scene to " + ptr->GetName());
  173. return xml->Save(dest);
  174. }
  175. bool Scene::LoadAsync(File* file)
  176. {
  177. if (!file)
  178. {
  179. LOGERROR("Null file for async loading");
  180. return false;
  181. }
  182. StopAsyncLoading();
  183. // Check ID
  184. if (file->ReadFileID() != "USCN")
  185. {
  186. LOGERROR(file->GetName() + " is not a valid scene file");
  187. return false;
  188. }
  189. LOGINFO("Loading scene from " + file->GetName());
  190. Clear();
  191. // Store own old ID for resolving possible root node references
  192. unsigned nodeID = file->ReadUInt();
  193. resolver_.AddNode(nodeID, this);
  194. // Load root level components first
  195. if (!Node::Load(*file, resolver_, false))
  196. return false;
  197. // Then prepare for loading all root level child nodes in the async update
  198. asyncLoading_ = true;
  199. asyncProgress_.file_ = file;
  200. asyncProgress_.xmlFile_.Reset();
  201. asyncProgress_.xmlElement_ = XMLElement();
  202. asyncProgress_.loadedNodes_ = 0;
  203. asyncProgress_.totalNodes_ = file->ReadVLE();
  204. return true;
  205. }
  206. bool Scene::LoadAsyncXML(File* file)
  207. {
  208. if (!file)
  209. {
  210. LOGERROR("Null file for async loading");
  211. return false;
  212. }
  213. StopAsyncLoading();
  214. SharedPtr<XMLFile> xml(new XMLFile(context_));
  215. if (!xml->Load(*file))
  216. return false;
  217. LOGINFO("Loading scene from " + file->GetName());
  218. Clear();
  219. XMLElement rootElement = xml->GetRoot();
  220. // Store own old ID for resolving possible root node references
  221. unsigned nodeID = rootElement.GetInt("id");
  222. resolver_.AddNode(nodeID, this);
  223. // Load the root level components first
  224. if (!Node::LoadXML(rootElement, resolver_, false))
  225. return false;
  226. // Then prepare for loading all root level child nodes in the async update
  227. XMLElement childNodeElement = rootElement.GetChild("node");
  228. asyncLoading_ = true;
  229. asyncProgress_.file_ = file;
  230. asyncProgress_.xmlFile_ = xml;
  231. asyncProgress_.xmlElement_ = childNodeElement;
  232. asyncProgress_.loadedNodes_ = 0;
  233. asyncProgress_.totalNodes_ = 0;
  234. // Count the amount of child nodes
  235. while (childNodeElement)
  236. {
  237. ++asyncProgress_.totalNodes_;
  238. childNodeElement = childNodeElement.GetNext("node");
  239. }
  240. return true;
  241. }
  242. void Scene::StopAsyncLoading()
  243. {
  244. asyncLoading_ = false;
  245. asyncProgress_.file_.Reset();
  246. asyncProgress_.xmlFile_.Reset();
  247. asyncProgress_.xmlElement_ = XMLElement();
  248. resolver_.Reset();
  249. }
  250. Node* Scene::Instantiate(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  251. {
  252. PROFILE(Instantiate);
  253. SceneResolver resolver;
  254. unsigned nodeID = source.ReadInt();
  255. // Rewrite IDs when instantiating
  256. Node* node = CreateChild(0, mode);
  257. resolver.AddNode(nodeID, node);
  258. if (node->Load(source, resolver, true, true, mode))
  259. {
  260. resolver.Resolve();
  261. node->ApplyAttributes();
  262. node->SetTransform(position, rotation);
  263. return node;
  264. }
  265. else
  266. {
  267. node->Remove();
  268. return 0;
  269. }
  270. }
  271. Node* Scene::InstantiateXML(const XMLElement& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  272. {
  273. PROFILE(InstantiateXML);
  274. SceneResolver resolver;
  275. unsigned nodeID = source.GetInt("id");
  276. // Rewrite IDs when instantiating
  277. Node* node = CreateChild(0, mode);
  278. resolver.AddNode(nodeID, node);
  279. if (node->LoadXML(source, resolver, true, true, mode))
  280. {
  281. resolver.Resolve();
  282. node->ApplyAttributes();
  283. node->SetTransform(position, rotation);
  284. return node;
  285. }
  286. else
  287. {
  288. node->Remove();
  289. return 0;
  290. }
  291. }
  292. Node* Scene::InstantiateXML(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  293. {
  294. SharedPtr<XMLFile> xml(new XMLFile(context_));
  295. if (!xml->Load(source))
  296. return false;
  297. return InstantiateXML(xml->GetRoot(), position, rotation, mode);
  298. }
  299. void Scene::Clear()
  300. {
  301. StopAsyncLoading();
  302. RemoveAllChildren();
  303. RemoveAllComponents();
  304. fileName_ = String();
  305. checksum_ = 0;
  306. }
  307. void Scene::SetActive(bool enable)
  308. {
  309. active_ = enable;
  310. }
  311. void Scene::SetSmoothingConstant(float constant)
  312. {
  313. smoothingConstant_ = Max(constant, M_EPSILON);
  314. }
  315. void Scene::SetSnapThreshold(float threshold)
  316. {
  317. snapThreshold_ = Max(threshold, 0.0f);
  318. }
  319. void Scene::AddRequiredPackageFile(PackageFile* package)
  320. {
  321. // Do not add packages that failed to load
  322. if (!package || !package->GetNumFiles())
  323. return;
  324. requiredPackageFiles_.Push(SharedPtr<PackageFile>(package));
  325. }
  326. void Scene::ClearRequiredPackageFiles()
  327. {
  328. requiredPackageFiles_.Clear();
  329. }
  330. void Scene::RegisterVar(const String& name)
  331. {
  332. varNames_[ShortStringHash(name)] = name;
  333. }
  334. void Scene::UnregisterVar(const String& name)
  335. {
  336. varNames_.Erase(ShortStringHash(name));
  337. }
  338. void Scene::UnregisterAllVars()
  339. {
  340. varNames_.Clear();
  341. }
  342. Node* Scene::GetNode(unsigned id) const
  343. {
  344. if (id < FIRST_LOCAL_ID)
  345. {
  346. HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Find(id);
  347. if (i != replicatedNodes_.End())
  348. return i->second_;
  349. else
  350. return 0;
  351. }
  352. else
  353. {
  354. HashMap<unsigned, Node*>::ConstIterator i = localNodes_.Find(id);
  355. if (i != localNodes_.End())
  356. return i->second_;
  357. else
  358. return 0;
  359. }
  360. }
  361. Component* Scene::GetComponent(unsigned id) const
  362. {
  363. if (id < FIRST_LOCAL_ID)
  364. {
  365. HashMap<unsigned, Component*>::ConstIterator i = replicatedComponents_.Find(id);
  366. if (i != replicatedComponents_.End())
  367. return i->second_;
  368. else
  369. return 0;
  370. }
  371. else
  372. {
  373. HashMap<unsigned, Component*>::ConstIterator i = localComponents_.Find(id);
  374. if (i != localComponents_.End())
  375. return i->second_;
  376. else
  377. return 0;
  378. }
  379. }
  380. float Scene::GetAsyncProgress() const
  381. {
  382. if (!asyncLoading_ || !asyncProgress_.totalNodes_)
  383. return 1.0f;
  384. else
  385. return (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  386. }
  387. const String& Scene::GetVarName(ShortStringHash hash) const
  388. {
  389. HashMap<ShortStringHash, String>::ConstIterator i = varNames_.Find(hash);
  390. return i != varNames_.End() ? i->second_ : emptyVarName;
  391. }
  392. void Scene::Update(float timeStep)
  393. {
  394. if (asyncLoading_)
  395. {
  396. UpdateAsyncLoading();
  397. return;
  398. }
  399. PROFILE(UpdateScene);
  400. using namespace SceneUpdate;
  401. VariantMap eventData;
  402. eventData[P_SCENE] = (void*)this;
  403. eventData[P_TIMESTEP] = timeStep;
  404. // Update variable timestep logic
  405. SendEvent(E_SCENEUPDATE, eventData);
  406. // Update scene subsystems. If a physics world is present, it will be updated, triggering fixed timestep logic updates
  407. SendEvent(E_SCENESUBSYSTEMUPDATE, eventData);
  408. // Update transform smoothing
  409. {
  410. PROFILE(UpdateSmoothing);
  411. float constant = 1.0f - Clamp(powf(2.0f, -timeStep * smoothingConstant_), 0.0f, 1.0f);
  412. float squaredSnapThreshold = snapThreshold_ * snapThreshold_;
  413. using namespace UpdateSmoothing;
  414. VariantMap eventData;
  415. eventData[P_CONSTANT] = constant;
  416. eventData[P_SQUAREDSNAPTHRESHOLD] = squaredSnapThreshold;
  417. SendEvent(E_UPDATESMOOTHING, eventData);
  418. }
  419. // Post-update variable timestep logic
  420. SendEvent(E_SCENEPOSTUPDATE, eventData);
  421. }
  422. void Scene::BeginThreadedUpdate()
  423. {
  424. // Check the work queue subsystem whether it actually has created worker threads. If not, do not enter threaded mode.
  425. if (GetSubsystem<WorkQueue>()->GetNumThreads())
  426. threadedUpdate_ = true;
  427. }
  428. void Scene::EndThreadedUpdate()
  429. {
  430. if (!threadedUpdate_)
  431. return;
  432. threadedUpdate_ = false;
  433. if (!delayedDirtyComponents_.Empty())
  434. {
  435. PROFILE(EndThreadedUpdate);
  436. for (PODVector<Component*>::ConstIterator i = delayedDirtyComponents_.Begin(); i != delayedDirtyComponents_.End(); ++i)
  437. (*i)->OnMarkedDirty((*i)->GetNode());
  438. delayedDirtyComponents_.Clear();
  439. }
  440. }
  441. void Scene::DelayedMarkedDirty(Component* component)
  442. {
  443. MutexLock lock(sceneMutex_);
  444. delayedDirtyComponents_.Push(component);
  445. }
  446. unsigned Scene::GetFreeNodeID(CreateMode mode)
  447. {
  448. if (mode == REPLICATED)
  449. {
  450. for (;;)
  451. {
  452. if (!replicatedNodes_.Contains(replicatedNodeID_))
  453. return replicatedNodeID_;
  454. if (replicatedNodeID_ != LAST_REPLICATED_ID)
  455. ++replicatedNodeID_;
  456. else
  457. replicatedNodeID_ = FIRST_REPLICATED_ID;
  458. }
  459. }
  460. else
  461. {
  462. for (;;)
  463. {
  464. if (!localNodes_.Contains(localNodeID_))
  465. return localNodeID_;
  466. if (localNodeID_ != LAST_LOCAL_ID)
  467. ++localNodeID_;
  468. else
  469. localNodeID_ = FIRST_LOCAL_ID;
  470. }
  471. }
  472. }
  473. unsigned Scene::GetFreeComponentID(CreateMode mode)
  474. {
  475. if (mode == REPLICATED)
  476. {
  477. for (;;)
  478. {
  479. if (!replicatedComponents_.Contains(replicatedComponentID_))
  480. return replicatedComponentID_;
  481. if (replicatedComponentID_ != LAST_REPLICATED_ID)
  482. ++replicatedComponentID_;
  483. else
  484. replicatedComponentID_ = FIRST_REPLICATED_ID;
  485. }
  486. }
  487. else
  488. {
  489. for (;;)
  490. {
  491. if (!localComponents_.Contains(localComponentID_))
  492. return localComponentID_;
  493. if (localComponentID_ != LAST_LOCAL_ID)
  494. ++localComponentID_;
  495. else
  496. localComponentID_ = FIRST_LOCAL_ID;
  497. }
  498. }
  499. }
  500. void Scene::NodeAdded(Node* node)
  501. {
  502. if (!node || node->GetScene())
  503. return;
  504. node->SetScene(this);
  505. // If we already have an existing node with the same ID, must remove the scene reference from it
  506. unsigned id = node->GetID();
  507. if (id < FIRST_LOCAL_ID)
  508. {
  509. HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Find(id);
  510. if (i != replicatedNodes_.End() && i->second_ != node)
  511. {
  512. LOGWARNING("Overwriting node with ID " + String(id));
  513. i->second_->SetScene(0);
  514. i->second_->SetOwner(0);
  515. }
  516. replicatedNodes_[id] = node;
  517. MarkNetworkUpdate(node);
  518. MarkReplicationDirty(node);
  519. }
  520. else
  521. {
  522. HashMap<unsigned, Node*>::Iterator i = localNodes_.Find(id);
  523. if (i != localNodes_.End() && i->second_ != node)
  524. {
  525. LOGWARNING("Overwriting node with ID " + String(id));
  526. i->second_->SetScene(0);
  527. i->second_->SetOwner(0);
  528. }
  529. localNodes_[id] = node;
  530. }
  531. }
  532. void Scene::NodeRemoved(Node* node)
  533. {
  534. if (!node || node->GetScene() != this)
  535. return;
  536. unsigned id = node->GetID();
  537. if (id < FIRST_LOCAL_ID)
  538. {
  539. replicatedNodes_.Erase(id);
  540. MarkReplicationDirty(node);
  541. }
  542. else
  543. localNodes_.Erase(id);
  544. node->SetID(0);
  545. node->SetScene(0);
  546. }
  547. void Scene::ComponentAdded(Component* component)
  548. {
  549. if (!component)
  550. return;
  551. unsigned id = component->GetID();
  552. if (id < FIRST_LOCAL_ID)
  553. {
  554. HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Find(id);
  555. if (i != replicatedComponents_.End() && i->second_ != component)
  556. LOGWARNING("Overwriting component with ID " + String(id));
  557. replicatedComponents_[id] = component;
  558. }
  559. else
  560. {
  561. HashMap<unsigned, Component*>::Iterator i = localComponents_.Find(id);
  562. if (i != localComponents_.End() && i->second_ != component)
  563. LOGWARNING("Overwriting component with ID " + String(id));
  564. localComponents_[id] = component;
  565. }
  566. }
  567. void Scene::ComponentRemoved(Component* component)
  568. {
  569. if (!component)
  570. return;
  571. unsigned id = component->GetID();
  572. if (id < FIRST_LOCAL_ID)
  573. replicatedComponents_.Erase(id);
  574. else
  575. localComponents_.Erase(id);
  576. component->SetID(0);
  577. }
  578. void Scene::SetVarNamesAttr(String value)
  579. {
  580. Vector<String> varNames = value.Split(';');
  581. varNames_.Clear();
  582. for (Vector<String>::ConstIterator i = varNames.Begin(); i != varNames.End(); ++i)
  583. varNames_[ShortStringHash(*i)] = *i;
  584. }
  585. String Scene::GetVarNamesAttr() const
  586. {
  587. String ret;
  588. for (HashMap<ShortStringHash, String>::ConstIterator i = varNames_.Begin(); i != varNames_.End(); ++i)
  589. {
  590. if (i != varNames_.Begin())
  591. ret += ';';
  592. ret += i->second_;
  593. }
  594. return ret;
  595. }
  596. void Scene::PrepareNetworkUpdate()
  597. {
  598. for (HashSet<unsigned>::Iterator i = networkUpdateNodes_.Begin(); i != networkUpdateNodes_.End(); ++i)
  599. {
  600. Node* node = GetNode(*i);
  601. if (node)
  602. node->PrepareNetworkUpdate();
  603. }
  604. for (HashSet<unsigned>::Iterator i = networkUpdateComponents_.Begin(); i != networkUpdateComponents_.End(); ++i)
  605. {
  606. Component* component = GetComponent(*i);
  607. if (component)
  608. component->PrepareNetworkUpdate();
  609. }
  610. networkUpdateNodes_.Clear();
  611. networkUpdateComponents_.Clear();
  612. }
  613. void Scene::CleanupConnection(Connection* connection)
  614. {
  615. Node::CleanupConnection(connection);
  616. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  617. i->second_->CleanupConnection(connection);
  618. for (HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Begin(); i != replicatedComponents_.End(); ++i)
  619. i->second_->CleanupConnection(connection);
  620. }
  621. void Scene::MarkNetworkUpdate(Node* node)
  622. {
  623. if (node)
  624. networkUpdateNodes_.Insert(node->GetID());
  625. }
  626. void Scene::MarkNetworkUpdate(Component* component)
  627. {
  628. if (component)
  629. networkUpdateComponents_.Insert(component->GetID());
  630. }
  631. void Scene::MarkReplicationDirty(Node* node)
  632. {
  633. unsigned id = node->GetID();
  634. if (id < FIRST_LOCAL_ID && networkState_)
  635. {
  636. for (PODVector<ReplicationState*>::Iterator i = networkState_->replicationStates_.Begin(); i !=
  637. networkState_->replicationStates_.End(); ++i)
  638. {
  639. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*i);
  640. nodeState->sceneState_->dirtyNodes_.Insert(id);
  641. }
  642. }
  643. }
  644. void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  645. {
  646. using namespace Update;
  647. if (active_)
  648. Update(eventData[P_TIMESTEP].GetFloat());
  649. }
  650. void Scene::UpdateAsyncLoading()
  651. {
  652. PROFILE(UpdateAsyncLoading);
  653. Timer asyncLoadTimer;
  654. for (;;)
  655. {
  656. if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
  657. {
  658. FinishAsyncLoading();
  659. return;
  660. }
  661. // Read one child node with its full sub-hierarchy from either from binary or XML
  662. if (!asyncProgress_.xmlFile_)
  663. {
  664. unsigned nodeID = asyncProgress_.file_->ReadUInt();
  665. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  666. resolver_.AddNode(nodeID, newNode);
  667. newNode->Load(*asyncProgress_.file_, resolver_);
  668. }
  669. else
  670. {
  671. unsigned nodeID = asyncProgress_.xmlElement_.GetInt("id");
  672. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  673. resolver_.AddNode(nodeID, newNode);
  674. newNode->LoadXML(asyncProgress_.xmlElement_, resolver_);
  675. asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNext("node");
  676. }
  677. ++asyncProgress_.loadedNodes_;
  678. // Break if time limit exceeded, so that we keep sufficient FPS
  679. if (asyncLoadTimer.GetMSec(false) >= ASYNC_LOAD_MAX_MSEC)
  680. break;
  681. }
  682. using namespace AsyncLoadProgress;
  683. VariantMap eventData;
  684. eventData[P_SCENE] = (void*)this;
  685. eventData[P_PROGRESS] = (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  686. eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
  687. eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
  688. SendEvent(E_ASYNCLOADPROGRESS, eventData);
  689. }
  690. void Scene::FinishAsyncLoading()
  691. {
  692. resolver_.Resolve();
  693. ApplyAttributes();
  694. FinishLoading(asyncProgress_.file_);
  695. StopAsyncLoading();
  696. using namespace AsyncLoadFinished;
  697. VariantMap eventData;
  698. eventData[P_SCENE] = (void*)this;
  699. SendEvent(E_ASYNCLOADFINISHED, eventData);
  700. }
  701. void Scene::FinishLoading(Deserializer* source)
  702. {
  703. if (source)
  704. {
  705. fileName_ = source->GetName();
  706. checksum_ = source->GetChecksum();
  707. }
  708. }
  709. void RegisterSceneLibrary(Context* context)
  710. {
  711. Node::RegisterObject(context);
  712. Scene::RegisterObject(context);
  713. SmoothedTransform::RegisterObject(context);
  714. }