2
0

Scene.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. //
  2. // Copyright (c) 2008-2015 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 "../Scene/Component.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../IO/File.h"
  26. #include "../IO/Log.h"
  27. #include "../Scene/ObjectAnimation.h"
  28. #include "../IO/PackageFile.h"
  29. #include "../Core/Profiler.h"
  30. #include "../Scene/ReplicationState.h"
  31. #include "../Resource/ResourceCache.h"
  32. #include "../Resource/ResourceEvents.h"
  33. #include "../Scene/Scene.h"
  34. #include "../Scene/SceneEvents.h"
  35. #include "../Scene/SmoothedTransform.h"
  36. #include "../Scene/SplinePath.h"
  37. #include "../Scene/UnknownComponent.h"
  38. #include "../Scene/ValueAnimation.h"
  39. #include "../Core/WorkQueue.h"
  40. #include "../Resource/XMLFile.h"
  41. #include "../DebugNew.h"
  42. namespace Urho3D
  43. {
  44. const char* SCENE_CATEGORY = "Scene";
  45. const char* LOGIC_CATEGORY = "Logic";
  46. const char* SUBSYSTEM_CATEGORY = "Subsystem";
  47. static const float DEFAULT_SMOOTHING_CONSTANT = 50.0f;
  48. static const float DEFAULT_SNAP_THRESHOLD = 5.0f;
  49. Scene::Scene(Context* context) :
  50. Node(context),
  51. replicatedNodeID_(FIRST_REPLICATED_ID),
  52. replicatedComponentID_(FIRST_REPLICATED_ID),
  53. localNodeID_(FIRST_LOCAL_ID),
  54. localComponentID_(FIRST_LOCAL_ID),
  55. checksum_(0),
  56. asyncLoadingMs_(5),
  57. timeScale_(1.0f),
  58. elapsedTime_(0),
  59. smoothingConstant_(DEFAULT_SMOOTHING_CONSTANT),
  60. snapThreshold_(DEFAULT_SNAP_THRESHOLD),
  61. updateEnabled_(true),
  62. asyncLoading_(false),
  63. threadedUpdate_(false)
  64. {
  65. // Assign an ID to self so that nodes can refer to this node as a parent
  66. SetID(GetFreeNodeID(REPLICATED));
  67. NodeAdded(this);
  68. SubscribeToEvent(E_UPDATE, HANDLER(Scene, HandleUpdate));
  69. SubscribeToEvent(E_RESOURCEBACKGROUNDLOADED, HANDLER(Scene, HandleResourceBackgroundLoaded));
  70. }
  71. Scene::~Scene()
  72. {
  73. // Remove root-level components first, so that scene subsystems such as the octree destroy themselves. This will speed up
  74. // the removal of child nodes' components
  75. RemoveAllComponents();
  76. RemoveAllChildren();
  77. // Remove scene reference and owner from all nodes that still exist
  78. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  79. i->second_->ResetScene();
  80. for (HashMap<unsigned, Node*>::Iterator i = localNodes_.Begin(); i != localNodes_.End(); ++i)
  81. i->second_->ResetScene();
  82. }
  83. void Scene::RegisterObject(Context* context)
  84. {
  85. context->RegisterFactory<Scene>();
  86. ACCESSOR_ATTRIBUTE("Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT);
  87. ACCESSOR_ATTRIBUTE("Time Scale", GetTimeScale, SetTimeScale, float, 1.0f, AM_DEFAULT);
  88. ACCESSOR_ATTRIBUTE("Smoothing Constant", GetSmoothingConstant, SetSmoothingConstant, float, DEFAULT_SMOOTHING_CONSTANT, AM_DEFAULT);
  89. ACCESSOR_ATTRIBUTE("Snap Threshold", GetSnapThreshold, SetSnapThreshold, float, DEFAULT_SNAP_THRESHOLD, AM_DEFAULT);
  90. ACCESSOR_ATTRIBUTE("Elapsed Time", GetElapsedTime, SetElapsedTime, float, 0.0f, AM_FILE);
  91. ATTRIBUTE("Next Replicated Node ID", int, replicatedNodeID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  92. ATTRIBUTE("Next Replicated Component ID", int, replicatedComponentID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  93. ATTRIBUTE("Next Local Node ID", int, localNodeID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  94. ATTRIBUTE("Next Local Component ID", int, localComponentID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  95. ATTRIBUTE("Variables", VariantMap, vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data
  96. MIXED_ACCESSOR_ATTRIBUTE("Variable Names", GetVarNamesAttr, SetVarNamesAttr, String, String::EMPTY, AM_FILE | AM_NOEDIT);
  97. }
  98. bool Scene::Load(Deserializer& source, bool setInstanceDefault)
  99. {
  100. PROFILE(LoadScene);
  101. StopAsyncLoading();
  102. // Check ID
  103. if (source.ReadFileID() != "USCN")
  104. {
  105. LOGERROR(source.GetName() + " is not a valid scene file");
  106. return false;
  107. }
  108. LOGINFO("Loading scene from " + source.GetName());
  109. Clear();
  110. // Load the whole scene, then perform post-load if successfully loaded
  111. if (Node::Load(source, setInstanceDefault))
  112. {
  113. FinishLoading(&source);
  114. return true;
  115. }
  116. else
  117. return false;
  118. }
  119. bool Scene::Save(Serializer& dest) const
  120. {
  121. PROFILE(SaveScene);
  122. // Write ID first
  123. if (!dest.WriteFileID("USCN"))
  124. {
  125. LOGERROR("Could not save scene, writing to stream failed");
  126. return false;
  127. }
  128. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  129. if (ptr)
  130. LOGINFO("Saving scene to " + ptr->GetName());
  131. if (Node::Save(dest))
  132. {
  133. FinishSaving(&dest);
  134. return true;
  135. }
  136. else
  137. return false;
  138. }
  139. bool Scene::LoadXML(const XMLElement& source, bool setInstanceDefault)
  140. {
  141. PROFILE(LoadSceneXML);
  142. StopAsyncLoading();
  143. // Load the whole scene, then perform post-load if successfully loaded
  144. // Note: the scene filename and checksum can not be set, as we only used an XML element
  145. if (Node::LoadXML(source, setInstanceDefault))
  146. {
  147. FinishLoading(0);
  148. return true;
  149. }
  150. else
  151. return false;
  152. }
  153. void Scene::MarkNetworkUpdate()
  154. {
  155. if (!networkUpdate_)
  156. {
  157. MarkNetworkUpdate(this);
  158. networkUpdate_ = true;
  159. }
  160. }
  161. void Scene::AddReplicationState(NodeReplicationState* state)
  162. {
  163. Node::AddReplicationState(state);
  164. // This is the first update for a new connection. Mark all replicated nodes dirty
  165. for (HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  166. state->sceneState_->dirtyNodes_.Insert(i->first_);
  167. }
  168. bool Scene::LoadXML(Deserializer& source)
  169. {
  170. PROFILE(LoadSceneXML);
  171. StopAsyncLoading();
  172. SharedPtr<XMLFile> xml(new XMLFile(context_));
  173. if (!xml->Load(source))
  174. return false;
  175. LOGINFO("Loading scene from " + source.GetName());
  176. Clear();
  177. if (Node::LoadXML(xml->GetRoot()))
  178. {
  179. FinishLoading(&source);
  180. return true;
  181. }
  182. else
  183. return false;
  184. }
  185. bool Scene::SaveXML(Serializer& dest, const String& indentation) const
  186. {
  187. PROFILE(SaveSceneXML);
  188. SharedPtr<XMLFile> xml(new XMLFile(context_));
  189. XMLElement rootElem = xml->CreateRoot("scene");
  190. if (!SaveXML(rootElem))
  191. return false;
  192. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  193. if (ptr)
  194. LOGINFO("Saving scene to " + ptr->GetName());
  195. if (xml->Save(dest, indentation))
  196. {
  197. FinishSaving(&dest);
  198. return true;
  199. }
  200. else
  201. return false;
  202. }
  203. bool Scene::LoadAsync(File* file, LoadMode mode)
  204. {
  205. if (!file)
  206. {
  207. LOGERROR("Null file for async loading");
  208. return false;
  209. }
  210. StopAsyncLoading();
  211. // Check ID
  212. bool isSceneFile = file->ReadFileID() == "USCN";
  213. if (!isSceneFile)
  214. {
  215. // In resource load mode can load also object prefabs, which have no identifier
  216. if (mode > LOAD_RESOURCES_ONLY)
  217. {
  218. LOGERROR(file->GetName() + " is not a valid scene file");
  219. return false;
  220. }
  221. else
  222. file->Seek(0);
  223. }
  224. if (mode > LOAD_RESOURCES_ONLY)
  225. {
  226. LOGINFO("Loading scene from " + file->GetName());
  227. Clear();
  228. }
  229. asyncLoading_ = true;
  230. asyncProgress_.file_ = file;
  231. asyncProgress_.mode_ = mode;
  232. asyncProgress_.loadedNodes_ = asyncProgress_.totalNodes_ = asyncProgress_.loadedResources_ = asyncProgress_.totalResources_ = 0;
  233. asyncProgress_.resources_.Clear();
  234. if (mode > LOAD_RESOURCES_ONLY)
  235. {
  236. // Preload resources if appropriate, then return to the original position for loading the scene content
  237. if (mode != LOAD_SCENE)
  238. {
  239. PROFILE(FindResourcesToPreload);
  240. unsigned currentPos = file->GetPosition();
  241. PreloadResources(file, isSceneFile);
  242. file->Seek(currentPos);
  243. }
  244. // Store own old ID for resolving possible root node references
  245. unsigned nodeID = file->ReadUInt();
  246. resolver_.AddNode(nodeID, this);
  247. // Load root level components first
  248. if (!Node::Load(*file, resolver_, false))
  249. {
  250. StopAsyncLoading();
  251. return false;
  252. }
  253. // Then prepare to load child nodes in the async updates
  254. asyncProgress_.totalNodes_ = file->ReadVLE();
  255. }
  256. else
  257. {
  258. PROFILE(FindResourcesToPreload);
  259. LOGINFO("Preloading resources from " + file->GetName());
  260. PreloadResources(file, isSceneFile);
  261. }
  262. return true;
  263. }
  264. bool Scene::LoadAsyncXML(File* file, LoadMode mode)
  265. {
  266. if (!file)
  267. {
  268. LOGERROR("Null file for async loading");
  269. return false;
  270. }
  271. StopAsyncLoading();
  272. SharedPtr<XMLFile> xml(new XMLFile(context_));
  273. if (!xml->Load(*file))
  274. return false;
  275. if (mode > LOAD_RESOURCES_ONLY)
  276. {
  277. LOGINFO("Loading scene from " + file->GetName());
  278. Clear();
  279. }
  280. asyncLoading_ = true;
  281. asyncProgress_.xmlFile_ = xml;
  282. asyncProgress_.file_ = file;
  283. asyncProgress_.mode_ = mode;
  284. asyncProgress_.loadedNodes_ = asyncProgress_.totalNodes_ = asyncProgress_.loadedResources_ = asyncProgress_.totalResources_ = 0;
  285. asyncProgress_.resources_.Clear();
  286. if (mode > LOAD_RESOURCES_ONLY)
  287. {
  288. XMLElement rootElement = xml->GetRoot();
  289. // Preload resources if appropriate
  290. if (mode != LOAD_SCENE)
  291. {
  292. PROFILE(FindResourcesToPreload);
  293. PreloadResourcesXML(rootElement);
  294. }
  295. // Store own old ID for resolving possible root node references
  296. unsigned nodeID = rootElement.GetInt("id");
  297. resolver_.AddNode(nodeID, this);
  298. // Load the root level components first
  299. if (!Node::LoadXML(rootElement, resolver_, false))
  300. return false;
  301. // Then prepare for loading all root level child nodes in the async update
  302. XMLElement childNodeElement = rootElement.GetChild("node");
  303. asyncProgress_.xmlElement_ = childNodeElement;
  304. // Count the amount of child nodes
  305. while (childNodeElement)
  306. {
  307. ++asyncProgress_.totalNodes_;
  308. childNodeElement = childNodeElement.GetNext("node");
  309. }
  310. }
  311. else
  312. {
  313. PROFILE(FindResourcesToPreload);
  314. LOGINFO("Preloading resources from " + file->GetName());
  315. PreloadResourcesXML(xml->GetRoot());
  316. }
  317. return true;
  318. }
  319. void Scene::StopAsyncLoading()
  320. {
  321. asyncLoading_ = false;
  322. asyncProgress_.file_.Reset();
  323. asyncProgress_.xmlFile_.Reset();
  324. asyncProgress_.xmlElement_ = XMLElement::EMPTY;
  325. asyncProgress_.resources_.Clear();
  326. resolver_.Reset();
  327. }
  328. Node* Scene::Instantiate(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  329. {
  330. PROFILE(Instantiate);
  331. SceneResolver resolver;
  332. unsigned nodeID = source.ReadInt();
  333. // Rewrite IDs when instantiating
  334. Node* node = CreateChild(0, mode);
  335. resolver.AddNode(nodeID, node);
  336. if (node->Load(source, resolver, true, true, mode))
  337. {
  338. resolver.Resolve();
  339. node->ApplyAttributes();
  340. node->SetTransform(position, rotation);
  341. return node;
  342. }
  343. else
  344. {
  345. node->Remove();
  346. return 0;
  347. }
  348. }
  349. Node* Scene::InstantiateXML(const XMLElement& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  350. {
  351. PROFILE(InstantiateXML);
  352. SceneResolver resolver;
  353. unsigned nodeID = source.GetInt("id");
  354. // Rewrite IDs when instantiating
  355. Node* node = CreateChild(0, mode);
  356. resolver.AddNode(nodeID, node);
  357. if (node->LoadXML(source, resolver, true, true, mode))
  358. {
  359. resolver.Resolve();
  360. node->ApplyAttributes();
  361. node->SetTransform(position, rotation);
  362. return node;
  363. }
  364. else
  365. {
  366. node->Remove();
  367. return 0;
  368. }
  369. }
  370. Node* Scene::InstantiateXML(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  371. {
  372. SharedPtr<XMLFile> xml(new XMLFile(context_));
  373. if (!xml->Load(source))
  374. return 0;
  375. return InstantiateXML(xml->GetRoot(), position, rotation, mode);
  376. }
  377. void Scene::Clear(bool clearReplicated, bool clearLocal)
  378. {
  379. StopAsyncLoading();
  380. RemoveChildren(clearReplicated, clearLocal, true);
  381. RemoveComponents(clearReplicated, clearLocal);
  382. // Only clear name etc. if clearing completely
  383. if (clearReplicated && clearLocal)
  384. {
  385. UnregisterAllVars();
  386. SetName(String::EMPTY);
  387. fileName_.Clear();
  388. checksum_ = 0;
  389. }
  390. // Reset ID generators
  391. if (clearReplicated)
  392. {
  393. replicatedNodeID_ = FIRST_REPLICATED_ID;
  394. replicatedComponentID_ = FIRST_REPLICATED_ID;
  395. }
  396. if (clearLocal)
  397. {
  398. localNodeID_ = FIRST_LOCAL_ID;
  399. localComponentID_ = FIRST_LOCAL_ID;
  400. }
  401. }
  402. void Scene::SetUpdateEnabled(bool enable)
  403. {
  404. updateEnabled_ = enable;
  405. }
  406. void Scene::SetTimeScale(float scale)
  407. {
  408. timeScale_ = Max(scale, M_EPSILON);
  409. Node::MarkNetworkUpdate();
  410. }
  411. void Scene::SetSmoothingConstant(float constant)
  412. {
  413. smoothingConstant_ = Max(constant, M_EPSILON);
  414. Node::MarkNetworkUpdate();
  415. }
  416. void Scene::SetSnapThreshold(float threshold)
  417. {
  418. snapThreshold_ = Max(threshold, 0.0f);
  419. Node::MarkNetworkUpdate();
  420. }
  421. void Scene::SetAsyncLoadingMs(int ms)
  422. {
  423. asyncLoadingMs_ = Max(ms, 1);
  424. }
  425. void Scene::SetElapsedTime(float time)
  426. {
  427. elapsedTime_ = time;
  428. }
  429. void Scene::AddRequiredPackageFile(PackageFile* package)
  430. {
  431. // Do not add packages that failed to load
  432. if (!package || !package->GetNumFiles())
  433. return;
  434. requiredPackageFiles_.Push(SharedPtr<PackageFile>(package));
  435. }
  436. void Scene::ClearRequiredPackageFiles()
  437. {
  438. requiredPackageFiles_.Clear();
  439. }
  440. void Scene::RegisterVar(const String& name)
  441. {
  442. varNames_[name] = name;
  443. }
  444. void Scene::UnregisterVar(const String& name)
  445. {
  446. varNames_.Erase(name);
  447. }
  448. void Scene::UnregisterAllVars()
  449. {
  450. varNames_.Clear();
  451. }
  452. Node* Scene::GetNode(unsigned id) const
  453. {
  454. if (id < FIRST_LOCAL_ID)
  455. {
  456. HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Find(id);
  457. if (i != replicatedNodes_.End())
  458. return i->second_;
  459. else
  460. return 0;
  461. }
  462. else
  463. {
  464. HashMap<unsigned, Node*>::ConstIterator i = localNodes_.Find(id);
  465. if (i != localNodes_.End())
  466. return i->second_;
  467. else
  468. return 0;
  469. }
  470. }
  471. Component* Scene::GetComponent(unsigned id) const
  472. {
  473. if (id < FIRST_LOCAL_ID)
  474. {
  475. HashMap<unsigned, Component*>::ConstIterator i = replicatedComponents_.Find(id);
  476. if (i != replicatedComponents_.End())
  477. return i->second_;
  478. else
  479. return 0;
  480. }
  481. else
  482. {
  483. HashMap<unsigned, Component*>::ConstIterator i = localComponents_.Find(id);
  484. if (i != localComponents_.End())
  485. return i->second_;
  486. else
  487. return 0;
  488. }
  489. }
  490. float Scene::GetAsyncProgress() const
  491. {
  492. if (!asyncLoading_ || asyncProgress_.totalNodes_ + asyncProgress_.totalResources_ == 0)
  493. return 1.0f;
  494. else
  495. {
  496. return (float)(asyncProgress_.loadedNodes_ + asyncProgress_.loadedResources_) / (float)(asyncProgress_.totalNodes_ +
  497. asyncProgress_.totalResources_);
  498. }
  499. }
  500. const String& Scene::GetVarName(StringHash hash) const
  501. {
  502. HashMap<StringHash, String>::ConstIterator i = varNames_.Find(hash);
  503. return i != varNames_.End() ? i->second_ : String::EMPTY;
  504. }
  505. void Scene::Update(float timeStep)
  506. {
  507. if (asyncLoading_)
  508. {
  509. UpdateAsyncLoading();
  510. // If only preloading resources, scene update can continue
  511. if (asyncProgress_.mode_ > LOAD_RESOURCES_ONLY)
  512. return;
  513. }
  514. PROFILE(UpdateScene);
  515. timeStep *= timeScale_;
  516. using namespace SceneUpdate;
  517. VariantMap& eventData = GetEventDataMap();
  518. eventData[P_SCENE] = this;
  519. eventData[P_TIMESTEP] = timeStep;
  520. // Update variable timestep logic
  521. SendEvent(E_SCENEUPDATE, eventData);
  522. // Update scene attribute animation.
  523. SendEvent(E_ATTRIBUTEANIMATIONUPDATE, eventData);
  524. // Update scene subsystems. If a physics world is present, it will be updated, triggering fixed timestep logic updates
  525. SendEvent(E_SCENESUBSYSTEMUPDATE, eventData);
  526. // Update transform smoothing
  527. {
  528. PROFILE(UpdateSmoothing);
  529. float constant = 1.0f - Clamp(powf(2.0f, -timeStep * smoothingConstant_), 0.0f, 1.0f);
  530. float squaredSnapThreshold = snapThreshold_ * snapThreshold_;
  531. using namespace UpdateSmoothing;
  532. smoothingData_[P_CONSTANT] = constant;
  533. smoothingData_[P_SQUAREDSNAPTHRESHOLD] = squaredSnapThreshold;
  534. SendEvent(E_UPDATESMOOTHING, smoothingData_);
  535. }
  536. // Post-update variable timestep logic
  537. SendEvent(E_SCENEPOSTUPDATE, eventData);
  538. // Note: using a float for elapsed time accumulation is inherently inaccurate. The purpose of this value is
  539. // primarily to update material animation effects, as it is available to shaders. It can be reset by calling
  540. // SetElapsedTime()
  541. elapsedTime_ += timeStep;
  542. }
  543. void Scene::BeginThreadedUpdate()
  544. {
  545. // Check the work queue subsystem whether it actually has created worker threads. If not, do not enter threaded mode.
  546. if (GetSubsystem<WorkQueue>()->GetNumThreads())
  547. threadedUpdate_ = true;
  548. }
  549. void Scene::EndThreadedUpdate()
  550. {
  551. if (!threadedUpdate_)
  552. return;
  553. threadedUpdate_ = false;
  554. if (!delayedDirtyComponents_.Empty())
  555. {
  556. PROFILE(EndThreadedUpdate);
  557. for (PODVector<Component*>::ConstIterator i = delayedDirtyComponents_.Begin(); i != delayedDirtyComponents_.End(); ++i)
  558. (*i)->OnMarkedDirty((*i)->GetNode());
  559. delayedDirtyComponents_.Clear();
  560. }
  561. }
  562. void Scene::DelayedMarkedDirty(Component* component)
  563. {
  564. MutexLock lock(sceneMutex_);
  565. delayedDirtyComponents_.Push(component);
  566. }
  567. unsigned Scene::GetFreeNodeID(CreateMode mode)
  568. {
  569. if (mode == REPLICATED)
  570. {
  571. for (;;)
  572. {
  573. unsigned ret = replicatedNodeID_;
  574. if (replicatedNodeID_ < LAST_REPLICATED_ID)
  575. ++replicatedNodeID_;
  576. else
  577. replicatedNodeID_ = FIRST_REPLICATED_ID;
  578. if (!replicatedNodes_.Contains(ret))
  579. return ret;
  580. }
  581. }
  582. else
  583. {
  584. for (;;)
  585. {
  586. unsigned ret = localNodeID_;
  587. if (localNodeID_ < LAST_LOCAL_ID)
  588. ++localNodeID_;
  589. else
  590. localNodeID_ = FIRST_LOCAL_ID;
  591. if (!localNodes_.Contains(ret))
  592. return ret;
  593. }
  594. }
  595. }
  596. unsigned Scene::GetFreeComponentID(CreateMode mode)
  597. {
  598. if (mode == REPLICATED)
  599. {
  600. for (;;)
  601. {
  602. unsigned ret = replicatedComponentID_;
  603. if (replicatedComponentID_ < LAST_REPLICATED_ID)
  604. ++replicatedComponentID_;
  605. else
  606. replicatedComponentID_ = FIRST_REPLICATED_ID;
  607. if (!replicatedComponents_.Contains(ret))
  608. return ret;
  609. }
  610. }
  611. else
  612. {
  613. for (;;)
  614. {
  615. unsigned ret = localComponentID_;
  616. if (localComponentID_ < LAST_LOCAL_ID)
  617. ++localComponentID_;
  618. else
  619. localComponentID_ = FIRST_LOCAL_ID;
  620. if (!localComponents_.Contains(ret))
  621. return ret;
  622. }
  623. }
  624. }
  625. void Scene::NodeAdded(Node* node)
  626. {
  627. if (!node || node->GetScene() == this)
  628. return;
  629. // If node already exists in another scene, remove. This is unsupported, as components will not reinitialize themselves
  630. // to use the new scene
  631. Scene* oldScene = node->GetScene();
  632. if (oldScene)
  633. {
  634. LOGERROR("Moving a node from one scene to another is unsupported");
  635. oldScene->NodeRemoved(node);
  636. }
  637. node->SetScene(this);
  638. // If the new node has an ID of zero (default), assign a replicated ID now
  639. unsigned id = node->GetID();
  640. if (!id)
  641. {
  642. id = GetFreeNodeID(REPLICATED);
  643. node->SetID(id);
  644. }
  645. // If node with same ID exists, remove the scene reference from it and overwrite with the new node
  646. if (id < FIRST_LOCAL_ID)
  647. {
  648. HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Find(id);
  649. if (i != replicatedNodes_.End() && i->second_ != node)
  650. {
  651. LOGWARNING("Overwriting node with ID " + String(id));
  652. i->second_->ResetScene();
  653. }
  654. replicatedNodes_[id] = node;
  655. MarkNetworkUpdate(node);
  656. MarkReplicationDirty(node);
  657. }
  658. else
  659. {
  660. HashMap<unsigned, Node*>::Iterator i = localNodes_.Find(id);
  661. if (i != localNodes_.End() && i->second_ != node)
  662. {
  663. LOGWARNING("Overwriting node with ID " + String(id));
  664. i->second_->ResetScene();
  665. }
  666. localNodes_[id] = node;
  667. }
  668. }
  669. void Scene::NodeRemoved(Node* node)
  670. {
  671. if (!node || node->GetScene() != this)
  672. return;
  673. unsigned id = node->GetID();
  674. if (id < FIRST_LOCAL_ID)
  675. {
  676. replicatedNodes_.Erase(id);
  677. MarkReplicationDirty(node);
  678. }
  679. else
  680. localNodes_.Erase(id);
  681. node->SetID(0);
  682. node->SetScene(0);
  683. // Remove components and child nodes as well
  684. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  685. for (Vector<SharedPtr<Component> >::ConstIterator i = components.Begin(); i != components.End(); ++i)
  686. ComponentRemoved(*i);
  687. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  688. for (Vector<SharedPtr<Node> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  689. NodeRemoved(*i);
  690. }
  691. void Scene::ComponentAdded(Component* component)
  692. {
  693. if (!component)
  694. return;
  695. unsigned id = component->GetID();
  696. if (id < FIRST_LOCAL_ID)
  697. {
  698. HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Find(id);
  699. if (i != replicatedComponents_.End() && i->second_ != component)
  700. {
  701. LOGWARNING("Overwriting component with ID " + String(id));
  702. i->second_->SetID(0);
  703. }
  704. replicatedComponents_[id] = component;
  705. }
  706. else
  707. {
  708. HashMap<unsigned, Component*>::Iterator i = localComponents_.Find(id);
  709. if (i != localComponents_.End() && i->second_ != component)
  710. {
  711. LOGWARNING("Overwriting component with ID " + String(id));
  712. i->second_->SetID(0);
  713. }
  714. localComponents_[id] = component;
  715. }
  716. }
  717. void Scene::ComponentRemoved(Component* component)
  718. {
  719. if (!component)
  720. return;
  721. unsigned id = component->GetID();
  722. if (id < FIRST_LOCAL_ID)
  723. replicatedComponents_.Erase(id);
  724. else
  725. localComponents_.Erase(id);
  726. component->SetID(0);
  727. }
  728. void Scene::SetVarNamesAttr(const String& value)
  729. {
  730. Vector<String> varNames = value.Split(';');
  731. varNames_.Clear();
  732. for (Vector<String>::ConstIterator i = varNames.Begin(); i != varNames.End(); ++i)
  733. varNames_[*i] = *i;
  734. }
  735. String Scene::GetVarNamesAttr() const
  736. {
  737. String ret;
  738. if (!varNames_.Empty())
  739. {
  740. for (HashMap<StringHash, String>::ConstIterator i = varNames_.Begin(); i != varNames_.End(); ++i)
  741. ret += i->second_ + ';';
  742. ret.Resize(ret.Length() - 1);
  743. }
  744. return ret;
  745. }
  746. void Scene::PrepareNetworkUpdate()
  747. {
  748. for (HashSet<unsigned>::Iterator i = networkUpdateNodes_.Begin(); i != networkUpdateNodes_.End(); ++i)
  749. {
  750. Node* node = GetNode(*i);
  751. if (node)
  752. node->PrepareNetworkUpdate();
  753. }
  754. for (HashSet<unsigned>::Iterator i = networkUpdateComponents_.Begin(); i != networkUpdateComponents_.End(); ++i)
  755. {
  756. Component* component = GetComponent(*i);
  757. if (component)
  758. component->PrepareNetworkUpdate();
  759. }
  760. networkUpdateNodes_.Clear();
  761. networkUpdateComponents_.Clear();
  762. }
  763. void Scene::CleanupConnection(Connection* connection)
  764. {
  765. Node::CleanupConnection(connection);
  766. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  767. i->second_->CleanupConnection(connection);
  768. for (HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Begin(); i != replicatedComponents_.End(); ++i)
  769. i->second_->CleanupConnection(connection);
  770. }
  771. void Scene::MarkNetworkUpdate(Node* node)
  772. {
  773. if (node)
  774. {
  775. if (!threadedUpdate_)
  776. networkUpdateNodes_.Insert(node->GetID());
  777. else
  778. {
  779. MutexLock lock(sceneMutex_);
  780. networkUpdateNodes_.Insert(node->GetID());
  781. }
  782. }
  783. }
  784. void Scene::MarkNetworkUpdate(Component* component)
  785. {
  786. if (component)
  787. {
  788. if (!threadedUpdate_)
  789. networkUpdateComponents_.Insert(component->GetID());
  790. else
  791. {
  792. MutexLock lock(sceneMutex_);
  793. networkUpdateComponents_.Insert(component->GetID());
  794. }
  795. }
  796. }
  797. void Scene::MarkReplicationDirty(Node* node)
  798. {
  799. unsigned id = node->GetID();
  800. if (id < FIRST_LOCAL_ID && networkState_)
  801. {
  802. for (PODVector<ReplicationState*>::Iterator i = networkState_->replicationStates_.Begin(); i !=
  803. networkState_->replicationStates_.End(); ++i)
  804. {
  805. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*i);
  806. nodeState->sceneState_->dirtyNodes_.Insert(id);
  807. }
  808. }
  809. }
  810. void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  811. {
  812. using namespace Update;
  813. if (updateEnabled_)
  814. Update(eventData[P_TIMESTEP].GetFloat());
  815. }
  816. void Scene::HandleResourceBackgroundLoaded(StringHash eventType, VariantMap& eventData)
  817. {
  818. using namespace ResourceBackgroundLoaded;
  819. if (asyncLoading_)
  820. {
  821. Resource* resource = static_cast<Resource*>(eventData[P_RESOURCE].GetPtr());
  822. if (asyncProgress_.resources_.Contains(resource->GetNameHash()))
  823. {
  824. asyncProgress_.resources_.Erase(resource->GetNameHash());
  825. ++asyncProgress_.loadedResources_;
  826. }
  827. }
  828. }
  829. void Scene::UpdateAsyncLoading()
  830. {
  831. PROFILE(UpdateAsyncLoading);
  832. // If resources left to load, do not load nodes yet
  833. if (asyncProgress_.loadedResources_ < asyncProgress_.totalResources_)
  834. return;
  835. HiresTimer asyncLoadTimer;
  836. for (;;)
  837. {
  838. if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
  839. {
  840. FinishAsyncLoading();
  841. return;
  842. }
  843. // Read one child node with its full sub-hierarchy either from binary or XML
  844. /// \todo Works poorly in scenes where one root-level child node contains all content
  845. if (!asyncProgress_.xmlFile_)
  846. {
  847. unsigned nodeID = asyncProgress_.file_->ReadUInt();
  848. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  849. resolver_.AddNode(nodeID, newNode);
  850. newNode->Load(*asyncProgress_.file_, resolver_);
  851. }
  852. else
  853. {
  854. unsigned nodeID = asyncProgress_.xmlElement_.GetInt("id");
  855. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  856. resolver_.AddNode(nodeID, newNode);
  857. newNode->LoadXML(asyncProgress_.xmlElement_, resolver_);
  858. asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNext("node");
  859. }
  860. ++asyncProgress_.loadedNodes_;
  861. // Break if time limit exceeded, so that we keep sufficient FPS
  862. if (asyncLoadTimer.GetUSec(false) >= asyncLoadingMs_ * 1000)
  863. break;
  864. }
  865. using namespace AsyncLoadProgress;
  866. VariantMap& eventData = GetEventDataMap();
  867. eventData[P_SCENE] = this;
  868. eventData[P_PROGRESS] = GetAsyncProgress();
  869. eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
  870. eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
  871. eventData[P_LOADEDRESOURCES] = asyncProgress_.loadedResources_;
  872. eventData[P_TOTALRESOURCES] = asyncProgress_.totalResources_;
  873. SendEvent(E_ASYNCLOADPROGRESS, eventData);
  874. }
  875. void Scene::FinishAsyncLoading()
  876. {
  877. if (asyncProgress_.mode_ > LOAD_RESOURCES_ONLY)
  878. {
  879. resolver_.Resolve();
  880. ApplyAttributes();
  881. FinishLoading(asyncProgress_.file_);
  882. }
  883. StopAsyncLoading();
  884. using namespace AsyncLoadFinished;
  885. VariantMap& eventData = GetEventDataMap();
  886. eventData[P_SCENE] = this;
  887. SendEvent(E_ASYNCLOADFINISHED, eventData);
  888. }
  889. void Scene::FinishLoading(Deserializer* source)
  890. {
  891. if (source)
  892. {
  893. fileName_ = source->GetName();
  894. checksum_ = source->GetChecksum();
  895. }
  896. }
  897. void Scene::FinishSaving(Serializer* dest) const
  898. {
  899. Deserializer* ptr = dynamic_cast<Deserializer*>(dest);
  900. if (ptr)
  901. {
  902. fileName_ = ptr->GetName();
  903. checksum_ = ptr->GetChecksum();
  904. }
  905. }
  906. void Scene::PreloadResources(File* file, bool isSceneFile)
  907. {
  908. ResourceCache* cache = GetSubsystem<ResourceCache>();
  909. // Read node ID (not needed)
  910. /*unsigned nodeID = */file->ReadUInt();
  911. // Read Node or Scene attributes; these do not include any resources
  912. const Vector<AttributeInfo>* attributes = context_->GetAttributes(isSceneFile ? Scene::GetTypeStatic() : Node::GetTypeStatic());
  913. assert(attributes);
  914. for (unsigned i = 0; i < attributes->Size(); ++i)
  915. {
  916. const AttributeInfo& attr = attributes->At(i);
  917. if (!(attr.mode_ & AM_FILE))
  918. continue;
  919. Variant varValue = file->ReadVariant(attr.type_);
  920. }
  921. // Read component attributes
  922. unsigned numComponents = file->ReadVLE();
  923. for (unsigned i = 0; i < numComponents; ++i)
  924. {
  925. VectorBuffer compBuffer(*file, file->ReadVLE());
  926. StringHash compType = compBuffer.ReadStringHash();
  927. // Read component ID (not needed)
  928. /*unsigned compID = */compBuffer.ReadUInt();
  929. attributes = context_->GetAttributes(compType);
  930. if (attributes)
  931. {
  932. for (unsigned j = 0; j < attributes->Size(); ++j)
  933. {
  934. const AttributeInfo& attr = attributes->At(j);
  935. if (!(attr.mode_ & AM_FILE))
  936. continue;
  937. Variant varValue = compBuffer.ReadVariant(attr.type_);
  938. if (attr.type_ == VAR_RESOURCEREF)
  939. {
  940. const ResourceRef& ref = varValue.GetResourceRef();
  941. // Sanitate resource name beforehand so that when we get the background load event, the name matches exactly
  942. String name = cache->SanitateResourceName(ref.name_);
  943. bool success = cache->BackgroundLoadResource(ref.type_, name);
  944. if (success)
  945. {
  946. ++asyncProgress_.totalResources_;
  947. asyncProgress_.resources_.Insert(StringHash(name));
  948. }
  949. }
  950. else if (attr.type_ == VAR_RESOURCEREFLIST)
  951. {
  952. const ResourceRefList& refList = varValue.GetResourceRefList();
  953. for (unsigned k = 0; k < refList.names_.Size(); ++k)
  954. {
  955. String name = cache->SanitateResourceName(refList.names_[k]);
  956. bool success = cache->BackgroundLoadResource(refList.type_, name);
  957. if (success)
  958. {
  959. ++asyncProgress_.totalResources_;
  960. asyncProgress_.resources_.Insert(StringHash(name));
  961. }
  962. }
  963. }
  964. }
  965. }
  966. }
  967. // Read child nodes
  968. unsigned numChildren = file->ReadVLE();
  969. for (unsigned i = 0; i < numChildren; ++i)
  970. PreloadResources(file, false);
  971. }
  972. void Scene::PreloadResourcesXML(const XMLElement& element)
  973. {
  974. ResourceCache* cache = GetSubsystem<ResourceCache>();
  975. // Node or Scene attributes do not include any resources; therefore skip to the components
  976. XMLElement compElem = element.GetChild("component");
  977. while (compElem)
  978. {
  979. String typeName = compElem.GetAttribute("type");
  980. const Vector<AttributeInfo>* attributes = context_->GetAttributes(StringHash(typeName));
  981. if (attributes)
  982. {
  983. XMLElement attrElem = compElem.GetChild("attribute");
  984. unsigned startIndex = 0;
  985. while (attrElem)
  986. {
  987. String name = attrElem.GetAttribute("name");
  988. unsigned i = startIndex;
  989. unsigned attempts = attributes->Size();
  990. while (attempts)
  991. {
  992. const AttributeInfo& attr = attributes->At(i);
  993. if ((attr.mode_ & AM_FILE) && !attr.name_.Compare(name, true))
  994. {
  995. if (attr.type_ == VAR_RESOURCEREF)
  996. {
  997. ResourceRef ref = attrElem.GetVariantValue(attr.type_).GetResourceRef();
  998. String name = cache->SanitateResourceName(ref.name_);
  999. bool success = cache->BackgroundLoadResource(ref.type_, name);
  1000. if (success)
  1001. {
  1002. ++asyncProgress_.totalResources_;
  1003. asyncProgress_.resources_.Insert(StringHash(name));
  1004. }
  1005. }
  1006. else if (attr.type_ == VAR_RESOURCEREFLIST)
  1007. {
  1008. ResourceRefList refList = attrElem.GetVariantValue(attr.type_).GetResourceRefList();
  1009. for (unsigned k = 0; k < refList.names_.Size(); ++k)
  1010. {
  1011. String name = cache->SanitateResourceName(refList.names_[k]);
  1012. bool success = cache->BackgroundLoadResource(refList.type_, name);
  1013. if (success)
  1014. {
  1015. ++asyncProgress_.totalResources_;
  1016. asyncProgress_.resources_.Insert(StringHash(name));
  1017. }
  1018. }
  1019. }
  1020. startIndex = (i + 1) % attributes->Size();
  1021. break;
  1022. }
  1023. else
  1024. {
  1025. i = (i + 1) % attributes->Size();
  1026. --attempts;
  1027. }
  1028. }
  1029. attrElem = attrElem.GetNext("attribute");
  1030. }
  1031. }
  1032. compElem = compElem.GetNext("component");
  1033. }
  1034. XMLElement childElem = element.GetChild("node");
  1035. while (childElem)
  1036. {
  1037. PreloadResourcesXML(childElem);
  1038. childElem = childElem.GetNext("node");
  1039. }
  1040. }
  1041. void RegisterSceneLibrary(Context* context)
  1042. {
  1043. ValueAnimation::RegisterObject(context);
  1044. ObjectAnimation::RegisterObject(context);
  1045. Node::RegisterObject(context);
  1046. Scene::RegisterObject(context);
  1047. SmoothedTransform::RegisterObject(context);
  1048. UnknownComponent::RegisterObject(context);
  1049. SplinePath::RegisterObject(context);
  1050. }
  1051. }