engine.js 9.5 KB

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