ScriptInstance.h 8.9 KB

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