Scene.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  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 "../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(0);
  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(0);
  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->ApplyAttributes();
  446. node->SetTransform(position, rotation);
  447. return node;
  448. }
  449. else
  450. {
  451. node->Remove();
  452. return 0;
  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->ApplyAttributes();
  467. node->SetTransform(position, rotation);
  468. return node;
  469. }
  470. else
  471. {
  472. node->Remove();
  473. return 0;
  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->ApplyAttributes();
  488. node->SetTransform(position, rotation);
  489. return node;
  490. }
  491. else
  492. {
  493. node->Remove();
  494. return 0;
  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 0;
  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 0;
  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_ : 0;
  592. }
  593. else
  594. {
  595. HashMap<unsigned, Node*>::ConstIterator i = localNodes_.Find(id);
  596. return i != localNodes_.End() ? i->second_ : 0;
  597. }
  598. }
  599. Component* Scene::GetComponent(unsigned id) const
  600. {
  601. if (id < FIRST_LOCAL_ID)
  602. {
  603. HashMap<unsigned, Component*>::ConstIterator i = replicatedComponents_.Find(id);
  604. return i != replicatedComponents_.End() ? i->second_ : 0;
  605. }
  606. else
  607. {
  608. HashMap<unsigned, Component*>::ConstIterator i = localComponents_.Find(id);
  609. return i != localComponents_.End() ? i->second_ : 0;
  610. }
  611. }
  612. float Scene::GetAsyncProgress() const
  613. {
  614. return !asyncLoading_ || asyncProgress_.totalNodes_ + asyncProgress_.totalResources_ == 0 ? 1.0f :
  615. (float)(asyncProgress_.loadedNodes_ + asyncProgress_.loadedResources_) /
  616. (float)(asyncProgress_.totalNodes_ + asyncProgress_.totalResources_);
  617. }
  618. const String& Scene::GetVarName(StringHash hash) const
  619. {
  620. HashMap<StringHash, String>::ConstIterator i = varNames_.Find(hash);
  621. return i != varNames_.End() ? i->second_ : String::EMPTY;
  622. }
  623. void Scene::Update(float timeStep)
  624. {
  625. if (asyncLoading_)
  626. {
  627. UpdateAsyncLoading();
  628. // If only preloading resources, scene update can continue
  629. if (asyncProgress_.mode_ > LOAD_RESOURCES_ONLY)
  630. return;
  631. }
  632. URHO3D_PROFILE(UpdateScene);
  633. timeStep *= timeScale_;
  634. using namespace SceneUpdate;
  635. VariantMap& eventData = GetEventDataMap();
  636. eventData[P_SCENE] = this;
  637. eventData[P_TIMESTEP] = timeStep;
  638. // Update variable timestep logic
  639. SendEvent(E_SCENEUPDATE, eventData);
  640. // Update scene attribute animation.
  641. SendEvent(E_ATTRIBUTEANIMATIONUPDATE, eventData);
  642. // Update scene subsystems. If a physics world is present, it will be updated, triggering fixed timestep logic updates
  643. SendEvent(E_SCENESUBSYSTEMUPDATE, eventData);
  644. // Update transform smoothing
  645. {
  646. URHO3D_PROFILE(UpdateSmoothing);
  647. float constant = 1.0f - Clamp(powf(2.0f, -timeStep * smoothingConstant_), 0.0f, 1.0f);
  648. float squaredSnapThreshold = snapThreshold_ * snapThreshold_;
  649. using namespace UpdateSmoothing;
  650. smoothingData_[P_CONSTANT] = constant;
  651. smoothingData_[P_SQUAREDSNAPTHRESHOLD] = squaredSnapThreshold;
  652. SendEvent(E_UPDATESMOOTHING, smoothingData_);
  653. }
  654. // Post-update variable timestep logic
  655. SendEvent(E_SCENEPOSTUPDATE, eventData);
  656. // Note: using a float for elapsed time accumulation is inherently inaccurate. The purpose of this value is
  657. // primarily to update material animation effects, as it is available to shaders. It can be reset by calling
  658. // SetElapsedTime()
  659. elapsedTime_ += timeStep;
  660. }
  661. void Scene::BeginThreadedUpdate()
  662. {
  663. // Check the work queue subsystem whether it actually has created worker threads. If not, do not enter threaded mode.
  664. if (GetSubsystem<WorkQueue>()->GetNumThreads())
  665. threadedUpdate_ = true;
  666. }
  667. void Scene::EndThreadedUpdate()
  668. {
  669. if (!threadedUpdate_)
  670. return;
  671. threadedUpdate_ = false;
  672. if (!delayedDirtyComponents_.Empty())
  673. {
  674. URHO3D_PROFILE(EndThreadedUpdate);
  675. for (PODVector<Component*>::ConstIterator i = delayedDirtyComponents_.Begin(); i != delayedDirtyComponents_.End(); ++i)
  676. (*i)->OnMarkedDirty((*i)->GetNode());
  677. delayedDirtyComponents_.Clear();
  678. }
  679. }
  680. void Scene::DelayedMarkedDirty(Component* component)
  681. {
  682. MutexLock lock(sceneMutex_);
  683. delayedDirtyComponents_.Push(component);
  684. }
  685. unsigned Scene::GetFreeNodeID(CreateMode mode)
  686. {
  687. if (mode == REPLICATED)
  688. {
  689. for (;;)
  690. {
  691. unsigned ret = replicatedNodeID_;
  692. if (replicatedNodeID_ < LAST_REPLICATED_ID)
  693. ++replicatedNodeID_;
  694. else
  695. replicatedNodeID_ = FIRST_REPLICATED_ID;
  696. if (!replicatedNodes_.Contains(ret))
  697. return ret;
  698. }
  699. }
  700. else
  701. {
  702. for (;;)
  703. {
  704. unsigned ret = localNodeID_;
  705. if (localNodeID_ < LAST_LOCAL_ID)
  706. ++localNodeID_;
  707. else
  708. localNodeID_ = FIRST_LOCAL_ID;
  709. if (!localNodes_.Contains(ret))
  710. return ret;
  711. }
  712. }
  713. }
  714. unsigned Scene::GetFreeComponentID(CreateMode mode)
  715. {
  716. if (mode == REPLICATED)
  717. {
  718. for (;;)
  719. {
  720. unsigned ret = replicatedComponentID_;
  721. if (replicatedComponentID_ < LAST_REPLICATED_ID)
  722. ++replicatedComponentID_;
  723. else
  724. replicatedComponentID_ = FIRST_REPLICATED_ID;
  725. if (!replicatedComponents_.Contains(ret))
  726. return ret;
  727. }
  728. }
  729. else
  730. {
  731. for (;;)
  732. {
  733. unsigned ret = localComponentID_;
  734. if (localComponentID_ < LAST_LOCAL_ID)
  735. ++localComponentID_;
  736. else
  737. localComponentID_ = FIRST_LOCAL_ID;
  738. if (!localComponents_.Contains(ret))
  739. return ret;
  740. }
  741. }
  742. }
  743. void Scene::NodeAdded(Node* node)
  744. {
  745. if (!node || node->GetScene() == this)
  746. return;
  747. // Remove from old scene first
  748. Scene* oldScene = node->GetScene();
  749. if (oldScene)
  750. oldScene->NodeRemoved(node);
  751. node->SetScene(this);
  752. // If the new node has an ID of zero (default), assign a replicated ID now
  753. unsigned id = node->GetID();
  754. if (!id)
  755. {
  756. id = GetFreeNodeID(REPLICATED);
  757. node->SetID(id);
  758. }
  759. // If node with same ID exists, remove the scene reference from it and overwrite with the new node
  760. if (id < FIRST_LOCAL_ID)
  761. {
  762. HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Find(id);
  763. if (i != replicatedNodes_.End() && i->second_ != node)
  764. {
  765. URHO3D_LOGWARNING("Overwriting node with ID " + String(id));
  766. NodeRemoved(i->second_);
  767. }
  768. replicatedNodes_[id] = node;
  769. MarkNetworkUpdate(node);
  770. MarkReplicationDirty(node);
  771. }
  772. else
  773. {
  774. HashMap<unsigned, Node*>::Iterator i = localNodes_.Find(id);
  775. if (i != localNodes_.End() && i->second_ != node)
  776. {
  777. URHO3D_LOGWARNING("Overwriting node with ID " + String(id));
  778. NodeRemoved(i->second_);
  779. }
  780. localNodes_[id] = node;
  781. }
  782. // Add already created components and child nodes now
  783. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  784. for (Vector<SharedPtr<Component> >::ConstIterator i = components.Begin(); i != components.End(); ++i)
  785. ComponentAdded(*i);
  786. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  787. for (Vector<SharedPtr<Node> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  788. NodeAdded(*i);
  789. }
  790. void Scene::NodeRemoved(Node* node)
  791. {
  792. if (!node || node->GetScene() != this)
  793. return;
  794. unsigned id = node->GetID();
  795. if (id < FIRST_LOCAL_ID)
  796. {
  797. replicatedNodes_.Erase(id);
  798. MarkReplicationDirty(node);
  799. }
  800. else
  801. localNodes_.Erase(id);
  802. node->ResetScene();
  803. // Remove components and child nodes as well
  804. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  805. for (Vector<SharedPtr<Component> >::ConstIterator i = components.Begin(); i != components.End(); ++i)
  806. ComponentRemoved(*i);
  807. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  808. for (Vector<SharedPtr<Node> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  809. NodeRemoved(*i);
  810. }
  811. void Scene::ComponentAdded(Component* component)
  812. {
  813. if (!component)
  814. return;
  815. unsigned id = component->GetID();
  816. // If the new component has an ID of zero (default), assign a replicated ID now
  817. if (!id)
  818. {
  819. id = GetFreeComponentID(REPLICATED);
  820. component->SetID(id);
  821. }
  822. if (id < FIRST_LOCAL_ID)
  823. {
  824. HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Find(id);
  825. if (i != replicatedComponents_.End() && i->second_ != component)
  826. {
  827. URHO3D_LOGWARNING("Overwriting component with ID " + String(id));
  828. ComponentRemoved(i->second_);
  829. }
  830. replicatedComponents_[id] = component;
  831. }
  832. else
  833. {
  834. HashMap<unsigned, Component*>::Iterator i = localComponents_.Find(id);
  835. if (i != localComponents_.End() && i->second_ != component)
  836. {
  837. URHO3D_LOGWARNING("Overwriting component with ID " + String(id));
  838. ComponentRemoved(i->second_);
  839. }
  840. localComponents_[id] = component;
  841. }
  842. component->OnSceneSet(this);
  843. }
  844. void Scene::ComponentRemoved(Component* component)
  845. {
  846. if (!component)
  847. return;
  848. unsigned id = component->GetID();
  849. if (id < FIRST_LOCAL_ID)
  850. replicatedComponents_.Erase(id);
  851. else
  852. localComponents_.Erase(id);
  853. component->SetID(0);
  854. component->OnSceneSet(0);
  855. }
  856. void Scene::SetVarNamesAttr(const String& value)
  857. {
  858. Vector<String> varNames = value.Split(';');
  859. varNames_.Clear();
  860. for (Vector<String>::ConstIterator i = varNames.Begin(); i != varNames.End(); ++i)
  861. varNames_[*i] = *i;
  862. }
  863. String Scene::GetVarNamesAttr() const
  864. {
  865. String ret;
  866. if (!varNames_.Empty())
  867. {
  868. for (HashMap<StringHash, String>::ConstIterator i = varNames_.Begin(); i != varNames_.End(); ++i)
  869. ret += i->second_ + ';';
  870. ret.Resize(ret.Length() - 1);
  871. }
  872. return ret;
  873. }
  874. void Scene::PrepareNetworkUpdate()
  875. {
  876. for (HashSet<unsigned>::Iterator i = networkUpdateNodes_.Begin(); i != networkUpdateNodes_.End(); ++i)
  877. {
  878. Node* node = GetNode(*i);
  879. if (node)
  880. node->PrepareNetworkUpdate();
  881. }
  882. for (HashSet<unsigned>::Iterator i = networkUpdateComponents_.Begin(); i != networkUpdateComponents_.End(); ++i)
  883. {
  884. Component* component = GetComponent(*i);
  885. if (component)
  886. component->PrepareNetworkUpdate();
  887. }
  888. networkUpdateNodes_.Clear();
  889. networkUpdateComponents_.Clear();
  890. }
  891. void Scene::CleanupConnection(Connection* connection)
  892. {
  893. Node::CleanupConnection(connection);
  894. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  895. i->second_->CleanupConnection(connection);
  896. for (HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Begin(); i != replicatedComponents_.End(); ++i)
  897. i->second_->CleanupConnection(connection);
  898. }
  899. void Scene::MarkNetworkUpdate(Node* node)
  900. {
  901. if (node)
  902. {
  903. if (!threadedUpdate_)
  904. networkUpdateNodes_.Insert(node->GetID());
  905. else
  906. {
  907. MutexLock lock(sceneMutex_);
  908. networkUpdateNodes_.Insert(node->GetID());
  909. }
  910. }
  911. }
  912. void Scene::MarkNetworkUpdate(Component* component)
  913. {
  914. if (component)
  915. {
  916. if (!threadedUpdate_)
  917. networkUpdateComponents_.Insert(component->GetID());
  918. else
  919. {
  920. MutexLock lock(sceneMutex_);
  921. networkUpdateComponents_.Insert(component->GetID());
  922. }
  923. }
  924. }
  925. void Scene::MarkReplicationDirty(Node* node)
  926. {
  927. unsigned id = node->GetID();
  928. if (id < FIRST_LOCAL_ID && networkState_)
  929. {
  930. for (PODVector<ReplicationState*>::Iterator i = networkState_->replicationStates_.Begin();
  931. i != networkState_->replicationStates_.End(); ++i)
  932. {
  933. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*i);
  934. nodeState->sceneState_->dirtyNodes_.Insert(id);
  935. }
  936. }
  937. }
  938. void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  939. {
  940. if (!updateEnabled_)
  941. return;
  942. using namespace Update;
  943. Update(eventData[P_TIMESTEP].GetFloat());
  944. }
  945. void Scene::HandleResourceBackgroundLoaded(StringHash eventType, VariantMap& eventData)
  946. {
  947. using namespace ResourceBackgroundLoaded;
  948. if (asyncLoading_)
  949. {
  950. Resource* resource = static_cast<Resource*>(eventData[P_RESOURCE].GetPtr());
  951. if (asyncProgress_.resources_.Contains(resource->GetNameHash()))
  952. {
  953. asyncProgress_.resources_.Erase(resource->GetNameHash());
  954. ++asyncProgress_.loadedResources_;
  955. }
  956. }
  957. }
  958. void Scene::UpdateAsyncLoading()
  959. {
  960. URHO3D_PROFILE(UpdateAsyncLoading);
  961. // If resources left to load, do not load nodes yet
  962. if (asyncProgress_.loadedResources_ < asyncProgress_.totalResources_)
  963. return;
  964. HiresTimer asyncLoadTimer;
  965. for (;;)
  966. {
  967. if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
  968. {
  969. FinishAsyncLoading();
  970. return;
  971. }
  972. // Read one child node with its full sub-hierarchy either from binary, JSON, or XML
  973. /// \todo Works poorly in scenes where one root-level child node contains all content
  974. if (asyncProgress_.xmlFile_)
  975. {
  976. unsigned nodeID = asyncProgress_.xmlElement_.GetUInt("id");
  977. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  978. resolver_.AddNode(nodeID, newNode);
  979. newNode->LoadXML(asyncProgress_.xmlElement_, resolver_);
  980. asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNext("node");
  981. }
  982. else if (asyncProgress_.jsonFile_) // Load from JSON
  983. {
  984. const JSONValue& childValue = asyncProgress_.jsonFile_->GetRoot().Get("children").GetArray().At(asyncProgress_.jsonIndex_);
  985. unsigned nodeID =childValue.Get("id").GetUInt();
  986. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  987. resolver_.AddNode(nodeID, newNode);
  988. newNode->LoadJSON(childValue, resolver_);
  989. ++asyncProgress_.jsonIndex_;
  990. }
  991. else // Load from binary
  992. {
  993. unsigned nodeID = asyncProgress_.file_->ReadUInt();
  994. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  995. resolver_.AddNode(nodeID, newNode);
  996. newNode->Load(*asyncProgress_.file_, resolver_);
  997. }
  998. ++asyncProgress_.loadedNodes_;
  999. // Break if time limit exceeded, so that we keep sufficient FPS
  1000. if (asyncLoadTimer.GetUSec(false) >= asyncLoadingMs_ * 1000)
  1001. break;
  1002. }
  1003. using namespace AsyncLoadProgress;
  1004. VariantMap& eventData = GetEventDataMap();
  1005. eventData[P_SCENE] = this;
  1006. eventData[P_PROGRESS] = GetAsyncProgress();
  1007. eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
  1008. eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
  1009. eventData[P_LOADEDRESOURCES] = asyncProgress_.loadedResources_;
  1010. eventData[P_TOTALRESOURCES] = asyncProgress_.totalResources_;
  1011. SendEvent(E_ASYNCLOADPROGRESS, eventData);
  1012. }
  1013. void Scene::FinishAsyncLoading()
  1014. {
  1015. if (asyncProgress_.mode_ > LOAD_RESOURCES_ONLY)
  1016. {
  1017. resolver_.Resolve();
  1018. ApplyAttributes();
  1019. FinishLoading(asyncProgress_.file_);
  1020. }
  1021. StopAsyncLoading();
  1022. using namespace AsyncLoadFinished;
  1023. VariantMap& eventData = GetEventDataMap();
  1024. eventData[P_SCENE] = this;
  1025. SendEvent(E_ASYNCLOADFINISHED, eventData);
  1026. }
  1027. void Scene::FinishLoading(Deserializer* source)
  1028. {
  1029. if (source)
  1030. {
  1031. fileName_ = source->GetName();
  1032. checksum_ = source->GetChecksum();
  1033. }
  1034. }
  1035. void Scene::FinishSaving(Serializer* dest) const
  1036. {
  1037. Deserializer* ptr = dynamic_cast<Deserializer*>(dest);
  1038. if (ptr)
  1039. {
  1040. fileName_ = ptr->GetName();
  1041. checksum_ = ptr->GetChecksum();
  1042. }
  1043. }
  1044. void Scene::PreloadResources(File* file, bool isSceneFile)
  1045. {
  1046. // If not threaded, can not background load resources, so rather load synchronously later when needed
  1047. #ifdef URHO3D_THREADING
  1048. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1049. // Read node ID (not needed)
  1050. /*unsigned nodeID = */file->ReadUInt();
  1051. // Read Node or Scene attributes; these do not include any resources
  1052. const Vector<AttributeInfo>* attributes = context_->GetAttributes(isSceneFile ? Scene::GetTypeStatic() : Node::GetTypeStatic());
  1053. assert(attributes);
  1054. for (unsigned i = 0; i < attributes->Size(); ++i)
  1055. {
  1056. const AttributeInfo& attr = attributes->At(i);
  1057. if (!(attr.mode_ & AM_FILE))
  1058. continue;
  1059. /*Variant varValue = */file->ReadVariant(attr.type_);
  1060. }
  1061. // Read component attributes
  1062. unsigned numComponents = file->ReadVLE();
  1063. for (unsigned i = 0; i < numComponents; ++i)
  1064. {
  1065. VectorBuffer compBuffer(*file, file->ReadVLE());
  1066. StringHash compType = compBuffer.ReadStringHash();
  1067. // Read component ID (not needed)
  1068. /*unsigned compID = */compBuffer.ReadUInt();
  1069. attributes = context_->GetAttributes(compType);
  1070. if (attributes)
  1071. {
  1072. for (unsigned j = 0; j < attributes->Size(); ++j)
  1073. {
  1074. const AttributeInfo& attr = attributes->At(j);
  1075. if (!(attr.mode_ & AM_FILE))
  1076. continue;
  1077. Variant varValue = compBuffer.ReadVariant(attr.type_);
  1078. if (attr.type_ == VAR_RESOURCEREF)
  1079. {
  1080. const ResourceRef& ref = varValue.GetResourceRef();
  1081. // Sanitate resource name beforehand so that when we get the background load event, the name matches exactly
  1082. String name = cache->SanitateResourceName(ref.name_);
  1083. bool success = cache->BackgroundLoadResource(ref.type_, name);
  1084. if (success)
  1085. {
  1086. ++asyncProgress_.totalResources_;
  1087. asyncProgress_.resources_.Insert(StringHash(name));
  1088. }
  1089. }
  1090. else if (attr.type_ == VAR_RESOURCEREFLIST)
  1091. {
  1092. const ResourceRefList& refList = varValue.GetResourceRefList();
  1093. for (unsigned k = 0; k < refList.names_.Size(); ++k)
  1094. {
  1095. String name = cache->SanitateResourceName(refList.names_[k]);
  1096. bool success = cache->BackgroundLoadResource(refList.type_, name);
  1097. if (success)
  1098. {
  1099. ++asyncProgress_.totalResources_;
  1100. asyncProgress_.resources_.Insert(StringHash(name));
  1101. }
  1102. }
  1103. }
  1104. }
  1105. }
  1106. }
  1107. // Read child nodes
  1108. unsigned numChildren = file->ReadVLE();
  1109. for (unsigned i = 0; i < numChildren; ++i)
  1110. PreloadResources(file, false);
  1111. #endif
  1112. }
  1113. void Scene::PreloadResourcesXML(const XMLElement& element)
  1114. {
  1115. // If not threaded, can not background load resources, so rather load synchronously later when needed
  1116. #ifdef URHO3D_THREADING
  1117. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1118. // Node or Scene attributes do not include any resources; therefore skip to the components
  1119. XMLElement compElem = element.GetChild("component");
  1120. while (compElem)
  1121. {
  1122. String typeName = compElem.GetAttribute("type");
  1123. const Vector<AttributeInfo>* attributes = context_->GetAttributes(StringHash(typeName));
  1124. if (attributes)
  1125. {
  1126. XMLElement attrElem = compElem.GetChild("attribute");
  1127. unsigned startIndex = 0;
  1128. while (attrElem)
  1129. {
  1130. String name = attrElem.GetAttribute("name");
  1131. unsigned i = startIndex;
  1132. unsigned attempts = attributes->Size();
  1133. while (attempts)
  1134. {
  1135. const AttributeInfo& attr = attributes->At(i);
  1136. if ((attr.mode_ & AM_FILE) && !attr.name_.Compare(name, true))
  1137. {
  1138. if (attr.type_ == VAR_RESOURCEREF)
  1139. {
  1140. ResourceRef ref = attrElem.GetVariantValue(attr.type_).GetResourceRef();
  1141. String name = cache->SanitateResourceName(ref.name_);
  1142. bool success = cache->BackgroundLoadResource(ref.type_, name);
  1143. if (success)
  1144. {
  1145. ++asyncProgress_.totalResources_;
  1146. asyncProgress_.resources_.Insert(StringHash(name));
  1147. }
  1148. }
  1149. else if (attr.type_ == VAR_RESOURCEREFLIST)
  1150. {
  1151. ResourceRefList refList = attrElem.GetVariantValue(attr.type_).GetResourceRefList();
  1152. for (unsigned k = 0; k < refList.names_.Size(); ++k)
  1153. {
  1154. String name = cache->SanitateResourceName(refList.names_[k]);
  1155. bool success = cache->BackgroundLoadResource(refList.type_, name);
  1156. if (success)
  1157. {
  1158. ++asyncProgress_.totalResources_;
  1159. asyncProgress_.resources_.Insert(StringHash(name));
  1160. }
  1161. }
  1162. }
  1163. startIndex = (i + 1) % attributes->Size();
  1164. break;
  1165. }
  1166. else
  1167. {
  1168. i = (i + 1) % attributes->Size();
  1169. --attempts;
  1170. }
  1171. }
  1172. attrElem = attrElem.GetNext("attribute");
  1173. }
  1174. }
  1175. compElem = compElem.GetNext("component");
  1176. }
  1177. XMLElement childElem = element.GetChild("node");
  1178. while (childElem)
  1179. {
  1180. PreloadResourcesXML(childElem);
  1181. childElem = childElem.GetNext("node");
  1182. }
  1183. #endif
  1184. }
  1185. void Scene::PreloadResourcesJSON(const JSONValue& value)
  1186. {
  1187. // If not threaded, can not background load resources, so rather load synchronously later when needed
  1188. #ifdef URHO3D_THREADING
  1189. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1190. // Node or Scene attributes do not include any resources; therefore skip to the components
  1191. JSONArray componentArray = value.Get("components").GetArray();
  1192. for (unsigned i = 0; i < componentArray.Size(); i++)
  1193. {
  1194. const JSONValue& compValue = componentArray.At(i);
  1195. String typeName = compValue.Get("type").GetString();
  1196. const Vector<AttributeInfo>* attributes = context_->GetAttributes(StringHash(typeName));
  1197. if (attributes)
  1198. {
  1199. JSONArray attributesArray = compValue.Get("attributes").GetArray();
  1200. unsigned startIndex = 0;
  1201. for (unsigned j = 0; j < attributesArray.Size(); j++)
  1202. {
  1203. const JSONValue& attrVal = attributesArray.At(j);
  1204. String name = attrVal.Get("name").GetString();
  1205. unsigned i = startIndex;
  1206. unsigned attempts = attributes->Size();
  1207. while (attempts)
  1208. {
  1209. const AttributeInfo& attr = attributes->At(i);
  1210. if ((attr.mode_ & AM_FILE) && !attr.name_.Compare(name, true))
  1211. {
  1212. if (attr.type_ == VAR_RESOURCEREF)
  1213. {
  1214. ResourceRef ref = attrVal.Get("value").GetVariantValue(attr.type_).GetResourceRef();
  1215. String name = cache->SanitateResourceName(ref.name_);
  1216. bool success = cache->BackgroundLoadResource(ref.type_, name);
  1217. if (success)
  1218. {
  1219. ++asyncProgress_.totalResources_;
  1220. asyncProgress_.resources_.Insert(StringHash(name));
  1221. }
  1222. }
  1223. else if (attr.type_ == VAR_RESOURCEREFLIST)
  1224. {
  1225. ResourceRefList refList = attrVal.Get("value").GetVariantValue(attr.type_).GetResourceRefList();
  1226. for (unsigned k = 0; k < refList.names_.Size(); ++k)
  1227. {
  1228. String name = cache->SanitateResourceName(refList.names_[k]);
  1229. bool success = cache->BackgroundLoadResource(refList.type_, name);
  1230. if (success)
  1231. {
  1232. ++asyncProgress_.totalResources_;
  1233. asyncProgress_.resources_.Insert(StringHash(name));
  1234. }
  1235. }
  1236. }
  1237. startIndex = (i + 1) % attributes->Size();
  1238. break;
  1239. }
  1240. else
  1241. {
  1242. i = (i + 1) % attributes->Size();
  1243. --attempts;
  1244. }
  1245. }
  1246. }
  1247. }
  1248. }
  1249. JSONArray childrenArray = value.Get("children").GetArray();
  1250. for (unsigned i = 0; i < childrenArray.Size(); i++)
  1251. {
  1252. const JSONValue& childVal = childrenArray.At(i);
  1253. PreloadResourcesJSON(childVal);
  1254. }
  1255. #endif
  1256. }
  1257. void RegisterSceneLibrary(Context* context)
  1258. {
  1259. ValueAnimation::RegisterObject(context);
  1260. ObjectAnimation::RegisterObject(context);
  1261. Node::RegisterObject(context);
  1262. Scene::RegisterObject(context);
  1263. SmoothedTransform::RegisterObject(context);
  1264. UnknownComponent::RegisterObject(context);
  1265. SplinePath::RegisterObject(context);
  1266. }
  1267. }