JSVM.cpp 7.1 KB

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