JSVM.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. #include "JSEventHelper.h"
  20. namespace Atomic
  21. {
  22. JSVM* JSVM::instance_ = NULL;
  23. JSVM::JSVM(Context* context) :
  24. Object(context),
  25. ctx_(0),
  26. gcTime_(0.0f)
  27. {
  28. assert(!instance_);
  29. instance_ = this;
  30. metrics_ = new JSMetrics(context, this);
  31. context_->RegisterSubsystem(new JSEventDispatcher(context_));
  32. context_->SetGlobalEventListener(context_->GetSubsystem<JSEventDispatcher>());
  33. }
  34. JSVM::~JSVM()
  35. {
  36. context_->SetGlobalEventListener(0);
  37. context_->RemoveSubsystem(JSEventDispatcher::GetTypeStatic());
  38. duk_destroy_heap(ctx_);
  39. instance_ = NULL;
  40. }
  41. void JSVM::InitJSContext()
  42. {
  43. ctx_ = duk_create_heap_default();
  44. jsapi_init_atomic(this);
  45. // register whether we are in the editor
  46. duk_get_global_string(ctx_, "Atomic");
  47. duk_push_boolean(ctx_, context_->GetEditorContext() ? 1 : 0);
  48. duk_put_prop_string(ctx_, -2, "editor");
  49. duk_pop(ctx_);
  50. duk_push_global_stash(ctx_);
  51. duk_push_object(ctx_);
  52. duk_put_prop_index(ctx_, -2, JS_GLOBALSTASH_INDEX_COMPONENTS);
  53. duk_pop(ctx_);
  54. js_init_require(this);
  55. js_init_jsplugin(this);
  56. ui_ = new JSUI(context_);
  57. // handle this elsewhere?
  58. SubscribeToEvents();
  59. }
  60. void JSVM::SubscribeToEvents()
  61. {
  62. SubscribeToEvent(E_UPDATE, HANDLER(JSVM, HandleUpdate));
  63. }
  64. void JSVM::HandleUpdate(StringHash eventType, VariantMap& eventData)
  65. {
  66. PROFILE(JSVM_HandleUpdate);
  67. using namespace Update;
  68. // Take the frame time step, which is stored as a float
  69. float timeStep = eventData[P_TIMESTEP].GetFloat();
  70. gcTime_ += timeStep;
  71. if (gcTime_ > 5.0f)
  72. {
  73. PROFILE(JSVM_GC);
  74. // run twice to call finalizers
  75. // see duktape docs
  76. // also ensure #define DUK_OPT_NO_VOLUNTARY_GC
  77. // is enabled in duktape.h
  78. duk_gc(ctx_, 0);
  79. duk_gc(ctx_, 0);
  80. gcTime_ = 0;
  81. }
  82. duk_get_global_string(ctx_, "__js_atomic_main_update");
  83. if (duk_is_function(ctx_, -1))
  84. {
  85. duk_push_number(ctx_, timeStep);
  86. duk_pcall(ctx_, 1);
  87. duk_pop(ctx_);
  88. }
  89. else
  90. {
  91. duk_pop(ctx_);
  92. }
  93. }
  94. bool JSVM::ExecuteFunction(const String& functionName)
  95. {
  96. duk_get_global_string(ctx_, functionName.CString());
  97. if (duk_is_function(ctx_, -1))
  98. {
  99. bool ok = true;
  100. if (duk_pcall(ctx_, 0) != 0)
  101. {
  102. ok = false;
  103. if (duk_is_object(ctx_, -1))
  104. {
  105. SendJSErrorEvent();
  106. }
  107. else
  108. {
  109. assert(0);
  110. }
  111. }
  112. duk_pop(ctx_);
  113. return ok;
  114. }
  115. else
  116. {
  117. duk_pop(ctx_);
  118. }
  119. return false;
  120. }
  121. void JSVM::SendJSErrorEvent(const String& filename)
  122. {
  123. duk_context* ctx = GetJSContext();
  124. using namespace JSError;
  125. VariantMap eventData;
  126. if (duk_is_string(ctx, -1))
  127. {
  128. eventData[P_ERRORNAME] = "(Unknown Error Name)";
  129. eventData[P_ERRORFILENAME] = "(Unknown Filename)";
  130. eventData[P_ERRORLINENUMBER] = -1;
  131. eventData[P_ERRORMESSAGE] = duk_to_string(ctx, -1);
  132. eventData[P_ERRORSTACK] = "";
  133. SendEvent(E_JSERROR, eventData);
  134. return;
  135. }
  136. assert(duk_is_object(ctx, -1));
  137. duk_get_prop_string(ctx, -1, "fileName");
  138. if (duk_is_string(ctx, -1))
  139. {
  140. eventData[P_ERRORFILENAME] = duk_to_string(ctx, -1);
  141. }
  142. else
  143. {
  144. eventData[P_ERRORFILENAME] = filename;
  145. }
  146. // Component script are wrapped within a closure, the line number
  147. // needs to be offset by this header
  148. duk_get_prop_string(ctx, -2, "lineNumber");
  149. int lineNumber = (int) (duk_to_number(ctx, -1));
  150. eventData[P_ERRORLINENUMBER] = lineNumber;
  151. duk_get_prop_string(ctx, -3, "name");
  152. String name = duk_to_string(ctx, -1);
  153. eventData[P_ERRORNAME] = name;
  154. duk_get_prop_string(ctx, -4, "message");
  155. String message = duk_to_string(ctx, -1);
  156. eventData[P_ERRORMESSAGE] = message;
  157. // we're not getting good file/line from duktape on parser errors
  158. if (name == "SyntaxError")
  159. {
  160. lineNumber = -1;
  161. // parse line if we have it
  162. if (message.Contains("(line "))
  163. {
  164. if (!filename.Length())
  165. eventData[P_ERRORFILENAME] = lastModuleSearchFilename_;
  166. unsigned pos = message.Find("(line ");
  167. const char* parse = message.CString() + pos + 6;
  168. String number;
  169. while (*parse >= '0' && *parse<='9')
  170. {
  171. number += *parse;
  172. parse++;
  173. }
  174. lineNumber = ToInt(number);
  175. }
  176. eventData[P_ERRORLINENUMBER] = lineNumber;
  177. }
  178. duk_get_prop_string(ctx, -5, "stack");
  179. String stack = duk_to_string(ctx, -1);
  180. eventData[P_ERRORSTACK] = stack;
  181. duk_pop_n(ctx, 5);
  182. LOGERRORF("JSErrorEvent: %s : Line %i\n Name: %s\n Message: %s\n Stack:%s",
  183. filename.CString(), lineNumber, name.CString(), message.CString(), stack.CString());
  184. SendEvent(E_JSERROR, eventData);
  185. }
  186. bool JSVM::ExecuteScript(const String& scriptPath)
  187. {
  188. String path = scriptPath;
  189. if (!path.StartsWith("Scripts/"))
  190. path = "Scripts/" + path;
  191. if (!path.EndsWith(".js"))
  192. path += ".js";
  193. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile(path));
  194. if (file.Null())
  195. {
  196. return false;
  197. }
  198. String source;
  199. file->ReadText(source);
  200. duk_push_string(ctx_, file->GetFullPath().CString());
  201. if (duk_eval_raw(ctx_, source.CString(), 0,
  202. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  203. {
  204. if (duk_is_object(ctx_, -1))
  205. SendJSErrorEvent(path);
  206. duk_pop(ctx_);
  207. return false;
  208. }
  209. duk_pop(ctx_);
  210. return true;
  211. }
  212. bool JSVM::ExecuteFile(File *file)
  213. {
  214. if (!file)
  215. return false;
  216. String source;
  217. file->ReadText(source);
  218. duk_push_string(ctx_, file->GetFullPath().CString());
  219. if (duk_eval_raw(ctx_, source.CString(), 0,
  220. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  221. {
  222. SendJSErrorEvent(file->GetFullPath());
  223. duk_pop(ctx_);
  224. return false;
  225. }
  226. duk_pop(ctx_);
  227. return true;
  228. }
  229. void JSVM::GC()
  230. {
  231. // run twice to ensure finalizers are run
  232. duk_gc(ctx_, 0);
  233. duk_gc(ctx_, 0);
  234. }
  235. bool JSVM::ExecuteMain()
  236. {
  237. if (!GetSubsystem<ResourceCache>()->Exists("Scripts/main.js"))
  238. return true;
  239. duk_get_global_string(ctx_, "require");
  240. duk_push_string(ctx_, "Scripts/main");
  241. if (duk_pcall(ctx_, 1) != 0)
  242. {
  243. SendJSErrorEvent();
  244. return false;
  245. }
  246. if (duk_is_object(ctx_, -1))
  247. {
  248. duk_get_prop_string(ctx_, -1, "update");
  249. if (duk_is_function(ctx_, -1))
  250. {
  251. // store function for main loop
  252. duk_put_global_string(ctx_, "__js_atomic_main_update");
  253. }
  254. else
  255. {
  256. duk_pop(ctx_);
  257. }
  258. }
  259. // pop main module
  260. duk_pop(ctx_);
  261. return true;
  262. }
  263. }