JSComponent.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. ATOMIC_REFCOUNTED(JSComponentFactory)
  42. public:
  43. /// Construct.
  44. JSComponentFactory(Context* context) :
  45. ObjectFactory(context)
  46. {
  47. typeInfo_ = JSComponent::GetTypeInfoStatic();
  48. }
  49. /// Create an object of the specific type.
  50. SharedPtr<Object> CreateObject(const XMLElement& source = XMLElement::EMPTY)
  51. {
  52. // if in editor, just create the JSComponent
  53. if (context_->GetEditorContext())
  54. {
  55. return SharedPtr<Object>(new JSComponent(context_));
  56. }
  57. // At runtime, a XML JSComponent may refer to a "scriptClass"
  58. // component which is new'd in JS and creates the component itself
  59. // we peek ahead here to see if we have a JSComponentFile and if it is a script class
  60. String componentRef;
  61. if (source != XMLElement::EMPTY)
  62. {
  63. XMLElement attrElem = source.GetChild("attribute");
  64. while (attrElem)
  65. {
  66. if (attrElem.GetAttribute("name") == "ComponentFile")
  67. {
  68. componentRef = attrElem.GetAttribute("value");
  69. break;
  70. }
  71. attrElem = attrElem.GetNext("attribute");
  72. }
  73. }
  74. SharedPtr<Object> ptr;
  75. if (componentRef.Length())
  76. {
  77. Vector<String> split = componentRef.Split(';');
  78. if (split.Size() == 2)
  79. {
  80. ResourceCache* cache = context_->GetSubsystem<ResourceCache>();
  81. JSComponentFile* componentFile = cache->GetResource<JSComponentFile>(split[1]);
  82. if (componentFile)
  83. ptr = componentFile->CreateJSComponent();
  84. else
  85. {
  86. ATOMIC_LOGERRORF("Unable to load component file %s", split[1].CString());
  87. }
  88. }
  89. }
  90. if (ptr.Null())
  91. {
  92. ptr = new JSComponent(context_);
  93. }
  94. return ptr;
  95. }
  96. };
  97. JSComponent::JSComponent(Context* context) :
  98. ScriptComponent(context),
  99. updateEventMask_(USE_UPDATE | USE_POSTUPDATE | USE_FIXEDUPDATE | USE_FIXEDPOSTUPDATE),
  100. currentEventMask_(0),
  101. instanceInitialized_(false),
  102. started_(false),
  103. destroyed_(false),
  104. scriptClassInstance_(false),
  105. delayedStartCalled_(false),
  106. loading_(false)
  107. {
  108. vm_ = JSVM::GetJSVM(NULL);
  109. }
  110. JSComponent::~JSComponent()
  111. {
  112. }
  113. void JSComponent::RegisterObject(Context* context)
  114. {
  115. context->RegisterFactory( new JSComponentFactory(context), LOGIC_CATEGORY);
  116. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("ComponentFile", GetComponentFileAttr, SetComponentFileAttr, ResourceRef, ResourceRef(JSComponentFile::GetTypeStatic()), AM_DEFAULT);
  117. ATOMIC_COPY_BASE_ATTRIBUTES(ScriptComponent);
  118. }
  119. void JSComponent::OnSetEnabled()
  120. {
  121. UpdateEventSubscription();
  122. }
  123. void JSComponent::SetUpdateEventMask(unsigned char mask)
  124. {
  125. if (updateEventMask_ != mask)
  126. {
  127. updateEventMask_ = mask;
  128. UpdateEventSubscription();
  129. }
  130. }
  131. void JSComponent::ApplyAttributes()
  132. {
  133. }
  134. void JSComponent::InitInstance(bool hasArgs, int argIdx)
  135. {
  136. if (context_->GetEditorContext() || componentFile_.Null())
  137. return;
  138. duk_context* ctx = vm_->GetJSContext();
  139. duk_idx_t top = duk_get_top(ctx);
  140. // apply fields
  141. const FieldMap& fields = componentFile_->GetFields();
  142. if (fields.Size())
  143. {
  144. // push self
  145. js_push_class_object_instance(ctx, this, "JSComponent");
  146. FieldMap::ConstIterator itr = fields.Begin();
  147. while (itr != fields.End())
  148. {
  149. if (fieldValues_.Contains(itr->first_))
  150. {
  151. Variant& v = fieldValues_[itr->first_];
  152. if (v.GetType() == itr->second_)
  153. {
  154. js_push_variant(ctx, v);
  155. duk_put_prop_string(ctx, -2, itr->first_.CString());
  156. }
  157. }
  158. else
  159. {
  160. Variant v;
  161. componentFile_->GetDefaultFieldValue(itr->first_, v);
  162. js_push_variant(ctx, v);
  163. duk_put_prop_string(ctx, -2, itr->first_.CString());
  164. }
  165. itr++;
  166. }
  167. // pop self
  168. duk_pop(ctx);
  169. }
  170. // apply args if any
  171. if (hasArgs)
  172. {
  173. // push self
  174. js_push_class_object_instance(ctx, this, "JSComponent");
  175. duk_enum(ctx, argIdx, DUK_ENUM_OWN_PROPERTIES_ONLY);
  176. while (duk_next(ctx, -1, 1)) {
  177. duk_put_prop(ctx, -4);
  178. }
  179. // pop self and enum object
  180. duk_pop_2(ctx);
  181. }
  182. if (!componentFile_->GetScriptClass())
  183. {
  184. componentFile_->PushModule();
  185. if (!duk_is_object(ctx, -1))
  186. {
  187. duk_set_top(ctx, top);
  188. return;
  189. }
  190. // Check for "default" constructor which is used by TypeScript and ES2015
  191. duk_get_prop_string(ctx, -1, "default");
  192. if (!duk_is_function(ctx, -1))
  193. {
  194. duk_pop(ctx);
  195. // If "default" doesn't exist, look for component
  196. duk_get_prop_string(ctx, -1, "component");
  197. if (!duk_is_function(ctx, -1))
  198. {
  199. duk_set_top(ctx, top);
  200. return;
  201. }
  202. }
  203. // call with self
  204. js_push_class_object_instance(ctx, this, "JSComponent");
  205. if (duk_pcall(ctx, 1) != 0)
  206. {
  207. vm_->SendJSErrorEvent();
  208. duk_set_top(ctx, top);
  209. return;
  210. }
  211. }
  212. duk_set_top(ctx, top);
  213. instanceInitialized_ = true;
  214. }
  215. void JSComponent::CallScriptMethod(const String& name, bool passValue, float value)
  216. {
  217. if (destroyed_ || !node_ || !node_->GetScene())
  218. return;
  219. void* heapptr = JSGetHeapPtr();
  220. if (!heapptr)
  221. return;
  222. duk_context* ctx = vm_->GetJSContext();
  223. duk_idx_t top = duk_get_top(ctx);
  224. duk_push_heapptr(ctx, heapptr);
  225. duk_get_prop_string(ctx, -1, name.CString());
  226. if (!duk_is_function(ctx, -1))
  227. {
  228. duk_set_top(ctx, top);
  229. return;
  230. }
  231. // push this
  232. if (scriptClassInstance_)
  233. duk_push_heapptr(ctx, heapptr);
  234. if (passValue)
  235. duk_push_number(ctx, value);
  236. int status = scriptClassInstance_ ? duk_pcall_method(ctx, passValue ? 1 : 0) : duk_pcall(ctx, passValue ? 1 : 0);
  237. if (status != 0)
  238. {
  239. vm_->SendJSErrorEvent();
  240. duk_set_top(ctx, top);
  241. return;
  242. }
  243. duk_set_top(ctx, top);
  244. }
  245. void JSComponent::Start()
  246. {
  247. static String name = "start";
  248. CallScriptMethod(name);
  249. }
  250. void JSComponent::DelayedStart()
  251. {
  252. static String name = "delayedStart";
  253. CallScriptMethod(name);
  254. }
  255. void JSComponent::Update(float timeStep)
  256. {
  257. if (!instanceInitialized_)
  258. InitInstance();
  259. if (!started_)
  260. {
  261. started_ = true;
  262. Start();
  263. }
  264. static String name = "update";
  265. CallScriptMethod(name, true, timeStep);
  266. }
  267. void JSComponent::PostUpdate(float timeStep)
  268. {
  269. static String name = "postUpdate";
  270. CallScriptMethod(name, true, timeStep);
  271. }
  272. void JSComponent::FixedUpdate(float timeStep)
  273. {
  274. static String name = "fixedUpdate";
  275. CallScriptMethod(name, true, timeStep);
  276. }
  277. void JSComponent::FixedPostUpdate(float timeStep)
  278. {
  279. static String name = "fixedPostUpdate";
  280. CallScriptMethod(name, true, timeStep);
  281. }
  282. void JSComponent::OnNodeSet(Node* node)
  283. {
  284. if (node)
  285. {
  286. }
  287. else
  288. {
  289. Stop();
  290. }
  291. }
  292. void JSComponent::OnSceneSet(Scene* scene)
  293. {
  294. if (scene)
  295. UpdateEventSubscription();
  296. else
  297. {
  298. UnsubscribeFromEvent(E_SCENEUPDATE);
  299. UnsubscribeFromEvent(E_SCENEPOSTUPDATE);
  300. #ifdef ATOMIC_PHYSICS
  301. UnsubscribeFromEvent(E_PHYSICSPRESTEP);
  302. UnsubscribeFromEvent(E_PHYSICSPOSTSTEP);
  303. #endif
  304. currentEventMask_ = 0;
  305. }
  306. }
  307. void JSComponent::UpdateEventSubscription()
  308. {
  309. Scene* scene = GetScene();
  310. if (!scene)
  311. return;
  312. bool enabled = IsEnabledEffective();
  313. bool needUpdate = enabled && ((updateEventMask_ & USE_UPDATE) || !delayedStartCalled_);
  314. if (needUpdate && !(currentEventMask_ & USE_UPDATE))
  315. {
  316. SubscribeToEvent(scene, E_SCENEUPDATE, ATOMIC_HANDLER(JSComponent, HandleSceneUpdate));
  317. currentEventMask_ |= USE_UPDATE;
  318. }
  319. else if (!needUpdate && (currentEventMask_ & USE_UPDATE))
  320. {
  321. UnsubscribeFromEvent(scene, E_SCENEUPDATE);
  322. currentEventMask_ &= ~USE_UPDATE;
  323. }
  324. bool needPostUpdate = enabled && (updateEventMask_ & USE_POSTUPDATE);
  325. if (needPostUpdate && !(currentEventMask_ & USE_POSTUPDATE))
  326. {
  327. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, ATOMIC_HANDLER(JSComponent, HandleScenePostUpdate));
  328. currentEventMask_ |= USE_POSTUPDATE;
  329. }
  330. else if (!needPostUpdate && (currentEventMask_ & USE_POSTUPDATE))
  331. {
  332. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  333. currentEventMask_ &= ~USE_POSTUPDATE;
  334. }
  335. #ifdef ATOMIC_PHYSICS
  336. PhysicsWorld* world = scene->GetComponent<PhysicsWorld>();
  337. if (!world)
  338. return;
  339. bool needFixedUpdate = enabled && (updateEventMask_ & USE_FIXEDUPDATE);
  340. if (needFixedUpdate && !(currentEventMask_ & USE_FIXEDUPDATE))
  341. {
  342. SubscribeToEvent(world, E_PHYSICSPRESTEP, ATOMIC_HANDLER(JSComponent, HandlePhysicsPreStep));
  343. currentEventMask_ |= USE_FIXEDUPDATE;
  344. }
  345. else if (!needFixedUpdate && (currentEventMask_ & USE_FIXEDUPDATE))
  346. {
  347. UnsubscribeFromEvent(world, E_PHYSICSPRESTEP);
  348. currentEventMask_ &= ~USE_FIXEDUPDATE;
  349. }
  350. bool needFixedPostUpdate = enabled && (updateEventMask_ & USE_FIXEDPOSTUPDATE);
  351. if (needFixedPostUpdate && !(currentEventMask_ & USE_FIXEDPOSTUPDATE))
  352. {
  353. SubscribeToEvent(world, E_PHYSICSPOSTSTEP, ATOMIC_HANDLER(JSComponent, HandlePhysicsPostStep));
  354. currentEventMask_ |= USE_FIXEDPOSTUPDATE;
  355. }
  356. else if (!needFixedPostUpdate && (currentEventMask_ & USE_FIXEDPOSTUPDATE))
  357. {
  358. UnsubscribeFromEvent(world, E_PHYSICSPOSTSTEP);
  359. currentEventMask_ &= ~USE_FIXEDPOSTUPDATE;
  360. }
  361. #endif
  362. }
  363. void JSComponent::HandleSceneUpdate(StringHash eventType, VariantMap& eventData)
  364. {
  365. using namespace SceneUpdate;
  366. assert(!destroyed_);
  367. // Execute user-defined delayed start function before first update
  368. if (!delayedStartCalled_)
  369. {
  370. DelayedStart();
  371. delayedStartCalled_ = true;
  372. // If did not need actual update events, unsubscribe now
  373. if (!(updateEventMask_ & USE_UPDATE))
  374. {
  375. UnsubscribeFromEvent(GetScene(), E_SCENEUPDATE);
  376. currentEventMask_ &= ~USE_UPDATE;
  377. return;
  378. }
  379. }
  380. // Then execute user-defined update function
  381. Update(eventData[P_TIMESTEP].GetFloat());
  382. }
  383. void JSComponent::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  384. {
  385. using namespace ScenePostUpdate;
  386. // Execute user-defined post-update function
  387. PostUpdate(eventData[P_TIMESTEP].GetFloat());
  388. }
  389. #ifdef ATOMIC_PHYSICS
  390. void JSComponent::HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData)
  391. {
  392. using namespace PhysicsPreStep;
  393. // Execute user-defined fixed update function
  394. FixedUpdate(eventData[P_TIMESTEP].GetFloat());
  395. }
  396. void JSComponent::HandlePhysicsPostStep(StringHash eventType, VariantMap& eventData)
  397. {
  398. using namespace PhysicsPostStep;
  399. // Execute user-defined fixed post-update function
  400. FixedPostUpdate(eventData[P_TIMESTEP].GetFloat());
  401. }
  402. #endif
  403. bool JSComponent::Load(Deserializer& source, bool setInstanceDefault)
  404. {
  405. loading_ = true;
  406. bool success = Component::Load(source, setInstanceDefault);
  407. loading_ = false;
  408. return success;
  409. }
  410. bool JSComponent::LoadXML(const XMLElement& source, bool setInstanceDefault)
  411. {
  412. loading_ = true;
  413. bool success = Component::LoadXML(source, setInstanceDefault);
  414. loading_ = false;
  415. return success;
  416. }
  417. bool JSComponent::MatchScriptName(const String& path)
  418. {
  419. if (componentFile_.Null())
  420. return false;
  421. String _path = path;
  422. _path.Replace(".js", "", false);
  423. const String& name = componentFile_->GetName();
  424. if (_path == name)
  425. return true;
  426. String pathName, fileName, ext;
  427. SplitPath(name, pathName, fileName, ext);
  428. if (fileName == _path)
  429. return true;
  430. return false;
  431. }
  432. ResourceRef JSComponent::GetComponentFileAttr() const
  433. {
  434. return GetResourceRef(componentFile_, JSComponentFile::GetTypeStatic());
  435. }
  436. void JSComponent::SetComponentFileAttr(const ResourceRef& value)
  437. {
  438. ResourceCache* cache = GetSubsystem<ResourceCache>();
  439. SetComponentFile(cache->GetResource<JSComponentFile>(value.name_));
  440. }
  441. }