JSComponent.cpp 13 KB

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