JSVM.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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 "JSEvents.h"
  13. #include "JSVM.h"
  14. #include "JSAtomic.h"
  15. #include "JSUI.h"
  16. namespace Atomic
  17. {
  18. JSVM* JSVM::instance_ = NULL;
  19. JSVM::JSVM(Context* context) :
  20. Object(context),
  21. ctx_(0),
  22. gcTime_(0.0f)
  23. {
  24. assert(!instance_);
  25. instance_ = this;
  26. }
  27. JSVM::~JSVM()
  28. {
  29. duk_destroy_heap(ctx_);
  30. instance_ = NULL;
  31. }
  32. void JSVM::InitJSContext()
  33. {
  34. ctx_ = duk_create_heap_default();
  35. // create root Atomic Object
  36. duk_push_global_object(ctx_);
  37. duk_push_object(ctx_);
  38. duk_put_prop_string(ctx_, -2, "Atomic");
  39. duk_pop(ctx_);
  40. duk_push_global_stash(ctx_);
  41. duk_push_object(ctx_);
  42. duk_put_prop_index(ctx_, -2, JS_GLOBALSTASH_INDEX_COMPONENTS);
  43. duk_pop(ctx_);
  44. duk_get_global_string(ctx_, "Duktape");
  45. duk_push_c_function(ctx_, js_module_search, 1);
  46. duk_put_prop_string(ctx_, -2, "modSearch");
  47. duk_pop(ctx_);
  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. int JSVM::js_module_search(duk_context* ctx)
  235. {
  236. JSVM* vm = GetJSVM(ctx);
  237. ResourceCache* cache = vm->GetContext()->GetSubsystem<ResourceCache>();
  238. String path = duk_to_string(ctx, 0);
  239. // first check if this is an AtomicModule
  240. // attempting to avoid module search paths
  241. // so have AtomicEditor, Atomic, and the projects "Modules"
  242. String pathName, fileName, extension;
  243. SplitPath(path, pathName, fileName, extension);
  244. if (fileName.StartsWith("AtomicEditor"))
  245. {
  246. path = "AtomicEditor/Modules/" + path + ".js";
  247. }
  248. else if (fileName.StartsWith("Atomic"))
  249. {
  250. path = "AtomicModules/" + path + ".js";
  251. }
  252. else
  253. {
  254. path = vm->moduleSearchPath_ + "/" + path + ".js";
  255. }
  256. SharedPtr<File> jsfile(cache->GetFile(path));
  257. if (!jsfile)
  258. {
  259. duk_push_null(ctx);
  260. }
  261. else
  262. {
  263. vm->SetLastModuleSearchFile(jsfile->GetFullPath());
  264. String source;
  265. jsfile->ReadText(source);
  266. duk_push_string(ctx, source.CString());
  267. }
  268. return 1;
  269. }
  270. void JSVM::SendJSErrorEvent(const String& filename)
  271. {
  272. duk_context* ctx = GetJSContext();
  273. assert(duk_is_object(ctx, -1));
  274. using namespace JSError;
  275. VariantMap eventData;
  276. duk_get_prop_string(ctx, -1, "fileName");
  277. if (duk_is_string(ctx, -1))
  278. {
  279. eventData[P_ERRORFILENAME] = duk_to_string(ctx, -1);
  280. }
  281. else
  282. {
  283. eventData[P_ERRORFILENAME] = filename;
  284. }
  285. // Component script are wrapped within a closure, the line number
  286. // needs to be offset by this header
  287. duk_get_prop_string(ctx, -2, "lineNumber");
  288. int lineNumber = (int) (duk_to_number(ctx, -1));
  289. eventData[P_ERRORLINENUMBER] = lineNumber;
  290. duk_get_prop_string(ctx, -3, "name");
  291. String name = duk_to_string(ctx, -1);
  292. eventData[P_ERRORNAME] = name;
  293. duk_get_prop_string(ctx, -4, "message");
  294. String message = duk_to_string(ctx, -1);
  295. eventData[P_ERRORMESSAGE] = message;
  296. // we're not getting good file/line from duktape on parser errors
  297. if (name == "SyntaxError")
  298. {
  299. lineNumber = -1;
  300. // parse line if we have it
  301. if (message.Contains("(line "))
  302. {
  303. if (!filename.Length())
  304. eventData[P_ERRORFILENAME] = lastModuleSearchFilename_;
  305. unsigned pos = message.Find("(line ");
  306. const char* parse = message.CString() + pos + 6;
  307. String number;
  308. while (*parse >= '0' && *parse<='9')
  309. {
  310. number += *parse;
  311. parse++;
  312. }
  313. lineNumber = ToInt(number);
  314. }
  315. eventData[P_ERRORLINENUMBER] = lineNumber;
  316. }
  317. duk_get_prop_string(ctx, -5, "stack");
  318. String stack = duk_to_string(ctx, -1);
  319. eventData[P_ERRORSTACK] = stack;
  320. duk_pop_n(ctx, 5);
  321. LOGERRORF("JSErrorEvent: %s : Line %i\n Name: %s\n Message: %s\n Stack:%s",
  322. filename.CString(), lineNumber, name.CString(), message.CString(), stack.CString());
  323. SendEvent(E_JSERROR, eventData);
  324. }
  325. bool JSVM::ExecuteScript(const String& scriptPath)
  326. {
  327. String path = scriptPath;
  328. if (!path.StartsWith("Scripts/"))
  329. path = "Scripts/" + path;
  330. if (!path.EndsWith(".js"))
  331. path += ".js";
  332. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile(path));
  333. if (file.Null())
  334. {
  335. return false;
  336. }
  337. String source;
  338. file->ReadText(source);
  339. duk_push_string(ctx_, file->GetFullPath().CString());
  340. if (duk_eval_raw(ctx_, source.CString(), 0,
  341. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  342. {
  343. if (duk_is_object(ctx_, -1))
  344. SendJSErrorEvent(path);
  345. duk_pop(ctx_);
  346. return false;
  347. }
  348. duk_pop(ctx_);
  349. return true;
  350. }
  351. bool JSVM::ExecuteFile(File *file)
  352. {
  353. if (!file)
  354. return false;
  355. String source;
  356. file->ReadText(source);
  357. duk_push_string(ctx_, file->GetFullPath().CString());
  358. if (duk_eval_raw(ctx_, source.CString(), 0,
  359. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  360. {
  361. if (duk_is_object(ctx_, -1))
  362. SendJSErrorEvent(file->GetFullPath());
  363. duk_pop(ctx_);
  364. return false;
  365. }
  366. duk_pop(ctx_);
  367. return true;
  368. }
  369. bool JSVM::ExecuteMain()
  370. {
  371. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile("Scripts/main.js"));
  372. if (file.Null())
  373. {
  374. return false;
  375. }
  376. String source;
  377. file->ReadText(source);
  378. duk_push_string(ctx_, file->GetFullPath().CString());
  379. if (duk_eval_raw(ctx_, source.CString(), 0,
  380. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  381. {
  382. if (duk_is_object(ctx_, -1))
  383. SendJSErrorEvent(file->GetFullPath());
  384. duk_pop(ctx_);
  385. return false;
  386. }
  387. duk_pop(ctx_);
  388. return true;
  389. }
  390. }