JSComponent.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include <Atomic/IO/Log.h>
  24. #include <Atomic/IO/FileSystem.h>
  25. #include <Atomic/Core/Context.h>
  26. #include <Atomic/Resource/ResourceCache.h>
  27. #ifdef ATOMIC_PHYSICS
  28. #include <Atomic/Physics/PhysicsEvents.h>
  29. #include <Atomic/Physics/PhysicsWorld.h>
  30. #endif
  31. #include <Atomic/Scene/Scene.h>
  32. #include <Atomic/Scene/SceneEvents.h>
  33. #include "JSVM.h"
  34. #include "JSComponentFile.h"
  35. #include "JSComponent.h"
  36. namespace Atomic
  37. {
  38. extern const char* LOGIC_CATEGORY;
  39. class JSComponentFactory : public ObjectFactory
  40. {
  41. public:
  42. /// Construct.
  43. JSComponentFactory(Context* context) :
  44. ObjectFactory(context)
  45. {
  46. type_ = JSComponent::GetTypeStatic();
  47. baseType_ = JSComponent::GetBaseTypeStatic();
  48. typeName_ = JSComponent::GetTypeNameStatic();
  49. }
  50. /// Create an object of the specific type.
  51. SharedPtr<Object> CreateObject(const XMLElement& source = XMLElement::EMPTY)
  52. {
  53. // if in editor, just create the JSComponent
  54. if (context_->GetEditorContext())
  55. {
  56. return SharedPtr<Object>(new JSComponent(context_));
  57. }
  58. // At runtime, a XML JSComponent may refer to a "scriptClass"
  59. // component which is new'd in JS and creates the component itself
  60. // we peek ahead here to see if we have a JSComponentFile and if it is a script class
  61. String componentRef;
  62. if (source != XMLElement::EMPTY)
  63. {
  64. XMLElement attrElem = source.GetChild("attribute");
  65. while (attrElem)
  66. {
  67. if (attrElem.GetAttribute("name") == "ComponentFile")
  68. {
  69. componentRef = attrElem.GetAttribute("value");
  70. break;
  71. }
  72. attrElem = attrElem.GetNext("attribute");
  73. }
  74. }
  75. SharedPtr<Object> ptr;
  76. if (componentRef.Length())
  77. {
  78. Vector<String> split = componentRef.Split(';');
  79. if (split.Size() == 2)
  80. {
  81. ResourceCache* cache = context_->GetSubsystem<ResourceCache>();
  82. JSComponentFile* componentFile = cache->GetResource<JSComponentFile>(split[1]);
  83. if (componentFile)
  84. ptr = componentFile->CreateJSComponent();
  85. else
  86. {
  87. LOGERRORF("Unable to load component file %s", split[1].CString());
  88. }
  89. }
  90. }
  91. if (ptr.Null())
  92. {
  93. ptr = new JSComponent(context_);
  94. }
  95. return ptr;
  96. }
  97. };
  98. JSComponent::JSComponent(Context* context) :
  99. Component(context),
  100. updateEventMask_(USE_UPDATE | USE_POSTUPDATE | USE_FIXEDUPDATE | USE_FIXEDPOSTUPDATE),
  101. currentEventMask_(0),
  102. instanceInitialized_(false),
  103. started_(false),
  104. destroyed_(false),
  105. scriptClassInstance_(false),
  106. delayedStartCalled_(false),
  107. loading_(false)
  108. {
  109. vm_ = JSVM::GetJSVM(NULL);
  110. }
  111. JSComponent::~JSComponent()
  112. {
  113. }
  114. void JSComponent::RegisterObject(Context* context)
  115. {
  116. context->RegisterFactory(new JSComponentFactory(context), LOGIC_CATEGORY);
  117. ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  118. ATTRIBUTE("FieldValues", VariantMap, fieldValues_, Variant::emptyVariantMap, AM_FILE);
  119. MIXED_ACCESSOR_ATTRIBUTE("ComponentFile", GetScriptAttr, SetScriptAttr, ResourceRef, ResourceRef(JSComponentFile::GetTypeStatic()), AM_DEFAULT);
  120. }
  121. void JSComponent::OnSetEnabled()
  122. {
  123. UpdateEventSubscription();
  124. }
  125. void JSComponent::SetUpdateEventMask(unsigned char mask)
  126. {
  127. if (updateEventMask_ != mask)
  128. {
  129. updateEventMask_ = mask;
  130. UpdateEventSubscription();
  131. }
  132. }
  133. void JSComponent::UpdateReferences(bool remove)
  134. {
  135. if (context_->GetEditorContext())
  136. return;
  137. duk_context* ctx = vm_->GetJSContext();
  138. int top = duk_get_top(ctx);
  139. duk_push_global_stash(ctx);
  140. duk_get_prop_index(ctx, -1, JS_GLOBALSTASH_INDEX_NODE_REGISTRY);
  141. // can't use instance as key, as this coerces to [Object] for
  142. // string property, pointer will be string representation of
  143. // address, so, unique key
  144. if (node_)
  145. {
  146. duk_push_pointer(ctx, (void*) node_);
  147. if (remove)
  148. duk_push_undefined(ctx);
  149. else
  150. js_push_class_object_instance(ctx, node_);
  151. duk_put_prop(ctx, -3);
  152. }
  153. duk_push_pointer(ctx, (void*) this);
  154. if (remove)
  155. duk_push_undefined(ctx);
  156. else
  157. js_push_class_object_instance(ctx, this);
  158. duk_put_prop(ctx, -3);
  159. duk_pop_2(ctx);
  160. assert(duk_get_top(ctx) == top);
  161. }
  162. void JSComponent::ApplyAttributes()
  163. {
  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. if (!duk_is_object(ctx, -1))
  219. {
  220. duk_set_top(ctx, top);
  221. return;
  222. }
  223. duk_get_prop_string(ctx, -1, "component");
  224. if (!duk_is_function(ctx, -1))
  225. {
  226. duk_set_top(ctx, top);
  227. return;
  228. }
  229. // call with self
  230. js_push_class_object_instance(ctx, this, "JSComponent");
  231. if (duk_pcall(ctx, 1) != 0)
  232. {
  233. vm_->SendJSErrorEvent();
  234. duk_set_top(ctx, top);
  235. return;
  236. }
  237. }
  238. duk_set_top(ctx, top);
  239. instanceInitialized_ = true;
  240. }
  241. void JSComponent::CallScriptMethod(const String& name, bool passValue, float value)
  242. {
  243. if (destroyed_ || !node_ || !node_->GetScene())
  244. return;
  245. void* heapptr = JSGetHeapPtr();
  246. if (!heapptr)
  247. return;
  248. duk_context* ctx = vm_->GetJSContext();
  249. duk_idx_t top = duk_get_top(ctx);
  250. duk_push_heapptr(ctx, heapptr);
  251. duk_get_prop_string(ctx, -1, name.CString());
  252. if (!duk_is_function(ctx, -1))
  253. {
  254. duk_set_top(ctx, top);
  255. return;
  256. }
  257. // push this
  258. if (scriptClassInstance_)
  259. duk_push_heapptr(ctx, heapptr);
  260. if (passValue)
  261. duk_push_number(ctx, value);
  262. int status = scriptClassInstance_ ? duk_pcall_method(ctx, passValue ? 1 : 0) : duk_pcall(ctx, passValue ? 1 : 0);
  263. if (status != 0)
  264. {
  265. vm_->SendJSErrorEvent();
  266. duk_set_top(ctx, top);
  267. return;
  268. }
  269. duk_set_top(ctx, top);
  270. }
  271. void JSComponent::Start()
  272. {
  273. static String name = "start";
  274. CallScriptMethod(name);
  275. }
  276. void JSComponent::DelayedStart()
  277. {
  278. static String name = "delayedStart";
  279. CallScriptMethod(name);
  280. }
  281. void JSComponent::Update(float timeStep)
  282. {
  283. if (!instanceInitialized_)
  284. InitInstance();
  285. if (!started_)
  286. {
  287. started_ = true;
  288. Start();
  289. }
  290. static String name = "update";
  291. CallScriptMethod(name, true, timeStep);
  292. }
  293. void JSComponent::PostUpdate(float timeStep)
  294. {
  295. static String name = "postUpdate";
  296. CallScriptMethod(name, true, timeStep);
  297. }
  298. void JSComponent::FixedUpdate(float timeStep)
  299. {
  300. static String name = "fixedUpdate";
  301. CallScriptMethod(name, true, timeStep);
  302. }
  303. void JSComponent::FixedPostUpdate(float timeStep)
  304. {
  305. static String name = "fixedPostUpdate";
  306. CallScriptMethod(name, true, timeStep);
  307. }
  308. void JSComponent::OnNodeSet(Node* node)
  309. {
  310. if (node)
  311. {
  312. UpdateReferences();
  313. }
  314. else
  315. {
  316. // We are being detached from a node: execute user-defined stop function and prepare for destruction
  317. UpdateReferences(true);
  318. Stop();
  319. }
  320. }
  321. void JSComponent::OnSceneSet(Scene* scene)
  322. {
  323. if (scene)
  324. UpdateEventSubscription();
  325. else
  326. {
  327. UnsubscribeFromEvent(E_SCENEUPDATE);
  328. UnsubscribeFromEvent(E_SCENEPOSTUPDATE);
  329. #ifdef ATOMIC_PHYSICS
  330. UnsubscribeFromEvent(E_PHYSICSPRESTEP);
  331. UnsubscribeFromEvent(E_PHYSICSPOSTSTEP);
  332. #endif
  333. currentEventMask_ = 0;
  334. }
  335. }
  336. void JSComponent::UpdateEventSubscription()
  337. {
  338. Scene* scene = GetScene();
  339. if (!scene)
  340. return;
  341. bool enabled = IsEnabledEffective();
  342. bool needUpdate = enabled && ((updateEventMask_ & USE_UPDATE) || !delayedStartCalled_);
  343. if (needUpdate && !(currentEventMask_ & USE_UPDATE))
  344. {
  345. SubscribeToEvent(scene, E_SCENEUPDATE, HANDLER(JSComponent, HandleSceneUpdate));
  346. currentEventMask_ |= USE_UPDATE;
  347. }
  348. else if (!needUpdate && (currentEventMask_ & USE_UPDATE))
  349. {
  350. UnsubscribeFromEvent(scene, E_SCENEUPDATE);
  351. currentEventMask_ &= ~USE_UPDATE;
  352. }
  353. bool needPostUpdate = enabled && (updateEventMask_ & USE_POSTUPDATE);
  354. if (needPostUpdate && !(currentEventMask_ & USE_POSTUPDATE))
  355. {
  356. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(JSComponent, HandleScenePostUpdate));
  357. currentEventMask_ |= USE_POSTUPDATE;
  358. }
  359. else if (!needUpdate && (currentEventMask_ & USE_POSTUPDATE))
  360. {
  361. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  362. currentEventMask_ &= ~USE_POSTUPDATE;
  363. }
  364. #ifdef ATOMIC_PHYSICS
  365. PhysicsWorld* world = scene->GetComponent<PhysicsWorld>();
  366. if (!world)
  367. return;
  368. bool needFixedUpdate = enabled && (updateEventMask_ & USE_FIXEDUPDATE);
  369. if (needFixedUpdate && !(currentEventMask_ & USE_FIXEDUPDATE))
  370. {
  371. SubscribeToEvent(world, E_PHYSICSPRESTEP, HANDLER(JSComponent, HandlePhysicsPreStep));
  372. currentEventMask_ |= USE_FIXEDUPDATE;
  373. }
  374. else if (!needFixedUpdate && (currentEventMask_ & USE_FIXEDUPDATE))
  375. {
  376. UnsubscribeFromEvent(world, E_PHYSICSPRESTEP);
  377. currentEventMask_ &= ~USE_FIXEDUPDATE;
  378. }
  379. bool needFixedPostUpdate = enabled && (updateEventMask_ & USE_FIXEDPOSTUPDATE);
  380. if (needFixedPostUpdate && !(currentEventMask_ & USE_FIXEDPOSTUPDATE))
  381. {
  382. SubscribeToEvent(world, E_PHYSICSPOSTSTEP, HANDLER(JSComponent, HandlePhysicsPostStep));
  383. currentEventMask_ |= USE_FIXEDPOSTUPDATE;
  384. }
  385. else if (!needFixedPostUpdate && (currentEventMask_ & USE_FIXEDPOSTUPDATE))
  386. {
  387. UnsubscribeFromEvent(world, E_PHYSICSPOSTSTEP);
  388. currentEventMask_ &= ~USE_FIXEDPOSTUPDATE;
  389. }
  390. #endif
  391. }
  392. void JSComponent::HandleSceneUpdate(StringHash eventType, VariantMap& eventData)
  393. {
  394. using namespace SceneUpdate;
  395. assert(!destroyed_);
  396. // Execute user-defined delayed start function before first update
  397. if (!delayedStartCalled_)
  398. {
  399. DelayedStart();
  400. delayedStartCalled_ = true;
  401. // If did not need actual update events, unsubscribe now
  402. if (!(updateEventMask_ & USE_UPDATE))
  403. {
  404. UnsubscribeFromEvent(GetScene(), E_SCENEUPDATE);
  405. currentEventMask_ &= ~USE_UPDATE;
  406. return;
  407. }
  408. }
  409. // Then execute user-defined update function
  410. Update(eventData[P_TIMESTEP].GetFloat());
  411. }
  412. void JSComponent::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  413. {
  414. using namespace ScenePostUpdate;
  415. // Execute user-defined post-update function
  416. PostUpdate(eventData[P_TIMESTEP].GetFloat());
  417. }
  418. #ifdef ATOMIC_PHYSICS
  419. void JSComponent::HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData)
  420. {
  421. using namespace PhysicsPreStep;
  422. // Execute user-defined fixed update function
  423. FixedUpdate(eventData[P_TIMESTEP].GetFloat());
  424. }
  425. void JSComponent::HandlePhysicsPostStep(StringHash eventType, VariantMap& eventData)
  426. {
  427. using namespace PhysicsPostStep;
  428. // Execute user-defined fixed post-update function
  429. FixedPostUpdate(eventData[P_TIMESTEP].GetFloat());
  430. }
  431. #endif
  432. bool JSComponent::Load(Deserializer& source, bool setInstanceDefault)
  433. {
  434. loading_ = true;
  435. bool success = Component::Load(source, setInstanceDefault);
  436. loading_ = false;
  437. return success;
  438. }
  439. bool JSComponent::LoadXML(const XMLElement& source, bool setInstanceDefault)
  440. {
  441. loading_ = true;
  442. bool success = Component::LoadXML(source, setInstanceDefault);
  443. loading_ = false;
  444. return success;
  445. }
  446. bool JSComponent::MatchScriptName(const String& path)
  447. {
  448. if (componentFile_.Null())
  449. return false;
  450. String _path = path;
  451. _path.Replace(".js", "", false);
  452. const String& name = componentFile_->GetName();
  453. if (_path == name)
  454. return true;
  455. String pathName, fileName, ext;
  456. SplitPath(name, pathName, fileName, ext);
  457. if (fileName == _path)
  458. return true;
  459. return false;
  460. }
  461. void JSComponent::SetComponentFile(JSComponentFile* cfile)
  462. {
  463. componentFile_ = cfile;
  464. }
  465. ResourceRef JSComponent::GetScriptAttr() const
  466. {
  467. return GetResourceRef(componentFile_, JSComponentFile::GetTypeStatic());
  468. }
  469. void JSComponent::SetScriptAttr(const ResourceRef& value)
  470. {
  471. ResourceCache* cache = GetSubsystem<ResourceCache>();
  472. SetComponentFile(cache->GetResource<JSComponentFile>(value.name_));
  473. }
  474. }