engine.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. // The following is concatenated with generated code, and acts as the end
  2. // of a wrapper for said code. See pre.js for the other part of the
  3. // wrapper.
  4. exposedLibs['PATH'] = PATH;
  5. exposedLibs['FS'] = FS;
  6. return Module;
  7. },
  8. };
  9. (function() {
  10. var engine = Engine;
  11. var DOWNLOAD_ATTEMPTS_MAX = 4;
  12. var basePath = null;
  13. var wasmFilenameExtensionOverride = null;
  14. var engineLoadPromise = null;
  15. var loadingFiles = {};
  16. function getPathLeaf(path) {
  17. while (path.endsWith('/'))
  18. path = path.slice(0, -1);
  19. return path.slice(path.lastIndexOf('/') + 1);
  20. }
  21. function getBasePath(path) {
  22. if (path.endsWith('/'))
  23. path = path.slice(0, -1);
  24. if (path.lastIndexOf('.') > path.lastIndexOf('/'))
  25. path = path.slice(0, path.lastIndexOf('.'));
  26. return path;
  27. }
  28. function getBaseName(path) {
  29. return getPathLeaf(getBasePath(path));
  30. }
  31. Engine = function Engine() {
  32. this.rtenv = null;
  33. var LIBS = {};
  34. var initPromise = null;
  35. var unloadAfterInit = true;
  36. var preloadedFiles = [];
  37. var resizeCanvasOnStart = true;
  38. var progressFunc = null;
  39. var preloadProgressTracker = {};
  40. var lastProgress = { loaded: 0, total: 0 };
  41. var canvas = null;
  42. var executableName = null;
  43. var locale = null;
  44. var stdout = null;
  45. var stderr = null;
  46. this.init = function(newBasePath) {
  47. if (!initPromise) {
  48. initPromise = Engine.load(newBasePath).then(
  49. instantiate.bind(this)
  50. );
  51. requestAnimationFrame(animateProgress);
  52. if (unloadAfterInit)
  53. initPromise.then(Engine.unloadEngine);
  54. }
  55. return initPromise;
  56. };
  57. function instantiate(wasmBuf) {
  58. var rtenvProps = {
  59. engine: this,
  60. ENV: {},
  61. };
  62. if (typeof stdout === 'function')
  63. rtenvProps.print = stdout;
  64. if (typeof stderr === 'function')
  65. rtenvProps.printErr = stderr;
  66. rtenvProps.instantiateWasm = function(imports, onSuccess) {
  67. WebAssembly.instantiate(wasmBuf, imports).then(function(result) {
  68. onSuccess(result.instance);
  69. });
  70. return {};
  71. };
  72. return new Promise(function(resolve, reject) {
  73. rtenvProps.onRuntimeInitialized = resolve;
  74. rtenvProps.onAbort = reject;
  75. rtenvProps.thisProgram = executableName;
  76. rtenvProps.engine.rtenv = Engine.RuntimeEnvironment(rtenvProps, LIBS);
  77. });
  78. }
  79. this.preloadFile = function(pathOrBuffer, destPath) {
  80. if (pathOrBuffer instanceof ArrayBuffer) {
  81. pathOrBuffer = new Uint8Array(pathOrBuffer);
  82. } else if (ArrayBuffer.isView(pathOrBuffer)) {
  83. pathOrBuffer = new Uint8Array(pathOrBuffer.buffer);
  84. }
  85. if (pathOrBuffer instanceof Uint8Array) {
  86. preloadedFiles.push({
  87. path: destPath,
  88. buffer: pathOrBuffer
  89. });
  90. return Promise.resolve();
  91. } else if (typeof pathOrBuffer === 'string') {
  92. return loadPromise(pathOrBuffer, preloadProgressTracker).then(function(xhr) {
  93. preloadedFiles.push({
  94. path: destPath || pathOrBuffer,
  95. buffer: xhr.response
  96. });
  97. });
  98. } else {
  99. throw Promise.reject("Invalid object for preloading");
  100. }
  101. };
  102. this.start = function() {
  103. return this.init().then(
  104. Function.prototype.apply.bind(synchronousStart, this, arguments)
  105. );
  106. };
  107. this.startGame = function(execName, mainPack) {
  108. executableName = execName;
  109. var mainArgs = [ '--main-pack', getPathLeaf(mainPack) ];
  110. return Promise.all([
  111. this.init(getBasePath(execName)),
  112. this.preloadFile(mainPack, getPathLeaf(mainPack))
  113. ]).then(
  114. Function.prototype.apply.bind(synchronousStart, this, mainArgs)
  115. );
  116. };
  117. function synchronousStart() {
  118. if (canvas instanceof HTMLCanvasElement) {
  119. this.rtenv.canvas = canvas;
  120. } else {
  121. var firstCanvas = document.getElementsByTagName('canvas')[0];
  122. if (firstCanvas instanceof HTMLCanvasElement) {
  123. this.rtenv.canvas = firstCanvas;
  124. } else {
  125. throw new Error("No canvas found");
  126. }
  127. }
  128. var actualCanvas = this.rtenv.canvas;
  129. // canvas can grab focus on click
  130. if (actualCanvas.tabIndex < 0) {
  131. actualCanvas.tabIndex = 0;
  132. }
  133. // necessary to calculate cursor coordinates correctly
  134. actualCanvas.style.padding = 0;
  135. actualCanvas.style.borderWidth = 0;
  136. actualCanvas.style.borderStyle = 'none';
  137. // disable right-click context menu
  138. actualCanvas.addEventListener('contextmenu', function(ev) {
  139. ev.preventDefault();
  140. }, false);
  141. // until context restoration is implemented
  142. actualCanvas.addEventListener('webglcontextlost', function(ev) {
  143. alert("WebGL context lost, please reload the page");
  144. ev.preventDefault();
  145. }, false);
  146. if (locale) {
  147. this.rtenv.locale = locale;
  148. } else {
  149. this.rtenv.locale = navigator.languages ? navigator.languages[0] : navigator.language;
  150. }
  151. this.rtenv.locale = this.rtenv.locale.split('.')[0];
  152. this.rtenv.resizeCanvasOnStart = resizeCanvasOnStart;
  153. preloadedFiles.forEach(function(file) {
  154. var dir = LIBS.PATH.dirname(file.path);
  155. try {
  156. LIBS.FS.stat(dir);
  157. } catch (e) {
  158. if (e.code !== 'ENOENT') {
  159. throw e;
  160. }
  161. LIBS.FS.mkdirTree(dir);
  162. }
  163. // With memory growth, canOwn should be false.
  164. LIBS.FS.createDataFile(file.path, null, new Uint8Array(file.buffer), true, true, false);
  165. }, this);
  166. preloadedFiles = null;
  167. initPromise = null;
  168. this.rtenv.callMain(arguments);
  169. }
  170. this.setProgressFunc = function(func) {
  171. progressFunc = func;
  172. };
  173. this.setResizeCanvasOnStart = function(enabled) {
  174. resizeCanvasOnStart = enabled;
  175. };
  176. function animateProgress() {
  177. var loaded = 0;
  178. var total = 0;
  179. var totalIsValid = true;
  180. var progressIsFinal = true;
  181. [loadingFiles, preloadProgressTracker].forEach(function(tracker) {
  182. Object.keys(tracker).forEach(function(file) {
  183. if (!tracker[file].final)
  184. progressIsFinal = false;
  185. if (!totalIsValid || tracker[file].total === 0) {
  186. totalIsValid = false;
  187. total = 0;
  188. } else {
  189. total += tracker[file].total;
  190. }
  191. loaded += tracker[file].loaded;
  192. });
  193. });
  194. if (loaded !== lastProgress.loaded || total !== lastProgress.total) {
  195. lastProgress.loaded = loaded;
  196. lastProgress.total = total;
  197. if (typeof progressFunc === 'function')
  198. progressFunc(loaded, total);
  199. }
  200. if (!progressIsFinal)
  201. requestAnimationFrame(animateProgress);
  202. }
  203. this.setCanvas = function(elem) {
  204. canvas = elem;
  205. };
  206. this.setExecutableName = function(newName) {
  207. executableName = newName;
  208. };
  209. this.setLocale = function(newLocale) {
  210. locale = newLocale;
  211. };
  212. this.setUnloadAfterInit = function(enabled) {
  213. if (enabled && !unloadAfterInit && initPromise) {
  214. initPromise.then(Engine.unloadEngine);
  215. }
  216. unloadAfterInit = enabled;
  217. };
  218. this.setStdoutFunc = function(func) {
  219. var print = function(text) {
  220. if (arguments.length > 1) {
  221. text = Array.prototype.slice.call(arguments).join(" ");
  222. }
  223. func(text);
  224. };
  225. if (this.rtenv)
  226. this.rtenv.print = print;
  227. stdout = print;
  228. };
  229. this.setStderrFunc = function(func) {
  230. var printErr = function(text) {
  231. if (arguments.length > 1)
  232. text = Array.prototype.slice.call(arguments).join(" ");
  233. func(text);
  234. };
  235. if (this.rtenv)
  236. this.rtenv.printErr = printErr;
  237. stderr = printErr;
  238. };
  239. }; // Engine()
  240. Engine.RuntimeEnvironment = engine.RuntimeEnvironment;
  241. Engine.isWebGLAvailable = function(majorVersion = 1) {
  242. var testContext = false;
  243. try {
  244. var testCanvas = document.createElement('canvas');
  245. if (majorVersion === 1) {
  246. testContext = testCanvas.getContext('webgl') || testCanvas.getContext('experimental-webgl');
  247. } else if (majorVersion === 2) {
  248. testContext = testCanvas.getContext('webgl2') || testCanvas.getContext('experimental-webgl2');
  249. }
  250. } catch (e) {}
  251. return !!testContext;
  252. };
  253. Engine.setWebAssemblyFilenameExtension = function(override) {
  254. if (String(override).length === 0) {
  255. throw new Error('Invalid WebAssembly filename extension override');
  256. }
  257. wasmFilenameExtensionOverride = String(override);
  258. }
  259. Engine.load = function(newBasePath) {
  260. if (newBasePath !== undefined) basePath = getBasePath(newBasePath);
  261. if (engineLoadPromise === null) {
  262. if (typeof WebAssembly !== 'object')
  263. return Promise.reject(new Error("Browser doesn't support WebAssembly"));
  264. // TODO cache/retrieve module to/from idb
  265. engineLoadPromise = loadPromise(basePath + '.' + (wasmFilenameExtensionOverride || 'wasm')).then(function(xhr) {
  266. return xhr.response;
  267. });
  268. engineLoadPromise = engineLoadPromise.catch(function(err) {
  269. engineLoadPromise = null;
  270. throw err;
  271. });
  272. }
  273. return engineLoadPromise;
  274. };
  275. Engine.unload = function() {
  276. engineLoadPromise = null;
  277. };
  278. function loadPromise(file, tracker) {
  279. if (tracker === undefined)
  280. tracker = loadingFiles;
  281. return new Promise(function(resolve, reject) {
  282. loadXHR(resolve, reject, file, tracker);
  283. });
  284. }
  285. function loadXHR(resolve, reject, file, tracker) {
  286. var xhr = new XMLHttpRequest;
  287. xhr.open('GET', file);
  288. if (!file.endsWith('.js')) {
  289. xhr.responseType = 'arraybuffer';
  290. }
  291. ['loadstart', 'progress', 'load', 'error', 'abort'].forEach(function(ev) {
  292. xhr.addEventListener(ev, onXHREvent.bind(xhr, resolve, reject, file, tracker));
  293. });
  294. xhr.send();
  295. }
  296. function onXHREvent(resolve, reject, file, tracker, ev) {
  297. if (this.status >= 400) {
  298. if (this.status < 500 || ++tracker[file].attempts >= DOWNLOAD_ATTEMPTS_MAX) {
  299. reject(new Error("Failed loading file '" + file + "': " + this.statusText));
  300. this.abort();
  301. return;
  302. } else {
  303. setTimeout(loadXHR.bind(null, resolve, reject, file, tracker), 1000);
  304. }
  305. }
  306. switch (ev.type) {
  307. case 'loadstart':
  308. if (tracker[file] === undefined) {
  309. tracker[file] = {
  310. total: ev.total,
  311. loaded: ev.loaded,
  312. attempts: 0,
  313. final: false,
  314. };
  315. }
  316. break;
  317. case 'progress':
  318. tracker[file].loaded = ev.loaded;
  319. tracker[file].total = ev.total;
  320. break;
  321. case 'load':
  322. tracker[file].final = true;
  323. resolve(this);
  324. break;
  325. case 'error':
  326. if (++tracker[file].attempts >= DOWNLOAD_ATTEMPTS_MAX) {
  327. tracker[file].final = true;
  328. reject(new Error("Failed loading file '" + file + "'"));
  329. } else {
  330. setTimeout(loadXHR.bind(null, resolve, reject, file, tracker), 1000);
  331. }
  332. break;
  333. case 'abort':
  334. tracker[file].final = true;
  335. reject(new Error("Loading file '" + file + "' was aborted."));
  336. break;
  337. }
  338. }
  339. })();