JSVM.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  2. // Please see LICENSE.md in repository root for license information
  3. // https://github.com/AtomicGameEngine/AtomicGameEngine
  4. #include <Duktape/duktape.h>
  5. #include <Atomic/Core/Profiler.h>
  6. #include <Atomic/Core/CoreEvents.h>
  7. #include <Atomic/IO/File.h>
  8. #include <Atomic/IO/Log.h>
  9. #include <Atomic/IO/FileSystem.h>
  10. #include <Atomic/IO/PackageFile.h>
  11. #include <Atomic/Resource/ResourceCache.h>
  12. #include "JSRequire.h"
  13. #include "JSEvents.h"
  14. #include "JSVM.h"
  15. #include "JSAtomic.h"
  16. #include "JSUI.h"
  17. #include "JSMetrics.h"
  18. namespace Atomic
  19. {
  20. JSVM* JSVM::instance_ = NULL;
  21. JSVM::JSVM(Context* context) :
  22. Object(context),
  23. ctx_(0),
  24. gcTime_(0.0f)
  25. {
  26. assert(!instance_);
  27. instance_ = this;
  28. metrics_ = new JSMetrics(context, this);
  29. }
  30. JSVM::~JSVM()
  31. {
  32. duk_destroy_heap(ctx_);
  33. instance_ = NULL;
  34. }
  35. void JSVM::InitJSContext()
  36. {
  37. ctx_ = duk_create_heap_default();
  38. // create root Atomic Object
  39. duk_push_global_object(ctx_);
  40. duk_push_object(ctx_);
  41. duk_put_prop_string(ctx_, -2, "Atomic");
  42. duk_pop(ctx_);
  43. duk_push_global_stash(ctx_);
  44. duk_push_object(ctx_);
  45. duk_put_prop_index(ctx_, -2, JS_GLOBALSTASH_INDEX_COMPONENTS);
  46. duk_pop(ctx_);
  47. js_init_require(this);
  48. jsapi_init_atomic(this);
  49. InitComponents();
  50. ui_ = new JSUI(context_);
  51. // handle this elsewhere?
  52. SubscribeToEvents();
  53. }
  54. void JSVM::SubscribeToEvents()
  55. {
  56. SubscribeToEvent(E_UPDATE, HANDLER(JSVM, HandleUpdate));
  57. }
  58. void JSVM::HandleUpdate(StringHash eventType, VariantMap& eventData)
  59. {
  60. PROFILE(JSVM_HandleUpdate);
  61. using namespace Update;
  62. // Take the frame time step, which is stored as a float
  63. float timeStep = eventData[P_TIMESTEP].GetFloat();
  64. gcTime_ += timeStep;
  65. if (gcTime_ > 5.0f)
  66. {
  67. PROFILE(JSVM_GC);
  68. // run twice to call finalizers
  69. // see duktape docs
  70. // also ensure #define DUK_OPT_NO_VOLUNTARY_GC
  71. // is enabled in duktape.h
  72. duk_gc(ctx_, 0);
  73. duk_gc(ctx_, 0);
  74. gcTime_ = 0;
  75. }
  76. duk_get_global_string(ctx_, "__js_atomicgame_update");
  77. if (duk_is_function(ctx_, -1))
  78. {
  79. duk_push_number(ctx_, timeStep);
  80. duk_pcall(ctx_, 1);
  81. duk_pop(ctx_);
  82. }
  83. else
  84. {
  85. duk_pop(ctx_);
  86. }
  87. }
  88. bool JSVM::ExecuteFunction(const String& functionName)
  89. {
  90. duk_get_global_string(ctx_, functionName.CString());
  91. if (duk_is_function(ctx_, -1))
  92. {
  93. bool ok = true;
  94. if (duk_pcall(ctx_, 0) != 0)
  95. {
  96. ok = false;
  97. if (duk_is_object(ctx_, -1))
  98. {
  99. SendJSErrorEvent();
  100. }
  101. else
  102. {
  103. assert(0);
  104. }
  105. }
  106. duk_pop(ctx_);
  107. return ok;
  108. }
  109. else
  110. {
  111. duk_pop(ctx_);
  112. }
  113. return false;
  114. }
  115. bool JSVM::GenerateComponent(const String &cname, const String &jsfilename, const String& csource)
  116. {
  117. String source = "(function() {var start = null; var update = null; var fixedUpdate = null; var postUpdate = null;\n function __component_function(self) {\n";
  118. source += csource.CString();
  119. source += "self.node.components = self.node.components || {};\n";
  120. source.AppendWithFormat("self.node.components[\"%s\"] = self.node.components[\"%s\"] || [];\n",
  121. cname.CString(), cname.CString());
  122. source += "if (start instanceof Function) self.start = start; " \
  123. "if (update instanceof Function) self.update = update; "\
  124. "if (fixedUpdate instanceof Function) self.fixedUpdate = fixedUpdate; " \
  125. "if (postUpdate instanceof Function) self.postUpdate = postUpdate;\n";
  126. String scriptName = cname;
  127. scriptName[0] = tolower(scriptName[0]);
  128. source.AppendWithFormat("self.node.%s = self.node.%s || self;\n",
  129. scriptName.CString(), scriptName.CString());
  130. source.AppendWithFormat("self.node.components[\"%s\"].push(self);\n",
  131. cname.CString());
  132. source += "}\n return __component_function;\n});";
  133. duk_push_string(ctx_, jsfilename.CString());
  134. if (duk_eval_raw(ctx_, source.CString(), source.Length(),
  135. DUK_COMPILE_EVAL | DUK_COMPILE_NOSOURCE | DUK_COMPILE_SAFE) != 0)
  136. {
  137. if (duk_is_object(ctx_, -1))
  138. {
  139. SendJSErrorEvent(jsfilename);
  140. duk_pop(ctx_);
  141. }
  142. else
  143. {
  144. assert(0);
  145. }
  146. }
  147. else if (duk_pcall(ctx_, 0) != 0)
  148. {
  149. if (duk_is_object(ctx_, -1))
  150. {
  151. SendJSErrorEvent(jsfilename);
  152. duk_pop(ctx_);
  153. }
  154. else
  155. {
  156. assert(0);
  157. }
  158. }
  159. else
  160. {
  161. if (!duk_is_function(ctx_, -1))
  162. {
  163. const char* error = duk_to_string(ctx_, -1);
  164. SendJSErrorEvent();
  165. }
  166. duk_put_prop_string(ctx_, -2, cname.CString());
  167. return true;
  168. }
  169. return false;
  170. }
  171. void JSVM::InitPackageComponents()
  172. {
  173. ResourceCache* cache = GetSubsystem<ResourceCache>();
  174. duk_push_global_stash(ctx_);
  175. duk_get_prop_index(ctx_, -1, JS_GLOBALSTASH_INDEX_COMPONENTS);
  176. const Vector<SharedPtr<PackageFile> >& packageFiles = cache->GetPackageFiles();
  177. for (unsigned i = 0; i < packageFiles.Size(); i++)
  178. {
  179. SharedPtr<PackageFile> package = packageFiles[i];
  180. const Vector<String>& files = package->GetCaseEntryNames();
  181. for (unsigned j = 0; j < files.Size(); j++)
  182. {
  183. String name = files[j];
  184. if (!name.StartsWith("Components/"))
  185. continue;
  186. String cname = GetFileName(name);
  187. String jsname = name;
  188. SharedPtr<File> jsfile(cache->GetFile(name));
  189. String csource;
  190. jsfile->ReadText(csource);
  191. if (!GenerateComponent(cname, jsname, csource))
  192. break;
  193. }
  194. }
  195. // pop stash and component object
  196. duk_pop_2(ctx_);
  197. }
  198. void JSVM::InitComponents()
  199. {
  200. ResourceCache* cache = GetSubsystem<ResourceCache>();
  201. // TODO: better way to detect player?
  202. const Vector<SharedPtr<PackageFile> >& packageFiles = cache->GetPackageFiles();
  203. for (unsigned i = 0; i < packageFiles.Size(); i++)
  204. {
  205. String packageName = packageFiles[i]->GetName();
  206. if (packageName.Find("AtomicResources") != String::NPOS)
  207. {
  208. InitPackageComponents();
  209. return;
  210. }
  211. }
  212. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  213. const Vector<String>& dirs = cache->GetResourceDirs();
  214. duk_push_global_stash(ctx_);
  215. duk_get_prop_index(ctx_, -1, JS_GLOBALSTASH_INDEX_COMPONENTS);
  216. for (unsigned i = 0; i < dirs.Size(); i++)
  217. {
  218. Vector<String> files;
  219. fileSystem->ScanDir(files ,dirs[i]+"/Components", "*.js", SCAN_FILES, true );
  220. for (unsigned j = 0; j < files.Size(); j++)
  221. {
  222. String cname = GetFileName(files[j]);
  223. String jsname = dirs[i]+"Components/" + files[j];
  224. SharedPtr<File> jsfile = cache->GetFile("Components/" + files[j]);
  225. String csource;
  226. jsfile->ReadText(csource);
  227. if (!GenerateComponent(cname, jsname, csource))
  228. break;
  229. }
  230. }
  231. // pop stash and component object
  232. duk_pop_2(ctx_);
  233. }
  234. void JSVM::SendJSErrorEvent(const String& filename)
  235. {
  236. duk_context* ctx = GetJSContext();
  237. assert(duk_is_object(ctx, -1));
  238. using namespace JSError;
  239. VariantMap eventData;
  240. duk_get_prop_string(ctx, -1, "fileName");
  241. if (duk_is_string(ctx, -1))
  242. {
  243. eventData[P_ERRORFILENAME] = duk_to_string(ctx, -1);
  244. }
  245. else
  246. {
  247. eventData[P_ERRORFILENAME] = filename;
  248. }
  249. // Component script are wrapped within a closure, the line number
  250. // needs to be offset by this header
  251. duk_get_prop_string(ctx, -2, "lineNumber");
  252. int lineNumber = (int) (duk_to_number(ctx, -1));
  253. eventData[P_ERRORLINENUMBER] = lineNumber;
  254. duk_get_prop_string(ctx, -3, "name");
  255. String name = duk_to_string(ctx, -1);
  256. eventData[P_ERRORNAME] = name;
  257. duk_get_prop_string(ctx, -4, "message");
  258. String message = duk_to_string(ctx, -1);
  259. eventData[P_ERRORMESSAGE] = message;
  260. // we're not getting good file/line from duktape on parser errors
  261. if (name == "SyntaxError")
  262. {
  263. lineNumber = -1;
  264. // parse line if we have it
  265. if (message.Contains("(line "))
  266. {
  267. if (!filename.Length())
  268. eventData[P_ERRORFILENAME] = lastModuleSearchFilename_;
  269. unsigned pos = message.Find("(line ");
  270. const char* parse = message.CString() + pos + 6;
  271. String number;
  272. while (*parse >= '0' && *parse<='9')
  273. {
  274. number += *parse;
  275. parse++;
  276. }
  277. lineNumber = ToInt(number);
  278. }
  279. eventData[P_ERRORLINENUMBER] = lineNumber;
  280. }
  281. duk_get_prop_string(ctx, -5, "stack");
  282. String stack = duk_to_string(ctx, -1);
  283. eventData[P_ERRORSTACK] = stack;
  284. duk_pop_n(ctx, 5);
  285. LOGERRORF("JSErrorEvent: %s : Line %i\n Name: %s\n Message: %s\n Stack:%s",
  286. filename.CString(), lineNumber, name.CString(), message.CString(), stack.CString());
  287. SendEvent(E_JSERROR, eventData);
  288. }
  289. bool JSVM::ExecuteScript(const String& scriptPath)
  290. {
  291. String path = scriptPath;
  292. if (!path.StartsWith("Scripts/"))
  293. path = "Scripts/" + path;
  294. if (!path.EndsWith(".js"))
  295. path += ".js";
  296. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile(path));
  297. if (file.Null())
  298. {
  299. return false;
  300. }
  301. String source;
  302. file->ReadText(source);
  303. duk_push_string(ctx_, file->GetFullPath().CString());
  304. if (duk_eval_raw(ctx_, source.CString(), 0,
  305. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  306. {
  307. if (duk_is_object(ctx_, -1))
  308. SendJSErrorEvent(path);
  309. duk_pop(ctx_);
  310. return false;
  311. }
  312. duk_pop(ctx_);
  313. return true;
  314. }
  315. bool JSVM::ExecuteFile(File *file)
  316. {
  317. if (!file)
  318. return false;
  319. String source;
  320. file->ReadText(source);
  321. duk_push_string(ctx_, file->GetFullPath().CString());
  322. if (duk_eval_raw(ctx_, source.CString(), 0,
  323. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  324. {
  325. if (duk_is_object(ctx_, -1))
  326. SendJSErrorEvent(file->GetFullPath());
  327. duk_pop(ctx_);
  328. return false;
  329. }
  330. duk_pop(ctx_);
  331. return true;
  332. }
  333. void JSVM::GC()
  334. {
  335. // run twice to ensure finalizers are run
  336. duk_gc(ctx_, 0);
  337. duk_gc(ctx_, 0);
  338. }
  339. bool JSVM::ExecuteMain()
  340. {
  341. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile("Scripts/main.js"));
  342. if (file.Null())
  343. {
  344. return false;
  345. }
  346. String source;
  347. file->ReadText(source);
  348. duk_push_string(ctx_, file->GetFullPath().CString());
  349. if (duk_eval_raw(ctx_, source.CString(), 0,
  350. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  351. {
  352. if (duk_is_object(ctx_, -1))
  353. SendJSErrorEvent(file->GetFullPath());
  354. duk_pop(ctx_);
  355. return false;
  356. }
  357. duk_pop(ctx_);
  358. return true;
  359. }
  360. }