Scene.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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 "StringUtils.h"
  34. #include "XMLFile.h"
  35. OBJECTTYPESTATIC(Scene);
  36. static const int ASYNC_LOAD_MIN_FPS = 50;
  37. static const int ASYNC_LOAD_MAX_MSEC = (int)(1000.0f / ASYNC_LOAD_MIN_FPS);
  38. Scene::Scene(Context* context) :
  39. Node(context),
  40. networkMode_(NM_NONETWORK),
  41. nonLocalNodeID_(FIRST_NONLOCAL_ID),
  42. nonLocalComponentID_(FIRST_NONLOCAL_ID),
  43. localNodeID_(FIRST_LOCAL_ID),
  44. localComponentID_(FIRST_LOCAL_ID),
  45. checksum_(0),
  46. active_(true),
  47. asyncLoading_(false)
  48. {
  49. // Assign an ID to self so that nodes can refer to this node as a parent
  50. SetID(GetFreeunsigned(false));
  51. NodeAdded(this);
  52. SubscribeToEvent(E_UPDATE, HANDLER(Scene, HandleUpdate));
  53. }
  54. Scene::~Scene()
  55. {
  56. // Remove scene reference and owner from all nodes that still exist
  57. for (std::map<unsigned, Node*>::iterator i = allNodes_.begin(); i != allNodes_.end(); ++i)
  58. {
  59. i->second->SetScene(0);
  60. i->second->SetOwner(0);
  61. }
  62. }
  63. void Scene::RegisterObject(Context* context)
  64. {
  65. context->RegisterFactory<Scene>();
  66. context->CopyBaseAttributes<Node, Scene>();
  67. ATTRIBUTE(Scene, VAR_INT, "Next Non-Local Node ID", nonLocalNodeID_, FIRST_NONLOCAL_ID);
  68. ATTRIBUTE(Scene, VAR_INT, "Next Non-Local Component ID", nonLocalComponentID_, FIRST_NONLOCAL_ID);
  69. ATTRIBUTE(Scene, VAR_INT, "Next Local Node ID", localNodeID_, FIRST_LOCAL_ID);
  70. ATTRIBUTE(Scene, VAR_INT, "Next Local Component ID", localComponentID_, FIRST_LOCAL_ID);
  71. }
  72. bool Scene::Load(Deserializer& source)
  73. {
  74. StopAsyncLoading();
  75. // Check ID
  76. if (source.ReadID() != "USCN")
  77. {
  78. LOGERROR(source.GetName() + " is not a valid scene file");
  79. return false;
  80. }
  81. // Load the whole scene, then perform post-load if successfully loaded
  82. if (Node::Load(source))
  83. {
  84. FinishLoading(&source);
  85. return true;
  86. }
  87. else
  88. return false;
  89. }
  90. bool Scene::Save(Serializer& dest)
  91. {
  92. // Write ID first
  93. if (!dest.WriteID("USCN"))
  94. {
  95. LOGERROR("Could not save scene, writing to stream failed");
  96. return false;
  97. }
  98. return Node::Save(dest);
  99. }
  100. bool Scene::LoadXML(const XMLElement& source)
  101. {
  102. StopAsyncLoading();
  103. // Load the whole scene, then perform post-load if successfully loaded
  104. // Note: the scene filename and checksum can not be set, as we only used an XML element
  105. if (Node::LoadXML(source))
  106. {
  107. FinishLoading(0);
  108. return true;
  109. }
  110. else
  111. return false;
  112. }
  113. void Scene::Update(float timeStep)
  114. {
  115. if (asyncLoading_)
  116. {
  117. UpdateAsyncLoading();
  118. return;
  119. }
  120. PROFILE(UpdateScene);
  121. using namespace SceneUpdate;
  122. VariantMap eventData;
  123. eventData[P_SCENE] = (void*)this;
  124. eventData[P_TIMESTEP] = timeStep;
  125. // Update variable timestep logic
  126. SendEvent(E_SCENEUPDATE, eventData);
  127. // Update scene subsystems. If a physics world is present, it will be updated, triggering fixed timestep logic updates
  128. SendEvent(E_SCENESUBSYSTEMUPDATE, eventData);
  129. // Post-update variable timestep logic
  130. SendEvent(E_SCENEPOSTUPDATE, eventData);
  131. }
  132. bool Scene::LoadXML(Deserializer& source)
  133. {
  134. StopAsyncLoading();
  135. SharedPtr<XMLFile> xml(new XMLFile(context_));
  136. if (!xml->Load(source))
  137. return false;
  138. // Load the whole scene, then perform post-load if successfully loaded
  139. if (Node::LoadXML(xml->GetRootElement()))
  140. {
  141. FinishLoading(&source);
  142. return true;
  143. }
  144. else
  145. return false;
  146. }
  147. bool Scene::SaveXML(Serializer& dest)
  148. {
  149. SharedPtr<XMLFile> xml(new XMLFile(context_));
  150. XMLElement rootElem = xml->CreateRootElement("scene");
  151. if (!SaveXML(rootElem))
  152. return false;
  153. return xml->Save(dest);
  154. }
  155. bool Scene::LoadAsync(File* file)
  156. {
  157. if (!file)
  158. {
  159. LOGERROR("Null file for async loading");
  160. return false;
  161. }
  162. StopAsyncLoading();
  163. // Check ID
  164. if (file->ReadID() != "USCN")
  165. {
  166. LOGERROR(file->GetName() + " is not a valid scene file");
  167. return false;
  168. }
  169. // Clear the previous scene and load the root level components first
  170. Clear();
  171. if (!Node::Load(*file, false))
  172. return false;
  173. // Then prepare for loading all root level child nodes in the async update
  174. asyncLoading_ = true;
  175. asyncProgress_.file_ = file;
  176. asyncProgress_.xmlFile_.Reset();
  177. asyncProgress_.xmlElement_ = XMLElement();
  178. asyncProgress_.loadedNodes_ = 0;
  179. asyncProgress_.totalNodes_ = file->ReadVLE();
  180. return true;
  181. }
  182. bool Scene::LoadAsyncXML(File* file)
  183. {
  184. if (!file)
  185. {
  186. LOGERROR("Null file for async loading");
  187. return false;
  188. }
  189. StopAsyncLoading();
  190. SharedPtr<XMLFile> xmlFile(new XMLFile(context_));
  191. if (!xmlFile->Load(*file))
  192. return false;
  193. // Clear the previous scene and load the root level components first
  194. Clear();
  195. XMLElement rootElement = xmlFile->GetRootElement();
  196. if (!Node::LoadXML(rootElement, false))
  197. return false;
  198. // Then prepare for loading all root level child nodes in the async update
  199. XMLElement childNodeElement = rootElement.GetChildElement("node");
  200. asyncLoading_ = true;
  201. asyncProgress_.file_ = file;
  202. asyncProgress_.xmlFile_ = xmlFile;
  203. asyncProgress_.xmlElement_ = childNodeElement;
  204. asyncProgress_.loadedNodes_ = 0;
  205. asyncProgress_.totalNodes_ = 0;
  206. // Count the amount of child nodes
  207. while (childNodeElement)
  208. {
  209. ++asyncProgress_.totalNodes_;
  210. childNodeElement = childNodeElement.GetNextElement("node");
  211. }
  212. return true;
  213. }
  214. void Scene::StopAsyncLoading()
  215. {
  216. asyncLoading_ = false;
  217. asyncProgress_.file_.Reset();
  218. asyncProgress_.xmlFile_.Reset();
  219. asyncProgress_.xmlElement_ = XMLElement();
  220. }
  221. void Scene::SetActive(bool enable)
  222. {
  223. active_ = enable;
  224. }
  225. void Scene::SetNetworkMode(NetworkMode mode)
  226. {
  227. networkMode_ = mode;
  228. }
  229. void Scene::Clear()
  230. {
  231. RemoveAllChildren();
  232. RemoveAllComponents();
  233. fileName_ = std::string();
  234. checksum_ = 0;
  235. }
  236. void Scene::ClearNonLocal()
  237. {
  238. // Because node removal can remove arbitrary other nodes, can not iterate. Instead loop until the first node is local,
  239. // or the map is empty
  240. while ((allNodes_.size()) && (allNodes_.begin()->first < FIRST_LOCAL_ID))
  241. allNodes_.begin()->second->Remove();
  242. }
  243. void Scene::AddRequiredPackageFile(PackageFile* file)
  244. {
  245. if (file)
  246. requiredPackageFiles_.push_back(SharedPtr<PackageFile>(file));
  247. }
  248. void Scene::ClearRequiredPackageFiles()
  249. {
  250. requiredPackageFiles_.clear();
  251. }
  252. void Scene::ResetOwner(Connection* owner)
  253. {
  254. for (std::map<unsigned, Node*>::iterator i = allNodes_.begin(); i != allNodes_.end(); ++i)
  255. {
  256. if (i->second->GetOwner() == owner)
  257. i->second->SetOwner(0);
  258. }
  259. }
  260. Node* Scene::GetNodeByID(unsigned id) const
  261. {
  262. std::map<unsigned, Node*>::const_iterator i = allNodes_.find(id);
  263. if (i != allNodes_.end())
  264. return i->second;
  265. else
  266. return 0;
  267. }
  268. Component* Scene::GetComponentByID(unsigned id) const
  269. {
  270. std::map<unsigned, Component*>::const_iterator i = allComponents_.find(id);
  271. if (i != allComponents_.end())
  272. return i->second;
  273. else
  274. return 0;
  275. }
  276. float Scene::GetAsyncProgress() const
  277. {
  278. if ((!asyncLoading_) || (!asyncProgress_.totalNodes_))
  279. return 1.0f;
  280. else
  281. return (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  282. }
  283. unsigned Scene::GetFreeunsigned(bool local)
  284. {
  285. if (!local)
  286. {
  287. for (;;)
  288. {
  289. if (allNodes_.find(nonLocalNodeID_) == allNodes_.end())
  290. return nonLocalNodeID_;
  291. if (nonLocalNodeID_ != LAST_NONLOCAL_ID)
  292. ++nonLocalNodeID_;
  293. else
  294. nonLocalNodeID_ = FIRST_NONLOCAL_ID;
  295. }
  296. }
  297. else
  298. {
  299. for (;;)
  300. {
  301. if (allNodes_.find(localNodeID_) == allNodes_.end())
  302. return localNodeID_;
  303. if (localNodeID_ != LAST_LOCAL_ID)
  304. ++localNodeID_;
  305. else
  306. localNodeID_ = FIRST_LOCAL_ID;
  307. }
  308. }
  309. }
  310. unsigned Scene::GetFreeComponentID(bool local)
  311. {
  312. if (!local)
  313. {
  314. for (;;)
  315. {
  316. if (allComponents_.find(nonLocalComponentID_) == allComponents_.end())
  317. return nonLocalComponentID_;
  318. if (nonLocalComponentID_ != LAST_NONLOCAL_ID)
  319. ++nonLocalComponentID_;
  320. else
  321. nonLocalComponentID_ = FIRST_NONLOCAL_ID;
  322. }
  323. }
  324. else
  325. {
  326. for (;;)
  327. {
  328. if (allComponents_.find(localComponentID_) == allComponents_.end())
  329. return localComponentID_;
  330. if (localComponentID_ != LAST_LOCAL_ID)
  331. ++localComponentID_;
  332. else
  333. localComponentID_ = FIRST_LOCAL_ID;
  334. }
  335. }
  336. }
  337. void Scene::NodeAdded(Node* node)
  338. {
  339. if ((!node) || (node->GetScene()))
  340. return;
  341. node->SetScene(this);
  342. // If we already have an existing node with the same ID, must remove the scene reference from it
  343. unsigned id = node->GetID();
  344. std::map<unsigned, Node*>::iterator i = allNodes_.find(id);
  345. if ((i != allNodes_.end()) && (i->second != node))
  346. {
  347. LOGWARNING("Overwriting node with ID " + ToString(id));
  348. i->second->SetScene(0);
  349. i->second->SetOwner(0);
  350. }
  351. allNodes_[id] = node;
  352. }
  353. void Scene::NodeRemoved(Node* node)
  354. {
  355. if ((!node) || (node->GetScene() != this))
  356. return;
  357. allNodes_.erase(node->GetID());
  358. node->SetID(0);
  359. node->SetScene(0);
  360. }
  361. void Scene::ComponentAdded(Component* component)
  362. {
  363. if (!component)
  364. return;
  365. allComponents_[component->GetID()] = component;
  366. }
  367. void Scene::ComponentRemoved(Component* component)
  368. {
  369. if (!component)
  370. return;
  371. allComponents_.erase(component->GetID());
  372. component->SetID(0);
  373. }
  374. void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  375. {
  376. using namespace Update;
  377. if (active_)
  378. Update(eventData[P_TIMESTEP].GetFloat());
  379. }
  380. void Scene::UpdateAsyncLoading()
  381. {
  382. PROFILE(UpdateAsyncLoading);
  383. Timer asyncLoadTimer;
  384. for (;;)
  385. {
  386. if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
  387. {
  388. FinishAsyncLoading();
  389. return;
  390. }
  391. // Read one child node either from binary or XML
  392. if (!asyncProgress_.xmlFile_)
  393. {
  394. Node* newNode = CreateChild(asyncProgress_.file_->ReadUInt(), false);
  395. newNode->Load(*asyncProgress_.file_);
  396. }
  397. else
  398. {
  399. Node* newNode = CreateChild(asyncProgress_.xmlElement_.GetInt("id"), false);
  400. newNode->LoadXML(asyncProgress_.xmlElement_);
  401. asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNextElement("node");
  402. }
  403. ++asyncProgress_.loadedNodes_;
  404. // Break if time limit exceeded, so that we keep sufficient FPS
  405. if (asyncLoadTimer.GetMSec(false) >= ASYNC_LOAD_MAX_MSEC)
  406. break;
  407. }
  408. using namespace AsyncLoadProgress;
  409. VariantMap eventData;
  410. eventData[P_SCENE] = (void*)this;
  411. eventData[P_PROGRESS] = (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  412. eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
  413. eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
  414. SendEvent(E_ASYNCLOADPROGRESS, eventData);
  415. }
  416. void Scene::FinishAsyncLoading()
  417. {
  418. FinishLoading(asyncProgress_.file_);
  419. StopAsyncLoading();
  420. using namespace AsyncLoadFinished;
  421. VariantMap eventData;
  422. eventData[P_SCENE] = (void*)this;
  423. SendEvent(E_ASYNCLOADFINISHED, eventData);
  424. }
  425. void Scene::FinishLoading(Deserializer* source)
  426. {
  427. PostLoad();
  428. if (source)
  429. {
  430. fileName_ = source->GetName();
  431. checksum_ = source->GetChecksum();
  432. }
  433. }
  434. void RegisterSceneLibrary(Context* context)
  435. {
  436. Node::RegisterObject(context);
  437. Scene::RegisterObject(context);
  438. }