JSComponent.cpp 12 KB

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