JSComponent.cpp 12 KB

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