JSComponent.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. //
  2. // Copyright (c) 2008-2014 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. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  23. // Please see LICENSE.md in repository root for license information
  24. // https://github.com/AtomicGameEngine/AtomicGameEngine
  25. #include <Atomic/IO/Log.h>
  26. #include <Atomic/IO/FileSystem.h>
  27. #include <Atomic/Core/Context.h>
  28. #include <Atomic/Resource/ResourceCache.h>
  29. #ifdef ATOMIC_PHYSICS
  30. #include <Atomic/Physics/PhysicsEvents.h>
  31. #include <Atomic/Physics/PhysicsWorld.h>
  32. #endif
  33. #include <Atomic/Scene/Scene.h>
  34. #include <Atomic/Scene/SceneEvents.h>
  35. #include "JSVM.h"
  36. #include "JSComponentFile.h"
  37. #include "JSComponent.h"
  38. namespace Atomic
  39. {
  40. extern const char* LOGIC_CATEGORY;
  41. class JSComponentFactory : public ObjectFactory
  42. {
  43. public:
  44. /// Construct.
  45. JSComponentFactory(Context* context) :
  46. ObjectFactory(context)
  47. {
  48. type_ = JSComponent::GetTypeStatic();
  49. baseType_ = JSComponent::GetBaseTypeStatic();
  50. typeName_ = JSComponent::GetTypeNameStatic();
  51. }
  52. /// Create an object of the specific type.
  53. SharedPtr<Object> CreateObject()
  54. {
  55. SharedPtr<Object> ptr;
  56. Variant& v = context_->GetVar("__JSComponent_ComponentFile");
  57. // __JSComponent_ComponentFile will only be set when coming from XML
  58. // in player builds, not in editor
  59. if (v.GetType() == VAR_STRING)
  60. {
  61. String componentRef = v.GetString();
  62. // clear it, in case we end up recursively creating components
  63. context_->GetVars()["__JSComponent_ComponentFile"] = Variant::EMPTY;
  64. Vector<String> split = componentRef.Split(';');
  65. if (split.Size() == 2)
  66. {
  67. ResourceCache* cache = context_->GetSubsystem<ResourceCache>();
  68. JSComponentFile* componentFile = cache->GetResource<JSComponentFile>(split[1]);
  69. if (componentFile)
  70. {
  71. ptr = componentFile->CreateJSComponent();
  72. }
  73. }
  74. }
  75. if (ptr.Null())
  76. {
  77. ptr = new JSComponent(context_);
  78. }
  79. return ptr;
  80. }
  81. };
  82. JSComponent::JSComponent(Context* context) :
  83. Component(context),
  84. updateEventMask_(USE_UPDATE | USE_POSTUPDATE | USE_FIXEDUPDATE | USE_FIXEDPOSTUPDATE),
  85. currentEventMask_(0),
  86. started_(false),
  87. destroyed_(false),
  88. scriptClassInstance_(false),
  89. delayedStartCalled_(false),
  90. loading_(false)
  91. {
  92. vm_ = JSVM::GetJSVM(NULL);
  93. }
  94. JSComponent::~JSComponent()
  95. {
  96. }
  97. void JSComponent::RegisterObject(Context* context)
  98. {
  99. context->RegisterFactory(new JSComponentFactory(context), LOGIC_CATEGORY);
  100. ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  101. ATTRIBUTE("FieldValues", VariantMap, fieldValues_, Variant::emptyVariantMap, AM_FILE);
  102. MIXED_ACCESSOR_ATTRIBUTE("ComponentFile", GetScriptAttr, SetScriptAttr, ResourceRef, ResourceRef(JSComponentFile::GetTypeStatic()), AM_DEFAULT);
  103. }
  104. void JSComponent::OnSetEnabled()
  105. {
  106. UpdateEventSubscription();
  107. }
  108. void JSComponent::SetUpdateEventMask(unsigned char mask)
  109. {
  110. if (updateEventMask_ != mask)
  111. {
  112. updateEventMask_ = mask;
  113. UpdateEventSubscription();
  114. }
  115. }
  116. void JSComponent::UpdateReferences(bool remove)
  117. {
  118. duk_context* ctx = vm_->GetJSContext();
  119. int top = duk_get_top(ctx);
  120. duk_push_global_stash(ctx);
  121. duk_get_prop_index(ctx, -1, JS_GLOBALSTASH_INDEX_NODE_REGISTRY);
  122. // can't use instance as key, as this coerces to [Object] for
  123. // string property, pointer will be string representation of
  124. // address, so, unique key
  125. if (node_)
  126. {
  127. duk_push_pointer(ctx, (void*) node_);
  128. if (remove)
  129. duk_push_undefined(ctx);
  130. else
  131. js_push_class_object_instance(ctx, node_);
  132. duk_put_prop(ctx, -3);
  133. }
  134. duk_push_pointer(ctx, (void*) this);
  135. if (remove)
  136. duk_push_undefined(ctx);
  137. else
  138. js_push_class_object_instance(ctx, this);
  139. duk_put_prop(ctx, -3);
  140. duk_pop_2(ctx);
  141. assert(duk_get_top(ctx) == top);
  142. }
  143. void JSComponent::ApplyAttributes()
  144. {
  145. if (!started_)
  146. InitInstance();
  147. }
  148. void JSComponent::InitInstance(bool hasArgs, int argIdx)
  149. {
  150. if (context_->GetEditorContext() || componentFile_.Null())
  151. return;
  152. duk_context* ctx = vm_->GetJSContext();
  153. duk_idx_t top = duk_get_top(ctx);
  154. // store, so pop doesn't clear
  155. UpdateReferences();
  156. // apply fields
  157. const HashMap<String, VariantType>& fields = componentFile_->GetFields();
  158. if (fields.Size())
  159. {
  160. // push self
  161. js_push_class_object_instance(ctx, this, "JSComponent");
  162. HashMap<String, VariantType>::ConstIterator itr = fields.Begin();
  163. while (itr != fields.End())
  164. {
  165. if (fieldValues_.Contains(itr->first_))
  166. {
  167. Variant& v = fieldValues_[itr->first_];
  168. if (v.GetType() == itr->second_)
  169. {
  170. js_push_variant(ctx, v);
  171. duk_put_prop_string(ctx, -2, itr->first_.CString());
  172. }
  173. }
  174. else
  175. {
  176. Variant v;
  177. componentFile_->GetDefaultFieldValue(itr->first_, v);
  178. js_push_variant(ctx, v);
  179. duk_put_prop_string(ctx, -2, itr->first_.CString());
  180. }
  181. itr++;
  182. }
  183. // pop self
  184. duk_pop(ctx);
  185. }
  186. // apply args if any
  187. if (hasArgs)
  188. {
  189. // push self
  190. js_push_class_object_instance(ctx, this, "JSComponent");
  191. duk_enum(ctx, argIdx, DUK_ENUM_OWN_PROPERTIES_ONLY);
  192. while (duk_next(ctx, -1, 1)) {
  193. duk_put_prop(ctx, -4);
  194. }
  195. // pop self and enum object
  196. duk_pop_2(ctx);
  197. }
  198. if (!componentFile_->GetScriptClass())
  199. {
  200. componentFile_->PushModule();
  201. if (!duk_is_function(ctx, -1))
  202. {
  203. duk_set_top(ctx, top);
  204. return;
  205. }
  206. // call with self
  207. js_push_class_object_instance(ctx, this, "JSComponent");
  208. if (duk_pcall(ctx, 1) != 0)
  209. {
  210. vm_->SendJSErrorEvent();
  211. duk_set_top(ctx, top);
  212. return;
  213. }
  214. }
  215. duk_set_top(ctx, top);
  216. if (!started_)
  217. {
  218. started_ = true;
  219. Start();
  220. }
  221. }
  222. void JSComponent::CallScriptMethod(const String& name, bool passValue, float value)
  223. {
  224. void* heapptr = JSGetHeapPtr();
  225. if (!heapptr)
  226. return;
  227. duk_context* ctx = vm_->GetJSContext();
  228. duk_idx_t top = duk_get_top(ctx);
  229. duk_push_heapptr(ctx, heapptr);
  230. duk_get_prop_string(ctx, -1, name.CString());
  231. if (!duk_is_function(ctx, -1))
  232. {
  233. duk_set_top(ctx, top);
  234. return;
  235. }
  236. // push this
  237. if (scriptClassInstance_)
  238. duk_push_heapptr(ctx, heapptr);
  239. if (passValue)
  240. duk_push_number(ctx, value);
  241. int status = scriptClassInstance_ ? duk_pcall_method(ctx, passValue ? 1 : 0) : duk_pcall(ctx, passValue ? 1 : 0);
  242. if (status != 0)
  243. {
  244. vm_->SendJSErrorEvent();
  245. duk_set_top(ctx, top);
  246. return;
  247. }
  248. duk_set_top(ctx, top);
  249. }
  250. void JSComponent::Start()
  251. {
  252. static String name = "start";
  253. CallScriptMethod(name);
  254. }
  255. void JSComponent::DelayedStart()
  256. {
  257. static String name = "delayedStart";
  258. CallScriptMethod(name);
  259. }
  260. void JSComponent::Update(float timeStep)
  261. {
  262. static String name = "update";
  263. CallScriptMethod(name, true, timeStep);
  264. }
  265. void JSComponent::PostUpdate(float timeStep)
  266. {
  267. static String name = "postUpdate";
  268. CallScriptMethod(name, true, timeStep);
  269. }
  270. void JSComponent::FixedUpdate(float timeStep)
  271. {
  272. static String name = "fixedUpdate";
  273. CallScriptMethod(name, true, timeStep);
  274. }
  275. void JSComponent::FixedPostUpdate(float timeStep)
  276. {
  277. static String name = "fixedPostUpdate";
  278. CallScriptMethod(name, true, timeStep);
  279. }
  280. void JSComponent::OnNodeSet(Node* node)
  281. {
  282. if (node)
  283. {
  284. // We have been attached to a node. Set initial update event subscription state
  285. UpdateEventSubscription();
  286. }
  287. else
  288. {
  289. // We are being detached from a node: execute user-defined stop function and prepare for destruction
  290. UpdateReferences(true);
  291. Stop();
  292. }
  293. }
  294. void JSComponent::UpdateEventSubscription()
  295. {
  296. // If scene node is not assigned yet, no need to update subscription
  297. if (!node_)
  298. return;
  299. Scene* scene = GetScene();
  300. if (!scene)
  301. {
  302. LOGWARNING("Node is detached from scene, can not subscribe to update events");
  303. return;
  304. }
  305. bool enabled = IsEnabledEffective();
  306. bool needUpdate = enabled && ((updateEventMask_ & USE_UPDATE) || !delayedStartCalled_);
  307. if (needUpdate && !(currentEventMask_ & USE_UPDATE))
  308. {
  309. SubscribeToEvent(scene, E_SCENEUPDATE, HANDLER(JSComponent, HandleSceneUpdate));
  310. currentEventMask_ |= USE_UPDATE;
  311. }
  312. else if (!needUpdate && (currentEventMask_ & USE_UPDATE))
  313. {
  314. UnsubscribeFromEvent(scene, E_SCENEUPDATE);
  315. currentEventMask_ &= ~USE_UPDATE;
  316. }
  317. bool needPostUpdate = enabled && (updateEventMask_ & USE_POSTUPDATE);
  318. if (needPostUpdate && !(currentEventMask_ & USE_POSTUPDATE))
  319. {
  320. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(JSComponent, HandleScenePostUpdate));
  321. currentEventMask_ |= USE_POSTUPDATE;
  322. }
  323. else if (!needUpdate && (currentEventMask_ & USE_POSTUPDATE))
  324. {
  325. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  326. currentEventMask_ &= ~USE_POSTUPDATE;
  327. }
  328. #ifdef ATOMIC_PHYSICS
  329. PhysicsWorld* world = scene->GetComponent<PhysicsWorld>();
  330. if (!world)
  331. return;
  332. bool needFixedUpdate = enabled && (updateEventMask_ & USE_FIXEDUPDATE);
  333. if (needFixedUpdate && !(currentEventMask_ & USE_FIXEDUPDATE))
  334. {
  335. SubscribeToEvent(world, E_PHYSICSPRESTEP, HANDLER(JSComponent, HandlePhysicsPreStep));
  336. currentEventMask_ |= USE_FIXEDUPDATE;
  337. }
  338. else if (!needFixedUpdate && (currentEventMask_ & USE_FIXEDUPDATE))
  339. {
  340. UnsubscribeFromEvent(world, E_PHYSICSPRESTEP);
  341. currentEventMask_ &= ~USE_FIXEDUPDATE;
  342. }
  343. bool needFixedPostUpdate = enabled && (updateEventMask_ & USE_FIXEDPOSTUPDATE);
  344. if (needFixedPostUpdate && !(currentEventMask_ & USE_FIXEDPOSTUPDATE))
  345. {
  346. SubscribeToEvent(world, E_PHYSICSPOSTSTEP, HANDLER(JSComponent, HandlePhysicsPostStep));
  347. currentEventMask_ |= USE_FIXEDPOSTUPDATE;
  348. }
  349. else if (!needFixedPostUpdate && (currentEventMask_ & USE_FIXEDPOSTUPDATE))
  350. {
  351. UnsubscribeFromEvent(world, E_PHYSICSPOSTSTEP);
  352. currentEventMask_ &= ~USE_FIXEDPOSTUPDATE;
  353. }
  354. #endif
  355. }
  356. void JSComponent::HandleSceneUpdate(StringHash eventType, VariantMap& eventData)
  357. {
  358. using namespace SceneUpdate;
  359. assert(!destroyed_);
  360. // Execute user-defined delayed start function before first update
  361. if (!delayedStartCalled_)
  362. {
  363. DelayedStart();
  364. delayedStartCalled_ = true;
  365. // If did not need actual update events, unsubscribe now
  366. if (!(updateEventMask_ & USE_UPDATE))
  367. {
  368. UnsubscribeFromEvent(GetScene(), E_SCENEUPDATE);
  369. currentEventMask_ &= ~USE_UPDATE;
  370. return;
  371. }
  372. }
  373. // Then execute user-defined update function
  374. Update(eventData[P_TIMESTEP].GetFloat());
  375. }
  376. void JSComponent::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  377. {
  378. using namespace ScenePostUpdate;
  379. // Execute user-defined post-update function
  380. PostUpdate(eventData[P_TIMESTEP].GetFloat());
  381. }
  382. #ifdef ATOMIC_PHYSICS
  383. void JSComponent::HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData)
  384. {
  385. using namespace PhysicsPreStep;
  386. // Execute user-defined fixed update function
  387. FixedUpdate(eventData[P_TIMESTEP].GetFloat());
  388. }
  389. void JSComponent::HandlePhysicsPostStep(StringHash eventType, VariantMap& eventData)
  390. {
  391. using namespace PhysicsPostStep;
  392. // Execute user-defined fixed post-update function
  393. FixedPostUpdate(eventData[P_TIMESTEP].GetFloat());
  394. }
  395. #endif
  396. bool JSComponent::Load(Deserializer& source, bool setInstanceDefault)
  397. {
  398. loading_ = true;
  399. bool success = Component::Load(source, setInstanceDefault);
  400. loading_ = false;
  401. return success;
  402. }
  403. bool JSComponent::LoadXML(const XMLElement& source, bool setInstanceDefault)
  404. {
  405. loading_ = true;
  406. bool success = Component::LoadXML(source, setInstanceDefault);
  407. loading_ = false;
  408. return success;
  409. }
  410. void JSComponent::SetComponentFile(JSComponentFile* cfile, bool loading)
  411. {
  412. componentFile_ = cfile;
  413. }
  414. ResourceRef JSComponent::GetScriptAttr() const
  415. {
  416. return GetResourceRef(componentFile_, JSComponentFile::GetTypeStatic());
  417. }
  418. void JSComponent::SetScriptAttr(const ResourceRef& value)
  419. {
  420. ResourceCache* cache = GetSubsystem<ResourceCache>();
  421. SetComponentFile(cache->GetResource<JSComponentFile>(value.name_), loading_);
  422. }
  423. }