Scene.cpp 44 KB

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