JSVM.cpp 11 KB

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