ScriptInstance.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. //
  2. // Copyright (c) 2008-2020 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. /// \file
  23. #pragma once
  24. #include "../AngelScript/ScriptEventListener.h"
  25. #include "../Scene/Component.h"
  26. class asIScriptFunction;
  27. class asIScriptObject;
  28. class asIScriptContext;
  29. namespace Urho3D
  30. {
  31. class Script;
  32. class ScriptFile;
  33. /// Inbuilt scripted component methods.
  34. enum ScriptInstanceMethod
  35. {
  36. METHOD_START = 0,
  37. METHOD_STOP,
  38. METHOD_DELAYEDSTART,
  39. METHOD_UPDATE,
  40. METHOD_POSTUPDATE,
  41. METHOD_FIXEDUPDATE,
  42. METHOD_FIXEDPOSTUPDATE,
  43. METHOD_LOAD,
  44. METHOD_SAVE,
  45. METHOD_READNETWORKUPDATE,
  46. METHOD_WRITENETWORKUPDATE,
  47. METHOD_APPLYATTRIBUTES,
  48. METHOD_TRANSFORMCHANGED,
  49. MAX_SCRIPT_METHODS
  50. };
  51. /// %Script object component.
  52. class URHO3D_API ScriptInstance : public Component, public ScriptEventListener
  53. {
  54. URHO3D_OBJECT(ScriptInstance, Component);
  55. public:
  56. /// Construct.
  57. explicit ScriptInstance(Context* context);
  58. /// Destruct.
  59. ~ScriptInstance() override;
  60. /// Register object factory.
  61. static void RegisterObject(Context* context);
  62. /// Handle attribute write access.
  63. void OnSetAttribute(const AttributeInfo& attr, const Variant& src) override;
  64. /// Handle attribute read access.
  65. void OnGetAttribute(const AttributeInfo& attr, Variant& dest) const override;
  66. /// Return attribute descriptions, or null if none defined.
  67. const Vector<AttributeInfo>* GetAttributes() const override { return &attributeInfos_; }
  68. /// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
  69. void ApplyAttributes() override;
  70. /// Handle enabled/disabled state change.
  71. void OnSetEnabled() override;
  72. /// Add a scripted event handler.
  73. void AddEventHandler(StringHash eventType, const String& handlerName) override;
  74. /// Add a scripted event handler for a specific sender.
  75. void AddEventHandler(Object* sender, StringHash eventType, const String& handlerName) override;
  76. /// Remove a scripted event handler.
  77. void RemoveEventHandler(StringHash eventType) override;
  78. /// Remove a scripted event handler for a specific sender.
  79. void RemoveEventHandler(Object* sender, StringHash eventType) override;
  80. /// Remove all scripted event handlers for a specific sender.
  81. void RemoveEventHandlers(Object* sender) override;
  82. /// Remove all scripted event handlers.
  83. void RemoveEventHandlers() override;
  84. /// Remove all scripted event handlers, except those listed.
  85. void RemoveEventHandlersExcept(const PODVector<StringHash>& exceptions) override;
  86. /// Return whether has subscribed to an event.
  87. bool HasEventHandler(StringHash eventType) const override;
  88. /// Return whether has subscribed to a specific sender's event.
  89. bool HasEventHandler(Object* sender, StringHash eventType) const override;
  90. /// Create object of certain class from the script file. Return true if successful.
  91. bool CreateObject(ScriptFile* scriptFile, const String& className);
  92. /// Set script file only. Recreate object if necessary.
  93. void SetScriptFile(ScriptFile* scriptFile);
  94. /// Set class name only. Recreate object if necessary.
  95. void SetClassName(const String& className);
  96. /// Query for a method by declaration and execute. Log an error if not found.
  97. bool Execute(const String& declaration, const VariantVector& parameters = Variant::emptyVariantVector);
  98. /// Execute a method.
  99. bool Execute(asIScriptFunction* method, const VariantVector& parameters = Variant::emptyVariantVector);
  100. /// Add a delay-executed method call, optionally repeating.
  101. void DelayedExecute
  102. (float delay, bool repeat, const String& declaration, const VariantVector& parameters = Variant::emptyVariantVector);
  103. /// Clear pending delay-executed method calls. If empty declaration given, clears all.
  104. void ClearDelayedExecute(const String& declaration = String::EMPTY);
  105. /// Return script file.
  106. ScriptFile* GetScriptFile() const { return scriptFile_; }
  107. /// Return script object.
  108. asIScriptObject* GetScriptObject() const { return scriptObject_; }
  109. /// Return class name.
  110. const String& GetClassName() const { return className_; }
  111. /// Check if the object is derived from a class.
  112. bool IsA(const String& className) const;
  113. /// Check if has a method.
  114. bool HasMethod(const String& declaration) const;
  115. /// Set script file attribute.
  116. void SetScriptFileAttr(const ResourceRef& value);
  117. /// Set delayed method calls attribute.
  118. void SetDelayedCallsAttr(const PODVector<unsigned char>& value);
  119. /// Set script file serialization attribute by calling a script function.
  120. void SetScriptDataAttr(const PODVector<unsigned char>& data);
  121. /// Set script network serialization attribute by calling a script function.
  122. void SetScriptNetworkDataAttr(const PODVector<unsigned char>& data);
  123. /// Return script file attribute.
  124. ResourceRef GetScriptFileAttr() const;
  125. /// Return delayed method calls attribute.
  126. PODVector<unsigned char> GetDelayedCallsAttr() const;
  127. /// Get script file serialization attribute by calling a script function.
  128. PODVector<unsigned char> GetScriptDataAttr() const;
  129. /// Get script network serialization attribute by calling a script function.
  130. PODVector<unsigned char> GetScriptNetworkDataAttr() const;
  131. protected:
  132. /// Handle scene being assigned.
  133. void OnSceneSet(Scene* scene) override;
  134. /// Handle node transform being dirtied.
  135. void OnMarkedDirty(Node* node) override;
  136. private:
  137. /// (Re)create the script object and check for supported methods if successfully created.
  138. void CreateObject();
  139. /// Release the script object.
  140. void ReleaseObject();
  141. /// Check for supported script methods.
  142. void GetScriptMethods();
  143. /// Check for script attributes.
  144. void GetScriptAttributes();
  145. /// Store values of script attributes for hot reload.
  146. void StoreScriptAttributes();
  147. /// Restore values of script attributes after hot reload is complete.
  148. void RestoreScriptAttributes();
  149. /// Clear supported script methods.
  150. void ClearScriptMethods();
  151. /// Clear attributes to C++ side attributes only.
  152. void ClearScriptAttributes();
  153. /// Subscribe/unsubscribe from scene updates as necessary.
  154. void UpdateEventSubscription();
  155. /// Handle scene update event.
  156. void HandleSceneUpdate(StringHash eventType, VariantMap& eventData);
  157. /// Handle scene post-update event.
  158. void HandleScenePostUpdate(StringHash eventType, VariantMap& eventData);
  159. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  160. /// Handle physics pre-step event.
  161. void HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData);
  162. /// Handle physics post-step event.
  163. void HandlePhysicsPostStep(StringHash eventType, VariantMap& eventData);
  164. #endif
  165. /// Handle an event in script.
  166. void HandleScriptEvent(StringHash eventType, VariantMap& eventData);
  167. /// Handle script file reload start.
  168. void HandleScriptFileReload(StringHash eventType, VariantMap& eventData);
  169. /// Handle script file reload finished.
  170. void HandleScriptFileReloadFinished(StringHash eventType, VariantMap& eventData);
  171. /// Script file.
  172. WeakPtr<ScriptFile> scriptFile_;
  173. /// Script object.
  174. asIScriptObject* scriptObject_{};
  175. /// Class name.
  176. String className_;
  177. /// Pointers to supported inbuilt methods.
  178. asIScriptFunction* methods_[MAX_SCRIPT_METHODS]{};
  179. /// Delayed method calls.
  180. Vector<DelayedCall> delayedCalls_;
  181. /// Attributes, including script object variables.
  182. Vector<AttributeInfo> attributeInfos_;
  183. /// Storage for unapplied node and component ID attributes.
  184. HashMap<AttributeInfo*, unsigned> idAttributes_;
  185. /// Storage for attributes while script object is being hot-reloaded.
  186. HashMap<String, Variant> storedAttributes_;
  187. /// Subscribed to scene update events flag.
  188. bool subscribed_{};
  189. /// Subscribed to scene post and fixed update events flag.
  190. bool subscribedPostFixed_{};
  191. };
  192. /// Return the active AngelScript context. Provided as a wrapper to the AngelScript API function to avoid undefined symbol error in shared library Urho3D builds.
  193. URHO3D_API asIScriptContext* GetActiveASContext();
  194. /// Return the Urho3D context of the active AngelScript context.
  195. URHO3D_API Context* GetScriptContext();
  196. /// Return the ScriptInstance of the active AngelScript context.
  197. URHO3D_API ScriptInstance* GetScriptContextInstance();
  198. /// Return the scene node of the active AngelScript context.
  199. URHO3D_API Node* GetScriptContextNode();
  200. /// Return the scene of the active AngelScript context.
  201. URHO3D_API Scene* GetScriptContextScene();
  202. /// Return the event listener of the active AngelScript context.
  203. URHO3D_API ScriptEventListener* GetScriptContextEventListener();
  204. /// Return the event listener of the active AngelScript context as an Object pointer.
  205. URHO3D_API Object* GetScriptContextEventListenerObject();
  206. }