Scene.cpp 26 KB

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