Scene.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. #pragma once
  23. #include "../Container/HashSet.h"
  24. #include "../Core/Mutex.h"
  25. #include "../Resource/XMLElement.h"
  26. #include "../Resource/JSONFile.h"
  27. #include "../Scene/Node.h"
  28. #include "../Scene/SceneResolver.h"
  29. namespace Atomic
  30. {
  31. class File;
  32. class PackageFile;
  33. static const unsigned FIRST_REPLICATED_ID = 0x1;
  34. static const unsigned LAST_REPLICATED_ID = 0xffffff;
  35. static const unsigned FIRST_LOCAL_ID = 0x01000000;
  36. static const unsigned LAST_LOCAL_ID = 0xffffffff;
  37. /// Asynchronous scene loading mode.
  38. enum LoadMode
  39. {
  40. /// Preload resources used by a scene or object prefab file, but do not load any scene content.
  41. LOAD_RESOURCES_ONLY = 0,
  42. /// Load scene content without preloading. Resources will be requested synchronously when encountered.
  43. LOAD_SCENE,
  44. /// Default mode: preload resources used by the scene first, then load the scene content.
  45. LOAD_SCENE_AND_RESOURCES
  46. };
  47. /// Asynchronous loading progress of a scene.
  48. struct AsyncProgress
  49. {
  50. /// File for binary mode.
  51. SharedPtr<File> file_;
  52. /// XML file for XML mode.
  53. SharedPtr<XMLFile> xmlFile_;
  54. /// JSON file for JSON mode
  55. SharedPtr<JSONFile> jsonFile_;
  56. /// Current XML element for XML mode.
  57. XMLElement xmlElement_;
  58. /// Current JSON child array and for JSON mode
  59. unsigned jsonIndex_;
  60. /// Current load mode.
  61. LoadMode mode_;
  62. /// Resource name hashes left to load.
  63. HashSet<StringHash> resources_;
  64. /// Loaded resources.
  65. unsigned loadedResources_;
  66. /// Total resources.
  67. unsigned totalResources_;
  68. /// Loaded root-level nodes.
  69. unsigned loadedNodes_;
  70. /// Total root-level nodes.
  71. unsigned totalNodes_;
  72. };
  73. /// Root scene node, represents the whole scene.
  74. class ATOMIC_API Scene : public Node
  75. {
  76. ATOMIC_OBJECT(Scene, Node);
  77. using Node::GetComponent;
  78. using Node::SaveXML;
  79. using Node::SaveJSON;
  80. public:
  81. /// Construct.
  82. Scene(Context* context);
  83. /// Destruct.
  84. virtual ~Scene();
  85. /// Register object factory. Node must be registered first.
  86. static void RegisterObject(Context* context);
  87. /// Load from binary data. Removes all existing child nodes and components first. Return true if successful.
  88. virtual bool Load(Deserializer& source, bool setInstanceDefault = false);
  89. /// Save to binary data. Return true if successful.
  90. virtual bool Save(Serializer& dest) const;
  91. /// Load from XML data. Removes all existing child nodes and components first. Return true if successful.
  92. virtual bool LoadXML(const XMLElement& source, bool setInstanceDefault = false);
  93. /// Load from JSON data. Removes all existing child nodes and components first. Return true if successful.
  94. virtual bool LoadJSON(const JSONValue& source, bool setInstanceDefault = false);
  95. /// Mark for attribute check on the next network update.
  96. virtual void MarkNetworkUpdate();
  97. /// Add a replication state that is tracking this scene.
  98. virtual void AddReplicationState(NodeReplicationState* state);
  99. /// Load from an XML file. Return true if successful.
  100. bool LoadXML(Deserializer& source);
  101. /// Load from a JSON file. Return true if successful.
  102. bool LoadJSON(Deserializer& source);
  103. /// Save to an XML file. Return true if successful.
  104. bool SaveXML(Serializer& dest, const String& indentation = "\t") const;
  105. /// Save to a JSON file. Return true if successful.
  106. bool SaveJSON(Serializer& dest, const String& indentation = "\t") const;
  107. /// Load from a binary file asynchronously. Return true if started successfully. The LOAD_RESOURCES_ONLY mode can also be used to preload resources from object prefab files.
  108. bool LoadAsync(File* file, LoadMode mode = LOAD_SCENE_AND_RESOURCES);
  109. /// Load from an XML file asynchronously. Return true if started successfully. The LOAD_RESOURCES_ONLY mode can also be used to preload resources from object prefab files.
  110. bool LoadAsyncXML(File* file, LoadMode mode = LOAD_SCENE_AND_RESOURCES);
  111. /// Load from a JSON file asynchronously. Return true if started successfully. The LOAD_RESOURCES_ONLY mode can also be used to preload resources from object prefab files.
  112. bool LoadAsyncJSON(File* file, LoadMode mode = LOAD_SCENE_AND_RESOURCES);
  113. /// Stop asynchronous loading.
  114. void StopAsyncLoading();
  115. /// Instantiate scene content from binary data. Return root node if successful.
  116. Node* Instantiate(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode = REPLICATED);
  117. /// Instantiate scene content from XML data. Return root node if successful.
  118. Node* InstantiateXML
  119. (const XMLElement& source, const Vector3& position, const Quaternion& rotation, CreateMode mode = REPLICATED);
  120. /// Instantiate scene content from XML data. Return root node if successful.
  121. Node* InstantiateXML(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode = REPLICATED);
  122. /// Instantiate scene content from JSON data. Return root node if successful.
  123. Node* InstantiateJSON
  124. (const JSONValue& source, const Vector3& position, const Quaternion& rotation, CreateMode mode = REPLICATED);
  125. /// Instantiate scene content from JSON data. Return root node if successful.
  126. Node* InstantiateJSON(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode = REPLICATED);
  127. /// Clear scene completely of either replicated, local or all nodes and components.
  128. void Clear(bool clearReplicated = true, bool clearLocal = true);
  129. /// Enable or disable scene update.
  130. void SetUpdateEnabled(bool enable);
  131. /// Set update time scale. 1.0 = real time (default.)
  132. void SetTimeScale(float scale);
  133. /// Set elapsed time in seconds. This can be used to prevent inaccuracy in the timer if the scene runs for a long time.
  134. void SetElapsedTime(float time);
  135. /// Set network client motion smoothing constant.
  136. void SetSmoothingConstant(float constant);
  137. /// Set network client motion smoothing snap threshold.
  138. void SetSnapThreshold(float threshold);
  139. /// Set maximum milliseconds per frame to spend on async scene loading.
  140. void SetAsyncLoadingMs(int ms);
  141. /// Add a required package file for networking. To be called on the server.
  142. void AddRequiredPackageFile(PackageFile* package);
  143. /// Clear required package files.
  144. void ClearRequiredPackageFiles();
  145. /// Register a node user variable hash reverse mapping (for editing.)
  146. void RegisterVar(const String& name);
  147. /// Unregister a node user variable hash reverse mapping.
  148. void UnregisterVar(const String& name);
  149. /// Clear all registered node user variable hash reverse mappings.
  150. void UnregisterAllVars();
  151. /// Return node from the whole scene by ID, or null if not found.
  152. Node* GetNode(unsigned id) const;
  153. /// Return component from the whole scene by ID, or null if not found.
  154. Component* GetComponent(unsigned id) const;
  155. /// Get nodes with specific tag from the whole scene, return false if empty.
  156. bool GetNodesWithTag(PODVector<Node*>& dest, const String& tag) const;
  157. /// Return whether updates are enabled.
  158. bool IsUpdateEnabled() const { return updateEnabled_; }
  159. /// Return whether an asynchronous loading operation is in progress.
  160. bool IsAsyncLoading() const { return asyncLoading_; }
  161. /// Return asynchronous loading progress between 0.0 and 1.0, or 1.0 if not in progress.
  162. float GetAsyncProgress() const;
  163. /// Return the load mode of the current asynchronous loading operation.
  164. LoadMode GetAsyncLoadMode() const { return asyncProgress_.mode_; }
  165. /// Return source file name.
  166. const String& GetFileName() const { return fileName_; }
  167. /// Return source file checksum.
  168. unsigned GetChecksum() const { return checksum_; }
  169. /// Return update time scale.
  170. float GetTimeScale() const { return timeScale_; }
  171. /// Return elapsed time in seconds.
  172. float GetElapsedTime() const { return elapsedTime_; }
  173. /// Return motion smoothing constant.
  174. float GetSmoothingConstant() const { return smoothingConstant_; }
  175. /// Return motion smoothing snap threshold.
  176. float GetSnapThreshold() const { return snapThreshold_; }
  177. /// Return maximum milliseconds per frame to spend on async loading.
  178. int GetAsyncLoadingMs() const { return asyncLoadingMs_; }
  179. /// Return required package files.
  180. const Vector<SharedPtr<PackageFile> >& GetRequiredPackageFiles() const { return requiredPackageFiles_; }
  181. /// Return a node user variable name, or empty if not registered.
  182. const String& GetVarName(StringHash hash) const;
  183. /// Update scene. Called by HandleUpdate.
  184. void Update(float timeStep);
  185. /// Begin a threaded update. During threaded update components can choose to delay dirty processing.
  186. void BeginThreadedUpdate();
  187. /// End a threaded update. Notify components that marked themselves for delayed dirty processing.
  188. void EndThreadedUpdate();
  189. /// Add a component to the delayed dirty notify queue. Is thread-safe.
  190. void DelayedMarkedDirty(Component* component);
  191. /// Return threaded update flag.
  192. bool IsThreadedUpdate() const { return threadedUpdate_; }
  193. /// Get free node ID, either non-local or local.
  194. unsigned GetFreeNodeID(CreateMode mode);
  195. /// Get free component ID, either non-local or local.
  196. unsigned GetFreeComponentID(CreateMode mode);
  197. /// Cache node by tag if tag not zero, no checking if already added. Used internaly in Node::AddTag.
  198. void NodeTagAdded(Node* node, const String& tag);
  199. /// Cache node by tag if tag not zero.
  200. void NodeTagRemoved(Node* node, const String& tag);
  201. /// Node added. Assign scene pointer and add to ID map.
  202. void NodeAdded(Node* node);
  203. /// Node removed. Remove from ID map.
  204. void NodeRemoved(Node* node);
  205. /// Component added. Add to ID map.
  206. void ComponentAdded(Component* component);
  207. /// Component removed. Remove from ID map.
  208. void ComponentRemoved(Component* component);
  209. /// Set node user variable reverse mappings.
  210. void SetVarNamesAttr(const String& value);
  211. /// Return node user variable reverse mappings.
  212. String GetVarNamesAttr() const;
  213. /// Prepare network update by comparing attributes and marking replication states dirty as necessary.
  214. void PrepareNetworkUpdate();
  215. /// Clean up all references to a network connection that is about to be removed.
  216. void CleanupConnection(Connection* connection);
  217. /// Mark a node for attribute check on the next network update.
  218. void MarkNetworkUpdate(Node* node);
  219. /// Mark a component for attribute check on the next network update.
  220. void MarkNetworkUpdate(Component* component);
  221. /// Mark a node dirty in scene replication states. The node does not need to have own replication state yet.
  222. void MarkReplicationDirty(Node* node);
  223. private:
  224. /// Handle the logic update event to update the scene, if active.
  225. void HandleUpdate(StringHash eventType, VariantMap& eventData);
  226. /// Handle a background loaded resource completing.
  227. void HandleResourceBackgroundLoaded(StringHash eventType, VariantMap& eventData);
  228. /// Update asynchronous loading.
  229. void UpdateAsyncLoading();
  230. /// Finish asynchronous loading.
  231. void FinishAsyncLoading();
  232. /// Finish loading. Sets the scene filename and checksum.
  233. void FinishLoading(Deserializer* source);
  234. /// Finish saving. Sets the scene filename and checksum.
  235. void FinishSaving(Serializer* dest) const;
  236. /// Preload resources from a binary scene or object prefab file.
  237. void PreloadResources(File* file, bool isSceneFile);
  238. /// Preload resources from an XML scene or object prefab file.
  239. void PreloadResourcesXML(const XMLElement& element);
  240. /// Preload resources from a JSON scene or object prefab file.
  241. void PreloadResourcesJSON(const JSONValue& value);
  242. /// Replicated scene nodes by ID.
  243. HashMap<unsigned, Node*> replicatedNodes_;
  244. /// Local scene nodes by ID.
  245. HashMap<unsigned, Node*> localNodes_;
  246. /// Replicated components by ID.
  247. HashMap<unsigned, Component*> replicatedComponents_;
  248. /// Local components by ID.
  249. HashMap<unsigned, Component*> localComponents_;
  250. /// Cached tagged nodes by tag.
  251. HashMap<StringHash, PODVector<Node*> > taggedNodes_;
  252. /// Asynchronous loading progress.
  253. AsyncProgress asyncProgress_;
  254. /// Node and component ID resolver for asynchronous loading.
  255. SceneResolver resolver_;
  256. /// Source file name.
  257. mutable String fileName_;
  258. /// Required package files for networking.
  259. Vector<SharedPtr<PackageFile> > requiredPackageFiles_;
  260. /// Registered node user variable reverse mappings.
  261. HashMap<StringHash, String> varNames_;
  262. /// Nodes to check for attribute changes on the next network update.
  263. HashSet<unsigned> networkUpdateNodes_;
  264. /// Components to check for attribute changes on the next network update.
  265. HashSet<unsigned> networkUpdateComponents_;
  266. /// Delayed dirty notification queue for components.
  267. PODVector<Component*> delayedDirtyComponents_;
  268. /// Mutex for the delayed dirty notification queue.
  269. Mutex sceneMutex_;
  270. /// Preallocated event data map for smoothing update events.
  271. VariantMap smoothingData_;
  272. /// Next free non-local node ID.
  273. unsigned replicatedNodeID_;
  274. /// Next free non-local component ID.
  275. unsigned replicatedComponentID_;
  276. /// Next free local node ID.
  277. unsigned localNodeID_;
  278. /// Next free local component ID.
  279. unsigned localComponentID_;
  280. /// Scene source file checksum.
  281. mutable unsigned checksum_;
  282. /// Maximum milliseconds per frame to spend on async scene loading.
  283. int asyncLoadingMs_;
  284. /// Scene update time scale.
  285. float timeScale_;
  286. /// Elapsed time accumulator.
  287. float elapsedTime_;
  288. /// Motion smoothing constant.
  289. float smoothingConstant_;
  290. /// Motion smoothing snap threshold.
  291. float snapThreshold_;
  292. /// Update enabled flag.
  293. bool updateEnabled_;
  294. /// Asynchronous loading flag.
  295. bool asyncLoading_;
  296. /// Threaded update flag.
  297. bool threadedUpdate_;
  298. };
  299. /// Register Scene library objects.
  300. void ATOMIC_API RegisterSceneLibrary(Context* context);
  301. }