JSVM.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. void JSVM::GenerateComponent(const String &cname, const String &jsfilename, const String& csource)
  115. {
  116. String source = "(function() {\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 (typeof start != \"undefined\") self.start = start; " \
  122. "if (typeof update != \"undefined\") self.update = update; "\
  123. "if (typeof fixedUpdate != \"undefined\") self.fixedUpdate = fixedUpdate; " \
  124. "if (typeof postUpdate != \"undefined\") 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. assert(false);
  164. }
  165. duk_put_prop_string(ctx_, -2, cname.CString());
  166. }
  167. }
  168. void JSVM::InitPackageComponents()
  169. {
  170. ResourceCache* cache = GetSubsystem<ResourceCache>();
  171. duk_push_global_stash(ctx_);
  172. duk_get_prop_index(ctx_, -1, JS_GLOBALSTASH_INDEX_COMPONENTS);
  173. const Vector<SharedPtr<PackageFile> >& packageFiles = cache->GetPackageFiles();
  174. for (unsigned i = 0; i < packageFiles.Size(); i++)
  175. {
  176. SharedPtr<PackageFile> package = packageFiles[i];
  177. const Vector<String>& files = package->GetCaseEntryNames();
  178. for (unsigned j = 0; j < files.Size(); j++)
  179. {
  180. String name = files[j];
  181. if (!name.StartsWith("Components/"))
  182. continue;
  183. String cname = GetFileName(name);
  184. String jsname = name;
  185. SharedPtr<File> jsfile(cache->GetFile(name));
  186. String csource;
  187. jsfile->ReadText(csource);
  188. GenerateComponent(cname, jsname, csource);
  189. }
  190. }
  191. // pop stash and component object
  192. duk_pop_2(ctx_);
  193. }
  194. void JSVM::InitComponents()
  195. {
  196. ResourceCache* cache = GetSubsystem<ResourceCache>();
  197. if (cache->GetPackageFiles().Size())
  198. {
  199. InitPackageComponents();
  200. return;
  201. }
  202. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  203. const Vector<String>& dirs = cache->GetResourceDirs();
  204. duk_push_global_stash(ctx_);
  205. duk_get_prop_index(ctx_, -1, JS_GLOBALSTASH_INDEX_COMPONENTS);
  206. for (unsigned i = 0; i < dirs.Size(); i++)
  207. {
  208. Vector<String> files;
  209. fileSystem->ScanDir(files ,dirs[i]+"/Components", "*.js", SCAN_FILES, true );
  210. for (unsigned j = 0; j < files.Size(); j++)
  211. {
  212. String cname = GetFileName(files[j]);
  213. String jsname = dirs[i]+"Components/" + files[j];
  214. SharedPtr<File> jsfile = cache->GetFile("Components/" + files[j]);
  215. String csource;
  216. jsfile->ReadText(csource);
  217. GenerateComponent(cname, jsname, csource);
  218. }
  219. }
  220. // pop stash and component object
  221. duk_pop_2(ctx_);
  222. }
  223. int JSVM::js_module_search(duk_context* ctx)
  224. {
  225. JSVM* vm = GetJSVM(ctx);
  226. ResourceCache* cache = vm->GetContext()->GetSubsystem<ResourceCache>();
  227. String path = duk_to_string(ctx, 0);
  228. // first check if this is an AtomicModule
  229. // attempting to avoid module search paths
  230. // so have AtomicEditor, Atomic, and the projects "Modules"
  231. String pathName, fileName, extension;
  232. SplitPath(path, pathName, fileName, extension);
  233. if (fileName.StartsWith("AtomicEditor"))
  234. {
  235. path = "AtomicEditor/Modules/" + path + ".js";
  236. }
  237. else if (fileName.StartsWith("Atomic"))
  238. {
  239. path = "AtomicModules/" + path + ".js";
  240. }
  241. else
  242. {
  243. path = vm->moduleSearchPath_ + "/" + path + ".js";
  244. }
  245. SharedPtr<File> jsfile(cache->GetFile(path));
  246. if (!jsfile)
  247. {
  248. duk_push_null(ctx);
  249. }
  250. else
  251. {
  252. vm->SetLastModuleSearchFile(jsfile->GetFullPath());
  253. String source;
  254. jsfile->ReadText(source);
  255. duk_push_string(ctx, source.CString());
  256. }
  257. return 1;
  258. }
  259. void JSVM::SendJSErrorEvent(const String& filename)
  260. {
  261. duk_context* ctx = GetJSContext();
  262. assert(duk_is_object(ctx, -1));
  263. using namespace JSError;
  264. VariantMap eventData;
  265. duk_get_prop_string(ctx, -1, "fileName");
  266. if (duk_is_string(ctx, -1))
  267. {
  268. eventData[P_ERRORFILENAME] = duk_to_string(ctx, -1);
  269. }
  270. else
  271. {
  272. eventData[P_ERRORFILENAME] = filename;
  273. }
  274. // Component script are wrapped within a closure, the line number
  275. // needs to be offset by this header
  276. duk_get_prop_string(ctx, -2, "lineNumber");
  277. int lineNumber = (int) (duk_to_number(ctx, -1));
  278. eventData[P_ERRORLINENUMBER] = lineNumber;
  279. duk_get_prop_string(ctx, -3, "name");
  280. String name = duk_to_string(ctx, -1);
  281. eventData[P_ERRORNAME] = name;
  282. duk_get_prop_string(ctx, -4, "message");
  283. String message = duk_to_string(ctx, -1);
  284. eventData[P_ERRORMESSAGE] = message;
  285. // we're not getting good file/line from duktape on parser errors
  286. if (name == "SyntaxError")
  287. {
  288. lineNumber = -1;
  289. // parse line if we have it
  290. if (message.Contains("(line "))
  291. {
  292. if (!filename.Length())
  293. eventData[P_ERRORFILENAME] = lastModuleSearchFilename_;
  294. unsigned pos = message.Find("(line ");
  295. const char* parse = message.CString() + pos + 6;
  296. String number;
  297. while (*parse >= '0' && *parse<='9')
  298. {
  299. number += *parse;
  300. parse++;
  301. }
  302. lineNumber = ToInt(number);
  303. }
  304. eventData[P_ERRORLINENUMBER] = lineNumber;
  305. }
  306. duk_get_prop_string(ctx, -5, "stack");
  307. String stack = duk_to_string(ctx, -1);
  308. eventData[P_ERRORSTACK] = stack;
  309. duk_pop_n(ctx, 5);
  310. LOGERRORF("JSErrorEvent: %s : Line %i\n Name: %s\n Message: %s\n Stack:%s",
  311. filename.CString(), lineNumber, name.CString(), message.CString(), stack.CString());
  312. SendEvent(E_JSERROR, eventData);
  313. }
  314. bool JSVM::ExecuteScript(const String& scriptPath)
  315. {
  316. String path = scriptPath;
  317. if (!path.StartsWith("Scripts/"))
  318. path = "Scripts/" + path;
  319. if (!path.EndsWith(".js"))
  320. path += ".js";
  321. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile(path));
  322. if (file.Null())
  323. {
  324. return false;
  325. }
  326. String source;
  327. file->ReadText(source);
  328. duk_push_string(ctx_, file->GetFullPath().CString());
  329. if (duk_eval_raw(ctx_, source.CString(), 0,
  330. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  331. {
  332. if (duk_is_object(ctx_, -1))
  333. SendJSErrorEvent(path);
  334. duk_pop(ctx_);
  335. return false;
  336. }
  337. duk_pop(ctx_);
  338. return true;
  339. }
  340. bool JSVM::ExecuteFile(File *file)
  341. {
  342. if (!file)
  343. return false;
  344. String source;
  345. file->ReadText(source);
  346. duk_push_string(ctx_, file->GetFullPath().CString());
  347. if (duk_eval_raw(ctx_, source.CString(), 0,
  348. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  349. {
  350. if (duk_is_object(ctx_, -1))
  351. SendJSErrorEvent(file->GetFullPath());
  352. duk_pop(ctx_);
  353. return false;
  354. }
  355. duk_pop(ctx_);
  356. return true;
  357. }
  358. bool JSVM::ExecuteMain()
  359. {
  360. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile("Scripts/main.js"));
  361. if (file.Null())
  362. {
  363. return false;
  364. }
  365. String source;
  366. file->ReadText(source);
  367. duk_push_string(ctx_, file->GetFullPath().CString());
  368. if (duk_eval_raw(ctx_, source.CString(), 0,
  369. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  370. {
  371. if (duk_is_object(ctx_, -1))
  372. SendJSErrorEvent(file->GetFullPath());
  373. duk_pop(ctx_);
  374. return false;
  375. }
  376. duk_pop(ctx_);
  377. return true;
  378. }
  379. }