JSVM.cpp 6.8 KB

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