Scene.cpp 37 KB

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