2
0

Scene.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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 "Scene.h"
  32. #include "SceneEvents.h"
  33. #include "WorkQueue.h"
  34. #include "XMLFile.h"
  35. static const int ASYNC_LOAD_MIN_FPS = 50;
  36. static const int ASYNC_LOAD_MAX_MSEC = (int)(1000.0f / ASYNC_LOAD_MIN_FPS);
  37. static const float DEFAULT_SMOOTHING_CONSTANT = 50.0f;
  38. static const float DEFAULT_SNAP_THRESHOLD = 1.0f;
  39. static const String emptyVarName;
  40. OBJECTTYPESTATIC(Scene);
  41. Scene::Scene(Context* context) :
  42. Node(context),
  43. replicatedNodeID_(FIRST_REPLICATED_ID),
  44. replicatedComponentID_(FIRST_REPLICATED_ID),
  45. localNodeID_(FIRST_LOCAL_ID),
  46. localComponentID_(FIRST_LOCAL_ID),
  47. smoothingConstant_(DEFAULT_SMOOTHING_CONSTANT),
  48. snapThreshold_(DEFAULT_SNAP_THRESHOLD),
  49. checksum_(0),
  50. active_(true),
  51. asyncLoading_(false),
  52. threadedUpdate_(false)
  53. {
  54. // Assign an ID to self so that nodes can refer to this node as a parent
  55. SetID(GetFreeNodeID(REPLICATED));
  56. NodeAdded(this);
  57. SubscribeToEvent(E_UPDATE, HANDLER(Scene, HandleUpdate));
  58. }
  59. Scene::~Scene()
  60. {
  61. // Remove scene reference and owner from all nodes that still exist
  62. for (Map<unsigned, Node*>::Iterator i = allNodes_.Begin(); i != allNodes_.End(); ++i)
  63. {
  64. i->second_->SetScene(0);
  65. i->second_->SetOwner(0);
  66. }
  67. }
  68. void Scene::RegisterObject(Context* context)
  69. {
  70. context->RegisterFactory<Scene>();
  71. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_STRING, "Name", GetName, SetName, String, String(), AM_DEFAULT);
  72. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_VECTOR3, "Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_DEFAULT | AM_LATESTDATA);
  73. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_QUATERNION, "Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  74. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_VECTOR3, "Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  75. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Smoothing Constant", GetSmoothingConstant, SetSmoothingConstant, float, DEFAULT_SMOOTHING_CONSTANT, AM_DEFAULT);
  76. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Snap Threshold", GetSnapThreshold, SetSnapThreshold, float, DEFAULT_SNAP_THRESHOLD, AM_DEFAULT);
  77. ATTRIBUTE(Scene, VAR_INT, "Next Replicated Node ID", replicatedNodeID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  78. ATTRIBUTE(Scene, VAR_INT, "Next Replicated Component ID", replicatedComponentID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  79. ATTRIBUTE(Scene, VAR_INT, "Next Local Node ID", localNodeID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  80. ATTRIBUTE(Scene, VAR_INT, "Next Local Component ID", localComponentID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  81. ATTRIBUTE(Scene, VAR_VARIANTMAP, "Variables", vars_, VariantMap(), AM_FILE); // Network replication of vars uses custom data
  82. ACCESSOR_ATTRIBUTE(Scene, VAR_STRING, "Variable Names", GetVarNamesAttr, SetVarNamesAttr, String, String(), AM_FILE | AM_NOEDIT);
  83. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_NET | AM_LATESTDATA | AM_NOEDIT);
  84. }
  85. bool Scene::Load(Deserializer& source)
  86. {
  87. StopAsyncLoading();
  88. // Check ID
  89. if (source.ReadFileID() != "USCN")
  90. {
  91. LOGERROR(source.GetName() + " is not a valid scene file");
  92. return false;
  93. }
  94. LOGINFO("Loading scene from " + source.GetName());
  95. // Load the whole scene, then perform post-load if successfully loaded
  96. if (Node::Load(source))
  97. {
  98. FinishLoading(&source);
  99. return true;
  100. }
  101. else
  102. return false;
  103. }
  104. bool Scene::Save(Serializer& dest)
  105. {
  106. // Write ID first
  107. if (!dest.WriteFileID("USCN"))
  108. {
  109. LOGERROR("Could not save scene, writing to stream failed");
  110. return false;
  111. }
  112. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  113. if (ptr)
  114. LOGINFO("Saving scene to " + ptr->GetName());
  115. return Node::Save(dest);
  116. }
  117. bool Scene::LoadXML(const XMLElement& source)
  118. {
  119. StopAsyncLoading();
  120. // Load the whole scene, then perform post-load if successfully loaded
  121. // Note: the scene filename and checksum can not be set, as we only used an XML element
  122. if (Node::LoadXML(source))
  123. {
  124. FinishLoading(0);
  125. return true;
  126. }
  127. else
  128. return false;
  129. }
  130. bool Scene::LoadXML(Deserializer& source)
  131. {
  132. StopAsyncLoading();
  133. SharedPtr<XMLFile> xml(new XMLFile(context_));
  134. if (!xml->Load(source))
  135. return false;
  136. LOGINFO("Loading scene from " + source.GetName());
  137. // Load the whole scene, then perform post-load if successfully loaded
  138. if (Node::LoadXML(xml->GetRoot()))
  139. {
  140. FinishLoading(&source);
  141. return true;
  142. }
  143. else
  144. return false;
  145. }
  146. bool Scene::SaveXML(Serializer& dest)
  147. {
  148. SharedPtr<XMLFile> xml(new XMLFile(context_));
  149. XMLElement rootElem = xml->CreateRoot("scene");
  150. if (!SaveXML(rootElem))
  151. return false;
  152. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  153. if (ptr)
  154. LOGINFO("Saving scene to " + ptr->GetName());
  155. return xml->Save(dest);
  156. }
  157. bool Scene::LoadAsync(File* file)
  158. {
  159. if (!file)
  160. {
  161. LOGERROR("Null file for async loading");
  162. return false;
  163. }
  164. StopAsyncLoading();
  165. // Check ID
  166. if (file->ReadFileID() != "USCN")
  167. {
  168. LOGERROR(file->GetName() + " is not a valid scene file");
  169. return false;
  170. }
  171. LOGINFO("Loading scene from " + file->GetName());
  172. // Clear the previous scene and load the root level components first
  173. Clear();
  174. if (!Node::Load(*file, false))
  175. return false;
  176. // Then prepare for loading all root level child nodes in the async update
  177. asyncLoading_ = true;
  178. asyncProgress_.file_ = file;
  179. asyncProgress_.xmlFile_.Reset();
  180. asyncProgress_.xmlElement_ = XMLElement();
  181. asyncProgress_.loadedNodes_ = 0;
  182. asyncProgress_.totalNodes_ = file->ReadVLE();
  183. return true;
  184. }
  185. bool Scene::LoadAsyncXML(File* file)
  186. {
  187. if (!file)
  188. {
  189. LOGERROR("Null file for async loading");
  190. return false;
  191. }
  192. StopAsyncLoading();
  193. SharedPtr<XMLFile> xmlFile(new XMLFile(context_));
  194. if (!xmlFile->Load(*file))
  195. return false;
  196. LOGINFO("Loading scene from " + file->GetName());
  197. // Clear the previous scene and load the root level components first
  198. Clear();
  199. XMLElement rootElement = xmlFile->GetRoot();
  200. if (!Node::LoadXML(rootElement, false))
  201. return false;
  202. // Then prepare for loading all root level child nodes in the async update
  203. XMLElement childNodeElement = rootElement.GetChild("node");
  204. asyncLoading_ = true;
  205. asyncProgress_.file_ = file;
  206. asyncProgress_.xmlFile_ = xmlFile;
  207. asyncProgress_.xmlElement_ = childNodeElement;
  208. asyncProgress_.loadedNodes_ = 0;
  209. asyncProgress_.totalNodes_ = 0;
  210. // Count the amount of child nodes
  211. while (childNodeElement)
  212. {
  213. ++asyncProgress_.totalNodes_;
  214. childNodeElement = childNodeElement.GetNext("node");
  215. }
  216. return true;
  217. }
  218. void Scene::StopAsyncLoading()
  219. {
  220. asyncLoading_ = false;
  221. asyncProgress_.file_.Reset();
  222. asyncProgress_.xmlFile_.Reset();
  223. asyncProgress_.xmlElement_ = XMLElement();
  224. }
  225. void Scene::Clear()
  226. {
  227. StopAsyncLoading();
  228. RemoveAllChildren();
  229. RemoveAllComponents();
  230. fileName_ = String();
  231. checksum_ = 0;
  232. }
  233. void Scene::SetActive(bool enable)
  234. {
  235. active_ = enable;
  236. }
  237. void Scene::SetSmoothingConstant(float constant)
  238. {
  239. smoothingConstant_ = Max(constant, M_EPSILON);
  240. }
  241. void Scene::SetSnapThreshold(float threshold)
  242. {
  243. snapThreshold_ = Max(threshold, 0.0f);
  244. }
  245. void Scene::AddRequiredPackageFile(PackageFile* package)
  246. {
  247. // Do not add packages that failed to load
  248. if (!package || !package->GetNumFiles())
  249. return;
  250. requiredPackageFiles_.Push(SharedPtr<PackageFile>(package));
  251. }
  252. void Scene::ClearRequiredPackageFiles()
  253. {
  254. requiredPackageFiles_.Clear();
  255. }
  256. void Scene::ResetOwner(Connection* owner)
  257. {
  258. for (Map<unsigned, Node*>::Iterator i = allNodes_.Begin(); i != allNodes_.End(); ++i)
  259. {
  260. if (i->second_->GetOwner() == owner)
  261. i->second_->SetOwner(0);
  262. }
  263. }
  264. void Scene::RegisterVar(const String& name)
  265. {
  266. varNames_[ShortStringHash(name)] = name;
  267. }
  268. void Scene::UnregisterVar(const String& name)
  269. {
  270. varNames_.Erase(ShortStringHash(name));
  271. }
  272. void Scene::UnregisterAllVars()
  273. {
  274. varNames_.Clear();
  275. }
  276. Node* Scene::GetNode(unsigned id) const
  277. {
  278. Map<unsigned, Node*>::ConstIterator i = allNodes_.Find(id);
  279. if (i != allNodes_.End())
  280. return i->second_;
  281. else
  282. return 0;
  283. }
  284. Component* Scene::GetComponent(unsigned id) const
  285. {
  286. Map<unsigned, Component*>::ConstIterator i = allComponents_.Find(id);
  287. if (i != allComponents_.End())
  288. return i->second_;
  289. else
  290. return 0;
  291. }
  292. float Scene::GetAsyncProgress() const
  293. {
  294. if (!asyncLoading_ || !asyncProgress_.totalNodes_)
  295. return 1.0f;
  296. else
  297. return (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  298. }
  299. const String& Scene::GetVarName(ShortStringHash hash) const
  300. {
  301. Map<ShortStringHash, String>::ConstIterator i = varNames_.Find(hash);
  302. return i != varNames_.End() ? i->second_ : emptyVarName;
  303. }
  304. void Scene::Update(float timeStep)
  305. {
  306. if (asyncLoading_)
  307. {
  308. UpdateAsyncLoading();
  309. return;
  310. }
  311. PROFILE(UpdateScene);
  312. using namespace SceneUpdate;
  313. VariantMap eventData;
  314. eventData[P_SCENE] = (void*)this;
  315. eventData[P_TIMESTEP] = timeStep;
  316. // Update variable timestep logic
  317. SendEvent(E_SCENEUPDATE, eventData);
  318. // Update scene subsystems. If a physics world is present, it will be updated, triggering fixed timestep logic updates
  319. SendEvent(E_SCENESUBSYSTEMUPDATE, eventData);
  320. // Update smoothing if enabled (network client scenes)
  321. if (IsSmoothed())
  322. {
  323. PROFILE(UpdateSmoothing);
  324. float constant = 1.0f - Clamp(powf(2.0f, -timeStep * smoothingConstant_), 0.0f, 1.0f);
  325. float squaredSnapThreshold = snapThreshold_ * snapThreshold_;
  326. for (Map<unsigned, Node*>::ConstIterator i = allNodes_.Begin(); i != allNodes_.End() && i->first_ < FIRST_LOCAL_ID; ++i)
  327. i->second_->UpdateSmoothing(constant, squaredSnapThreshold);
  328. }
  329. // Post-update variable timestep logic
  330. SendEvent(E_SCENEPOSTUPDATE, eventData);
  331. }
  332. void Scene::BeginThreadedUpdate()
  333. {
  334. // Check the work queue subsystem whether it actually has created worker threads. If not, do not enter threaded mode.
  335. if (GetSubsystem<WorkQueue>()->GetNumThreads())
  336. threadedUpdate_ = true;
  337. }
  338. void Scene::EndThreadedUpdate()
  339. {
  340. if (!threadedUpdate_)
  341. return;
  342. threadedUpdate_ = false;
  343. if (!delayedDirtyComponents_.Empty())
  344. {
  345. PROFILE(EndThreadedUpdate);
  346. for (PODVector<Component*>::ConstIterator i = delayedDirtyComponents_.Begin(); i != delayedDirtyComponents_.End(); ++i)
  347. (*i)->OnMarkedDirty((*i)->GetNode());
  348. delayedDirtyComponents_.Clear();
  349. }
  350. }
  351. void Scene::DelayedMarkedDirty(Component* component)
  352. {
  353. MutexLock lock(sceneMutex_);
  354. delayedDirtyComponents_.Push(component);
  355. }
  356. unsigned Scene::GetFreeNodeID(CreateMode mode)
  357. {
  358. if (mode == REPLICATED)
  359. {
  360. for (;;)
  361. {
  362. if (!allNodes_.Contains(replicatedNodeID_))
  363. return replicatedNodeID_;
  364. if (replicatedNodeID_ != LAST_REPLICATED_ID)
  365. ++replicatedNodeID_;
  366. else
  367. replicatedNodeID_ = FIRST_REPLICATED_ID;
  368. }
  369. }
  370. else
  371. {
  372. for (;;)
  373. {
  374. if (!allNodes_.Contains(localNodeID_))
  375. return localNodeID_;
  376. if (localNodeID_ != LAST_LOCAL_ID)
  377. ++localNodeID_;
  378. else
  379. localNodeID_ = FIRST_LOCAL_ID;
  380. }
  381. }
  382. }
  383. unsigned Scene::GetFreeComponentID(CreateMode mode)
  384. {
  385. if (mode == REPLICATED)
  386. {
  387. for (;;)
  388. {
  389. if (!allComponents_.Contains(replicatedComponentID_))
  390. return replicatedComponentID_;
  391. if (replicatedComponentID_ != LAST_REPLICATED_ID)
  392. ++replicatedComponentID_;
  393. else
  394. replicatedComponentID_ = FIRST_REPLICATED_ID;
  395. }
  396. }
  397. else
  398. {
  399. for (;;)
  400. {
  401. if (!allComponents_.Contains(localComponentID_))
  402. return localComponentID_;
  403. if (localComponentID_ != LAST_LOCAL_ID)
  404. ++localComponentID_;
  405. else
  406. localComponentID_ = FIRST_LOCAL_ID;
  407. }
  408. }
  409. }
  410. void Scene::NodeAdded(Node* node)
  411. {
  412. if (!node || node->GetScene())
  413. return;
  414. node->SetScene(this);
  415. // If we already have an existing node with the same ID, must remove the scene reference from it
  416. unsigned id = node->GetID();
  417. Map<unsigned, Node*>::Iterator i = allNodes_.Find(id);
  418. if (i != allNodes_.End() && i->second_ != node)
  419. {
  420. LOGWARNING("Overwriting node with ID " + String(id));
  421. i->second_->SetScene(0);
  422. i->second_->SetOwner(0);
  423. }
  424. allNodes_[id] = node;
  425. }
  426. void Scene::NodeRemoved(Node* node)
  427. {
  428. if (!node || node->GetScene() != this)
  429. return;
  430. allNodes_.Erase(node->GetID());
  431. node->SetID(0);
  432. node->SetScene(0);
  433. }
  434. void Scene::ComponentAdded(Component* component)
  435. {
  436. if (!component)
  437. return;
  438. unsigned id = component->GetID();
  439. Map<unsigned, Component*>::Iterator i = allComponents_.Find(id);
  440. if (i != allComponents_.End() && i->second_ != component)
  441. LOGWARNING("Overwriting component with ID " + String(id));
  442. allComponents_[id] = component;
  443. }
  444. void Scene::ComponentRemoved(Component* component)
  445. {
  446. if (!component)
  447. return;
  448. allComponents_.Erase(component->GetID());
  449. component->SetID(0);
  450. }
  451. void Scene::SetVarNamesAttr(String value)
  452. {
  453. Vector<String> varNames = value.Split(';');
  454. varNames_.Clear();
  455. for (Vector<String>::ConstIterator i = varNames.Begin(); i != varNames.End(); ++i)
  456. varNames_[ShortStringHash(*i)] = *i;
  457. }
  458. String Scene::GetVarNamesAttr() const
  459. {
  460. String ret;
  461. for (Map<ShortStringHash, String>::ConstIterator i = varNames_.Begin(); i != varNames_.End(); ++i)
  462. {
  463. if (i != varNames_.Begin())
  464. ret += ';';
  465. ret += i->second_;
  466. }
  467. return ret;
  468. }
  469. void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  470. {
  471. using namespace Update;
  472. if (active_)
  473. Update(eventData[P_TIMESTEP].GetFloat());
  474. }
  475. void Scene::UpdateAsyncLoading()
  476. {
  477. PROFILE(UpdateAsyncLoading);
  478. Timer asyncLoadTimer;
  479. for (;;)
  480. {
  481. if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
  482. {
  483. FinishAsyncLoading();
  484. return;
  485. }
  486. // Read one child node either from binary or XML
  487. if (!asyncProgress_.xmlFile_)
  488. {
  489. Node* newNode = CreateChild(asyncProgress_.file_->ReadUInt(), REPLICATED);
  490. newNode->Load(*asyncProgress_.file_);
  491. }
  492. else
  493. {
  494. Node* newNode = CreateChild(asyncProgress_.xmlElement_.GetInt("id"), REPLICATED);
  495. newNode->LoadXML(asyncProgress_.xmlElement_);
  496. asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNext("node");
  497. }
  498. ++asyncProgress_.loadedNodes_;
  499. // Break if time limit exceeded, so that we keep sufficient FPS
  500. if (asyncLoadTimer.GetMSec(false) >= ASYNC_LOAD_MAX_MSEC)
  501. break;
  502. }
  503. using namespace AsyncLoadProgress;
  504. VariantMap eventData;
  505. eventData[P_SCENE] = (void*)this;
  506. eventData[P_PROGRESS] = (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  507. eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
  508. eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
  509. SendEvent(E_ASYNCLOADPROGRESS, eventData);
  510. }
  511. void Scene::FinishAsyncLoading()
  512. {
  513. FinishLoading(asyncProgress_.file_);
  514. StopAsyncLoading();
  515. using namespace AsyncLoadFinished;
  516. VariantMap eventData;
  517. eventData[P_SCENE] = (void*)this;
  518. SendEvent(E_ASYNCLOADFINISHED, eventData);
  519. }
  520. void Scene::FinishLoading(Deserializer* source)
  521. {
  522. ApplyAttributes();
  523. if (source)
  524. {
  525. fileName_ = source->GetName();
  526. checksum_ = source->GetChecksum();
  527. }
  528. }
  529. void RegisterSceneLibrary(Context* context)
  530. {
  531. Node::RegisterObject(context);
  532. Scene::RegisterObject(context);
  533. }