JSVM.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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 "Precompiled.h"
  5. #include <Duktape/duktape.h>
  6. #include "../Core/Profiler.h"
  7. #include "../Core/CoreEvents.h"
  8. #include "../IO/File.h"
  9. #include "../IO/Log.h"
  10. #include "../IO/FileSystem.h"
  11. #include "../IO/PackageFile.h"
  12. #include "../Resource/ResourceCache.h"
  13. #include "../Javascript/JSEvents.h"
  14. #include "../Javascript/JSVM.h"
  15. #include "../Javascript/JSAtomic.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. // handle this elsewhere?
  51. SubscribeToEvents();
  52. }
  53. void JSVM::SubscribeToEvents()
  54. {
  55. SubscribeToEvent(E_UPDATE, HANDLER(JSVM, HandleUpdate));
  56. }
  57. void JSVM::HandleUpdate(StringHash eventType, VariantMap& eventData)
  58. {
  59. PROFILE(JSVM_HandleUpdate);
  60. using namespace Update;
  61. // Take the frame time step, which is stored as a float
  62. float timeStep = eventData[P_TIMESTEP].GetFloat();
  63. gcTime_ += timeStep;
  64. if (gcTime_ > 5.0f)
  65. {
  66. PROFILE(JSVM_GC);
  67. // run twice to call finalizers
  68. // see duktape docs
  69. // also ensure #define DUK_OPT_NO_VOLUNTARY_GC
  70. // is enabled in duktape.h
  71. duk_gc(ctx_, 0);
  72. duk_gc(ctx_, 0);
  73. gcTime_ = 0;
  74. }
  75. duk_get_global_string(ctx_, "__js_atomicgame_update");
  76. if (duk_is_function(ctx_, -1))
  77. {
  78. duk_push_number(ctx_, timeStep);
  79. duk_pcall(ctx_, 1);
  80. duk_pop(ctx_);
  81. }
  82. else
  83. {
  84. duk_pop(ctx_);
  85. }
  86. }
  87. bool JSVM::ExecuteFunction(const String& functionName)
  88. {
  89. duk_get_global_string(ctx_, functionName.CString());
  90. if (duk_is_function(ctx_, -1))
  91. {
  92. bool ok = true;
  93. if (duk_pcall(ctx_, 0) != 0)
  94. {
  95. ok = false;
  96. if (duk_is_object(ctx_, -1))
  97. {
  98. SendJSErrorEvent();
  99. }
  100. else
  101. {
  102. assert(0);
  103. }
  104. }
  105. duk_pop(ctx_);
  106. return ok;
  107. }
  108. else
  109. {
  110. duk_pop(ctx_);
  111. }
  112. return false;
  113. }
  114. bool JSVM::GenerateComponent(const String &cname, const String &jsfilename, const String& csource)
  115. {
  116. String source = "(function() {var start = null; var update = null; var fixedUpdate = null; var postUpdate = null;\n function __component_function(self) {\n";
  117. source += csource.CString();
  118. source += "self.node.components = self.node.components || {};\n";
  119. source.AppendWithFormat("self.node.components[\"%s\"] = self.node.components[\"%s\"] || [];\n",
  120. cname.CString(), cname.CString());
  121. source += "if (start instanceof Function) self.start = start; " \
  122. "if (update instanceof Function) self.update = update; "\
  123. "if (fixedUpdate instanceof Function) self.fixedUpdate = fixedUpdate; " \
  124. "if (postUpdate instanceof Function) self.postUpdate = postUpdate;\n";
  125. String scriptName = cname;
  126. scriptName[0] = tolower(scriptName[0]);
  127. source.AppendWithFormat("self.node.%s = self.node.%s || self;\n",
  128. scriptName.CString(), scriptName.CString());
  129. source.AppendWithFormat("self.node.components[\"%s\"].push(self);\n",
  130. cname.CString());
  131. source += "}\n return __component_function;\n});";
  132. duk_push_string(ctx_, jsfilename.CString());
  133. if (duk_eval_raw(ctx_, source.CString(), source.Length(),
  134. DUK_COMPILE_EVAL | DUK_COMPILE_NOSOURCE | DUK_COMPILE_SAFE) != 0)
  135. {
  136. if (duk_is_object(ctx_, -1))
  137. {
  138. SendJSErrorEvent(jsfilename);
  139. duk_pop(ctx_);
  140. }
  141. else
  142. {
  143. assert(0);
  144. }
  145. }
  146. else if (duk_pcall(ctx_, 0) != 0)
  147. {
  148. if (duk_is_object(ctx_, -1))
  149. {
  150. SendJSErrorEvent(jsfilename);
  151. duk_pop(ctx_);
  152. }
  153. else
  154. {
  155. assert(0);
  156. }
  157. }
  158. else
  159. {
  160. if (!duk_is_function(ctx_, -1))
  161. {
  162. const char* error = duk_to_string(ctx_, -1);
  163. SendJSErrorEvent();
  164. }
  165. duk_put_prop_string(ctx_, -2, cname.CString());
  166. return true;
  167. }
  168. return false;
  169. }
  170. void JSVM::InitPackageComponents()
  171. {
  172. ResourceCache* cache = GetSubsystem<ResourceCache>();
  173. duk_push_global_stash(ctx_);
  174. duk_get_prop_index(ctx_, -1, JS_GLOBALSTASH_INDEX_COMPONENTS);
  175. const Vector<SharedPtr<PackageFile> >& packageFiles = cache->GetPackageFiles();
  176. for (unsigned i = 0; i < packageFiles.Size(); i++)
  177. {
  178. SharedPtr<PackageFile> package = packageFiles[i];
  179. const Vector<String>& files = package->GetCaseEntryNames();
  180. for (unsigned j = 0; j < files.Size(); j++)
  181. {
  182. String name = files[j];
  183. if (!name.StartsWith("Components/"))
  184. continue;
  185. String cname = GetFileName(name);
  186. String jsname = name;
  187. SharedPtr<File> jsfile(cache->GetFile(name));
  188. String csource;
  189. jsfile->ReadText(csource);
  190. if (!GenerateComponent(cname, jsname, csource))
  191. break;
  192. }
  193. }
  194. // pop stash and component object
  195. duk_pop_2(ctx_);
  196. }
  197. void JSVM::InitComponents()
  198. {
  199. ResourceCache* cache = GetSubsystem<ResourceCache>();
  200. if (cache->GetPackageFiles().Size())
  201. {
  202. InitPackageComponents();
  203. return;
  204. }
  205. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  206. const Vector<String>& dirs = cache->GetResourceDirs();
  207. duk_push_global_stash(ctx_);
  208. duk_get_prop_index(ctx_, -1, JS_GLOBALSTASH_INDEX_COMPONENTS);
  209. for (unsigned i = 0; i < dirs.Size(); i++)
  210. {
  211. Vector<String> files;
  212. fileSystem->ScanDir(files ,dirs[i]+"/Components", "*.js", SCAN_FILES, true );
  213. for (unsigned j = 0; j < files.Size(); j++)
  214. {
  215. String cname = GetFileName(files[j]);
  216. String jsname = dirs[i]+"Components/" + files[j];
  217. SharedPtr<File> jsfile = cache->GetFile("Components/" + files[j]);
  218. String csource;
  219. jsfile->ReadText(csource);
  220. if (!GenerateComponent(cname, jsname, csource))
  221. break;
  222. }
  223. }
  224. // pop stash and component object
  225. duk_pop_2(ctx_);
  226. }
  227. int JSVM::js_module_search(duk_context* ctx)
  228. {
  229. JSVM* vm = GetJSVM(ctx);
  230. ResourceCache* cache = vm->GetContext()->GetSubsystem<ResourceCache>();
  231. String path = duk_to_string(ctx, 0);
  232. // first check if this is an AtomicModule
  233. // attempting to avoid module search paths
  234. // so have AtomicEditor, Atomic, and the projects "Modules"
  235. String pathName, fileName, extension;
  236. SplitPath(path, pathName, fileName, extension);
  237. if (fileName.StartsWith("AtomicEditor"))
  238. {
  239. path = "AtomicEditor/Modules/" + path + ".js";
  240. }
  241. else if (fileName.StartsWith("Atomic"))
  242. {
  243. path = "AtomicModules/" + path + ".js";
  244. }
  245. else
  246. {
  247. path = vm->moduleSearchPath_ + "/" + path + ".js";
  248. }
  249. SharedPtr<File> jsfile(cache->GetFile(path));
  250. if (!jsfile)
  251. {
  252. duk_push_null(ctx);
  253. }
  254. else
  255. {
  256. vm->SetLastModuleSearchFile(jsfile->GetFullPath());
  257. String source;
  258. jsfile->ReadText(source);
  259. duk_push_string(ctx, source.CString());
  260. }
  261. return 1;
  262. }
  263. void JSVM::SendJSErrorEvent(const String& filename)
  264. {
  265. duk_context* ctx = GetJSContext();
  266. assert(duk_is_object(ctx, -1));
  267. using namespace JSError;
  268. VariantMap eventData;
  269. duk_get_prop_string(ctx, -1, "fileName");
  270. if (duk_is_string(ctx, -1))
  271. {
  272. eventData[P_ERRORFILENAME] = duk_to_string(ctx, -1);
  273. }
  274. else
  275. {
  276. eventData[P_ERRORFILENAME] = filename;
  277. }
  278. // Component script are wrapped within a closure, the line number
  279. // needs to be offset by this header
  280. duk_get_prop_string(ctx, -2, "lineNumber");
  281. int lineNumber = (int) (duk_to_number(ctx, -1));
  282. eventData[P_ERRORLINENUMBER] = lineNumber;
  283. duk_get_prop_string(ctx, -3, "name");
  284. String name = duk_to_string(ctx, -1);
  285. eventData[P_ERRORNAME] = name;
  286. duk_get_prop_string(ctx, -4, "message");
  287. String message = duk_to_string(ctx, -1);
  288. eventData[P_ERRORMESSAGE] = message;
  289. // we're not getting good file/line from duktape on parser errors
  290. if (name == "SyntaxError")
  291. {
  292. lineNumber = -1;
  293. // parse line if we have it
  294. if (message.Contains("(line "))
  295. {
  296. if (!filename.Length())
  297. eventData[P_ERRORFILENAME] = lastModuleSearchFilename_;
  298. unsigned pos = message.Find("(line ");
  299. const char* parse = message.CString() + pos + 6;
  300. String number;
  301. while (*parse >= '0' && *parse<='9')
  302. {
  303. number += *parse;
  304. parse++;
  305. }
  306. lineNumber = ToInt(number);
  307. }
  308. eventData[P_ERRORLINENUMBER] = lineNumber;
  309. }
  310. duk_get_prop_string(ctx, -5, "stack");
  311. String stack = duk_to_string(ctx, -1);
  312. eventData[P_ERRORSTACK] = stack;
  313. duk_pop_n(ctx, 5);
  314. LOGERRORF("JSErrorEvent: %s : Line %i\n Name: %s\n Message: %s\n Stack:%s",
  315. filename.CString(), lineNumber, name.CString(), message.CString(), stack.CString());
  316. SendEvent(E_JSERROR, eventData);
  317. }
  318. bool JSVM::ExecuteScript(const String& scriptPath)
  319. {
  320. String path = scriptPath;
  321. if (!path.StartsWith("Scripts/"))
  322. path = "Scripts/" + path;
  323. if (!path.EndsWith(".js"))
  324. path += ".js";
  325. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile(path));
  326. if (file.Null())
  327. {
  328. return false;
  329. }
  330. String source;
  331. file->ReadText(source);
  332. duk_push_string(ctx_, file->GetFullPath().CString());
  333. if (duk_eval_raw(ctx_, source.CString(), 0,
  334. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  335. {
  336. if (duk_is_object(ctx_, -1))
  337. SendJSErrorEvent(path);
  338. duk_pop(ctx_);
  339. return false;
  340. }
  341. duk_pop(ctx_);
  342. return true;
  343. }
  344. bool JSVM::ExecuteFile(File *file)
  345. {
  346. if (!file)
  347. return false;
  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. bool JSVM::ExecuteMain()
  363. {
  364. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile("Scripts/main.js"));
  365. if (file.Null())
  366. {
  367. return false;
  368. }
  369. String source;
  370. file->ReadText(source);
  371. duk_push_string(ctx_, file->GetFullPath().CString());
  372. if (duk_eval_raw(ctx_, source.CString(), 0,
  373. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  374. {
  375. if (duk_is_object(ctx_, -1))
  376. SendJSErrorEvent(file->GetFullPath());
  377. duk_pop(ctx_);
  378. return false;
  379. }
  380. duk_pop(ctx_);
  381. return true;
  382. }
  383. }