Scene.cpp 25 KB

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