ScriptInstance.h 10 KB

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