Scene.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542
  1. //
  2. // Copyright (c) 2008-2017 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 "../Resource/JSONFile.h"
  34. #include "../Scene/Component.h"
  35. #include "../Scene/ObjectAnimation.h"
  36. #include "../Scene/ReplicationState.h"
  37. #include "../Scene/Scene.h"
  38. #include "../Scene/SceneEvents.h"
  39. #include "../Scene/SmoothedTransform.h"
  40. #include "../Scene/SplinePath.h"
  41. #include "../Scene/UnknownComponent.h"
  42. #include "../Scene/ValueAnimation.h"
  43. #include "../DebugNew.h"
  44. namespace Urho3D
  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, URHO3D_HANDLER(Scene, HandleUpdate));
  71. SubscribeToEvent(E_RESOURCEBACKGROUNDLOADED, URHO3D_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. URHO3D_ACCESSOR_ATTRIBUTE("Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT);
  89. URHO3D_ACCESSOR_ATTRIBUTE("Time Scale", GetTimeScale, SetTimeScale, float, 1.0f, AM_DEFAULT);
  90. URHO3D_ACCESSOR_ATTRIBUTE("Smoothing Constant", GetSmoothingConstant, SetSmoothingConstant, float, DEFAULT_SMOOTHING_CONSTANT,
  91. AM_DEFAULT);
  92. URHO3D_ACCESSOR_ATTRIBUTE("Snap Threshold", GetSnapThreshold, SetSnapThreshold, float, DEFAULT_SNAP_THRESHOLD, AM_DEFAULT);
  93. URHO3D_ACCESSOR_ATTRIBUTE("Elapsed Time", GetElapsedTime, SetElapsedTime, float, 0.0f, AM_FILE);
  94. URHO3D_ATTRIBUTE("Next Replicated Node ID", unsigned, replicatedNodeID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  95. URHO3D_ATTRIBUTE("Next Replicated Component ID", unsigned, replicatedComponentID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  96. URHO3D_ATTRIBUTE("Next Local Node ID", unsigned, localNodeID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  97. URHO3D_ATTRIBUTE("Next Local Component ID", unsigned, localComponentID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  98. URHO3D_ATTRIBUTE("Variables", VariantMap, vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data
  99. URHO3D_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. URHO3D_PROFILE(LoadScene);
  104. StopAsyncLoading();
  105. // Check ID
  106. if (source.ReadFileID() != "USCN")
  107. {
  108. URHO3D_LOGERROR(source.GetName() + " is not a valid scene file");
  109. return false;
  110. }
  111. URHO3D_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. URHO3D_PROFILE(SaveScene);
  125. // Write ID first
  126. if (!dest.WriteFileID("USCN"))
  127. {
  128. URHO3D_LOGERROR("Could not save scene, writing to stream failed");
  129. return false;
  130. }
  131. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  132. if (ptr)
  133. URHO3D_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. URHO3D_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(nullptr);
  151. return true;
  152. }
  153. else
  154. return false;
  155. }
  156. bool Scene::LoadJSON(const JSONValue& source, bool setInstanceDefault)
  157. {
  158. URHO3D_PROFILE(LoadSceneJSON);
  159. StopAsyncLoading();
  160. // Load the whole scene, then perform post-load if successfully loaded
  161. // Note: the scene filename and checksum can not be set, as we only used an XML element
  162. if (Node::LoadJSON(source, setInstanceDefault))
  163. {
  164. FinishLoading(nullptr);
  165. return true;
  166. }
  167. else
  168. return false;
  169. }
  170. void Scene::MarkNetworkUpdate()
  171. {
  172. if (!networkUpdate_)
  173. {
  174. MarkNetworkUpdate(this);
  175. networkUpdate_ = true;
  176. }
  177. }
  178. void Scene::AddReplicationState(NodeReplicationState* state)
  179. {
  180. Node::AddReplicationState(state);
  181. // This is the first update for a new connection. Mark all replicated nodes dirty
  182. for (HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  183. state->sceneState_->dirtyNodes_.Insert(i->first_);
  184. }
  185. bool Scene::LoadXML(Deserializer& source)
  186. {
  187. URHO3D_PROFILE(LoadSceneXML);
  188. StopAsyncLoading();
  189. SharedPtr<XMLFile> xml(new XMLFile(context_));
  190. if (!xml->Load(source))
  191. return false;
  192. URHO3D_LOGINFO("Loading scene from " + source.GetName());
  193. Clear();
  194. if (Node::LoadXML(xml->GetRoot()))
  195. {
  196. FinishLoading(&source);
  197. return true;
  198. }
  199. else
  200. return false;
  201. }
  202. bool Scene::LoadJSON(Deserializer& source)
  203. {
  204. URHO3D_PROFILE(LoadSceneJSON);
  205. StopAsyncLoading();
  206. SharedPtr<JSONFile> json(new JSONFile(context_));
  207. if (!json->Load(source))
  208. return false;
  209. URHO3D_LOGINFO("Loading scene from " + source.GetName());
  210. Clear();
  211. if (Node::LoadJSON(json->GetRoot()))
  212. {
  213. FinishLoading(&source);
  214. return true;
  215. }
  216. else
  217. return false;
  218. }
  219. bool Scene::SaveXML(Serializer& dest, const String& indentation) const
  220. {
  221. URHO3D_PROFILE(SaveSceneXML);
  222. SharedPtr<XMLFile> xml(new XMLFile(context_));
  223. XMLElement rootElem = xml->CreateRoot("scene");
  224. if (!SaveXML(rootElem))
  225. return false;
  226. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  227. if (ptr)
  228. URHO3D_LOGINFO("Saving scene to " + ptr->GetName());
  229. if (xml->Save(dest, indentation))
  230. {
  231. FinishSaving(&dest);
  232. return true;
  233. }
  234. else
  235. return false;
  236. }
  237. bool Scene::SaveJSON(Serializer& dest, const String& indentation) const
  238. {
  239. URHO3D_PROFILE(SaveSceneJSON);
  240. SharedPtr<JSONFile> json(new JSONFile(context_));
  241. JSONValue rootVal;
  242. if (!SaveJSON(rootVal))
  243. return false;
  244. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  245. if (ptr)
  246. URHO3D_LOGINFO("Saving scene to " + ptr->GetName());
  247. json->GetRoot() = rootVal;
  248. if (json->Save(dest, indentation))
  249. {
  250. FinishSaving(&dest);
  251. return true;
  252. }
  253. else
  254. return false;
  255. }
  256. bool Scene::LoadAsync(File* file, LoadMode mode)
  257. {
  258. if (!file)
  259. {
  260. URHO3D_LOGERROR("Null file for async loading");
  261. return false;
  262. }
  263. StopAsyncLoading();
  264. // Check ID
  265. bool isSceneFile = file->ReadFileID() == "USCN";
  266. if (!isSceneFile)
  267. {
  268. // In resource load mode can load also object prefabs, which have no identifier
  269. if (mode > LOAD_RESOURCES_ONLY)
  270. {
  271. URHO3D_LOGERROR(file->GetName() + " is not a valid scene file");
  272. return false;
  273. }
  274. else
  275. file->Seek(0);
  276. }
  277. if (mode > LOAD_RESOURCES_ONLY)
  278. {
  279. URHO3D_LOGINFO("Loading scene from " + file->GetName());
  280. Clear();
  281. }
  282. asyncLoading_ = true;
  283. asyncProgress_.file_ = file;
  284. asyncProgress_.mode_ = mode;
  285. asyncProgress_.loadedNodes_ = asyncProgress_.totalNodes_ = asyncProgress_.loadedResources_ = asyncProgress_.totalResources_ = 0;
  286. asyncProgress_.resources_.Clear();
  287. if (mode > LOAD_RESOURCES_ONLY)
  288. {
  289. // Preload resources if appropriate, then return to the original position for loading the scene content
  290. if (mode != LOAD_SCENE)
  291. {
  292. URHO3D_PROFILE(FindResourcesToPreload);
  293. unsigned currentPos = file->GetPosition();
  294. PreloadResources(file, isSceneFile);
  295. file->Seek(currentPos);
  296. }
  297. // Store own old ID for resolving possible root node references
  298. unsigned nodeID = file->ReadUInt();
  299. resolver_.AddNode(nodeID, this);
  300. // Load root level components first
  301. if (!Node::Load(*file, resolver_, false))
  302. {
  303. StopAsyncLoading();
  304. return false;
  305. }
  306. // Then prepare to load child nodes in the async updates
  307. asyncProgress_.totalNodes_ = file->ReadVLE();
  308. }
  309. else
  310. {
  311. URHO3D_PROFILE(FindResourcesToPreload);
  312. URHO3D_LOGINFO("Preloading resources from " + file->GetName());
  313. PreloadResources(file, isSceneFile);
  314. }
  315. return true;
  316. }
  317. bool Scene::LoadAsyncXML(File* file, LoadMode mode)
  318. {
  319. if (!file)
  320. {
  321. URHO3D_LOGERROR("Null file for async loading");
  322. return false;
  323. }
  324. StopAsyncLoading();
  325. SharedPtr<XMLFile> xml(new XMLFile(context_));
  326. if (!xml->Load(*file))
  327. return false;
  328. if (mode > LOAD_RESOURCES_ONLY)
  329. {
  330. URHO3D_LOGINFO("Loading scene from " + file->GetName());
  331. Clear();
  332. }
  333. asyncLoading_ = true;
  334. asyncProgress_.xmlFile_ = xml;
  335. asyncProgress_.file_ = file;
  336. asyncProgress_.mode_ = mode;
  337. asyncProgress_.loadedNodes_ = asyncProgress_.totalNodes_ = asyncProgress_.loadedResources_ = asyncProgress_.totalResources_ = 0;
  338. asyncProgress_.resources_.Clear();
  339. if (mode > LOAD_RESOURCES_ONLY)
  340. {
  341. XMLElement rootElement = xml->GetRoot();
  342. // Preload resources if appropriate
  343. if (mode != LOAD_SCENE)
  344. {
  345. URHO3D_PROFILE(FindResourcesToPreload);
  346. PreloadResourcesXML(rootElement);
  347. }
  348. // Store own old ID for resolving possible root node references
  349. unsigned nodeID = rootElement.GetUInt("id");
  350. resolver_.AddNode(nodeID, this);
  351. // Load the root level components first
  352. if (!Node::LoadXML(rootElement, resolver_, false))
  353. return false;
  354. // Then prepare for loading all root level child nodes in the async update
  355. XMLElement childNodeElement = rootElement.GetChild("node");
  356. asyncProgress_.xmlElement_ = childNodeElement;
  357. // Count the amount of child nodes
  358. while (childNodeElement)
  359. {
  360. ++asyncProgress_.totalNodes_;
  361. childNodeElement = childNodeElement.GetNext("node");
  362. }
  363. }
  364. else
  365. {
  366. URHO3D_PROFILE(FindResourcesToPreload);
  367. URHO3D_LOGINFO("Preloading resources from " + file->GetName());
  368. PreloadResourcesXML(xml->GetRoot());
  369. }
  370. return true;
  371. }
  372. bool Scene::LoadAsyncJSON(File* file, LoadMode mode)
  373. {
  374. if (!file)
  375. {
  376. URHO3D_LOGERROR("Null file for async loading");
  377. return false;
  378. }
  379. StopAsyncLoading();
  380. SharedPtr<JSONFile> json(new JSONFile(context_));
  381. if (!json->Load(*file))
  382. return false;
  383. if (mode > LOAD_RESOURCES_ONLY)
  384. {
  385. URHO3D_LOGINFO("Loading scene from " + file->GetName());
  386. Clear();
  387. }
  388. asyncLoading_ = true;
  389. asyncProgress_.jsonFile_ = json;
  390. asyncProgress_.file_ = file;
  391. asyncProgress_.mode_ = mode;
  392. asyncProgress_.loadedNodes_ = asyncProgress_.totalNodes_ = asyncProgress_.loadedResources_ = asyncProgress_.totalResources_ = 0;
  393. asyncProgress_.resources_.Clear();
  394. if (mode > LOAD_RESOURCES_ONLY)
  395. {
  396. JSONValue rootVal = json->GetRoot();
  397. // Preload resources if appropriate
  398. if (mode != LOAD_SCENE)
  399. {
  400. URHO3D_PROFILE(FindResourcesToPreload);
  401. PreloadResourcesJSON(rootVal);
  402. }
  403. // Store own old ID for resolving possible root node references
  404. unsigned nodeID = rootVal.Get("id").GetUInt();
  405. resolver_.AddNode(nodeID, this);
  406. // Load the root level components first
  407. if (!Node::LoadJSON(rootVal, resolver_, false))
  408. return false;
  409. // Then prepare for loading all root level child nodes in the async update
  410. JSONArray childrenArray = rootVal.Get("children").GetArray();
  411. asyncProgress_.jsonIndex_ = 0;
  412. // Count the amount of child nodes
  413. asyncProgress_.totalNodes_ = childrenArray.Size();
  414. }
  415. else
  416. {
  417. URHO3D_PROFILE(FindResourcesToPreload);
  418. URHO3D_LOGINFO("Preloading resources from " + file->GetName());
  419. PreloadResourcesJSON(json->GetRoot());
  420. }
  421. return true;
  422. }
  423. void Scene::StopAsyncLoading()
  424. {
  425. asyncLoading_ = false;
  426. asyncProgress_.file_.Reset();
  427. asyncProgress_.xmlFile_.Reset();
  428. asyncProgress_.jsonFile_.Reset();
  429. asyncProgress_.xmlElement_ = XMLElement::EMPTY;
  430. asyncProgress_.jsonIndex_ = 0;
  431. asyncProgress_.resources_.Clear();
  432. resolver_.Reset();
  433. }
  434. Node* Scene::Instantiate(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  435. {
  436. URHO3D_PROFILE(Instantiate);
  437. SceneResolver resolver;
  438. unsigned nodeID = source.ReadUInt();
  439. // Rewrite IDs when instantiating
  440. Node* node = CreateChild(0, mode);
  441. resolver.AddNode(nodeID, node);
  442. if (node->Load(source, resolver, true, true, mode))
  443. {
  444. resolver.Resolve();
  445. node->SetTransform(position, rotation);
  446. node->ApplyAttributes();
  447. return node;
  448. }
  449. else
  450. {
  451. node->Remove();
  452. return nullptr;
  453. }
  454. }
  455. Node* Scene::InstantiateXML(const XMLElement& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  456. {
  457. URHO3D_PROFILE(InstantiateXML);
  458. SceneResolver resolver;
  459. unsigned nodeID = source.GetUInt("id");
  460. // Rewrite IDs when instantiating
  461. Node* node = CreateChild(0, mode);
  462. resolver.AddNode(nodeID, node);
  463. if (node->LoadXML(source, resolver, true, true, mode))
  464. {
  465. resolver.Resolve();
  466. node->SetTransform(position, rotation);
  467. node->ApplyAttributes();
  468. return node;
  469. }
  470. else
  471. {
  472. node->Remove();
  473. return nullptr;
  474. }
  475. }
  476. Node* Scene::InstantiateJSON(const JSONValue& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  477. {
  478. URHO3D_PROFILE(InstantiateJSON);
  479. SceneResolver resolver;
  480. unsigned nodeID = source.Get("id").GetUInt();
  481. // Rewrite IDs when instantiating
  482. Node* node = CreateChild(0, mode);
  483. resolver.AddNode(nodeID, node);
  484. if (node->LoadJSON(source, resolver, true, true, mode))
  485. {
  486. resolver.Resolve();
  487. node->SetTransform(position, rotation);
  488. node->ApplyAttributes();
  489. return node;
  490. }
  491. else
  492. {
  493. node->Remove();
  494. return nullptr;
  495. }
  496. }
  497. Node* Scene::InstantiateXML(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  498. {
  499. SharedPtr<XMLFile> xml(new XMLFile(context_));
  500. if (!xml->Load(source))
  501. return nullptr;
  502. return InstantiateXML(xml->GetRoot(), position, rotation, mode);
  503. }
  504. Node* Scene::InstantiateJSON(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  505. {
  506. SharedPtr<JSONFile> json(new JSONFile(context_));
  507. if (!json->Load(source))
  508. return nullptr;
  509. return InstantiateJSON(json->GetRoot(), position, rotation, mode);
  510. }
  511. void Scene::Clear(bool clearReplicated, bool clearLocal)
  512. {
  513. StopAsyncLoading();
  514. RemoveChildren(clearReplicated, clearLocal, true);
  515. RemoveComponents(clearReplicated, clearLocal);
  516. // Only clear name etc. if clearing completely
  517. if (clearReplicated && clearLocal)
  518. {
  519. UnregisterAllVars();
  520. SetName(String::EMPTY);
  521. fileName_.Clear();
  522. checksum_ = 0;
  523. }
  524. // Reset ID generators
  525. if (clearReplicated)
  526. {
  527. replicatedNodeID_ = FIRST_REPLICATED_ID;
  528. replicatedComponentID_ = FIRST_REPLICATED_ID;
  529. }
  530. if (clearLocal)
  531. {
  532. localNodeID_ = FIRST_LOCAL_ID;
  533. localComponentID_ = FIRST_LOCAL_ID;
  534. }
  535. }
  536. void Scene::SetUpdateEnabled(bool enable)
  537. {
  538. updateEnabled_ = enable;
  539. }
  540. void Scene::SetTimeScale(float scale)
  541. {
  542. timeScale_ = Max(scale, M_EPSILON);
  543. Node::MarkNetworkUpdate();
  544. }
  545. void Scene::SetSmoothingConstant(float constant)
  546. {
  547. smoothingConstant_ = Max(constant, M_EPSILON);
  548. Node::MarkNetworkUpdate();
  549. }
  550. void Scene::SetSnapThreshold(float threshold)
  551. {
  552. snapThreshold_ = Max(threshold, 0.0f);
  553. Node::MarkNetworkUpdate();
  554. }
  555. void Scene::SetAsyncLoadingMs(int ms)
  556. {
  557. asyncLoadingMs_ = Max(ms, 1);
  558. }
  559. void Scene::SetElapsedTime(float time)
  560. {
  561. elapsedTime_ = time;
  562. }
  563. void Scene::AddRequiredPackageFile(PackageFile* package)
  564. {
  565. // Do not add packages that failed to load
  566. if (!package || !package->GetNumFiles())
  567. return;
  568. requiredPackageFiles_.Push(SharedPtr<PackageFile>(package));
  569. }
  570. void Scene::ClearRequiredPackageFiles()
  571. {
  572. requiredPackageFiles_.Clear();
  573. }
  574. void Scene::RegisterVar(const String& name)
  575. {
  576. varNames_[name] = name;
  577. }
  578. void Scene::UnregisterVar(const String& name)
  579. {
  580. varNames_.Erase(name);
  581. }
  582. void Scene::UnregisterAllVars()
  583. {
  584. varNames_.Clear();
  585. }
  586. Node* Scene::GetNode(unsigned id) const
  587. {
  588. if (id < FIRST_LOCAL_ID)
  589. {
  590. HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Find(id);
  591. return i != replicatedNodes_.End() ? i->second_ : nullptr;
  592. }
  593. else
  594. {
  595. HashMap<unsigned, Node*>::ConstIterator i = localNodes_.Find(id);
  596. return i != localNodes_.End() ? i->second_ : nullptr;
  597. }
  598. }
  599. bool Scene::GetNodesWithTag(PODVector<Node*>& dest, const String& tag) const
  600. {
  601. dest.Clear();
  602. HashMap<StringHash, PODVector<Node*> >::ConstIterator it = taggedNodes_.Find(tag);
  603. if (it != taggedNodes_.End())
  604. {
  605. dest = it->second_;
  606. return true;
  607. }
  608. else
  609. return false;
  610. }
  611. Component* Scene::GetComponent(unsigned id) const
  612. {
  613. if (id < FIRST_LOCAL_ID)
  614. {
  615. HashMap<unsigned, Component*>::ConstIterator i = replicatedComponents_.Find(id);
  616. return i != replicatedComponents_.End() ? i->second_ : nullptr;
  617. }
  618. else
  619. {
  620. HashMap<unsigned, Component*>::ConstIterator i = localComponents_.Find(id);
  621. return i != localComponents_.End() ? i->second_ : nullptr;
  622. }
  623. }
  624. float Scene::GetAsyncProgress() const
  625. {
  626. return !asyncLoading_ || asyncProgress_.totalNodes_ + asyncProgress_.totalResources_ == 0 ? 1.0f :
  627. (float)(asyncProgress_.loadedNodes_ + asyncProgress_.loadedResources_) /
  628. (float)(asyncProgress_.totalNodes_ + asyncProgress_.totalResources_);
  629. }
  630. const String& Scene::GetVarName(StringHash hash) const
  631. {
  632. HashMap<StringHash, String>::ConstIterator i = varNames_.Find(hash);
  633. return i != varNames_.End() ? i->second_ : String::EMPTY;
  634. }
  635. void Scene::Update(float timeStep)
  636. {
  637. if (asyncLoading_)
  638. {
  639. UpdateAsyncLoading();
  640. // If only preloading resources, scene update can continue
  641. if (asyncProgress_.mode_ > LOAD_RESOURCES_ONLY)
  642. return;
  643. }
  644. URHO3D_PROFILE(UpdateScene);
  645. timeStep *= timeScale_;
  646. using namespace SceneUpdate;
  647. VariantMap& eventData = GetEventDataMap();
  648. eventData[P_SCENE] = this;
  649. eventData[P_TIMESTEP] = timeStep;
  650. // Update variable timestep logic
  651. SendEvent(E_SCENEUPDATE, eventData);
  652. // Update scene attribute animation.
  653. SendEvent(E_ATTRIBUTEANIMATIONUPDATE, eventData);
  654. // Update scene subsystems. If a physics world is present, it will be updated, triggering fixed timestep logic updates
  655. SendEvent(E_SCENESUBSYSTEMUPDATE, eventData);
  656. // Update transform smoothing
  657. {
  658. URHO3D_PROFILE(UpdateSmoothing);
  659. float constant = 1.0f - Clamp(powf(2.0f, -timeStep * smoothingConstant_), 0.0f, 1.0f);
  660. float squaredSnapThreshold = snapThreshold_ * snapThreshold_;
  661. using namespace UpdateSmoothing;
  662. smoothingData_[P_CONSTANT] = constant;
  663. smoothingData_[P_SQUAREDSNAPTHRESHOLD] = squaredSnapThreshold;
  664. SendEvent(E_UPDATESMOOTHING, smoothingData_);
  665. }
  666. // Post-update variable timestep logic
  667. SendEvent(E_SCENEPOSTUPDATE, eventData);
  668. // Note: using a float for elapsed time accumulation is inherently inaccurate. The purpose of this value is
  669. // primarily to update material animation effects, as it is available to shaders. It can be reset by calling
  670. // SetElapsedTime()
  671. elapsedTime_ += timeStep;
  672. }
  673. void Scene::BeginThreadedUpdate()
  674. {
  675. // Check the work queue subsystem whether it actually has created worker threads. If not, do not enter threaded mode.
  676. if (GetSubsystem<WorkQueue>()->GetNumThreads())
  677. threadedUpdate_ = true;
  678. }
  679. void Scene::EndThreadedUpdate()
  680. {
  681. if (!threadedUpdate_)
  682. return;
  683. threadedUpdate_ = false;
  684. if (!delayedDirtyComponents_.Empty())
  685. {
  686. URHO3D_PROFILE(EndThreadedUpdate);
  687. for (PODVector<Component*>::ConstIterator i = delayedDirtyComponents_.Begin(); i != delayedDirtyComponents_.End(); ++i)
  688. (*i)->OnMarkedDirty((*i)->GetNode());
  689. delayedDirtyComponents_.Clear();
  690. }
  691. }
  692. void Scene::DelayedMarkedDirty(Component* component)
  693. {
  694. MutexLock lock(sceneMutex_);
  695. delayedDirtyComponents_.Push(component);
  696. }
  697. unsigned Scene::GetFreeNodeID(CreateMode mode)
  698. {
  699. if (mode == REPLICATED)
  700. {
  701. for (;;)
  702. {
  703. unsigned ret = replicatedNodeID_;
  704. if (replicatedNodeID_ < LAST_REPLICATED_ID)
  705. ++replicatedNodeID_;
  706. else
  707. replicatedNodeID_ = FIRST_REPLICATED_ID;
  708. if (!replicatedNodes_.Contains(ret))
  709. return ret;
  710. }
  711. }
  712. else
  713. {
  714. for (;;)
  715. {
  716. unsigned ret = localNodeID_;
  717. if (localNodeID_ < LAST_LOCAL_ID)
  718. ++localNodeID_;
  719. else
  720. localNodeID_ = FIRST_LOCAL_ID;
  721. if (!localNodes_.Contains(ret))
  722. return ret;
  723. }
  724. }
  725. }
  726. unsigned Scene::GetFreeComponentID(CreateMode mode)
  727. {
  728. if (mode == REPLICATED)
  729. {
  730. for (;;)
  731. {
  732. unsigned ret = replicatedComponentID_;
  733. if (replicatedComponentID_ < LAST_REPLICATED_ID)
  734. ++replicatedComponentID_;
  735. else
  736. replicatedComponentID_ = FIRST_REPLICATED_ID;
  737. if (!replicatedComponents_.Contains(ret))
  738. return ret;
  739. }
  740. }
  741. else
  742. {
  743. for (;;)
  744. {
  745. unsigned ret = localComponentID_;
  746. if (localComponentID_ < LAST_LOCAL_ID)
  747. ++localComponentID_;
  748. else
  749. localComponentID_ = FIRST_LOCAL_ID;
  750. if (!localComponents_.Contains(ret))
  751. return ret;
  752. }
  753. }
  754. }
  755. void Scene::NodeAdded(Node* node)
  756. {
  757. if (!node || node->GetScene() == this)
  758. return;
  759. // Remove from old scene first
  760. Scene* oldScene = node->GetScene();
  761. if (oldScene)
  762. oldScene->NodeRemoved(node);
  763. node->SetScene(this);
  764. // If the new node has an ID of zero (default), assign a replicated ID now
  765. unsigned id = node->GetID();
  766. if (!id)
  767. {
  768. id = GetFreeNodeID(REPLICATED);
  769. node->SetID(id);
  770. }
  771. // If node with same ID exists, remove the scene reference from it and overwrite with the new node
  772. if (id < FIRST_LOCAL_ID)
  773. {
  774. HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Find(id);
  775. if (i != replicatedNodes_.End() && i->second_ != node)
  776. {
  777. URHO3D_LOGWARNING("Overwriting node with ID " + String(id));
  778. NodeRemoved(i->second_);
  779. }
  780. replicatedNodes_[id] = node;
  781. MarkNetworkUpdate(node);
  782. MarkReplicationDirty(node);
  783. }
  784. else
  785. {
  786. HashMap<unsigned, Node*>::Iterator i = localNodes_.Find(id);
  787. if (i != localNodes_.End() && i->second_ != node)
  788. {
  789. URHO3D_LOGWARNING("Overwriting node with ID " + String(id));
  790. NodeRemoved(i->second_);
  791. }
  792. localNodes_[id] = node;
  793. }
  794. // Cache tag if already tagged.
  795. if (!node->GetTags().Empty())
  796. {
  797. const StringVector& tags = node->GetTags();
  798. for (unsigned i = 0; i < tags.Size(); ++i)
  799. taggedNodes_[tags[i]].Push(node);
  800. }
  801. // Add already created components and child nodes now
  802. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  803. for (Vector<SharedPtr<Component> >::ConstIterator i = components.Begin(); i != components.End(); ++i)
  804. ComponentAdded(*i);
  805. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  806. for (Vector<SharedPtr<Node> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  807. NodeAdded(*i);
  808. }
  809. void Scene::NodeTagAdded(Node* node, const String& tag)
  810. {
  811. taggedNodes_[tag].Push(node);
  812. }
  813. void Scene::NodeTagRemoved(Node* node, const String& tag)
  814. {
  815. taggedNodes_[tag].Remove(node);
  816. }
  817. void Scene::NodeRemoved(Node* node)
  818. {
  819. if (!node || node->GetScene() != this)
  820. return;
  821. unsigned id = node->GetID();
  822. if (id < FIRST_LOCAL_ID)
  823. {
  824. replicatedNodes_.Erase(id);
  825. MarkReplicationDirty(node);
  826. }
  827. else
  828. localNodes_.Erase(id);
  829. node->ResetScene();
  830. // Remove node from tag cache
  831. if (!node->GetTags().Empty())
  832. {
  833. const StringVector& tags = node->GetTags();
  834. for (unsigned i = 0; i < tags.Size(); ++i)
  835. taggedNodes_[tags[i]].Remove(node);
  836. }
  837. // Remove components and child nodes as well
  838. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  839. for (Vector<SharedPtr<Component> >::ConstIterator i = components.Begin(); i != components.End(); ++i)
  840. ComponentRemoved(*i);
  841. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  842. for (Vector<SharedPtr<Node> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  843. NodeRemoved(*i);
  844. }
  845. void Scene::ComponentAdded(Component* component)
  846. {
  847. if (!component)
  848. return;
  849. unsigned id = component->GetID();
  850. // If the new component has an ID of zero (default), assign a replicated ID now
  851. if (!id)
  852. {
  853. id = GetFreeComponentID(REPLICATED);
  854. component->SetID(id);
  855. }
  856. if (id < FIRST_LOCAL_ID)
  857. {
  858. HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Find(id);
  859. if (i != replicatedComponents_.End() && i->second_ != component)
  860. {
  861. URHO3D_LOGWARNING("Overwriting component with ID " + String(id));
  862. ComponentRemoved(i->second_);
  863. }
  864. replicatedComponents_[id] = component;
  865. }
  866. else
  867. {
  868. HashMap<unsigned, Component*>::Iterator i = localComponents_.Find(id);
  869. if (i != localComponents_.End() && i->second_ != component)
  870. {
  871. URHO3D_LOGWARNING("Overwriting component with ID " + String(id));
  872. ComponentRemoved(i->second_);
  873. }
  874. localComponents_[id] = component;
  875. }
  876. component->OnSceneSet(this);
  877. }
  878. void Scene::ComponentRemoved(Component* component)
  879. {
  880. if (!component)
  881. return;
  882. unsigned id = component->GetID();
  883. if (id < FIRST_LOCAL_ID)
  884. replicatedComponents_.Erase(id);
  885. else
  886. localComponents_.Erase(id);
  887. component->SetID(0);
  888. component->OnSceneSet(nullptr);
  889. }
  890. void Scene::SetVarNamesAttr(const String& value)
  891. {
  892. Vector<String> varNames = value.Split(';');
  893. varNames_.Clear();
  894. for (Vector<String>::ConstIterator i = varNames.Begin(); i != varNames.End(); ++i)
  895. varNames_[*i] = *i;
  896. }
  897. String Scene::GetVarNamesAttr() const
  898. {
  899. String ret;
  900. if (!varNames_.Empty())
  901. {
  902. for (HashMap<StringHash, String>::ConstIterator i = varNames_.Begin(); i != varNames_.End(); ++i)
  903. ret += i->second_ + ";";
  904. ret.Resize(ret.Length() - 1);
  905. }
  906. return ret;
  907. }
  908. void Scene::PrepareNetworkUpdate()
  909. {
  910. for (HashSet<unsigned>::Iterator i = networkUpdateNodes_.Begin(); i != networkUpdateNodes_.End(); ++i)
  911. {
  912. Node* node = GetNode(*i);
  913. if (node)
  914. node->PrepareNetworkUpdate();
  915. }
  916. for (HashSet<unsigned>::Iterator i = networkUpdateComponents_.Begin(); i != networkUpdateComponents_.End(); ++i)
  917. {
  918. Component* component = GetComponent(*i);
  919. if (component)
  920. component->PrepareNetworkUpdate();
  921. }
  922. networkUpdateNodes_.Clear();
  923. networkUpdateComponents_.Clear();
  924. }
  925. void Scene::CleanupConnection(Connection* connection)
  926. {
  927. Node::CleanupConnection(connection);
  928. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  929. i->second_->CleanupConnection(connection);
  930. for (HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Begin(); i != replicatedComponents_.End(); ++i)
  931. i->second_->CleanupConnection(connection);
  932. }
  933. void Scene::MarkNetworkUpdate(Node* node)
  934. {
  935. if (node)
  936. {
  937. if (!threadedUpdate_)
  938. networkUpdateNodes_.Insert(node->GetID());
  939. else
  940. {
  941. MutexLock lock(sceneMutex_);
  942. networkUpdateNodes_.Insert(node->GetID());
  943. }
  944. }
  945. }
  946. void Scene::MarkNetworkUpdate(Component* component)
  947. {
  948. if (component)
  949. {
  950. if (!threadedUpdate_)
  951. networkUpdateComponents_.Insert(component->GetID());
  952. else
  953. {
  954. MutexLock lock(sceneMutex_);
  955. networkUpdateComponents_.Insert(component->GetID());
  956. }
  957. }
  958. }
  959. void Scene::MarkReplicationDirty(Node* node)
  960. {
  961. unsigned id = node->GetID();
  962. if (id < FIRST_LOCAL_ID && networkState_)
  963. {
  964. for (PODVector<ReplicationState*>::Iterator i = networkState_->replicationStates_.Begin();
  965. i != networkState_->replicationStates_.End(); ++i)
  966. {
  967. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*i);
  968. nodeState->sceneState_->dirtyNodes_.Insert(id);
  969. }
  970. }
  971. }
  972. void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  973. {
  974. if (!updateEnabled_)
  975. return;
  976. using namespace Update;
  977. Update(eventData[P_TIMESTEP].GetFloat());
  978. }
  979. void Scene::HandleResourceBackgroundLoaded(StringHash eventType, VariantMap& eventData)
  980. {
  981. using namespace ResourceBackgroundLoaded;
  982. if (asyncLoading_)
  983. {
  984. Resource* resource = static_cast<Resource*>(eventData[P_RESOURCE].GetPtr());
  985. if (asyncProgress_.resources_.Contains(resource->GetNameHash()))
  986. {
  987. asyncProgress_.resources_.Erase(resource->GetNameHash());
  988. ++asyncProgress_.loadedResources_;
  989. }
  990. }
  991. }
  992. void Scene::UpdateAsyncLoading()
  993. {
  994. URHO3D_PROFILE(UpdateAsyncLoading);
  995. // If resources left to load, do not load nodes yet
  996. if (asyncProgress_.loadedResources_ < asyncProgress_.totalResources_)
  997. return;
  998. HiresTimer asyncLoadTimer;
  999. for (;;)
  1000. {
  1001. if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
  1002. {
  1003. FinishAsyncLoading();
  1004. return;
  1005. }
  1006. // Read one child node with its full sub-hierarchy either from binary, JSON, or XML
  1007. /// \todo Works poorly in scenes where one root-level child node contains all content
  1008. if (asyncProgress_.xmlFile_)
  1009. {
  1010. unsigned nodeID = asyncProgress_.xmlElement_.GetUInt("id");
  1011. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  1012. resolver_.AddNode(nodeID, newNode);
  1013. newNode->LoadXML(asyncProgress_.xmlElement_, resolver_);
  1014. asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNext("node");
  1015. }
  1016. else if (asyncProgress_.jsonFile_) // Load from JSON
  1017. {
  1018. const JSONValue& childValue = asyncProgress_.jsonFile_->GetRoot().Get("children").GetArray().At(asyncProgress_.jsonIndex_);
  1019. unsigned nodeID =childValue.Get("id").GetUInt();
  1020. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  1021. resolver_.AddNode(nodeID, newNode);
  1022. newNode->LoadJSON(childValue, resolver_);
  1023. ++asyncProgress_.jsonIndex_;
  1024. }
  1025. else // Load from binary
  1026. {
  1027. unsigned nodeID = asyncProgress_.file_->ReadUInt();
  1028. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  1029. resolver_.AddNode(nodeID, newNode);
  1030. newNode->Load(*asyncProgress_.file_, resolver_);
  1031. }
  1032. ++asyncProgress_.loadedNodes_;
  1033. // Break if time limit exceeded, so that we keep sufficient FPS
  1034. if (asyncLoadTimer.GetUSec(false) >= asyncLoadingMs_ * 1000)
  1035. break;
  1036. }
  1037. using namespace AsyncLoadProgress;
  1038. VariantMap& eventData = GetEventDataMap();
  1039. eventData[P_SCENE] = this;
  1040. eventData[P_PROGRESS] = GetAsyncProgress();
  1041. eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
  1042. eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
  1043. eventData[P_LOADEDRESOURCES] = asyncProgress_.loadedResources_;
  1044. eventData[P_TOTALRESOURCES] = asyncProgress_.totalResources_;
  1045. SendEvent(E_ASYNCLOADPROGRESS, eventData);
  1046. }
  1047. void Scene::FinishAsyncLoading()
  1048. {
  1049. if (asyncProgress_.mode_ > LOAD_RESOURCES_ONLY)
  1050. {
  1051. resolver_.Resolve();
  1052. ApplyAttributes();
  1053. FinishLoading(asyncProgress_.file_);
  1054. }
  1055. StopAsyncLoading();
  1056. using namespace AsyncLoadFinished;
  1057. VariantMap& eventData = GetEventDataMap();
  1058. eventData[P_SCENE] = this;
  1059. SendEvent(E_ASYNCLOADFINISHED, eventData);
  1060. }
  1061. void Scene::FinishLoading(Deserializer* source)
  1062. {
  1063. if (source)
  1064. {
  1065. fileName_ = source->GetName();
  1066. checksum_ = source->GetChecksum();
  1067. }
  1068. }
  1069. void Scene::FinishSaving(Serializer* dest) const
  1070. {
  1071. Deserializer* ptr = dynamic_cast<Deserializer*>(dest);
  1072. if (ptr)
  1073. {
  1074. fileName_ = ptr->GetName();
  1075. checksum_ = ptr->GetChecksum();
  1076. }
  1077. }
  1078. void Scene::PreloadResources(File* file, bool isSceneFile)
  1079. {
  1080. // If not threaded, can not background load resources, so rather load synchronously later when needed
  1081. #ifdef URHO3D_THREADING
  1082. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1083. // Read node ID (not needed)
  1084. /*unsigned nodeID = */file->ReadUInt();
  1085. // Read Node or Scene attributes; these do not include any resources
  1086. const Vector<AttributeInfo>* attributes = context_->GetAttributes(isSceneFile ? Scene::GetTypeStatic() : Node::GetTypeStatic());
  1087. assert(attributes);
  1088. for (unsigned i = 0; i < attributes->Size(); ++i)
  1089. {
  1090. const AttributeInfo& attr = attributes->At(i);
  1091. if (!(attr.mode_ & AM_FILE))
  1092. continue;
  1093. /*Variant varValue = */file->ReadVariant(attr.type_);
  1094. }
  1095. // Read component attributes
  1096. unsigned numComponents = file->ReadVLE();
  1097. for (unsigned i = 0; i < numComponents; ++i)
  1098. {
  1099. VectorBuffer compBuffer(*file, file->ReadVLE());
  1100. StringHash compType = compBuffer.ReadStringHash();
  1101. // Read component ID (not needed)
  1102. /*unsigned compID = */compBuffer.ReadUInt();
  1103. attributes = context_->GetAttributes(compType);
  1104. if (attributes)
  1105. {
  1106. for (unsigned j = 0; j < attributes->Size(); ++j)
  1107. {
  1108. const AttributeInfo& attr = attributes->At(j);
  1109. if (!(attr.mode_ & AM_FILE))
  1110. continue;
  1111. Variant varValue = compBuffer.ReadVariant(attr.type_);
  1112. if (attr.type_ == VAR_RESOURCEREF)
  1113. {
  1114. const ResourceRef& ref = varValue.GetResourceRef();
  1115. // Sanitate resource name beforehand so that when we get the background load event, the name matches exactly
  1116. String name = cache->SanitateResourceName(ref.name_);
  1117. bool success = cache->BackgroundLoadResource(ref.type_, name);
  1118. if (success)
  1119. {
  1120. ++asyncProgress_.totalResources_;
  1121. asyncProgress_.resources_.Insert(StringHash(name));
  1122. }
  1123. }
  1124. else if (attr.type_ == VAR_RESOURCEREFLIST)
  1125. {
  1126. const ResourceRefList& refList = varValue.GetResourceRefList();
  1127. for (unsigned k = 0; k < refList.names_.Size(); ++k)
  1128. {
  1129. String name = cache->SanitateResourceName(refList.names_[k]);
  1130. bool success = cache->BackgroundLoadResource(refList.type_, name);
  1131. if (success)
  1132. {
  1133. ++asyncProgress_.totalResources_;
  1134. asyncProgress_.resources_.Insert(StringHash(name));
  1135. }
  1136. }
  1137. }
  1138. }
  1139. }
  1140. }
  1141. // Read child nodes
  1142. unsigned numChildren = file->ReadVLE();
  1143. for (unsigned i = 0; i < numChildren; ++i)
  1144. PreloadResources(file, false);
  1145. #endif
  1146. }
  1147. void Scene::PreloadResourcesXML(const XMLElement& element)
  1148. {
  1149. // If not threaded, can not background load resources, so rather load synchronously later when needed
  1150. #ifdef URHO3D_THREADING
  1151. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1152. // Node or Scene attributes do not include any resources; therefore skip to the components
  1153. XMLElement compElem = element.GetChild("component");
  1154. while (compElem)
  1155. {
  1156. String typeName = compElem.GetAttribute("type");
  1157. const Vector<AttributeInfo>* attributes = context_->GetAttributes(StringHash(typeName));
  1158. if (attributes)
  1159. {
  1160. XMLElement attrElem = compElem.GetChild("attribute");
  1161. unsigned startIndex = 0;
  1162. while (attrElem)
  1163. {
  1164. String name = attrElem.GetAttribute("name");
  1165. unsigned i = startIndex;
  1166. unsigned attempts = attributes->Size();
  1167. while (attempts)
  1168. {
  1169. const AttributeInfo& attr = attributes->At(i);
  1170. if ((attr.mode_ & AM_FILE) && !attr.name_.Compare(name, true))
  1171. {
  1172. if (attr.type_ == VAR_RESOURCEREF)
  1173. {
  1174. ResourceRef ref = attrElem.GetVariantValue(attr.type_).GetResourceRef();
  1175. String name = cache->SanitateResourceName(ref.name_);
  1176. bool success = cache->BackgroundLoadResource(ref.type_, name);
  1177. if (success)
  1178. {
  1179. ++asyncProgress_.totalResources_;
  1180. asyncProgress_.resources_.Insert(StringHash(name));
  1181. }
  1182. }
  1183. else if (attr.type_ == VAR_RESOURCEREFLIST)
  1184. {
  1185. ResourceRefList refList = attrElem.GetVariantValue(attr.type_).GetResourceRefList();
  1186. for (unsigned k = 0; k < refList.names_.Size(); ++k)
  1187. {
  1188. String name = cache->SanitateResourceName(refList.names_[k]);
  1189. bool success = cache->BackgroundLoadResource(refList.type_, name);
  1190. if (success)
  1191. {
  1192. ++asyncProgress_.totalResources_;
  1193. asyncProgress_.resources_.Insert(StringHash(name));
  1194. }
  1195. }
  1196. }
  1197. startIndex = (i + 1) % attributes->Size();
  1198. break;
  1199. }
  1200. else
  1201. {
  1202. i = (i + 1) % attributes->Size();
  1203. --attempts;
  1204. }
  1205. }
  1206. attrElem = attrElem.GetNext("attribute");
  1207. }
  1208. }
  1209. compElem = compElem.GetNext("component");
  1210. }
  1211. XMLElement childElem = element.GetChild("node");
  1212. while (childElem)
  1213. {
  1214. PreloadResourcesXML(childElem);
  1215. childElem = childElem.GetNext("node");
  1216. }
  1217. #endif
  1218. }
  1219. void Scene::PreloadResourcesJSON(const JSONValue& value)
  1220. {
  1221. // If not threaded, can not background load resources, so rather load synchronously later when needed
  1222. #ifdef URHO3D_THREADING
  1223. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1224. // Node or Scene attributes do not include any resources; therefore skip to the components
  1225. JSONArray componentArray = value.Get("components").GetArray();
  1226. for (unsigned i = 0; i < componentArray.Size(); i++)
  1227. {
  1228. const JSONValue& compValue = componentArray.At(i);
  1229. String typeName = compValue.Get("type").GetString();
  1230. const Vector<AttributeInfo>* attributes = context_->GetAttributes(StringHash(typeName));
  1231. if (attributes)
  1232. {
  1233. JSONArray attributesArray = compValue.Get("attributes").GetArray();
  1234. unsigned startIndex = 0;
  1235. for (unsigned j = 0; j < attributesArray.Size(); j++)
  1236. {
  1237. const JSONValue& attrVal = attributesArray.At(j);
  1238. String name = attrVal.Get("name").GetString();
  1239. unsigned i = startIndex;
  1240. unsigned attempts = attributes->Size();
  1241. while (attempts)
  1242. {
  1243. const AttributeInfo& attr = attributes->At(i);
  1244. if ((attr.mode_ & AM_FILE) && !attr.name_.Compare(name, true))
  1245. {
  1246. if (attr.type_ == VAR_RESOURCEREF)
  1247. {
  1248. ResourceRef ref = attrVal.Get("value").GetVariantValue(attr.type_).GetResourceRef();
  1249. String name = cache->SanitateResourceName(ref.name_);
  1250. bool success = cache->BackgroundLoadResource(ref.type_, name);
  1251. if (success)
  1252. {
  1253. ++asyncProgress_.totalResources_;
  1254. asyncProgress_.resources_.Insert(StringHash(name));
  1255. }
  1256. }
  1257. else if (attr.type_ == VAR_RESOURCEREFLIST)
  1258. {
  1259. ResourceRefList refList = attrVal.Get("value").GetVariantValue(attr.type_).GetResourceRefList();
  1260. for (unsigned k = 0; k < refList.names_.Size(); ++k)
  1261. {
  1262. String name = cache->SanitateResourceName(refList.names_[k]);
  1263. bool success = cache->BackgroundLoadResource(refList.type_, name);
  1264. if (success)
  1265. {
  1266. ++asyncProgress_.totalResources_;
  1267. asyncProgress_.resources_.Insert(StringHash(name));
  1268. }
  1269. }
  1270. }
  1271. startIndex = (i + 1) % attributes->Size();
  1272. break;
  1273. }
  1274. else
  1275. {
  1276. i = (i + 1) % attributes->Size();
  1277. --attempts;
  1278. }
  1279. }
  1280. }
  1281. }
  1282. }
  1283. JSONArray childrenArray = value.Get("children").GetArray();
  1284. for (unsigned i = 0; i < childrenArray.Size(); i++)
  1285. {
  1286. const JSONValue& childVal = childrenArray.At(i);
  1287. PreloadResourcesJSON(childVal);
  1288. }
  1289. #endif
  1290. }
  1291. void RegisterSceneLibrary(Context* context)
  1292. {
  1293. ValueAnimation::RegisterObject(context);
  1294. ObjectAnimation::RegisterObject(context);
  1295. Node::RegisterObject(context);
  1296. Scene::RegisterObject(context);
  1297. SmoothedTransform::RegisterObject(context);
  1298. UnknownComponent::RegisterObject(context);
  1299. SplinePath::RegisterObject(context);
  1300. }
  1301. }