JSComponent.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. {
  107. vm_ = JSVM::GetJSVM(NULL);
  108. }
  109. JSComponent::~JSComponent()
  110. {
  111. }
  112. void JSComponent::RegisterObject(Context* context)
  113. {
  114. context->RegisterFactory( new JSComponentFactory(context), LOGIC_CATEGORY);
  115. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("ComponentFile", GetComponentFileAttr, SetComponentFileAttr, ResourceRef, ResourceRef(JSComponentFile::GetTypeStatic()), AM_DEFAULT);
  116. ATOMIC_COPY_BASE_ATTRIBUTES(ScriptComponent);
  117. }
  118. void JSComponent::OnSetEnabled()
  119. {
  120. UpdateEventSubscription();
  121. }
  122. void JSComponent::SetUpdateEventMask(unsigned char mask)
  123. {
  124. if (updateEventMask_ != mask)
  125. {
  126. updateEventMask_ = mask;
  127. UpdateEventSubscription();
  128. }
  129. }
  130. bool JSComponent::IsInstanceInitialized() {
  131. return instanceInitialized_;
  132. }
  133. void JSComponent::InitInstance(bool hasArgs, int argIdx)
  134. {
  135. if (context_->GetEditorContext() || componentFile_.Null())
  136. return;
  137. duk_context* ctx = vm_->GetJSContext();
  138. duk_idx_t top = duk_get_top(ctx);
  139. // apply fields
  140. const FieldMap& fields = componentFile_->GetFields();
  141. if (fields.Size())
  142. {
  143. // push self
  144. js_push_class_object_instance(ctx, this, "JSComponent");
  145. FieldMap::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_.variantType_)
  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. if (!duk_is_object(ctx, -1))
  185. {
  186. duk_set_top(ctx, top);
  187. return;
  188. }
  189. // Check for "default" constructor which is used by TypeScript and ES2015
  190. duk_get_prop_string(ctx, -1, "default");
  191. if (!duk_is_function(ctx, -1))
  192. {
  193. duk_pop(ctx);
  194. // If "default" doesn't exist, look for component
  195. duk_get_prop_string(ctx, -1, "component");
  196. if (!duk_is_function(ctx, -1))
  197. {
  198. duk_set_top(ctx, top);
  199. return;
  200. }
  201. }
  202. // call with self
  203. js_push_class_object_instance(ctx, this, "JSComponent");
  204. if (duk_pcall(ctx, 1) != 0)
  205. {
  206. vm_->SendJSErrorEvent();
  207. duk_set_top(ctx, top);
  208. return;
  209. }
  210. }
  211. duk_set_top(ctx, top);
  212. instanceInitialized_ = true;
  213. }
  214. void JSComponent::CallScriptMethod(const String& name, bool passValue, float value)
  215. {
  216. if (destroyed_ || !node_ || !node_->GetScene())
  217. return;
  218. void* heapptr = JSGetHeapPtr();
  219. if (!heapptr)
  220. return;
  221. duk_context* ctx = vm_->GetJSContext();
  222. duk_idx_t top = duk_get_top(ctx);
  223. duk_push_heapptr(ctx, heapptr);
  224. duk_get_prop_string(ctx, -1, name.CString());
  225. if (!duk_is_function(ctx, -1))
  226. {
  227. duk_set_top(ctx, top);
  228. return;
  229. }
  230. // push this
  231. if (scriptClassInstance_)
  232. duk_push_heapptr(ctx, heapptr);
  233. if (passValue)
  234. duk_push_number(ctx, value);
  235. int status = scriptClassInstance_ ? duk_pcall_method(ctx, passValue ? 1 : 0) : duk_pcall(ctx, passValue ? 1 : 0);
  236. if (status != 0)
  237. {
  238. vm_->SendJSErrorEvent();
  239. duk_set_top(ctx, top);
  240. return;
  241. }
  242. duk_set_top(ctx, top);
  243. }
  244. void JSComponent::Start()
  245. {
  246. static String name = "start";
  247. CallScriptMethod(name);
  248. }
  249. void JSComponent::DelayedStart()
  250. {
  251. static String name = "delayedStart";
  252. CallScriptMethod(name);
  253. }
  254. void JSComponent::Update(float timeStep)
  255. {
  256. if (!instanceInitialized_)
  257. InitInstance();
  258. if (!started_)
  259. {
  260. started_ = true;
  261. Start();
  262. }
  263. static String name = "update";
  264. CallScriptMethod(name, true, timeStep);
  265. }
  266. void JSComponent::PostUpdate(float timeStep)
  267. {
  268. static String name = "postUpdate";
  269. CallScriptMethod(name, true, timeStep);
  270. }
  271. void JSComponent::FixedUpdate(float timeStep)
  272. {
  273. static String name = "fixedUpdate";
  274. CallScriptMethod(name, true, timeStep);
  275. }
  276. void JSComponent::FixedPostUpdate(float timeStep)
  277. {
  278. static String name = "fixedPostUpdate";
  279. CallScriptMethod(name, true, timeStep);
  280. }
  281. void JSComponent::OnNodeSet(Node* node)
  282. {
  283. if (node)
  284. {
  285. }
  286. else
  287. {
  288. Stop();
  289. }
  290. }
  291. void JSComponent::OnSceneSet(Scene* scene)
  292. {
  293. if (scene)
  294. UpdateEventSubscription();
  295. else
  296. {
  297. UnsubscribeFromEvent(E_SCENEUPDATE);
  298. UnsubscribeFromEvent(E_SCENEPOSTUPDATE);
  299. #ifdef ATOMIC_PHYSICS
  300. UnsubscribeFromEvent(E_PHYSICSPRESTEP);
  301. UnsubscribeFromEvent(E_PHYSICSPOSTSTEP);
  302. #endif
  303. currentEventMask_ = 0;
  304. }
  305. }
  306. void JSComponent::UpdateEventSubscription()
  307. {
  308. Scene* scene = GetScene();
  309. if (!scene)
  310. return;
  311. bool enabled = IsEnabledEffective();
  312. bool needUpdate = enabled && ((updateEventMask_ & USE_UPDATE) || !delayedStartCalled_);
  313. if (needUpdate && !(currentEventMask_ & USE_UPDATE))
  314. {
  315. SubscribeToEvent(scene, E_SCENEUPDATE, ATOMIC_HANDLER(JSComponent, HandleSceneUpdate));
  316. currentEventMask_ |= USE_UPDATE;
  317. }
  318. else if (!needUpdate && (currentEventMask_ & USE_UPDATE))
  319. {
  320. UnsubscribeFromEvent(scene, E_SCENEUPDATE);
  321. currentEventMask_ &= ~USE_UPDATE;
  322. }
  323. bool needPostUpdate = enabled && (updateEventMask_ & USE_POSTUPDATE);
  324. if (needPostUpdate && !(currentEventMask_ & USE_POSTUPDATE))
  325. {
  326. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, ATOMIC_HANDLER(JSComponent, HandleScenePostUpdate));
  327. currentEventMask_ |= USE_POSTUPDATE;
  328. }
  329. else if (!needPostUpdate && (currentEventMask_ & USE_POSTUPDATE))
  330. {
  331. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  332. currentEventMask_ &= ~USE_POSTUPDATE;
  333. }
  334. #ifdef ATOMIC_PHYSICS
  335. PhysicsWorld* world = scene->GetComponent<PhysicsWorld>();
  336. if (!world)
  337. return;
  338. bool needFixedUpdate = enabled && (updateEventMask_ & USE_FIXEDUPDATE);
  339. if (needFixedUpdate && !(currentEventMask_ & USE_FIXEDUPDATE))
  340. {
  341. SubscribeToEvent(world, E_PHYSICSPRESTEP, ATOMIC_HANDLER(JSComponent, HandlePhysicsPreStep));
  342. currentEventMask_ |= USE_FIXEDUPDATE;
  343. }
  344. else if (!needFixedUpdate && (currentEventMask_ & USE_FIXEDUPDATE))
  345. {
  346. UnsubscribeFromEvent(world, E_PHYSICSPRESTEP);
  347. currentEventMask_ &= ~USE_FIXEDUPDATE;
  348. }
  349. bool needFixedPostUpdate = enabled && (updateEventMask_ & USE_FIXEDPOSTUPDATE);
  350. if (needFixedPostUpdate && !(currentEventMask_ & USE_FIXEDPOSTUPDATE))
  351. {
  352. SubscribeToEvent(world, E_PHYSICSPOSTSTEP, ATOMIC_HANDLER(JSComponent, HandlePhysicsPostStep));
  353. currentEventMask_ |= USE_FIXEDPOSTUPDATE;
  354. }
  355. else if (!needFixedPostUpdate && (currentEventMask_ & USE_FIXEDPOSTUPDATE))
  356. {
  357. UnsubscribeFromEvent(world, E_PHYSICSPOSTSTEP);
  358. currentEventMask_ &= ~USE_FIXEDPOSTUPDATE;
  359. }
  360. #endif
  361. }
  362. void JSComponent::HandleSceneUpdate(StringHash eventType, VariantMap& eventData)
  363. {
  364. using namespace SceneUpdate;
  365. assert(!destroyed_);
  366. // Execute user-defined delayed start function before first update
  367. if (!delayedStartCalled_)
  368. {
  369. DelayedStart();
  370. delayedStartCalled_ = true;
  371. // If did not need actual update events, unsubscribe now
  372. if (!(updateEventMask_ & USE_UPDATE))
  373. {
  374. UnsubscribeFromEvent(GetScene(), E_SCENEUPDATE);
  375. currentEventMask_ &= ~USE_UPDATE;
  376. return;
  377. }
  378. }
  379. // Then execute user-defined update function
  380. Update(eventData[P_TIMESTEP].GetFloat());
  381. }
  382. void JSComponent::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  383. {
  384. using namespace ScenePostUpdate;
  385. // Execute user-defined post-update function
  386. PostUpdate(eventData[P_TIMESTEP].GetFloat());
  387. }
  388. #ifdef ATOMIC_PHYSICS
  389. void JSComponent::HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData)
  390. {
  391. using namespace PhysicsPreStep;
  392. // Execute user-defined fixed update function
  393. FixedUpdate(eventData[P_TIMESTEP].GetFloat());
  394. }
  395. void JSComponent::HandlePhysicsPostStep(StringHash eventType, VariantMap& eventData)
  396. {
  397. using namespace PhysicsPostStep;
  398. // Execute user-defined fixed post-update function
  399. FixedPostUpdate(eventData[P_TIMESTEP].GetFloat());
  400. }
  401. #endif
  402. bool JSComponent::MatchScriptName(const String& path)
  403. {
  404. if (componentFile_.Null())
  405. return false;
  406. String _path = path;
  407. _path.Replace(".js", "", false);
  408. const String& name = componentFile_->GetName();
  409. if (_path == name)
  410. return true;
  411. String pathName, fileName, ext;
  412. SplitPath(name, pathName, fileName, ext);
  413. if (fileName == _path)
  414. return true;
  415. return false;
  416. }
  417. ResourceRef JSComponent::GetComponentFileAttr() const
  418. {
  419. return GetResourceRef(componentFile_, JSComponentFile::GetTypeStatic());
  420. }
  421. void JSComponent::SetComponentFileAttr(const ResourceRef& value)
  422. {
  423. ResourceCache* cache = GetSubsystem<ResourceCache>();
  424. SetComponentFile(cache->GetResource<JSComponentFile>(value.name_));
  425. }
  426. }