EngineObject.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. #include "EngineObject.h"
  2. #include "JS.h"
  3. #include "ScriptEngine.h"
  4. #include "WallpaperEngine/Logging/Log.h"
  5. #include "WallpaperEngine/Audio/Drivers/AudioDriver.h"
  6. #include "WallpaperEngine/Audio/Drivers/Recorders/PlaybackRecorder.h"
  7. #include "WallpaperEngine/Data/Model/Property.h"
  8. #include "WallpaperEngine/Desktop/UserShortcut.h"
  9. #include "WallpaperEngine/Render/Wallpapers/CScene.h"
  10. #include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
  11. #include <algorithm>
  12. #include <chrono>
  13. #include <map>
  14. #include <numeric>
  15. #include <vector>
  16. using namespace WallpaperEngine::Scripting;
  17. extern float g_Time;
  18. extern float g_TimeLast;
  19. extern float g_Daytime;
  20. namespace {
  21. EngineObject& engineOf (const v8::FunctionCallbackInfo<v8::Value>& info) {
  22. return ScriptEngine::from (info.GetIsolate ()).getEngineObject ();
  23. }
  24. // read-only properties, writes are ignored instead of aborting the calling script
  25. void engine_set_value (const v8::FunctionCallbackInfo<v8::Value>&) { }
  26. // rebuilt on every read so scripts always see the current values
  27. void engine_get_user_properties (const v8::FunctionCallbackInfo<v8::Value>& info) {
  28. auto& engine = ScriptEngine::from (info.GetIsolate ());
  29. const auto context = engine.getContext ();
  30. const v8::Local<v8::Object> result = v8::Object::New (info.GetIsolate ());
  31. for (const auto& [name, property] : engine.getScene ().getUserProperties ()) {
  32. JS::set (context, result, name, engine.userPropertyToJs (*property));
  33. }
  34. info.GetReturnValue ().Set (result);
  35. }
  36. // the name is the usershortcut user property's; only a shortcut the user assigned is ever opened
  37. void engine_open_user_shortcut (const v8::FunctionCallbackInfo<v8::Value>& info) {
  38. if (info.Length () < 1 || !info[0]->IsString ()) {
  39. return;
  40. }
  41. const std::string propertyName = JS::toString (info.GetIsolate (), info[0]);
  42. const auto& properties = ScriptEngine::from (info.GetIsolate ()).getScene ().getUserProperties ();
  43. const auto property = properties.find (propertyName);
  44. if (property == properties.end () || !property->second->is<WallpaperEngine::Data::Model::PropertyUserShortcut> ()) {
  45. sLog.error ("openUserShortcut: no user shortcut property named ", propertyName);
  46. return;
  47. }
  48. const auto shortcut = WallpaperEngine::Desktop::UserShortcut::parse (property->second->getString ());
  49. if (!shortcut.has_value ()) {
  50. return;
  51. }
  52. // a script calling this from update() instead of a click must not start the app every frame
  53. static std::map<std::string, std::chrono::steady_clock::time_point> lastLaunch;
  54. const auto now = std::chrono::steady_clock::now ();
  55. if (const auto last = lastLaunch.find (propertyName);
  56. last != lastLaunch.end () && now - last->second < std::chrono::seconds (1)) {
  57. return;
  58. }
  59. lastLaunch[propertyName] = now;
  60. sLog.out ("Opening user shortcut ", propertyName, ": ", shortcut->target);
  61. shortcut->launch ();
  62. }
  63. // scripts only ever hand the result back to layer properties (layer.font = ...), so the path itself is the handle
  64. void engine_register_asset (const v8::FunctionCallbackInfo<v8::Value>& info) {
  65. if (info.Length () < 1 || !info[0]->IsString ()) {
  66. return;
  67. }
  68. info.GetReturnValue ().Set (info[0]);
  69. }
  70. // engine.isRunningInEditor() and friends: fixed answers, this is always a plain desktop wallpaper
  71. void engine_query_flag (const v8::FunctionCallbackInfo<v8::Value>& info, int answer) {
  72. info.GetReturnValue ().Set (answer != 0);
  73. }
  74. // the scene's own coordinate space (project width/height), not the monitor resolution
  75. void engine_get_canvas_size (const v8::FunctionCallbackInfo<v8::Value>& info) {
  76. auto& engine = ScriptEngine::from (info.GetIsolate ());
  77. const auto& camera = engine.getScene ().getCamera ();
  78. info.GetReturnValue ().Set (
  79. engine.getAdapters ().vec2->create (glm::vec2 (camera.getWidth (), camera.getHeight ()))
  80. );
  81. }
  82. glm::vec2 engine_screen_size (const ScriptEngine& engine) {
  83. const auto& screen = engine.getScene ().getScreenSize ();
  84. if (screen.x > 0 && screen.y > 0) {
  85. return glm::vec2 (screen);
  86. }
  87. const auto& camera = engine.getScene ().getCamera ();
  88. return { camera.getWidth (), camera.getHeight () };
  89. }
  90. void engine_get_screen_resolution (const v8::FunctionCallbackInfo<v8::Value>& info) {
  91. auto& engine = ScriptEngine::from (info.GetIsolate ());
  92. info.GetReturnValue ().Set (engine.getAdapters ().vec2->create (engine_screen_size (engine)));
  93. }
  94. // magic 1 asks for landscape instead of portrait
  95. void engine_query_orientation (const v8::FunctionCallbackInfo<v8::Value>& info, int landscape) {
  96. const auto size = engine_screen_size (ScriptEngine::from (info.GetIsolate ()));
  97. info.GetReturnValue ().Set (landscape != 0 ? size.x >= size.y : size.y > size.x);
  98. }
  99. // layers are never destroyed from scripts here, so any layer handle is still valid
  100. void engine_is_object_valid (const v8::FunctionCallbackInfo<v8::Value>& info) {
  101. info.GetReturnValue ().Set (
  102. info.Length () > 0
  103. && ScriptEngine::from (info.GetIsolate ()).getAdapters ().object->getObject (info[0]) != nullptr
  104. );
  105. }
  106. void engine_get_frametime (const v8::FunctionCallbackInfo<v8::Value>& info) {
  107. info.GetReturnValue ().Set (static_cast<double> (g_Time - g_TimeLast));
  108. }
  109. void engine_get_runtime (const v8::FunctionCallbackInfo<v8::Value>& info) {
  110. info.GetReturnValue ().Set (static_cast<double> (g_Time));
  111. }
  112. void engine_get_daytime (const v8::FunctionCallbackInfo<v8::Value>& info) {
  113. info.GetReturnValue ().Set (static_cast<double> (g_Daytime));
  114. }
  115. // the stop function setTimeout/setInterval return, also engine.clearTimeout without a timer bound to it
  116. // (scenescript64 sub_181656780)
  117. void engine_clear_timeout (const v8::FunctionCallbackInfo<v8::Value>& info) {
  118. auto& engine = ScriptEngine::from (info.GetIsolate ());
  119. if (engine.isEvaluatingModuleBody ()) {
  120. JS::throwSyntaxError (info.GetIsolate (), "timeout cannot be cleared from global scope.");
  121. return;
  122. }
  123. info.GetReturnValue ().Set (
  124. info.Data ()->IsArray () && engine.getEngineObject ().stopTimer (info.Data ().As<v8::Array> ())
  125. );
  126. }
  127. // engine.setTimeout (callback, delay) / setInterval (callback, delay), sub_181655E10 / sub_1816562D0: delays are
  128. // milliseconds, a timeout's is optional, an interval needs one above 0
  129. void engine_add_timer (const v8::FunctionCallbackInfo<v8::Value>& info, int interval) {
  130. auto& engine = ScriptEngine::from (info.GetIsolate ());
  131. if (engine.isEvaluatingModuleBody ()) {
  132. JS::throwSyntaxError (
  133. info.GetIsolate (),
  134. interval ? "setInterval cannot be called from global scope."
  135. : "setTimeout cannot be called from global scope."
  136. );
  137. return;
  138. }
  139. if (info.Length () < (interval ? 2 : 1) || !info[0]->IsFunction ()) {
  140. return;
  141. }
  142. float seconds = 0.0f;
  143. if (info.Length () > 1 && info[1]->IsNumber ()) {
  144. seconds = static_cast<float> (info[1].As<v8::Number> ()->Value () / 1000.0);
  145. } else if (interval) {
  146. return;
  147. }
  148. if (interval && seconds <= 0.0f) {
  149. return;
  150. }
  151. info.GetReturnValue ().Set (engineOf (info).addTimer (info[0].As<v8::Function> (), seconds, interval != 0));
  152. }
  153. // engine.registerAudioBuffers(resolution), scenescript64 2.8.42 sub_181655170: only from a module's top level
  154. // code, no number argument means 16, anything but 16/32/64 throws. Both errors are SyntaxErrors in live WE.
  155. void engine_register_audio_buffers (const v8::FunctionCallbackInfo<v8::Value>& info) {
  156. auto& engine = ScriptEngine::from (info.GetIsolate ());
  157. if (!engine.isEvaluatingModuleBody ()) {
  158. JS::throwSyntaxError (info.GetIsolate (), "registerAudioBuffers can only be called from global scope.");
  159. return;
  160. }
  161. int resolution = 16;
  162. if (info.Length () > 0 && info[0]->IsNumber ()) {
  163. resolution = info[0]->Int32Value (engine.getContext ()).FromMaybe (0);
  164. }
  165. if (resolution != 16 && resolution != 32 && resolution != 64) {
  166. JS::throwSyntaxError (info.GetIsolate (), "Resolution must be either 16, 32 or 64.");
  167. return;
  168. }
  169. info.GetReturnValue ().Set (engine.getEngineObject ().registerAudioBuffers (resolution));
  170. }
  171. } // namespace
  172. EngineObject::EngineObject (ScriptEngine& engine, Render::Wallpapers::CScene& scene) :
  173. m_scene (scene), m_engine (engine) {
  174. auto* isolate = engine.getIsolate ();
  175. const auto context = engine.getContext ();
  176. const v8::Local<v8::Object> instance = v8::Object::New (isolate);
  177. const v8::Local<v8::Function> ignore = JS::function (context, engine_set_value, {}, 1);
  178. const auto accessor = [&] (const char* name, v8::FunctionCallback getter) {
  179. instance->SetAccessorProperty (JS::name (isolate, name), JS::function (context, getter), ignore);
  180. };
  181. const auto method = [&] (const char* name, v8::FunctionCallback callback, int length) {
  182. JS::define (context, instance, name, JS::function (context, callback, {}, length));
  183. };
  184. accessor ("frametime", engine_get_frametime);
  185. accessor ("runtime", engine_get_runtime);
  186. accessor ("timeOfDay", engine_get_daytime);
  187. accessor ("canvasSize", engine_get_canvas_size);
  188. accessor ("userProperties", engine_get_user_properties);
  189. JS::define (context, instance, "AUDIO_RESOLUTION_16", v8::Integer::New (isolate, 16));
  190. JS::define (context, instance, "AUDIO_RESOLUTION_32", v8::Integer::New (isolate, 32));
  191. JS::define (context, instance, "AUDIO_RESOLUTION_64", v8::Integer::New (isolate, 64));
  192. method ("setInterval", JS::bind<engine_add_timer, 1>, 2);
  193. method ("setTimeout", JS::bind<engine_add_timer, 0>, 2);
  194. method ("registerAsset", engine_register_asset, 1);
  195. method ("openUserShortcut", engine_open_user_shortcut, 1);
  196. method ("registerAudioBuffers", engine_register_audio_buffers, 1);
  197. method ("isRunningInEditor", JS::bind<engine_query_flag, 0>, 0);
  198. method ("isDesktopDevice", JS::bind<engine_query_flag, 1>, 0);
  199. method ("isMobileDevice", JS::bind<engine_query_flag, 0>, 0);
  200. method ("isWallpaper", JS::bind<engine_query_flag, 1>, 0);
  201. method ("isScreensaver", JS::bind<engine_query_flag, 0>, 0);
  202. accessor ("screenResolution", engine_get_screen_resolution);
  203. method ("isPortrait", JS::bind<engine_query_orientation, 0>, 0);
  204. method ("isLandscape", JS::bind<engine_query_orientation, 1>, 0);
  205. method ("clearTimeout", engine_clear_timeout, 1);
  206. method ("isObjectValid", engine_is_object_valid, 1);
  207. this->m_instance.Reset (isolate, instance);
  208. }
  209. v8::Local<v8::Object> EngineObject::getInstance () const { return this->m_instance.Get (this->m_engine.getIsolate ()); }
  210. // WE keeps nine buffers per script context and wraps them in new Float32Arrays over a new ArrayBuffer on every call,
  211. // so all registrations of a resolution share their memory
  212. v8::Local<v8::Object> EngineObject::registerAudioBuffers (int resolution) {
  213. auto* isolate = this->m_engine.getIsolate ();
  214. const auto context = this->m_engine.getContext ();
  215. const int first = 3 * (resolution >> 5);
  216. for (int index = 0; index < 9; index++) {
  217. if (this->m_audioBuffers[index] == nullptr) {
  218. this->m_audioBuffers[index]
  219. = v8::ArrayBuffer::NewBackingStore (isolate, (16u << (index / 3)) * sizeof (float));
  220. std::fill_n (static_cast<float*> (this->m_audioBuffers[index]->Data ()), 16 << (index / 3), 0.0f);
  221. }
  222. }
  223. const v8::Local<v8::Object> result = v8::Object::New (isolate);
  224. static constexpr const char* sections[] = { "left", "right", "average" };
  225. for (int section = 0; section < 3; section++) {
  226. const auto buffer = v8::ArrayBuffer::New (isolate, this->m_audioBuffers[first + section]);
  227. JS::set (context, result, sections[section], v8::Float32Array::New (buffer, 0, resolution));
  228. }
  229. return result;
  230. }
  231. v8::Local<v8::Value> EngineObject::addTimer (v8::Local<v8::Function> callback, float seconds, bool interval) {
  232. auto* isolate = this->m_engine.getIsolate ();
  233. const auto* owner = this->m_engine.getRunningModule ();
  234. // timers belong to a script, without one running WE starts none
  235. if (owner == nullptr) {
  236. return v8::Undefined (isolate);
  237. }
  238. const uint64_t id = ++this->m_nextTimerId;
  239. const v8::Local<v8::Array> stopData = JS::data (isolate, { v8::Number::New (isolate, static_cast<double> (id)) });
  240. this->m_timers.push_back (
  241. { .id = id,
  242. .owner = owner->key,
  243. .ownerOrder = owner->order,
  244. .remaining = seconds,
  245. .duration = seconds,
  246. .interval = interval,
  247. .callback = v8::Global<v8::Function> (isolate, callback),
  248. .stopData = v8::Global<v8::Array> (isolate, stopData) }
  249. );
  250. return JS::function (this->m_engine.getContext (), engine_clear_timeout, stopData, 1);
  251. }
  252. // sub_181656780 disarms the function and then removes the first timer of the script that started this one, not
  253. // necessarily this one (a script stopping its second timer stops its first), which is kept as is
  254. bool EngineObject::stopTimer (v8::Local<v8::Array> data) {
  255. auto* isolate = this->m_engine.getIsolate ();
  256. const auto context = this->m_engine.getContext ();
  257. const auto value = JS::get (context, data, 0u);
  258. if (!value->IsNumber ()) {
  259. return false;
  260. }
  261. data->Set (context, 0, v8::Undefined (isolate)).Check ();
  262. const auto id = static_cast<uint64_t> (value.As<v8::Number> ()->Value ());
  263. const auto timer = std::ranges::find (this->m_timers, id, &Timer::id);
  264. if (timer == this->m_timers.end ()) {
  265. return false;
  266. }
  267. const auto first = std::ranges::find (this->m_timers, timer->owner, &Timer::owner);
  268. this->m_timers.erase (first);
  269. return true;
  270. }
  271. void EngineObject::tick () {
  272. auto* isolate = this->m_engine.getIsolate ();
  273. const auto context = this->m_engine.getContext ();
  274. // scenescript64 sub_18164F800 copies [left | right | average] into the registered buffers before any
  275. // callback runs, so what scripts write there lasts until the next frame
  276. if (this->m_audioBuffers[0] != nullptr) {
  277. const auto& recorder = this->m_scene.getAudioContext ().getDriver ().getRecorder ();
  278. const float* sources[] = { recorder.audio16, recorder.audio32, recorder.audio64 };
  279. for (int index = 0; index < 9; index++) {
  280. const int bands = 16 << (index / 3);
  281. std::copy_n (
  282. sources[index / 3] + (index % 3) * bands, bands,
  283. static_cast<float*> (this->m_audioBuffers[index]->Data ())
  284. );
  285. }
  286. }
  287. // script by script, each one's timers in the order they were started; timers started by a callback wait for the
  288. // next frame. Only ids are kept, callbacks stop and start timers
  289. const float frameTime = std::clamp (g_Time - g_TimeLast, 0.0f, 0.25f);
  290. std::vector<size_t> order (this->m_timers.size ());
  291. std::iota (order.begin (), order.end (), 0);
  292. std::ranges::stable_sort (order, {}, [this] (size_t index) { return this->m_timers[index].ownerOrder; });
  293. std::vector<uint64_t> ids;
  294. ids.reserve (order.size ());
  295. for (const auto index : order) {
  296. ids.push_back (this->m_timers[index].id);
  297. }
  298. for (const auto id : ids) {
  299. auto timer = std::ranges::find (this->m_timers, id, &Timer::id);
  300. if (timer == this->m_timers.end ()) {
  301. continue;
  302. }
  303. timer->remaining -= frameTime;
  304. if (timer->remaining > 0.0f) {
  305. continue;
  306. }
  307. const v8::HandleScope handleScope (isolate);
  308. const v8::TryCatch tryCatch (isolate);
  309. const bool interval = timer->interval;
  310. // the callback may start timers, which can move this one
  311. const std::string owner = timer->owner;
  312. if (this->m_engine.callAsModule (owner, timer->callback.Get (isolate)).IsEmpty ()) {
  313. logJSException (isolate, tryCatch, interval ? "setInterval" : "setTimeout");
  314. }
  315. // the callback may have stopped it
  316. timer = std::ranges::find (this->m_timers, id, &Timer::id);
  317. if (timer == this->m_timers.end ()) {
  318. continue;
  319. }
  320. // a finished timeout's stop function does nothing from then on
  321. if (interval) {
  322. timer->remaining = timer->duration;
  323. } else {
  324. timer->stopData.Get (isolate)->Set (context, 0, v8::Undefined (isolate)).Check ();
  325. this->m_timers.erase (timer);
  326. }
  327. }
  328. }