engine.js 10 KB

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