Scene.cpp 47 KB

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