JSVM.cpp 12 KB

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