JSComponent.cpp 12 KB

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