JSComponent.cpp 15 KB

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